Exemplo n.º 1
0
int refresh_gamepads(HWND hwnd)
{
	int test=FALSE;
	int i;
	LPDIRECTINPUT8 dinp;
	SendMessage(hwnd,CB_RESETCONTENT,0,0);
	if(test){
		DIDEVICEINSTANCE di;
		sprintf(di.tszInstanceName,"adaptoid");
		for(i=0;i<4;i++){
			di.guidInstance.Data1=rand();
			enum_gamepads(&di,hwnd);
		}
		printf("press key\n");
//		getkey();
	}
	else
	if(DirectInput8Create(GetModuleHandle(0),DIRECTINPUT_VERSION,&IID_IDirectInput8,(void *)&dinp,0)==DI_OK){
			IDirectInput8_EnumDevices(dinp, DI8DEVCLASS_GAMECTRL, enum_gamepads,
                      hwnd, DIEDFL_ATTACHEDONLY);
	}
	SendMessage(hwnd,CB_SETCURSEL,0,0);
	return TRUE;
}
Exemplo n.º 2
0
static void test_GetDeviceStatus(void)
{
    IDirectInput8A *pDI;
    HRESULT hr;

    hr = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, &IID_IDirectInput8A, (void **)&pDI, NULL);
    if (FAILED(hr))
    {
        win_skip("Failed to instantiate a IDirectInputA instance: 0x%08x\n", hr);
        return;
    }

    hr = IDirectInput8_GetDeviceStatus(pDI, NULL);
    ok(hr == E_POINTER, "IDirectInput8_GetDeviceStatus returned 0x%08x\n", hr);

    hr = IDirectInput8_GetDeviceStatus(pDI, &GUID_Unknown);
    todo_wine
    ok(hr == DIERR_DEVICENOTREG, "IDirectInput8_GetDeviceStatus returned 0x%08x\n", hr);

    hr = IDirectInput8_GetDeviceStatus(pDI, &GUID_SysMouse);
    ok(hr == DI_OK, "IDirectInput8_GetDeviceStatus returned 0x%08x\n", hr);

    IDirectInput8_Release(pDI);
}
InputLayer::InputLayer( 
	HINSTANCE hInst, 
	HWND hWnd, 
	bool bExclusive, 
	bool bUseKeyboard, 
	bool bUseMouse )
{


	m_pKeyboard = NULL;
	m_pMouse = NULL;

	if( m_pGlobalILayer )
	{
		assert(false);
	}
	m_pGlobalILayer = this;

	HRESULT hr;

	/**
	 * ´´½¨DI8 ¶ÔÏó
	 */
	HR(DirectInput8Create( hInst, DIRECTINPUT_VERSION, 
						IID_IDirectInput8, (void**)&m_pDI, NULL ));

	if( bUseKeyboard )
	{
		m_pKeyboard = new Keyboard( hWnd );
	}
	if( bUseMouse )
	{
		m_pMouse = new Mouse( hWnd, bExclusive );
	}

}
bool InputClass::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
{
	HRESULT result;


	

	// Initialize the location of the mouse on the screen.
	m_mouseX = 0;
	m_mouseY = 0;

	// Store the screen size which will be used for positioning the mouse cursor.
	m_screenWidth = screenWidth;
	m_screenHeight = screenHeight;

	// Initialize the main direct input interface.
	result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, NULL);
	if(FAILED(result))
	{
		return false;
	}

	// Initialize the direct input interface for the keyboard.
	result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, NULL);
	if(FAILED(result))
	{
		return false;
	}

	// Set the data format.  In this case since it is a keyboard we can use the predefined data format.
	result = m_keyboard->SetDataFormat(&c_dfDIKeyboard);
	if(FAILED(result))
	{
		return false;
	}

	// Set the cooperative level of the keyboard to not share with other programs.
	result = m_keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
	if(FAILED(result))
	{
		return false;
	}

	// Now acquire the keyboard.
	result = m_keyboard->Acquire();
	if(FAILED(result))
	{
		return false;
	}

	// Initialize the direct input interface for the mouse.
	result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, NULL);
	if(FAILED(result))
	{
		return false;
	}

	// Set the data format for the mouse using the pre-defined mouse data format.
	result = m_mouse->SetDataFormat(&c_dfDIMouse);
	if(FAILED(result))
	{
		return false;
	}

	// Set the cooperative level of the mouse to share with other programs.
	result = m_mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	if(FAILED(result))
	{
		return false;
	}

	// Acquire the mouse.
	result = m_mouse->Acquire();
	if(FAILED(result))
	{
		return false;
	}

	return true;
}
Exemplo n.º 5
0
// Initialise runtime
bool CRuntime::Initialise(CRuntimeSetup* crSetup)
{
	// Start by getting and saving the CPU capabilities.
	DWORD cpuFeatures = GetCPUCaps();
	supportMMX = cpuFeatures & CPU_FEATURE_MMX;
	supportSSE = cpuFeatures & CPU_FEATURE_SSE;
	supportSSE2 = cpuFeatures & CPU_FEATURE_SSE2;

	// Construct requires MMX for collisions
#ifndef APPRUNTIME
	if (!supportMMX)
		throw runtime_error("Your CPU does not support MMX technology (it must be pretty old!).  Please buy a newer PC then try again!");

#endif

	// Save hInstance
	hInstance = crSetup->hInstance;

	CapReader.pRuntime = this;

	CreateTempDirectory();

	// Get app properties
	BYTE* pData;
	int dataSize;
	HGLOBAL hData = OpenResourceBinary(997, "APPBLOCK", pData, dataSize);
	CapReader.ReadAppProperties(pData, dataSize, props);
	FreeResource(hData);

	// Cannot use both multisampling and motion blur
#ifndef APPRUNTIME
	if (multisamples > 0 && motionBlur)
		throw runtime_error("Cannot enable both multisamples and motion blur.  Please change one of these settings.");
#endif

#ifdef PYTHON
	// Get python
	hData = OpenResourceBinary(992, "PYTHONLIBS", pData, dataSize);
	CapReader.ReadPythonResources(pData, dataSize);
	FreeResource(hData);
	if(!SearchPath(NULL, "python26.dll", NULL, 0, NULL, NULL))
		throw runtime_error("Python26.dll was not found and is required to run this application or feature.  Reinstalling the application "
								"may fix this problem.");
	Py_Initialize();
#endif

	// Get menu resources
	hData = OpenResourceBinary(993, "MENUBLOCK", pData, dataSize);
	CapReader.ReadMenuResources(pData, dataSize, menus);
	FreeResource(hData);

	crSetup->winWidth = props.winWidth;
	crSetup->winHeight = props.winHeight;
	crSetup->eyeDistance = props.eyeDistance;
	crSetup->screensaver = props.screensaver;
	fpsMode = props.fpsMode;
	userFps = props.fps;

	//if (disableWindowsKey)
	//	g_hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL,  DisableWinKeyKeyboardProc, hInstance, 0);

#ifdef CONSTRUCT_DIRECTX9
	crSetup->display_params.fps_mode = props.fpsMode;
	crSetup->display_params.fullscreen = fullscreen = props.fullscreen;
	crSetup->display_params.backbuffer_width = props.winWidth;
	crSetup->display_params.backbuffer_height = props.winHeight;

	switch (multisamples) {
	case 0:	// Off
		crSetup->display_params.multisamples = 0;
		break;
	case 1: // 2x
		crSetup->display_params.multisamples = 2;
		break;
	case 2:	// 4x
		crSetup->display_params.multisamples = 4;
		break;
	case 3: // 8x
		crSetup->display_params.multisamples = 8;
		break;
	default:
		crSetup->display_params.multisamples = 0;
		break;
	}

	// PreInit gets the D3D caps and allows MakeWindows to create the correct number of windows to pass to Init()
	//Display.SetMultiMonitorMode(MMM_CLONE);
	//Display.PreInit();
	renderer.LoadD3D();
#endif

#ifndef CONSTRUCT_SDL
	// Create a window for the runtime
	if (!MakeWindows(crSetup))
		throw runtime_error("Cannot create window");
#else
	if (SDL_Init(SDL_INIT_VIDEO) < 0) 
		exit(1);

	// Register SDL_Quit to be called at exit; makes sure things are cleaned up when we quit.
	atexit(SDL_Quit);
    
	// Attempt to create window with 32bit pixels in hardware
	Display.screen = SDL_SetVideoMode(props.winWidth, props.winHeight, 32, SDL_HWSURFACE);
	SDL_SetAlpha(Display.screen, SDL_SRCALPHA, 255); // Set alpha to normal
#endif

	InitCommonControls();

	// The preview runtimes show the runtime in the title bar.
#ifdef CONSTRUCT_PREVIEW
	#ifdef CONSTRUCT_DIRECTX9
	props.appTitle += " (DX9 runtime)";
	#endif
	#ifdef APPRUNTIME
	props.appTitle += " (App runtime)";
	#endif
	#ifdef CONSTRUCT_SDL
	props.appTitle += " (SDL runtime)";
	#endif
#endif

#ifndef CONSTRUCT_SDL
	SetWindowText(hWnds.front(), props.appTitle);
#else
	SDL_WM_SetCaption(props.appTitle, NULL);
#endif

	// Restore mouse cursor from hourglass
	if (!props.screensaver)
		SetCursor(LoadCursor(NULL, IDC_ARROW));

	// Load a menu
	if (props.UseMenu)
		if (menus.size() != 0)
			SetMenu(hWnds.front(), menus[0]);

#ifndef APPRUNTIME
#ifndef CONSTRUCT_SDL
	// Direct-X setup
	crSetup->display_params.hWnds = hWnds;
	crSetup->display_params.hFocusWnd = hWnds.front();

	winWidthOffset = 0;
	winHeightOffset = 0;

	// Retrieve all display modes: can't set an invalid display mode size
	if (crSetup->display_params.fullscreen) {
		BOOL bRetVal;
		DEVMODE devMode;
		int iMode = 0;

		int wantedWidth = crSetup->display_params.backbuffer_width;
		int wantedHeight = crSetup->display_params.backbuffer_height;
		int bestWidth = 100000;
		int bestHeight = 100000;

		bool found = false;

		do
		{
			bRetVal = ::EnumDisplaySettings(NULL, iMode, &devMode);
			iMode++;

			if (bRetVal)
			{
				int curWidth = devMode.dmPelsWidth;
				int curHeight = devMode.dmPelsHeight;

				// Display mode found!
				if (curWidth == wantedWidth && curHeight == wantedHeight)
					found = true;

				// This display mode is big enough to fit the display in, but is smaller than the last best size
				if ((curWidth >= wantedWidth && curHeight >= wantedHeight)
					&& (curWidth < bestWidth && curHeight < bestHeight)) {
					bestWidth = curWidth;
					bestHeight = curHeight;
				}
			}
		}
		while (bRetVal);

		// Identical display mode not found: use next best that can fit it all on
		if (!found) {

			// Still 100000x100000: no resolution found that supports this
			if (bestWidth == 100000 || bestHeight == 100000)
				throw runtime_error("The display resolution required by this application is not supported.");

	#ifdef CONSTRUCT_PREVIEW
			CString msg;
			msg.Format("Switching to Fullscreen mode: Display mode %d x %d not supported, switching to next best %d x %d.\n\n"
				"The 'Window Width' and 'Window Height' values in Application Properties define the fullscreen resolution.",
				crSetup->display_params.backbuffer_width, crSetup->display_params.backbuffer_height, bestWidth, bestHeight);
			MessageBox(NULL, msg, "Fullscreen preview", MB_OK | MB_ICONEXCLAMATION);
	#endif

			crSetup->display_params.backbuffer_width = wantedWidth = bestWidth;
			crSetup->display_params.backbuffer_height = wantedHeight = bestHeight;
		}
	}

	// Set the eye distance before we initialize
	eyeDistance = crSetup->eyeDistance;
	renderer.SetEyeDistance(eyeDistance);

	// Start up the display engine
	//Display.Init(&(crSetup->d3dDisplaySetup));
	renderer.CreateDevice(crSetup->display_params);

	/*
	// No identical match for display mode
	if (crSetup->d3dDisplaySetup.resWidth != actualDisplayWidth || crSetup->d3dDisplaySetup.resHeight != actualDisplayHeight)
		if (tempDisplayTarget == unallocated_texture)
			tempDisplayTarget = CreateDisplayTargetTexture();

		winWidthOffset = (actualDisplayWidth - crSetup->d3dDisplaySetup.resWidth) / 2;
		winHeightOffset = (actualDisplayHeight - crSetup->d3dDisplaySetup.resHeight) / 2;
	}
	*/

	GetSwapChains();

	// Multi-monitor settings require the temp display target

	if (renderer.GetMultiMonitorMode() != cr::multimonitor_singlescreen) {
		if (tempDisplayTarget == unallocated_texture)
				tempDisplayTarget = CreateDisplayTargetTexture();
	}

	// Linear resizers
	if (props.sampler == 0) {
		renderer.SetSamplerState(cr::ss_magfilter, cr::ssv_point);
		renderer.SetSamplerState(cr::ss_minfilter, cr::ssv_point);
	}
	if (props.sampler == 1) {
		renderer.SetSamplerState(cr::ss_magfilter, cr::ssv_linear);
		renderer.SetSamplerState(cr::ss_minfilter, cr::ssv_linear);
	}

	// Premultiplied alpha mode
	renderer.SetAlphaBlending();

	// Runtime uses clamp-sampling
	renderer.SetSamplerState(cr::ss_addressu, cr::ssv_clamp);
	renderer.SetSamplerState(cr::ss_addressv, cr::ssv_clamp);

	// Create the multisampling target if one required
	//if (multisamples > 0)		// 0 is off
	//	multisampleTargets[0] = renderer.CreateRenderTargetTexture(crSetup->winWidth, crSetup->winHeight, cr::texture_format_a8r8g8b8, true);

#if defined(CONSTRUCT_DIRECTX9) && defined(CONSTRUCT_PREVIEW)
	// Handle shader simulation
	if (simShader != SS_NOSIM) {

		UINT ps_major = D3DSHADER_VERSION_MAJOR(renderer.GetCaps().PixelShaderVersion);
		UINT ps_minor = D3DSHADER_VERSION_MINOR(renderer.GetCaps().PixelShaderVersion);

		CString hardwarePS;
		hardwarePS.Format("%d.%d", ps_major, ps_minor);

		CString simulatedPS;

		switch (simShader) {
		case SS_PS14:
			simulatedPS = "1.4";
			break;
		case SS_PS11:
			simulatedPS = "1.1";
			break;
		case SS_PS00:
			simulatedPS = "0.0";
			break;
		}

		float ps_version = atof(hardwarePS);
		float sim_version = atof(simulatedPS);

		// If fullscreen MessageBox()'s won't work
		if (!fullscreen) {
		
			if (sim_version > ps_version) {
				CString msg;
				msg.Format("You have chosen to simulate a pixel shader version (PS %s) higher than your hardware supports (PS %s).  "
					"You can only simulate lower hardware capabilities.  The application will continue to use PS %s.",
					simulatedPS, hardwarePS, simulatedPS);
				MessageBox(NULL, msg, "Simulate shader", MB_OK | MB_ICONEXCLAMATION);
			}
			else if (sim_version == ps_version) {
				CString msg;
				msg.Format("You have chosen to simulate the same pixel shader version as your hardware supports (PS %s).  "
					"The application will continue normally.", hardwarePS);
				MessageBox(NULL, msg, "Simulate shader", MB_OK | MB_ICONINFORMATION);
			}
			else {
				CString msg;
				msg.Format("You are simulating pixel shader %s capabilites.  Your hardware supports pixel shader %s.",
					simulatedPS, hardwarePS);
				MessageBox(NULL, msg, "Simulate shader", MB_OK | MB_ICONEXCLAMATION);
			}

		}
	}
#endif // shader sims
#endif

	// Load the PNG image list
	hData = OpenResourceBinary(995, "IMAGEBLOCK", pData, dataSize);
	CapReader.ReadImageData(pData, dataSize, imagehandle_to_address);
	FreeResource(hData);

#ifdef CONSTRUCT_DIRECTX9
	// Initialise DirectInput
	if (FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION,
								IID_IDirectInput8, (void**)&dinput, NULL)))
		throw runtime_error("Failed to initialise DirectInput.  Please ensure you have DirectX 8 or above installed!");

	// Initialize the keyboard
	if (FAILED(dinput->CreateDevice(GUID_SysKeyboard, &d_keyboard, NULL)))
		throw runtime_error("Failed to initialise DirectInput.");
	if (FAILED(d_keyboard->SetDataFormat(&c_dfDIKeyboard)))
		throw runtime_error("Failed to initialise DirectInput.");

	if (FAILED(d_keyboard->SetCooperativeLevel(hWnds.front(), DISCL_BACKGROUND |
											 DISCL_NONEXCLUSIVE)))
		throw runtime_error("Failed to initialise DirectInput.");

	if (FAILED(d_keyboard->Acquire()))
		throw runtime_error("Failed to initialise DirectInput.");

	// initialize the mouse
	if (FAILED(dinput->CreateDevice(GUID_SysMouse, &d_mouse, NULL)))
		throw runtime_error("Failed to initialise DirectInput.");
	if (FAILED(d_mouse->SetCooperativeLevel(hWnds.front(), DISCL_BACKGROUND |
										  DISCL_NONEXCLUSIVE)))
		throw runtime_error("Failed to initialise DirectInput.");

	if (FAILED(d_mouse->SetDataFormat(&c_dfDIMouse)))
		throw runtime_error("Failed to initialise DirectInput.");

	if (FAILED(d_mouse->Acquire()))
		throw runtime_error("Failed to initialise DirectInput.");

	inputState.isDirectInput = true;

#endif
#endif //#ifndef APPRUNTIME

	// Save window dimensions
	winWidth = crSetup->winWidth;
	winHeight = crSetup->winHeight;
	RECT clientSize;
	GetClientRect(hWnds.front(), &clientSize);
	realWinWidth = clientSize.right - clientSize.left;
	realWinHeight = clientSize.bottom - clientSize.top;

	// Unpack dependencies before loading plugins
	UnpackDependencies();

	// Unpack the resource plugins to the temp dir and load them
	UnpackPlugins(1000);

	// Read the frame data
	hData = OpenResourceBinary(998, "LEVELBLOCK", pData, dataSize);
	CapReader.ReadFrameData(pData, dataSize);
	FreeResource(hData);

	// Map object type names to their pointers
	for (vector<CRunObjType*>::iterator i = objects.begin(); i != objects.end(); i++)
	{
		CString lowername = (*i)->Name;
		lowername.MakeLower();
		name_to_object[lowername] = *i;
	}

#ifdef CONSTRUCT_DEBUGGER
	// Create debugger once object types are known but before parsing event block (which may send logs)
	// Create invisible initially
	pDebug->Create();
	pDebug->ShowWindow(SW_HIDE);
#endif

	// Read the CAP event tree
	hData = OpenResourceBinary(999, "EVENTBLOCK", pData, dataSize);
	CapReader.ReadEventList(pData, dataSize);
	FreeResource(hData);

	// Iterate all events determining their modifiers
	vector<CRunLayout*>::iterator f = Frames.begin();
	const vector<CRunLayout*>::const_iterator Frames_end = Frames.end();

	for ( ; f != Frames_end; f++) {
		EventIterator e = (*f)->Events.begin();
		EventConstIterator Events_end = (*f)->Events.end();

		for ( ; e != Events_end; ++e) {

			// Recurse down tree finding SOL modifiers
			(*e)->GetSolModifiers(*f);

			// If this event line is a group, it can be marked as top level for optimisation
			if ((*e)->GetType() == EVENT_GROUP)
				((CEventGroup*)*e)->isTopLevel = true;
		}
	}

	// Initialise effects
#ifdef CONSTRUCT_DIRECTX9
	hData = OpenResourceBinary(994, "HLSL", pData, dataSize);
	CapReader.ReadHLSLData(pData, dataSize);
	FreeResource(hData);

	// If motionblur is required, set up the textures
	if (motionBlur) {

		InitMotionBlur();

	}

#endif //APPRUNTIME

	// Clock offset (timers relative to Run())
	clockOffset = clock();
	curFrame = 0;

	// Mark objects which are not to serialize
	CRunObjType* pNoSerialize = GetTypeFromName("No serialize");

	if (pNoSerialize) {
		if (!pNoSerialize->teams.empty()) {
			ObjTypeIterator t = pNoSerialize->teams.begin();
			ObjTypeIterator end = pNoSerialize->teams.end();

			for ( ; t != end; t++)
				(*t)->noSerialize = true;
		}		
	}

	// Set current frame
	CRunLayout* pFirstFrame = Frames.front();
	runningFrames.push_back(pFirstFrame);
	system.pLayout = pFirstFrame;
	pFirstFrame->systemDrawn = true;
	pFirstFrame->Load();

	// Load any other layouts which want their textures loaded on startup
	vector<CRunLayout*>::iterator ly = Frames.begin();
	ly++;	// already loaded 1st layout

	for ( ; ly != Frames.end(); ++ly) {
		if ((*ly)->texture_loading == CRunLayout::tl_load_on_app_start)
			(*ly)->LoadLayoutTextures();
		else if ((*ly)->texture_loading == CRunLayout::tl_use_app_setting && texture_loading == tl_load_on_app_start)
			(*ly)->LoadLayoutTextures();
	}

	// Directories exist etc. by now.
	completedInitialisation = true;

	// Initial frame mouse coord
	POINT mouse;
	GetCursorPos(&mouse);

	if (!fullscreen)
		ScreenToClient(hWnds.front(), &mouse);

	pFirstFrame->mouseX = mouse.x;
	pFirstFrame->mouseY = mouse.y;

	// Create initial frame objects (generatevent works)
	pFirstFrame->CreateInitialObjects();

	FlushDelayedObjects();

	system.changeResWidth = winWidth;
	system.changeResHeight = winHeight;

	// Start of Layout triggered only if not previewing another layout
	if (previewLayout <= 0)
		GenerateEvent(-1, SYSTEM_STARTOFFRAME, NULL);

#ifdef CONSTRUCT_DEBUGGER
	pDebug->ShowWindow(SW_SHOW);
	pDebug->SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
	pDebug->ModifyStyleEx(0, WS_EX_TOPMOST);
#endif

	// Previewing single layout?
	if (previewLayout > 0)		// if == 0, no need to jump anywhere, already on layout 1
		system.DoFrameChange(previewLayout, "none", 0);

	return true;
}
Exemplo n.º 6
0
	bool Input::init(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
	{
		HRESULT result;

		//store the screen width and height
		m_screenWidth = screenWidth;
		m_screenHeight = screenHeight;

		//init the mouse location
		m_mouseX = 0;
		m_mouseY = 0;

		//init the main direct input interface
		result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, NULL);
		if (FAILED(result))
		{
			return false;
		}

		//init the direct input interface for the keyboard
		result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, NULL);
		if (FAILED(result))
		{
			return false;
		}

		//set the data format, since it is a keyboard use the defualt keyboard format
		result = m_keyboard->SetDataFormat(&c_dfDIKeyboard);
		if (FAILED(result))
		{
			return false;
		}

		//Set the cooperative level of the keyboard to not share with other programs
		result = m_keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
		if (FAILED(result))
		{
			return false;
		}

		//now aquire the keyboard
		result = m_keyboard->Acquire();
		if (FAILED(result))
		{
			return false;
		}

		//init the direct input interface for the mouse
		result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, NULL);
		if (FAILED(result))
		{
			return false;
		}

		//set the data format for th mouse to use
		result = m_mouse->SetDataFormat(&c_dfDIMouse);
		if (FAILED(result))
		{
			return false;
		}

		//Aquire the mouse
		result = m_mouse->Acquire();
		if (FAILED(result))
		{
			return false;
		}

		return true;
	}
Exemplo n.º 7
0
C_RESULT open_dx_gamepad(void)
{
  HRESULT hr;
  HWND hDlg = GetConsoleHwnd();

    // Register with the DirectInput subsystem and get a pointer
    // to a IDirectInput interface we can use.
    // Create a DInput object
  
	if (g_pDI==NULL)
    if( VP_FAILED( hr = DirectInput8Create( GetModuleHandle( NULL ), DIRECTINPUT_VERSION,
                                         IID_IDirectInput8, ( VOID** )&g_pDI, NULL ) ) )
        return hr;


    if( g_bFilterOutXinputDevices )
        SetupForIsXInputDevice();

    DIJOYCONFIG PreferredJoyCfg = {0};
    DI_ENUM_CONTEXT enumContext;
    enumContext.pPreferredJoyCfg = &PreferredJoyCfg;
    enumContext.bPreferredJoyCfgValid = false;

    IDirectInputJoyConfig8* pJoyConfig = NULL;
    if( VP_FAILED( hr = g_pDI->QueryInterface( IID_IDirectInputJoyConfig8, ( void** )&pJoyConfig ) ) )
        return hr;

    PreferredJoyCfg.dwSize = sizeof( PreferredJoyCfg );
    if( SUCCEEDED( pJoyConfig->GetConfig( 0, &PreferredJoyCfg, DIJC_GUIDINSTANCE ) ) ) // This function is expected to fail if no g_pJoystick is attached
        enumContext.bPreferredJoyCfgValid = true;
    SAFE_RELEASE( pJoyConfig );

    // Look for a simple g_pJoystick we can use for this sample program.
    if( VP_FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL,
                                         Enumg_pJoysticksCallback,
                                         &enumContext, DIEDFL_ATTACHEDONLY ) ) )
        return hr;

    if( g_bFilterOutXinputDevices )
        CleanupForIsXInputDevice();

    // Make sure we got a g_pJoystick
    if( g_pJoystick == NULL )
    {
        //MessageBox( NULL, TEXT( "Joystick not found." ),
         //           TEXT( "A.R. Drone"),
           //         MB_ICONERROR | MB_OK );
       // EndDialog( hDlg, 0 );
        return C_FAIL;
    }

    // Set the data format to "simple g_pJoystick" - a predefined data format 
    //
    // A data format specifies which controls on a device we are interested in,
    // and how they should be reported. This tells DInput that we will be
    // passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState().
	if( VP_FAILED( hr = g_pJoystick->SetDataFormat( &c_dfDIJoystick2 ) ) )
        return C_FAIL;

    // Set the cooperative level to let DInput know how this device should
    // interact with the system and with other DInput applications.
	if( VP_FAILED( hr = g_pJoystick->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE |
                                                       DISCL_FOREGROUND ) ) )
        return C_FAIL;

    // Enumerate the g_pJoystick objects. The callback function enabled user
    // interface elements for objects that are found, and sets the min/max
    // values property for discovered axes.
    if( VP_FAILED( hr = g_pJoystick->EnumObjects( EnumObjectsCallback,
                                               ( VOID* )hDlg, DIDFT_ALL ) ) )
        return C_FAIL;

    return C_OK;
}
void CDirectXFramework::Init(HWND& hWnd, HINSTANCE& hInst, bool bWindowed)
{
	m_hWnd = hWnd;
	//////////////////////////////////////////////////////////////////////////
	// Direct3D Foundations - D3D Object, Present Parameters, and D3D Device
	//////////////////////////////////////////////////////////////////////////

	// Create the D3D Object
	m_pD3DObject = Direct3DCreate9(D3D_SDK_VERSION);

	// create the direct input object
	DirectInput8Create(hInst, 
		DIRECTINPUT_VERSION,
		IID_IDirectInput8,
		(void**)&m_pDInputObject, NULL);

	//RECT
	// Find the width and height of window using hWnd and GetWindowRect()
	RECT rect;
	GetWindowRect(hWnd, &rect);
	int screenWidth = rect.right - rect.left;
	int screenHeight = rect.bottom - rect.top;

	// Set D3D Device presentation parameters before creating the device
	D3DPRESENT_PARAMETERS D3Dpp;
	ZeroMemory(&D3Dpp, sizeof(D3Dpp));  // NULL the structure's memory

	D3Dpp.hDeviceWindow					= hWnd;										// Handle to the focus window
	D3Dpp.Windowed						= bWindowed;								// Windowed or Full-screen boolean
	D3Dpp.AutoDepthStencilFormat		= D3DFMT_D24S8;								// Format of depth/stencil buffer, 24 bit depth, 8 bit stencil
	D3Dpp.EnableAutoDepthStencil		= TRUE;										// Enables Z-Buffer (Depth Buffer)
	D3Dpp.BackBufferCount				= 1;										// Change if need of > 1 is required at a later date
	D3Dpp.BackBufferFormat				= D3DFMT_X8R8G8B8;							// Back-buffer format, 8 bits for each pixel
	D3Dpp.BackBufferHeight				= screenHeight  + 424;									// Make sure resolution is supported, use adapter modes
	D3Dpp.BackBufferWidth				= screenWidth + 224;									// (Same as above)
	D3Dpp.SwapEffect					= D3DSWAPEFFECT_DISCARD;					// Discard back-buffer, must stay discard to support multi-sample
	D3Dpp.PresentationInterval			= m_bVsync ? D3DPRESENT_INTERVAL_DEFAULT : D3DPRESENT_INTERVAL_IMMEDIATE; // Present back-buffer immediately, unless V-Sync is on	
	D3Dpp.Flags							= D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;		// This flag should improve performance, if not set to NULL.
	D3Dpp.FullScreen_RefreshRateInHz	= bWindowed ? 0 : D3DPRESENT_RATE_DEFAULT;	// Full-screen refresh rate, use adapter modes or default
	D3Dpp.MultiSampleQuality			= 0;										// MSAA currently off, check documentation for support.
	D3Dpp.MultiSampleType				= D3DMULTISAMPLE_NONE;						// MSAA currently off, check documentation for support.

	// Check device capabilities
	DWORD deviceBehaviorFlags = 0;
	m_pD3DObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_D3DCaps);



	// Determine vertex processing mode
	if(m_D3DCaps.DevCaps & D3DCREATE_HARDWARE_VERTEXPROCESSING)
	{
		// Hardware vertex processing supported? (Video Card)
		deviceBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;	
	}
	else
	{
		// If not, use software (CPU)
		deviceBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; 
	}

	// If hardware vertex processing is on, check pure device support
	if(m_D3DCaps.DevCaps & D3DDEVCAPS_PUREDEVICE && deviceBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING)
	{
		deviceBehaviorFlags |= D3DCREATE_PUREDEVICE;	
	}

	// Create the D3D Device with the present parameters and device flags above
	m_pD3DObject->CreateDevice(
		D3DADAPTER_DEFAULT,		// which adapter to use, set to primary
		D3DDEVTYPE_HAL,			// device type to use, set to hardware rasterization
		hWnd,					// handle to the focus window
		deviceBehaviorFlags,	// behavior flags
		&D3Dpp,					// presentation parameters
		&m_pD3DDevice);			// returned device pointer

	/*************************************
	create the direct input devices here!!
	***************************************/
	m_pDInputObject->CreateDevice(GUID_SysKeyboard, &m_pDIKeyboard, NULL);
	m_pDInputObject->CreateDevice(GUID_SysMouse, &m_pDIMouse, NULL);

	//setting data format
	m_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard);
	m_pDIMouse->SetDataFormat(&c_dfDIMouse2);

	//setting cooperative level
	m_pDIKeyboard->SetCooperativeLevel(m_hWnd,
		DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	m_pDIMouse->SetCooperativeLevel(m_hWnd,
		DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	// end of direct input****************************************************

	// create the SPRITE object
	D3DXCreateSprite(m_pD3DDevice, &m_pD3DSprite);

	// create a TEXTURE object
		D3DXCreateTextureFromFileEx(m_pD3DDevice, L"space.jpg", 0,0,0,0,
		D3DFMT_UNKNOWN,D3DPOOL_MANAGED, D3DX_DEFAULT, 
		D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255),
		&m_imageInfo, 0, &mainMenuTexture);

			D3DXCreateTextureFromFileEx(m_pD3DDevice, L"you win.jpg", 0,0,0,0,
		D3DFMT_UNKNOWN,D3DPOOL_MANAGED, D3DX_DEFAULT, 
		D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255),
		&m_imageInfo, 0, &winScreenTexture);

	// create a FONT object
	AddFontResourceEx(L"Delicious-Roman.otf", FR_PRIVATE, 0);
	D3DXCreateFont(m_pD3DDevice, 30, 0, FW_BOLD, 0, false, 
		DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
		DEFAULT_PITCH | FF_DONTCARE, TEXT("Delicious-Roman"), 
		&m_pD3DFont);

	

	/****************************************************************************
	Projectiles sprites
	****************************************************************************/
	//////////////////////////////////////////////////////////////////////
	//add a if check for game state to render player only during game play
	//////////////////////////////////////////////////////////////////////
	player.projectile.LoadProjectile(m_pD3DDevice);

	/**************************************************************************
	character sprites
	****************************************************************************/
	///////////////////////////////////////////////////////////////////////
	//add a if check for game state to render player only during game play
	//////////////////////////////////////////////////////////////////////
	playerWon = false;
	player.LoadPlayer(m_pD3DDevice);
	enemy.Loadenemy(m_pD3DDevice);
	enemy2.Loadenemy(m_pD3DDevice);
	explosion.LoadExplosion(m_pD3DDevice);
	explosion.LoadExplosionRect();
	explosion2.LoadExplosion(m_pD3DDevice);
	explosion2.LoadExplosionRect();
	/**************************************************************************
	Music and Sound Files
	****************************************************************************/
	// Load bgm
	MenuMusic = new SoundEffect();
	MenuMusic = SoundLoader::GetInstance()->LoadBGM("avenger BGM.mp3");
	AudioManager::GetInstance()->PlayBGM(*MenuMusic);
	enemy.KillCounter = 0;
// random seed for random positions
	srand(time(NULL));
//


};
Exemplo n.º 9
0
HRESULT InitDirectInput2( HWND hDlg )
{
    HRESULT hr;
	   
	DIPROPDWORD dipdw;

    // Setup the g_EffectsList circular linked list
    ZeroMemory( &g_EffectsList, sizeof( EFFECTS_NODE ) );
    g_EffectsList.pNext = &g_EffectsList;

    // Create a DInput object
    if( FAILED( hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI, NULL ) ) )
	{
		ctx->OutputToConsole("PlayFFE :: DirectInput8Create");
	    return hr;
	}

    // Get the first enumerated force feedback device
    if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumFFDevicesCallback2, 0, 
                                         DIEDFL_ATTACHEDONLY | 
                                         DIEDFL_FORCEFEEDBACK ) ) )
	{
		ctx->OutputToConsole("PlayFFE :: EnumDevices failed");		
		return hr;
	}

    
    if( g_pFFDevice == NULL )
    {

	   ctx->OutputToConsole("PlayFFE :: No force feedback device found.");
       return -1;
    }


    // Set the data format
    if( FAILED( hr = g_pFFDevice->SetDataFormat( &c_dfDIJoystick ) ) )
        return hr;


    // Set the coop level
    //hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_FOREGROUND) ;
	hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_BACKGROUND) ;

	

	//DISCL_NONEXCLUSIVE 

	// Since we will be playing force feedback effects, we should disable the
	// auto-centering spring.
	dipdw.diph.dwSize = sizeof( DIPROPDWORD );
	dipdw.diph.dwHeaderSize = sizeof( DIPROPHEADER );
	dipdw.diph.dwObj = 0;
	dipdw.diph.dwHow = DIPH_DEVICE;
	dipdw.dwData = FALSE;

	if( FAILED( hr = g_pFFDevice->SetProperty( DIPROP_AUTOCENTER, &dipdw.diph ) ) )
		return hr;

	// Enumerate and count the axes of the joystick 
	if( FAILED( hr = g_pFFDevice->EnumObjects( EnumAxesCallback,
		( VOID* )&g_dwNumForceFeedbackAxis, DIDFT_AXIS ) ) )
		return hr;


	// This simple sample only supports one or two axis joysticks
	if( g_dwNumForceFeedbackAxis > 2 )
		g_dwNumForceFeedbackAxis = 2;

	// This application needs only one effect: Applying raw forces.
	DWORD rgdwAxes[2] = { DIJOFS_X, DIJOFS_Y };
	LONG rglDirection[2] = { 0,0 };
	DICONSTANTFORCE cf = { 0 };
	cf.lMagnitude = 0;


	DIEFFECT eff;
	ZeroMemory( &eff, sizeof( eff ) );
	eff.dwSize = sizeof( DIEFFECT );
	eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS;
	eff.dwDuration = INFINITE;
	eff.dwSamplePeriod = 0;
	eff.dwGain = DI_FFNOMINALMAX;
	eff.dwTriggerButton = DIEB_NOTRIGGER;
	eff.dwTriggerRepeatInterval = 0;
	eff.cAxes = g_dwNumForceFeedbackAxis;
	eff.rgdwAxes = rgdwAxes;
	eff.rglDirection = rglDirection;
	eff.lpEnvelope = 0;
	eff.cbTypeSpecificParams = sizeof( DICONSTANTFORCE );
	eff.lpvTypeSpecificParams = &cf;
	eff.dwStartDelay = 0;
	
	// Create the prepared effect
	if( FAILED( hr = g_pFFDevice->CreateEffect( GUID_ConstantForce,
		&eff, &g_pEffect, NULL ) ) )
	{
		return hr;
	}

	if( NULL == g_pEffect )
		return E_FAIL;

    return S_OK;
}
Exemplo n.º 10
0
void CDirectXFramework::Init(HWND& hWnd, HINSTANCE& hInst, bool bWindowed)
{
	m_hWnd = hWnd;
	CoInitialize(NULL);
	
	CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, 
                  IID_IGraphBuilder, (void**)&m_pGraphBuilder);

	m_pGraphBuilder->QueryInterface(IID_IMediaControl,
                                (void**)&m_pMediaControl);

	m_pGraphBuilder->QueryInterface(IID_IMediaEvent,
                                (void**)&m_pMediaEvent);

	m_pGraphBuilder->RenderFile(L"intro.wmv", NULL);

	m_pMediaControl->QueryInterface(IID_IVideoWindow,
                                (void**)&m_pVideoWindow);
	// Setup the window
	m_pVideoWindow->put_Owner((OAHWND)m_hWnd);
	// Set the style
	m_pVideoWindow->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE);
	// Obtain the size of the window
	RECT WinRect;
	GetClientRect(m_hWnd, &WinRect);
	// Set the video size to the size of the window
	WinRect.top = 0;
	WinRect.bottom = 600;
	WinRect.left = 0;
	WinRect.right = 800;
	m_pVideoWindow->SetWindowPosition(WinRect.left, WinRect.top, 
										WinRect.right, WinRect.bottom);

	//////////////////////////////////////////////////////////////////////////
	// Direct3D Foundations - D3D Object, Present Parameters, and D3D Device
	//////////////////////////////////////////////////////////////////////////

	// Create the D3D Object
	m_pD3DObject = Direct3DCreate9(D3D_SDK_VERSION);

	// Find the width and height of window using hWnd and GetWindowRect()
	RECT rect;

	GetWindowRect(hWnd, &rect);
	int width = rect.right - rect.left;
	int height = rect.bottom - rect.top;

	// Set D3D Device presentation parameters before creating the device
	D3DPRESENT_PARAMETERS D3Dpp;
	ZeroMemory(&D3Dpp, sizeof(D3Dpp));  // NULL the structure's memory

	D3Dpp.hDeviceWindow					= hWnd;										// Handle to the focus window
	D3Dpp.Windowed						= bWindowed;								// Windowed or Full-screen boolean
	D3Dpp.AutoDepthStencilFormat		= D3DFMT_D24S8;								// Format of depth/stencil buffer, 24 bit depth, 8 bit stencil
	D3Dpp.EnableAutoDepthStencil		= TRUE;										// Enables Z-Buffer (Depth Buffer)
	D3Dpp.BackBufferCount				= 1;										// Change if need of > 1 is required at a later date
	D3Dpp.BackBufferFormat				= D3DFMT_X8R8G8B8;							// Back-buffer format, 8 bits for each pixel
	D3Dpp.BackBufferHeight				= height;									// Make sure resolution is supported, use adapter modes
	D3Dpp.BackBufferWidth				= width;									// (Same as above)
	D3Dpp.SwapEffect					= D3DSWAPEFFECT_DISCARD;					// Discard back-buffer, must stay discard to support multi-sample
	D3Dpp.PresentationInterval			= m_bVsync ? D3DPRESENT_INTERVAL_DEFAULT : D3DPRESENT_INTERVAL_IMMEDIATE; // Present back-buffer immediately, unless V-Sync is on								
	D3Dpp.Flags							= D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;		// This flag should improve performance, if not set to NULL.
	D3Dpp.FullScreen_RefreshRateInHz	= bWindowed ? 0 : D3DPRESENT_RATE_DEFAULT;	// Full-screen refresh rate, use adapter modes or default
	D3Dpp.MultiSampleQuality			= 0;										// MSAA currently off, check documentation for support.
	D3Dpp.MultiSampleType				= D3DMULTISAMPLE_NONE;						// MSAA currently off, check documentation for support.

	// Check device capabilities
	DWORD deviceBehaviorFlags = 0;
	m_pD3DObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_D3DCaps);

	// Determine vertex processing mode
	if(m_D3DCaps.DevCaps & D3DCREATE_HARDWARE_VERTEXPROCESSING)
	{
		// Hardware vertex processing supported? (Video Card)
		deviceBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;	
	}
	else
	{
		// If not, use software (CPU)
		deviceBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; 
	}
	
	// If hardware vertex processing is on, check pure device support
	if(m_D3DCaps.DevCaps & D3DDEVCAPS_PUREDEVICE && deviceBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING)
	{
		deviceBehaviorFlags |= D3DCREATE_PUREDEVICE;	
	}
	
	// Create the D3D Device with the present parameters and device flags above
	m_pD3DObject->CreateDevice(
		D3DADAPTER_DEFAULT,		// which adapter to use, set to primary
		D3DDEVTYPE_HAL,			// device type to use, set to hardware rasterization
		hWnd,					// handle to the focus window
		deviceBehaviorFlags,	// behavior flags
		&D3Dpp,					// presentation parameters
		&m_pD3DDevice);			// returned device pointer

	//*************************************************************************

	//////////////////////////////////////////////////////////////////////////
	// Create a Font Object
	//////////////////////////////////////////////////////////////////////////
	
	// Load a font for private use for this process

	// Load D3DXFont, each font style you want to support will need an ID3DXFont
	D3DXCreateFont(m_pD3DDevice, 30, 0, FW_BOLD, 0, false, 
                  DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
                  DEFAULT_PITCH | FF_DONTCARE, TEXT("Times New Roman"), 
                  &m_pD3DFont);

	

	//////////////////////////////////////////////////////////////////////////
	// Create Sprite Object and Textures
	//////////////////////////////////////////////////////////////////////////
	// Create a sprite object, note you will only need one for all 2D sprites

	D3DXCreateSprite(m_pD3DDevice, &m_pD3DSprite);
	D3DXCreateSprite(m_pD3DDevice, &m_Ball);
	D3DXCreateSprite(m_pD3DDevice, &m_Wall);

	// Create a texture, each different 2D sprite to display to the screen
	// will need a new texture object.  If drawing the same sprite texture
	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"Paddle.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
                  &m_imageInfo, 0, &m_pTexture);

	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"Ball.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
				  &m_ballImage, 0, &m_ballTexture);

	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"wall.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
				  &m_wallImage, 0, &m_wallTexture);

	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"START.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
				  &m_StartImage, 0, &m_StartText);

	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"CREDITS.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
				  &m_CreditImage, 0, &m_CreditText);
	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"CREDIT2.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
				  &m_Credit2Image, 0, &m_Credit2Text);
	D3DXCreateTextureFromFileEx(m_pD3DDevice, L"EXIT.tga", 0, 0, 0, 0,
                  D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, 
                  D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), 
				  &m_ExitImage, 0, &m_ExitText);

	// multiple times, just call that sprite's Draw() with different 
	// transformation values.


	//Paddle 1
	Paddle[0].xp = -12;
	Paddle[0].yp = 300;

	//Paddle 2
	Paddle[1].xp = 800;
	Paddle[1].yp = 300;

	//Ball
	Ball.xp = 400;
	Ball.yp = 300;

	//	Wall / Background
	Wall.xp = 400;
	Wall.yp = 300;

	//	Menu
	Menu.xp = 200;
	Menu.yp = 200;
	



	//Initial Direction
	Ball.DIR_UP_RIGHT = true;

	//MENU
	Menu.onGAME = false;
	Menu.onSTART = true;
	

	//*************************************************************************

	// create direct input object
	DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8,(void **)&m_pDIObject, NULL);

	// Create Keyboard
	m_pDIObject->CreateDevice(GUID_SysKeyboard, &m_pDIKeyboard, NULL);

	//Set Keyboard data format
	m_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard); 

	//Set Keyboard coop level
	m_pDIKeyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); 

	// Create Mouse
	m_pDIObject->CreateDevice(GUID_SysMouse, &m_pDIMouse, NULL);

	// Set Mouse Data Format
	m_pDIMouse->SetDataFormat(&c_dfDIMouse2);

	// Set Mouse Coop Level
	m_pDIMouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);


	//SOUND INITIALIZATION
	channel = 0;
	result = FMOD::System_Create(&system);
	
	result = system->init(100, FMOD_INIT_NORMAL, 0); // initialize fmod

	result = system->createSound("beep1.ogg", FMOD_DEFAULT, 0, &mySound1);
	result = system->createSound("beep2.ogg", FMOD_DEFAULT, 0, &mySound2);
	result = system->createSound("pongMusic.wav", FMOD_LOOP_NORMAL | FMOD_2D, 0, &myStream);


//BACKGROUND MUSIC---------------------------------------------
		result = system->playSound(myStream, 0, true, &channel);
		result = channel->setVolume(0.5f);
		result = channel->setPaused(false);
//-------------------------------------------------------------
}
Exemplo n.º 11
0
	bool InputWrapper::Init(HINSTANCE hinstance, HWND hwnd)
	{
		if (myIsInitialized == false)
		{
			myIsInitialized = true;
			HRESULT result;

			// Initialize the main direct input interface.
			result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&myDirectInputInterface, NULL);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Initialize the direct input interface for the keyboard.
			result = myDirectInputInterface->CreateDevice(GUID_SysKeyboard, &myKeyboard, NULL);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Set the data format.  In this case since it is a keyboard we can use the predefined data format.
			result = myKeyboard->SetDataFormat(&c_dfDIKeyboard);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Set the cooperative level of the keyboard to not share with other programs.
			result = myKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Now acquire the keyboard.
			result = myKeyboard->Acquire();
			if (FAILED(result) == true)
			{
				return false;
			}

			// Initialize the direct input interface for the mouse.
			result = myDirectInputInterface->CreateDevice(GUID_SysMouse, &myMouse, NULL);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Set the data format for the mouse using the pre-defined mouse data format.
			result = myMouse->SetDataFormat(&c_dfDIMouse);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Set the cooperative level of the mouse to share with other programs.
			result = myMouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
			if (FAILED(result) == true)
			{
				return false;
			}

			// Acquire the mouse.
			result = myMouse->Acquire();
			if (FAILED(result) == true)
			{
				return false;
			}
		}
		return true;
	}
Exemplo n.º 12
0
	//********************************************************************************************************************************************
	//		初期化
	//********************************************************************************************************************************************
	bool	InputManager::Initialize( void )
	{
		HRESULT	hResult	=	S_OK;

		//	DirectInputインターフェイスを取得
		hResult	=	DirectInput8Create( GetModuleHandle( NULL ), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pInput, NULL );

		//	マウスデバイスの初期化
		if( SUCCEEDED( hResult ) ){
			//	デバイスを作成
			hResult	=	m_pInput->CreateDevice( GUID_SysMouse, &m_pMouse, NULL );

			//	データ形式を設定
			if( SUCCEEDED( hResult ) ){
				hResult	=	m_pMouse->SetDataFormat( &c_dfDIMouse2 );
			}

			//	強調レベルの設定
			if( SUCCEEDED( hResult ) ){
				//	非排他
				hResult	=	m_pMouse->SetCooperativeLevel( iexSystem::Window, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND );
				//	排他
				//hResult	=	m_pMouse->SetCooperativeLevel( iexSystem::Window, DISCL_EXCLUSIVE | DISCL_FOREGROUND );
			}

			//	バッファサイズの設定
			if( SUCCEEDED( hResult ) ){
				DIPROPDWORD	dipdw;
				//	ヘッダー
				dipdw.diph.dwSize		=	sizeof( DIPROPDWORD );
				dipdw.diph.dwHeaderSize	=	sizeof( DIPROPHEADER );
				dipdw.diph.dwObj		=	0;
				dipdw.diph.dwHow		=	DIPH_DEVICE;
				//	データ
				dipdw.dwData			=	sizeof( DIMOUSESTATE2 );

				//	セット
				hResult	=	m_pMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph );
			}
		}

		//	キーボードデバイスの初期化
		if( SUCCEEDED( hResult ) ){
			//	デバイスを作成
			hResult	=	m_pInput->CreateDevice( GUID_SysKeyboard, &m_pKeyBoard, NULL );

			//	データ形式を設定
			if( SUCCEEDED( hResult ) ){
				hResult	=	m_pKeyBoard->SetDataFormat( &c_dfDIKeyboard ); 
			}

			//	強調レベルの設定
			if( SUCCEEDED( hResult ) ){
				hResult	=	m_pKeyBoard->SetCooperativeLevel( iexSystem::Window, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND );
			}
		}

		//	結果を返す
		if( SUCCEEDED( hResult ) )	return	true;
		else						return	false;
	}
void PsychHIDInitializeHIDStandardInterfaces(void)
{
    int i;
    HRESULT rc;
    HINSTANCE modulehandle = NULL;
    dinput = NULL;
    ndevices = 0;

    // Init x_dev array:
    for (i = 0; i < PSYCH_HID_MAX_DEVICES; i++) x_dev[i] = NULL;

    // Init keyboard queue arrays:
    memset(&psychHIDKbQueueFirstPress[0], 0, sizeof(psychHIDKbQueueFirstPress));
    memset(&psychHIDKbQueueFirstRelease[0], 0, sizeof(psychHIDKbQueueFirstRelease));
    memset(&psychHIDKbQueueLastPress[0], 0, sizeof(psychHIDKbQueueLastPress));
    memset(&psychHIDKbQueueLastRelease[0], 0, sizeof(psychHIDKbQueueLastRelease));
    memset(&psychHIDKbQueueActive[0], 0, sizeof(psychHIDKbQueueActive));
    memset(&psychHIDKbQueueScanKeys[0], 0, sizeof(psychHIDKbQueueScanKeys));

    // We need the module instance handle of ourselves, ie., the PsychHID mex file to
    // open a DirectInput-8 interface, so the OS can apply backwards compatibility fixes
    // specific to the way our mex file DLL was built. For this we need the name of the
    // mex file, which is dependent on Octave vs. Matlab and 32-Bit vs. 64-Bit:
#ifndef PTBOCTAVE3MEX
    // Matlab: 64-Bit or 32-Bit mex file?
#if defined(__LP64__) || defined(_M_IA64) || defined(_WIN64)
    // 64-Bit:
    modulehandle = GetModuleHandle("PsychHID.mexw64");
#else
    // 32-Bit:
    modulehandle = GetModuleHandle("PsychHID.mexw32");
#endif
#else
    // Octave: Same mex file file-extension for 32/64-Bit:
    modulehandle = GetModuleHandle("PsychHID.mex");
#endif

    // If this doesn't work, try with application module handle as fallback. This works usually on
    // Windows XP/Vista/7, but may fail catastrophically on Windows-8 and later:
    if (NULL == modulehandle) {
        printf("PsychHID-WARNING: Could not get module handle to PsychHID mex file. Did you rename it? Please don't do that!\n");
        printf("PsychHID-WARNING: Will try application module handle as fallback. This may end badly, e.g., with a crash. Cross your fingers!\n");
        modulehandle = GetModuleHandle(NULL);
    }

    if (NULL == modulehandle) PsychErrorExitMsg(PsychError_system, "PsychHID: FATAL ERROR: Couldn't get module handle to create interface to Microsoft DirectInput-8! Game over!");

    // Open a DirectInput-8 interface:
    rc = DirectInput8Create(modulehandle, DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&dinput, NULL);

    if (DI_OK != rc) {
        printf("PsychHID-ERROR: Error return from DirectInput8Create: %x\n", (int) rc);
        if (rc == DIERR_OLDDIRECTINPUTVERSION) printf("PsychHID-ERROR: You need to install a more recent version of DirectX -- at least DirectX-8.\n");
        PsychErrorExitMsg(PsychError_system, "PsychHID: FATAL ERROR: Couldn't create interface to Microsoft DirectInput-8! Game over!");
    }

    // Enumerate all DirectInput keyboard(-like) devices:
    rc = dinput->EnumDevices(DI8DEVCLASS_KEYBOARD, (LPDIENUMDEVICESCALLBACK) keyboardEnumCallback, NULL, DIEDFL_ATTACHEDONLY | DIEDFL_INCLUDEHIDDEN);
    if (DI_OK != rc) {
        printf("PsychHID-ERROR: Error return from DirectInput8 EnumDevices(): %x! Game over!\n", (int) rc);
        goto out;
    }

    // Enumerate all DirectInput mouse(-like) devices:
    rc = dinput->EnumDevices(DI8DEVCLASS_POINTER, (LPDIENUMDEVICESCALLBACK) keyboardEnumCallback, NULL, DIEDFL_ATTACHEDONLY | DIEDFL_INCLUDEHIDDEN);
    if (DI_OK != rc) {
        printf("PsychHID-ERROR: Error return from DirectInput8 EnumDevices(): %x! Game over!\n", (int) rc);
        goto out;
    }

    // Enumerate all DirectInput joystick/gamepad(-like) devices:
    rc = dinput->EnumDevices(DI8DEVCLASS_GAMECTRL, (LPDIENUMDEVICESCALLBACK) keyboardEnumCallback, NULL, DIEDFL_ATTACHEDONLY | DIEDFL_INCLUDEHIDDEN);
    if (DI_OK != rc) {
        printf("PsychHID-ERROR: Error return from DirectInput8 EnumDevices(): %x! Game over!\n", (int) rc);
        goto out;
    }

    // Create keyboard queue mutex for later use:
    KbQueueThreadTerminate = FALSE;
    PsychInitMutex(&KbQueueMutex);
    PsychInitCondition(&KbQueueCondition, NULL);

    // Create event object for signalling device state changes:
    hEvent = CreateEvent(   NULL,	// default security attributes
                            FALSE,	// auto-reset event: This would need to be set TRUE for PsychBroadcastCondition() to work on Windows!
                            FALSE,	// initial state is nonsignaled
                            NULL	// no object name
                        );

    // Ready.
    return;

out:
    ndevices = 0;

    // Close our dedicated x-display connection and we are done:
    if (dinput) dinput->Release();
    dinput = NULL;

    PsychErrorExitMsg(PsychError_system, "PsychHID: FATAL ERROR: X Input extension version 2.0 or later not available! Game over!");
}
Exemplo n.º 14
0
qboolean IN_InitDInput(void)
{
	HRESULT         hResult;
	DIPROPDWORD     dipdw = {
		{
		 sizeof(DIPROPDWORD),	// diph.dwSize
		 sizeof(DIPROPHEADER),	// diph.dwHeaderSize
		 0,						// diph.dwObj
		 DIPH_DEVICE,			// diph.dwHow
		 }
		,
		DINPUT_BUFFERSIZE,		// dwData
	};

#ifdef __GNUC__
	hResult = DirectInputCreate(g_wv.hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
#else
	hResult = DirectInput8Create(g_wv.hInstance, DIRECTINPUT_VERSION, &IID_IDirectInput8A, &g_pdi, NULL);
#endif

	if(FAILED(hResult))
	{
#ifdef __GNUC__
		Com_Printf("DirectInput8Create failed\n");
#else
		Com_Printf("DirectInput8Create failed\n");
#endif
		return qfalse;
	}

	// obtain an interface to the system mouse device.
	hResult = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);

	if(FAILED(hResult))
	{
		Com_Printf("Couldn't open DI mouse device\n");
		return qfalse;
	}

	// set the data format to "mouse format".
	hResult = IDirectInputDevice_SetDataFormat(g_pMouse, &df);

	if(FAILED(hResult))
	{
		Com_Printf("Couldn't set DI mouse format\n");
		return qfalse;
	}

	// set the DirectInput cooperativity level.
	hResult = IDirectInputDevice_SetCooperativeLevel(g_pMouse, g_wv.hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND);

	if(FAILED(hResult))
	{
		Com_Printf("Couldn't set DI coop level\n");
		return qfalse;
	}


	// set the buffer size to DINPUT_BUFFERSIZE elements.
	// the buffer size is a DWORD property associated with the device
	hResult = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);

	if(FAILED(hResult))
	{
		Com_Printf("Couldn't set DI buffersize\n");
		return qfalse;
	}

	return qtrue;
}
Exemplo n.º 15
0
int Game_Init(void *parms,  int num_parms)
{
// this function is where you do all the initialization 
// for your game

int index;         // looping var
char filename[80]; // used to build up files names

// initialize directdraw
DDraw_Init(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP);


#if 0 // directinput7 method

// first create the direct input object
if (DirectInputCreateEx(main_instance,DIRECTINPUT_VERSION,IID_IDirectInput7, (void **)&lpdi,NULL)!=DI_OK)
   return(0);

// create a keyboard device  //////////////////////////////////
if (lpdi->CreateDeviceEx(GUID_SysKeyboard, IID_IDirectInputDevice7, (void **)&lpdikey, NULL)!=DI_OK)
   return(0);

#endif


// first create the direct input object
if (DirectInput8Create(main_instance,DIRECTINPUT_VERSION,IID_IDirectInput8, (void **)&lpdi,NULL)!=DI_OK)
   return(0);

// create a keyboard device  //////////////////////////////////
if (lpdi->CreateDevice(GUID_SysKeyboard, &lpdikey, NULL)!=DI_OK)
   return(0);


// set cooperation level
if (lpdikey->SetCooperativeLevel(main_window_handle, 
                 DISCL_NONEXCLUSIVE | DISCL_BACKGROUND)!=DI_OK)
    return(0);

// set data format
if (lpdikey->SetDataFormat(&c_dfDIKeyboard)!=DI_OK)
   return(0);

// acquire the keyboard
if (lpdikey->Acquire()!=DI_OK)
   return(0);

///////////////////////////////////////////////////////////

// load the background
Load_Bitmap_File(&bitmap8bit, "REACTOR.BMP");

// set the palette to background image palette
Set_Palette(bitmap8bit.palette);

// create and load the reactor bitmap image
Create_Bitmap(&reactor, 0,0, 640, 480);
Load_Image_Bitmap(&reactor,&bitmap8bit,0,0,BITMAP_EXTRACT_MODE_ABS);
Unload_Bitmap_File(&bitmap8bit);

// now let's load in all the frames for the skelaton!!!

// create skelaton bob
if (!Create_BOB(&skelaton,0,0,56,72,32,
           BOB_ATTR_VISIBLE | BOB_ATTR_MULTI_ANIM,DDSCAPS_SYSTEMMEMORY))
   return(0);

// load the frames in 8 directions, 4 frames each
// each set of frames has a walk and a fire, frame sets
// are loaded in counter clockwise order looking down
// from a birds eys view or the x-z plane
for (int direction = 0; direction < 8; direction++)
    { 
    // build up file name
    sprintf(filename,"SKELSP%d.BMP",direction);

    // load in new bitmap file
    Load_Bitmap_File(&bitmap8bit,filename);
 
    Load_Frame_BOB(&skelaton,&bitmap8bit,0+direction*4,0,0,BITMAP_EXTRACT_MODE_CELL);  
    Load_Frame_BOB(&skelaton,&bitmap8bit,1+direction*4,1,0,BITMAP_EXTRACT_MODE_CELL);  
    Load_Frame_BOB(&skelaton,&bitmap8bit,2+direction*4,2,0,BITMAP_EXTRACT_MODE_CELL);  
    Load_Frame_BOB(&skelaton,&bitmap8bit,3+direction*4,0,1,BITMAP_EXTRACT_MODE_CELL);  

    // unload the bitmap file
    Unload_Bitmap_File(&bitmap8bit);

    // set the animation sequences for skelaton
    Load_Animation_BOB(&skelaton,direction,4,skelaton_anims[direction]);

    } // end for direction

// set up stating state of skelaton
Set_Animation_BOB(&skelaton, 0);
Set_Anim_Speed_BOB(&skelaton, 4);
Set_Vel_BOB(&skelaton, 0,0);
Set_Pos_BOB(&skelaton, 0, 128);

// set clipping rectangle to screen extents so mouse cursor
// doens't mess up at edges
RECT screen_rect = {0,0,screen_width,screen_height};
lpddclipper = DDraw_Attach_Clipper(lpddsback,1,&screen_rect);

// hide the mouse
ShowCursor(FALSE);

// return success
return(1);

} // end Game_Init
Exemplo n.º 16
0
bool InputClass::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
{
	HRESULT result;

	//Store the screen size which will be used for positioning the mouse cursor
	m_screenHeight = screenWidth;
	m_screenHeight = screenHeight;

	//initialize the mouse
	m_mouseX = 0;
	m_mouseY = 0;

	//initialize the directInput
	result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, NULL);
	if (FAILED(result))
	{
		return false;
	}

	//first initialize the keyboard
	result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, NULL);
	if (FAILED(result))
	{
		return false;
	}

	//Set the data format using the predifined format
	result = m_keyboard->SetDataFormat(&c_dfDIKeyboard);
	if (FAILED(result))
	{
		return false;
	}

	//set the keyboard to non-exclusive
	result = m_keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	if (FAILED(result))
	{
		return false;
	}

	//Aquire the keyboard
	result = m_keyboard->Acquire();
	if (FAILED(result))
	{
		return false;
	}

	//Init the mouse input
	result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, NULL);
	if (FAILED(result))
	{
		return false;
	}

	//set the data format for the mouse
	result = m_mouse->SetDataFormat(&c_dfDIMouse);
	if (FAILED(result))
	{
		return false;
	}

	//set the cooperative level of the mouse
	result = m_mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	if (FAILED(result))
	{
		return false;
	}

	//Acquire the mouse
	result = m_mouse->Acquire();
	if (FAILED(result))
	{
		return false;
	}

	return true;

}
void FTNoIR_Tracker::StartTracker(QFrame* frame)
{
    QMutexLocker foo(&mtx);
    this->frame = frame;
    iter = 0;
    auto hr = CoInitialize( nullptr );

    if( FAILED( hr = DirectInput8Create( GetModuleHandle( NULL ), DIRECTINPUT_VERSION,
                                         IID_IDirectInput8, ( VOID** )&g_pDI, NULL ) ) )
    {
        qDebug() << "create";
        goto fail;
    }
	
	if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL,
                                         EnumJoysticksCallback,
                                         this,
                                         DIEDFL_ATTACHEDONLY)))
    {
        qDebug() << "enum2";
        goto fail;
    }

    if (!g_pJoystick)
    {
        qDebug() << "ENODEV";
        goto fail;
    }

    if (FAILED(g_pJoystick->SetDataFormat(&c_dfDIJoystick)))
    {
        qDebug() << "format";
        goto fail;
    }

    if (FAILED(g_pJoystick->SetCooperativeLevel((HWND) frame->window()->winId(), DISCL_NONEXCLUSIVE | DISCL_BACKGROUND)))
    {
        qDebug() << "coop";
        goto fail;
    }

    iter = 0;

    if( FAILED( hr = g_pJoystick->EnumObjects( EnumObjectsCallback,
                                               ( VOID* )this, DIDFT_ALL )))
    {
        qDebug() << "enum axes";
        goto fail;
    }

    qDebug() << "joy init success";

    return;

fail:
    if (g_pJoystick)
        g_pJoystick->Release();
    if (g_pDI)
        g_pDI->Release();
    g_pJoystick = nullptr;
    g_pDI = nullptr;

    qDebug() << "joy init failure";
}
Exemplo n.º 18
0
    HRESULT InitDirectInput(unsigned int joystick_index)
    {
        HRESULT hr;

        state.is_initialized = false;

        // Register with the DirectInput subsystem and get a pointer
        // to a IDirectInput interface we can use.
        // Create a DInput object
        if (FAILED(hr = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION,
            IID_IDirectInput8, (VOID**)&g_pDI, nullptr)))
            return hr;


        if (g_bFilterOutXinputDevices)
            SetupForIsXInputDevice();

        enumContext.pPreferredJoyCfg = &PreferredJoyCfg;
        enumContext.bPreferredJoyCfgValid = false;

        IDirectInputJoyConfig8* pJoyConfig = nullptr;
        if (FAILED(hr = g_pDI->QueryInterface(IID_IDirectInputJoyConfig8, (void**)&pJoyConfig))) {
            state.message = "QueryInterface on IID_IDirectInputJoyConfig8 failed";
            return hr;
        }

        PreferredJoyCfg.dwSize = sizeof(PreferredJoyCfg);
        if (SUCCEEDED(pJoyConfig->GetConfig(joystick_index, &PreferredJoyCfg, DIJC_GUIDINSTANCE))) { // This function is expected to fail if no joystick is attached
            enumContext.bPreferredJoyCfgValid = true;

            joystick_info.is_valid = true;
            joystick_info.instance_guide = toDIGUID(PreferredJoyCfg.guidInstance);
            joystick_info.pid_vid = toString(PreferredJoyCfg.wszType);
        }
        DIJT_SAFE_RELEASE(pJoyConfig);

        // Look for a simple joystick we can use for this sample program.
        if (FAILED(hr = g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL,
            DirectInputJoyStick::impl::EnumJoysticksCallback,
            this, DIEDFL_ATTACHEDONLY))) {

            state.message = "EnumDevices failed";
            return hr;
        }

        if (g_bFilterOutXinputDevices)
            CleanupForIsXInputDevice();

        // Make sure we got a joystick
        if (!g_pJoystick)
        {
            state.message = "Joystick at index " + std::to_string(joystick_index) + " is not available";
            return S_FALSE;
        }

        // Set the data format to "simple joystick" - a predefined data format 
        //
        // A data format specifies which controls on a device we are interested in,
        // and how they should be reported. This tells DInput that we will be
        // passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState().
        if (FAILED(hr = g_pJoystick->SetDataFormat(&c_dfDIJoystick2)))
        {
            state.message = "Device does not support DIJOYSTATE2";
            return hr;
        }

        // Set the cooperative level to let DInput know how this device should
        // interact with the system and with other DInput applications.
        if (FAILED(hr = g_pJoystick->SetCooperativeLevel(NULL, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))) {

            state.message = "SetCooperativeLevel failed";
            return hr;
        }

        // Enumerate the joystick objects. The callback function enabled user
        // interface elements for objects that are found, and sets the min/max
        // values property for discovered axes.
        if (FAILED(hr = g_pJoystick->EnumObjects(DirectInputJoyStick::impl::EnumObjectsCallback,
            (VOID*) this, DIDFT_ALL))) {

            state.message = "EnumObjects failed";
            return hr;
        }

        InitForceFeedback();

        state.is_initialized = true;
        return S_OK;
    }
Exemplo n.º 19
0
void AppState::initInputDevices() {
    //创建DirectInput8对象
    IDirectInput8A* direct_input;
    dx::throwIfFailed(
        DirectInput8Create(
            hInstance_,
            DIRECTINPUT_VERSION,
            IID_IDirectInput8,
            (void **) &direct_input,
            nullptr)
    );
    direct_input_.reset(direct_input);


    //创建DirectInput8设备(键盘)
    IDirectInputDevice8A* keyboard_device;
    dx::throwIfFailed(
        direct_input_->CreateDevice(GUID_SysKeyboard, &keyboard_device, nullptr)
    );
    keyboard_device_.reset(keyboard_device);


    //为键盘设置格式
    dx::throwIfFailed(
        keyboard_device_->SetDataFormat(&c_dfDIKeyboard)
    );


    //为键盘设置行为
    dx::throwIfFailed(
        keyboard_device_->SetCooperativeLevel(windowHwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)
    );

    //为键盘设置缓冲方式
    DIPROPDWORD dipdw;
    dipdw.diph.dwSize = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj = 0;
    dipdw.diph.dwHow = DIPH_DEVICE;
    dipdw.dwData = kKeyInputBufferSize; // Arbitary buffer size

    dx::throwIfFailed(
        keyboard_device_->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph)
    );

    //创建事件,为自动型(使用完自动置为无信号状态),初始化为无信号状态
    HANDLE handle = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (!handle) {
        throw std::runtime_error("CreateEvent keyboard error!");
    }

    //为键盘安装事件通知关联,并准备获取采集
    keyboard_device_->SetEventNotification(handle);
    keyboard_device_->Acquire();

    //添加等待对象,以及触发事件
    addEventHandle(handle, std::bind(&AppState::updateKeyInputState, this));

    //创建DirectInput8设备(鼠标)
    IDirectInputDevice8A* mouse_device;
    dx::throwIfFailed(
        direct_input_->CreateDevice(GUID_SysMouse, &mouse_device, NULL)
    );
    mouse_device_.reset(mouse_device);


    //为鼠标设置格式(8按键鼠标)
    dx::throwIfFailed(
        mouse_device_->SetDataFormat(&c_dfDIMouse2)
    );


    //为鼠标设置行为
    dx::throwIfFailed(
        mouse_device_->SetCooperativeLevel(windowHwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)
    );


    //鼠标设置缓冲方式
    dipdw.diph.dwSize = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj = 0;
    dipdw.diph.dwHow = DIPH_DEVICE;
    dipdw.dwData = kMouseInputBufferSize;

    dx::throwIfFailed(
        mouse_device_->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph)
    );

    handle = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (!handle) {
        throw std::runtime_error("CreateEvent mouse error!");
    }

    mouse_device_->SetEventNotification(handle);
    mouse_device_->Acquire();

    addEventHandle(handle, std::bind(&AppState::updateMouseInputState, this));

    /*
     _pD3D = Direct3DCreate9(D3D_SDK_VERSION);
     if(_pD3D == nullptr)
     {
     BOOST_THROW_EXCEPTION(std::runtime_error("Direct3DCreate9 error!"));
     }

     D3DPRESENT_PARAMETERS d3dpp;
     ZeroMemory( &d3dpp, sizeof( d3dpp ) );
     d3dpp.Windowed = TRUE; //不是全屏
     d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
     d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

     hr = _pD3D->CreateDevice(
     D3DADAPTER_DEFAULT,
     D3DDEVTYPE_HAL,
     WindowHwnd,
     D3DCREATE_SOFTWARE_VERTEXPROCESSING,
     &d3dpp,
     &_pd3dDevice);

     if (FAILED(hr)) {
     BOOST_THROW_EXCEPTION(std::runtime_error("CreateDevice IDirect3DDevice9 error!"));
     }

     IDirect3DSurface8* lpDSCursor;
     hr = _pd3dDevice->CreateImageSurface(32, 32, D3DFMT_A8R8G8B8,&lpDSCursor);
     */

}
Exemplo n.º 20
0
void DXInput::Initialize(HWND hWindow)
{
	// Check if we have already initialized the system
	if (mInitialized)
	{
		// Write to log
		Log::Get()->Write(LogType::Warning, "[Input] System already initialized.");
		return;
	}

	// Write to log
	Log::Get()->Write(LogType::Message, "[Input] Initializing...");

	// Obtain an interface to DirectInput
	if (FAILED(DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&mpDI, nullptr)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to create DirectInput object.");
		return;
	}

	//----------------------------------------------------------------------------------------------------
	// Create keyboard device
	if (FAILED(mpDI->CreateDevice(GUID_SysKeyboard, &mpKeyboard, nullptr)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to create keyboard device.");
		return;
	}

	// Set the keyboard data format
	if (FAILED(mpKeyboard->SetDataFormat(&c_dfDIKeyboard)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to set keyboard data format.");
		return;
	}

	// Set the keyboard cooperative level
	if (FAILED(mpKeyboard->SetCooperativeLevel(hWindow, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE | DISCL_NOWINKEY)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to set keyboard cooperative level.");
		return;
	}

	// Acquire the keyboard device
	if (FAILED(mpKeyboard->Acquire()))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to acquire keyboard device.");
	}
	//----------------------------------------------------------------------------------------------------

	//----------------------------------------------------------------------------------------------------
	// Create mouse device
	if (FAILED(mpDI->CreateDevice(GUID_SysMouse, &mpMouse, nullptr)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to create mouse device.");
		return;
	}

	// Set the mouse data format
	if (FAILED(mpMouse->SetDataFormat(&c_dfDIMouse)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to set mouse data format.");
		return;
	}

	// Set the mouse cooperative level
	if (FAILED(mpMouse->SetCooperativeLevel(hWindow, DISCL_FOREGROUND | DISCL_EXCLUSIVE)))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to set mouse cooperative level.");
		return;
	}

	// Acquire the mouse device
	if (FAILED(mpMouse->Acquire()))
	{
		// Write to log
		Log::Get()->Write(LogType::Error, "[Input] Failed to acquire mouse device.");
	}

	// Calculate starting mouse position
	RECT clientRect;
	GetClientRect(hWindow, &clientRect);
	GetWindowRect(hWindow, &clientRect);
	mScreenWidth = clientRect.right - clientRect.left;
	mScreenHeight = clientRect.bottom - clientRect.top;
	mMouseX = mScreenWidth>> 1;
	mMouseY = mScreenHeight>> 1;
	//----------------------------------------------------------------------------------------------------

	//----------------------------------------------------------------------------------------------------
	// Enumerate for game pad device
	if (FAILED(mpDI->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumGamePadCallback, nullptr, DIEDFL_ATTACHEDONLY)))
	{
		// Write to log
		Log::Get()->Write(LogType::Warning, "[Input] Failed to enumerate for game pad devices.");
	}

	// Check if we have a game pad detected
	if (nullptr != mpGamePad)
	{
		// Set the game pad data format
		if (FAILED(mpGamePad->SetDataFormat(&c_dfDIJoystick)))
		{
			// Write to log
			Log::Get()->Write(LogType::Error, "[Input] Failed to set game pad data format.");
			return;
		}

		// Set the game pad cooperative level
		if (FAILED(mpGamePad->SetCooperativeLevel(hWindow, DISCL_FOREGROUND | DISCL_EXCLUSIVE)))
		{
			// Write to log
			Log::Get()->Write(LogType::Error, "[Input] Failed to set game pad cooperative level.");
			return;
		}

		// Acquire the game pad device
		if (FAILED(mpGamePad->Acquire()))
		{
			// Write to log
			Log::Get()->Write(LogType::Error, "[Input] Failed to acquire game pad device.");
		}
	}
	else
	{
		// Write to log
		Log::Get()->Write(LogType::Warning, "[Input] No game pad attached.");
	}

	// Set flag
	mInitialized = true;

	// Write to log
	Log::Get()->Write(LogType::Message, "[Input] System initialized.");
}
Exemplo n.º 21
0
	//************************************************
	//*主程序
	//************************************************
	int APIENTRY t1::_tWinMain(HINSTANCE &hInstance,
		HINSTANCE &hPrevInstance,
		LPTSTR    &lpCmdLine,
		int       &nCmdShow, HWND &_hWnd,
		std::string winClassName, std::string winName)
	{
		
		
		// 初始化句柄和状态
		bool bUnClosedLastWin = true;
		hWnd = _hWnd;
		gHinstance = hInstance;
		ShowCursor(FALSE);
		//g_nThreadExitCount = 0;

		//获得传递的命令行参数,得到被试着名字和任务编号
		char *pdest;
		int result;
		int pos1;
		pdest = strrchr(lpCmdLine, ' ');
		pos1 = pdest - lpCmdLine;
		if (pos1>0)
		{
			strncpy(m_TaskNumStr, lpCmdLine, pos1);
		}
		else
		{
			strcpy(m_TaskNumStr, "");
		}
		pdest = strrchr(lpCmdLine, '-');
		result = pdest - lpCmdLine;
		if (result>0)
		{
			strncpy(m_TesterName, lpCmdLine + pos1 + 1, result - pos1 - 1);
		}
		else
		{
			strcpy(m_TesterName, "");
		}
		if (pos1>0)
		{
			strcpy(m_DataName, lpCmdLine + pos1 + 1);
		}
		else
		{
			strcpy(m_DataName, "");
		}
		//读取任务设置
		if (!ReadSetting())
		{
			MessageBox(hWnd, "任务设置文件格式错误!", "测试任务", MB_OK);
			return 0;
		}

		 
		//注册窗口类
		WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS, MsgProc, 0L, 0L,
			hInstance, NULL, NULL, NULL, NULL,
			std::to_string(nCmdShow).c_str(), NULL };
		RegisterClassEx(&wc);

		x_resolution = GetSystemMetrics(SM_CXSCREEN);
		y_resolution = GetSystemMetrics(SM_CYSCREEN);
		rec_x_begin = (x_resolution - 1024) / 2;
		rec_y_begin = (y_resolution - 768) / 2;
		rec_x_end = (x_resolution + 1024) / 2;
		rec_y_end = (y_resolution + 768) / 2;

		_hWnd = hWnd = CreateWindow(std::to_string(nCmdShow).c_str(), std::to_string(nCmdShow).c_str(),
			WS_VISIBLE | WS_POPUP, 0, 0, x_resolution, y_resolution,
			NULL, NULL, hInstance, NULL);

		//显示主窗口
		SetFocus(hWnd);
		

		//创建DirectX设备
		if (FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION,
			IID_IDirectInput8,
			(void**)&m_lpkDInput, NULL)))
		{
			return 0;
		}

		float m_JoySpeedMax;
		if (m_HardSetting.m_JoySpeedMax > 0)
		{
			m_JoySpeedMax = m_HardSetting.m_JoySpeedMax;
		}
		else
		{
			m_JoySpeedMax = 200;
		}
		
		//关闭输入法
		HKL hkl;
		hkl = LoadKeyboardLayout("00000804", KLF_ACTIVATE);
		if (hkl != NULL)
		{
			ActivateKeyboardLayout(hkl, KLF_SETFORPROCESS);
		}
		//ShowCursor(FALSE);
		//设置操纵杆变化范围
		if (JoystickInit(hWnd, -m_JoySpeedMax, m_JoySpeedMax, 1))
		{
			JoystickUpdate();
		}
		else
		{
			MessageBox(hWnd, "请检查操纵杆连接是否正确!", "测试任务", MB_OK);
			return 0;
		}

		// declare a variable of our data structure to pass to the ThreadProcedure
		MYDATA MyThreadData;
		MyThreadData.nTime = 7509843;
		MyThreadData.nNumber = 39;

		//创建操纵杆输入线程
		// declare a DWORD to hold our thread's new generated ID
		HANDLE h = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)InputThreadProcedure,
			(LPVOID)&MyThreadData, NULL, &dwInputThreadID);

		
		//	SetPriorityClass(h,NORMAL_PRIORITY_CLASS);
		//	SetThreadPriority(h,THREAD_PRIORITY_ABOVE_NORMAL);

		// actually create and start the thread now!
		// the thread will run until we send it our own WM_THREADSTOP message
		srand((unsigned)time(NULL)); //初始化随机种子

		//初始化Direct3D
		bool b_InitD3d =  SUCCEEDED(InitD3D(hWnd));
		if (b_InitD3d)
		{
			//进入消息循环
			MSG msg;
			ZeroMemory(&msg, sizeof(msg));
			while (msg.message != WM_QUIT)
			{
				if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
				{
					//处理外部消息
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
				else
				{
					//执行测试过程
					UpdateState();
					if (m_bDisplayReady)
					{
						//渲染图形
						Render();
						hideLastWindow(bUnClosedLastWin, winClassName, winName, hInstance);
					}
				}
				Sleep(1);

				// 当按下“下一个任务”或“退出”时,终止消息循环
				if (m_TestState == STATE_NEXT 
					|| m_TestState == STATE_EXIT)
				{
					break;
				}
			}
		}
		
		ShowCursor(TRUE);
		CloseHandle(h);
		return rtn;
	}
CInputManagerImplementation::CInputManagerImplementation(HWND hWnd)
	: m_MovementX(0)
	, m_MovementY(0)
	, m_MovementZ(0)
	, m_ButtonLeft(false)
	, m_ButtonMiddle(false)
	, m_ButtonRight(false)
	, m_PreviousButtonLeft(false)
	, m_PreviousButtonMiddle(false)
	, m_PreviousButtonRight(false)
	, m_MouseSpeed(1)
	,m_FileName("")

{
	m_Alt = false;
	m_Ctrl = false;

	for (int i = 0; i < 256; ++i)
	{
		m_KeysPrevious[i] = m_KeysCurrent[i] = false;
	}

	for (int i = 0; i < 4; ++i)
	{
		m_PadButtensPrevious[i] = 0;
	}


	// mouse input
	HRESULT l_HR;
	DWORD l_CoopFlags = 0;

	/*l_CoopFlags= DISCL_EXCLUSIVE | DISCL_FOREGROUND;*/

	if (FAILED(l_HR = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&m_DI, NULL)))
		return;
	if (FAILED(l_HR = m_DI->CreateDevice(GUID_SysMouse, &m_Mouse, NULL)))
		return;
	if (FAILED(l_HR = m_Mouse->SetDataFormat(&c_dfDIMouse2)))
		return;
	//if (FAILED(l_HR = m_Mouse->SetCooperativeLevel(hWnd, l_CoopFlags)))
	//	return;

	HMODULE XInputLibrary = LoadLibraryA("xinput1_4.dll");
	if (!XInputLibrary)
	{
		XInputLibrary = LoadLibraryA("xinput9_1_0.dll");
	}

	if (!XInputLibrary)
	{
		XInputLibrary = LoadLibraryA("xinput1_3.dll");
	}

	if (XInputLibrary)
	{
		s_XInputGetState = (TF_XInputGetState *)GetProcAddress(XInputLibrary, "XInputGetState");
		if (!s_XInputGetState) { s_XInputGetState = FakeXInputGetState; }

	}

	if (m_Mouse != NULL)
		m_Mouse->Acquire();
	else
		MessageBox(hWnd, "Problem with de mouse input!", "Mouse", MB_ICONERROR | MB_OK);
}
Exemplo n.º 23
0
bool Direct3DInit(HWND hwnd, HINSTANCE hInstance)
{

	LPDIRECT3D9 pD3D9;
	pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
	if (pD3D9 == nullptr)
	{
		return false;
	}

	D3DCAPS9 caps;
	if (FAILED(pD3D9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps)))
	{
		return false;
	}
	int vp = 0;
	if (caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
	{
		vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
	}
	else
	{
		vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
	}

	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.BackBufferWidth = WINDOW_WIDTH;
	d3dpp.BackBufferHeight = WINDOW_HEIGHT;
	d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
	d3dpp.BackBufferCount = 2;
	d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality = 0;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = hwnd;
	d3dpp.Windowed = true;
	d3dpp.EnableAutoDepthStencil = true;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
	d3dpp.Flags = 0;
	d3dpp.FullScreen_RefreshRateInHz = 0;
	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	if (FAILED(pD3D9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, vp, &d3dpp, &gPD3DDevice)))
	{
		return false;
	}

	D3DADAPTER_IDENTIFIER9 ident;
	pD3D9->GetAdapterIdentifier(0, 0, &ident);
	int len = MultiByteToWideChar(CP_ACP, 0, ident.Description, -1, 0, 0);
	MultiByteToWideChar(CP_ACP, 0, ident.Description, -1, gStrAdapterDesc, len);

	DirectInput8Create(hInstance, 0x0800, IID_IDirectInput8, (void**)&gPDirectInput, nullptr);
	gPDirectInput->CreateDevice(GUID_SysMouse, &gPMouseInput, nullptr);
	gPMouseInput->SetDataFormat(&c_dfDIMouse);
	gPMouseInput->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	gPMouseInput->Acquire();

	gPDirectInput->CreateDevice(GUID_SysKeyboard, &gPKeyboardInput, nullptr);
	gPKeyboardInput->SetDataFormat(&c_dfDIKeyboard);
	gPKeyboardInput->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_NONEXCLUSIVE);
	gPKeyboardInput->Acquire();

	if (!ObjectInit(hwnd))
	{
		return false;
	}
	SAFE_RELEASE(pD3D9);

	return true;
}
Exemplo n.º 24
0
HRESULT 
InitDI8( TDI8Data* data )
{	
        DIPROPDWORD  dipdw; 
        dipdw.diph.dwSize = sizeof(DIPROPDWORD); 
        dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
        dipdw.diph.dwObj = 0; 
        dipdw.diph.dwHow = DIPH_DEVICE; 
        dipdw.dwData = MOUSE_BUFFERSIZE;

        /* Create The DI Object */
        if( DI_OK != DirectInput8Create( data->hInstance              ,  
                                         DIRECTINPUT_VERSION          , 
                                         ((REFIID)IID_IDirectInput8)  , 
                                         ((void**)&data->pDI)         , 
                                         NULL                         ) )
        {                                         
                return E_FAIL;
        }                
	
	/* Set up keyboard input */
	if( FAILED( data->pDI->CreateDevice( GUID_SysKeyboard , 
	                                     &data->pDIKeybrd , 
	                                     NULL             ) ) )
        {	                                     
		return E_FAIL;
        }
        
	if( FAILED( data->pDIKeybrd->SetDataFormat( &c_dfDIKeyboard ) ) )
	{
	        return E_FAIL;
        }
                 
        dipdw.dwData = KEYBOARD_BUFFERSIZE;
        if( FAILED( data->pDIKeybrd->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
        {
                return E_FAIL;
        }        	        

        if( FAILED( data->pDIKeybrd->SetCooperativeLevel( data->hWnd                            , 
                                                          DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ) ) )
        {                                                          
                return E_FAIL;
        }                

        if ( data->pDIKeybrd ) 
        {
                data->pDIKeybrd->Acquire(); 
        }                

        /* Set up mouse input */

        if( FAILED( data->pDI->CreateDevice( GUID_SysMouse   , 
                                             &data->pDIMouse , 
                                             NULL            ) ) )
        {                                             
                return E_FAIL;
        }                

        if( FAILED( data->pDIMouse->SetDataFormat( &c_dfDIMouse2 ) ) )
        {
                return E_FAIL;
        }
         
        dipdw.dwData = MOUSE_BUFFERSIZE; 
        if( FAILED( data->pDIMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
        {
                return E_FAIL;
        }

        if( FAILED( data->pDIMouse->SetCooperativeLevel( data->hWnd                         , 
                                                         DISCL_FOREGROUND | DISCL_EXCLUSIVE ) ) )
        {                                                         
                return E_FAIL;
        }                

        data->hMouse = CreateEvent( 0, 0, 0, 0 );

        if ( data->hMouse == NULL )
        {
                ShutdownDI8( data );
                return 0;
        }

        data->hr = data->pDIMouse->SetEventNotification( data->hMouse );

        if ( FAILED( data->hr ) )
        {
                ShutdownDI8( data );
                return 0;
        }

        if ( FAILED( data->hr ) )
        {
                ShutdownDI8( data );
                return 0;
        }

        if ( data->pDIMouse ) 
        {
                data->pDIMouse->Acquire();
        }                

	/*Set up Joystick input (Only the first joy) */
   /*
        if( FAILED( data->pDI->EnumDevices( DI8DEVCLASS_GAMECTRL  , 
                                            EnumJoysticksCallback , 
                                            (VOID*) data          , 
                                            DIEDFL_ATTACHEDONLY   ) ) )
        {
                return E_FAIL;
        }                

        if( FAILED( data->pDIJoy->SetDataFormat( &c_dfDIJoystick2 ) ) )
        {
                return E_FAIL;
        }                

        if( FAILED( data->pDIJoy->SetCooperativeLevel( data->hWnd                         ,  
                                                       DISCL_EXCLUSIVE | DISCL_FOREGROUND ) ) )
        {                                                       
                return E_FAIL;
        }                

        data->DIDevCaps.dwSize = sizeof( DIDEVCAPS );
        if ( FAILED( data->pDIJoy->GetCapabilities( &data->DIDevCaps ) ) )
        {
                return E_FAIL;
        }                

        if ( FAILED( data->pDIJoy->EnumObjects( EnumAxesCallback , 
                                                (VOID*) data     , 
                                                DIDFT_AXIS       ) ) )
        {                                                
                return E_FAIL;
        }                

        if( data->pDIJoy ) 
        {
                data->pDIJoy->Acquire();
        }
                    */
	return S_OK;
}
bool DirectInput::Initialize(HINSTANCE _hinstance, HWND _hwnd, int _screenWidth, int _screenHeight)
{
    HRESULT hr;

    //Store the screen size which will be used for positioning the mouse cursor
    screenWidth = _screenWidth;
    screenHeight = _screenHeight;

    //Initialize the location of the mouse on the screen
    mouseX = 0;
    mouseY = 0;

    //Initialize the main direct input interface
    hr = DirectInput8Create(_hinstance, 0x0800, IID_IDirectInput8, (void**)&directInput, NULL);
    if(FAILED(hr))
    {
        return false;
    }

    //Initialize the dsirect input interface for the keyboard
    hr = directInput->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
    if(FAILED(hr))
    {
        return false;
    }

    //Set the data format.  In this case since it is a keyboard we can use the predefined data format.
    hr = keyboard->SetDataFormat(&c_dfDIKeyboard);
    if(FAILED(hr))
    {
        return false;
    }

    //Set the cooperative level of the keyboard to not share with other programs
    //If you want to share with other programs just change the flag from DISCL_EXCLUSIVE to DISCL_NONEXCLUSIVE
    hr = keyboard->SetCooperativeLevel(_hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
    if(FAILED(hr))
    {
        return false;
    }

    //Now acquire the keyboard
    hr = keyboard->Acquire();
    if(FAILED(hr))
    {
        return false;
    }

    //Initialize the direct input interface for the mouse
    hr = directInput->CreateDevice(GUID_SysMouse, &mouse, NULL);
    if(FAILED(hr))
    {
        return false;
    }

    //Set the data format for the mouse using the pre-defined mouse data format
    hr = mouse->SetDataFormat(&c_dfDIMouse);
    if(FAILED(hr))
    {
        return false;
    }

    //Set the cooperative level of the mouse to share with other programs
    hr = mouse->SetCooperativeLevel(_hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if(FAILED(hr))
    {
        return false;
    }

    //Acqure the mouse
    hr = mouse->Acquire();
    if(FAILED(hr))
    {
        return false;
    }

    return true;
}
Exemplo n.º 26
0
// Public functions
bool DInput::Initialise( HINSTANCE h_instance, HWND hwnd ) {
	ZeroMemory( keyboard_keys_, sizeof( keyboard_keys_ ) );
	ZeroMemory( prev_keyboard_keys_, sizeof( prev_keyboard_keys_ ) );

	HRESULT result = DirectInput8Create( h_instance, direct_input_VERSION, IID_IDirectInput8, ( void** )&direct_input_, 0 );

	if( FAILED( result ) ) {
		return false;
	}

	result = direct_input_->CreateDevice( GUID_SysKeyboard, &keyboard_device_, 0 );

	if( FAILED( result ) ) {
		return false;
	}

	result = keyboard_device_->SetDataFormat( &c_dfDIKeyboard );

	if( FAILED( result ) ) {
		return false;
	}

	result = keyboard_device_->SetCooperativeLevel( hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE );

	if( FAILED( result ) ) {
		return false;
	}

	result = keyboard_device_->Acquire();

	if( FAILED( result ) ) {
		return false;
	}

	mousePosX_ = mousePosY_ = mouseWheel_ = 0;

	result = direct_input_->CreateDevice( GUID_SysMouse, &mouse_device_, 0 );

	if( FAILED( result ) ) {
		return false;
	}

	result = mouse_device_->SetDataFormat( &c_dfDIMouse );

	if( FAILED( result ) ) {
		return false;
	}

	result = mouse_device_->SetCooperativeLevel( hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE );

	if( FAILED( result ) ) {
		return false;
	}

	result = mouse_device_->Acquire();

	if( FAILED( result ) ) {
		return false;
	}

	return true;
}
Exemplo n.º 27
0
bool DirectInputController::Init(HINSTANCE hInstance, HWND hWnd) {
  HRESULT hr = S_OK;

  if (!_directInput) {
    hr = DirectInput8Create(hInstance,
                            DIRECTINPUT_VERSION, // Compatible version.
                            IID_IDirectInput8,   // DirectInput interface version.
                            (LPVOID*)&_directInput,
                            NULL);
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, DirectInput8Create failed");
      return false;
    }
  }

  // Create mouse device.
  if (!_mouseDevice) {
    hr = _directInput->CreateDevice(GUID_SysMouse, &_mouseDevice, NULL);
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, _directInput->CreateDevice (GUID_SysMouse) failed");
      return false;
    }

    hr = _mouseDevice->SetDataFormat(&c_dfDIMouse2); 
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, _mouseDevice->SetDataFormat failed");
      return false;
    }

    hr = _mouseDevice->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); 
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, _mouseDevice->SetCooperativeLevel failed");
      return false;
    }

    _mouseDevice->Acquire();
  }

  // Create keyboard device.
  if (!_keyboardDevice) {
    hr = _directInput->CreateDevice(GUID_SysKeyboard, &_keyboardDevice, NULL);
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, _directInput->CreateDevice (GUID_SysKeyboard) failed");
      return false;
    }

    hr = _keyboardDevice->SetDataFormat(&c_dfDIKeyboard); 
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, _keyboardDevice->SetDataFormat failed");
      return false;
    }

    hr = _keyboardDevice->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); 
    if (FAILED(hr)) {
      LOGE("Fatal error in DirectInputController::InitDirectInput, _keyboardDevice->SetCooperativeLevel failed");
      return false;
    }

    _keyboardDevice->Acquire();
  }

  return SUCCEEDED(hr);
}
Exemplo n.º 28
0
// 初期化
IZ_BOOL CMyAppl::Init(
	HINSTANCE hInst,
	HWND hDeviceWindow,
	HWND hFocusWindow)
{
	static const IZ_UINT MEM_SIZE = 16 * 1024 * 1024;	// 16MB
	static IZ_UINT8 MEM_BUF[MEM_SIZE];

	// システム初期化
	IZ_BOOL ret = CMySystem::GetInstance().Init(MEM_SIZE, MEM_BUF);
	VRETURN(ret);

	// グラフィックスデバイス設定
	izanagi::SGraphicsDeviceInitParams sParams;
	{
		sParams.hFocusWindow = hFocusWindow;
		sParams.hDeviceWindow = hDeviceWindow;
		
		sParams.Windowed = IZ_TRUE;						// 画面モード(ウインドウモード)

		sParams.BackBufferWidth = SCREEN_WIDTH;			// バックバッファの幅
		sParams.BackBufferHeight = SCREEN_HEIGHT;		// バックバッファの高さ

		sParams.MultiSampleType = D3DMULTISAMPLE_NONE;	// マルチ・サンプリングの種類

		sParams.Adapter = D3DADAPTER_DEFAULT;
		sParams.DeviceType = D3DDEVTYPE_HAL;
		sParams.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;

		sParams.DepthStencilFormat = D3DFMT_D24S8;

		sParams.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
	}

	// デバイスリセット
	ret = CMySystem::GetInstance().GetGraphicsDevice()->Reset(sParams);
	VRETURN(ret);

	// デバッグフォント初期化
	ret = CMySystem::GetInstance().InitDebugFont();
	VRETURN(ret);

	// リセット用コールバックセット
	//CMySystem::GetInstance().GetGraphicsDevice()->SetResetCallBack(_ResetResource);

	// ステート初期化
	ret = CStateManager::GetInstance().Init();
	VRETURN(ret);

	// カメラ初期化
	{
		izanagi::math::CVector vecPos(0.0f, 0.0f, 20.0f, 1.0f);
		izanagi::math::CVector vecRef(0.0f, 0.0f, 0.0f, 1.0f);
		izanagi::math::CVector vecUp(0.0f, 1.0f, 0.0f, 1.0f);

		CMyCamera::GetInstance().Init(
			vecPos, vecRef, vecUp,
			1.0f, 1000.0f,
			izanagi::math::CMath::Deg2Rad(90.0f),
			(IZ_FLOAT)SCREEN_WIDTH / SCREEN_HEIGHT);
	}

#if 1
	// パッド初期化
	{
		D_INPUT* pInput = NULL;
		HRESULT hr = DirectInput8Create(
						hInst,
						DIRECTINPUT_VERSION,
						IID_IDirectInput8,
						(void**)&pInput,
						NULL);
		IZ_ASSERT(SUCCEEDED(hr));
		
		ret = CMySystem::GetInstance().InitKeyboard();
		if (ret) {
			izanagi::SInputDeviceInitParam sInitParam(pInput, hDeviceWindow);
			CMySystem::GetInstance().GetKeyboard()->Init(&sInitParam);
		}

		pInput->Release();

		//VRETURN(ret);
	}
#endif

	return IZ_TRUE;
}
Exemplo n.º 29
0
//-----------------------------------------------------------------------------
// Name: OnCreateDevice()
// Desc: Setups a the mouse device using the flags from the dialog.
//-----------------------------------------------------------------------------
HRESULT OnCreateDevice( HWND hDlg )
{
    HRESULT hr;
    BOOL    bExclusive;
    BOOL    bForeground;
    BOOL    bImmediate;
    DWORD   dwCoopFlags;

    // Cleanup any previous call first
    KillTimer( hDlg, 0 );    
    FreeDirectInput();

    // Detrimine where the buffer would like to be allocated 
    bExclusive         = ( IsDlgButtonChecked( hDlg, IDC_EXCLUSIVE  ) == BST_CHECKED );
    bForeground        = ( IsDlgButtonChecked( hDlg, IDC_FOREGROUND ) == BST_CHECKED );
    bImmediate         = ( IsDlgButtonChecked( hDlg, IDC_IMMEDIATE  ) == BST_CHECKED );

    if( bExclusive )
        dwCoopFlags = DISCL_EXCLUSIVE;
    else
        dwCoopFlags = DISCL_NONEXCLUSIVE;

    if( bForeground )
        dwCoopFlags |= DISCL_FOREGROUND;
    else
        dwCoopFlags |= DISCL_BACKGROUND;

    // Create a DInput object
    if( FAILED( hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, 
                                         IID_IDirectInput8, (VOID**)&g_pDI, NULL ) ) )
        return hr;
    
    // Obtain an interface to the system mouse device.
    if( FAILED( hr = g_pDI->CreateDevice( GUID_SysMouse, &g_pMouse, NULL ) ) )
        return hr;
    
    // Set the data format to "mouse format" - a predefined data format 
    //
    // A data format specifies which controls on a device we
    // are interested in, and how they should be reported.
    //
    // This tells DirectInput that we will be passing a
    // DIMOUSESTATE2 structure to IDirectInputDevice::GetDeviceState.
    if( FAILED( hr = g_pMouse->SetDataFormat( &c_dfDIMouse2 ) ) )
        return hr;
    
    // Set the cooperativity level to let DirectInput know how
    // this device should interact with the system and with other
    // DirectInput applications.
    hr = g_pMouse->SetCooperativeLevel( hDlg, dwCoopFlags );
    if( hr == DIERR_UNSUPPORTED && !bForeground && bExclusive )
    {
        FreeDirectInput();
        MessageBox( hDlg, _T("SetCooperativeLevel() returned DIERR_UNSUPPORTED.\n")
                          _T("For security reasons, background exclusive mouse\n")
                          _T("access is not allowed."), 
                          _T("Mouse"), MB_OK );
        return S_OK;
    }

    if( FAILED(hr) )
        return hr;

    if( !bImmediate )
    {
        // IMPORTANT STEP TO USE BUFFERED DEVICE DATA!
        //
        // DirectInput uses unbuffered I/O (buffer size = 0) by default.
        // If you want to read buffered data, you need to set a nonzero
        // buffer size.
        //
        // Set the buffer size to SAMPLE_BUFFER_SIZE (defined above) elements.
        //
        // The buffer size is a DWORD property associated with the device.
        DIPROPDWORD dipdw;
        dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
        dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
        dipdw.diph.dwObj        = 0;
        dipdw.diph.dwHow        = DIPH_DEVICE;
        dipdw.dwData            = SAMPLE_BUFFER_SIZE; // Arbitary buffer size

        if( FAILED( hr = g_pMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
            return hr;
    }

    // Acquire the newly created device
    g_pMouse->Acquire();

    // Set a timer to go off 12 times a second, to read input
    // Note: Typically an application would poll the mouse
    //       much faster than this, but this slow rate is simply 
    //       for the purposes of demonstration
    SetTimer( hDlg, 0, 1000 / 12, NULL );

    return S_OK;
}
Exemplo n.º 30
0
//-----------------------------------------------------------------------------
// Purpose: Init_ForceFeedback 
//-----------------------------------------------------------------------------
void CInput::Init_ForceFeedback() 
{ 
	// abort startup if user requests no joystick
	if ( CommandLine()->FindParm("-noff" ) ) 
	{
		return; 
	}
 
	Assert( !m_pFF );

	m_pFF = new ForceFeedbackParams_t;
	Assert( m_pFF );
	Q_memset( m_pFF, 0, sizeof( *m_pFF ) );

	HRESULT hr = DirectInput8Create(GetModuleHandle(0), DIRECTINPUT_VERSION, 
        IID_IDirectInput8, (void**)&m_pFF->m_pIInput, NULL ); 

	if ( FAILED( hr ) )
	{
		return;
	}

	hr = m_pFF->m_pIInput->CreateDevice(GUID_Joystick, &m_pFF->m_pIJoystick, NULL );
	if ( FAILED( hr ) )
	{
		return;
	}

	hr = m_pFF->m_pIJoystick->SetDataFormat(&c_dfDIJoystick2 );

	if ( FAILED( hr ) )
	{
		return;
	}
	
	HWND mainWnd = (HWND)g_pEngineWindow->GetWindowHandle();

	hr = m_pFF->m_pIJoystick->SetCooperativeLevel( mainWnd, DISCL_BACKGROUND | DISCL_EXCLUSIVE );

	if ( FAILED( hr ) )
	{
		return;
	}

	DIPROPDWORD dwd;
	//The following code turns the center spring off
	dwd.diph.dwSize       = sizeof(DIPROPDWORD);
	dwd.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	dwd.diph.dwObj        = 0;
	dwd.diph.dwHow        = DIPH_DEVICE;
	dwd.dwData            = FALSE;

	if ( !ff_autocenter.GetBool() )
	{
		hr = m_pFF->m_pIJoystick->SetProperty( DIPROP_AUTOCENTER, &dwd.diph );
		if ( FAILED( hr ) )
		{
			return;
		}
	}

    // Acquire the device
	hr = m_pFF->m_pIJoystick->Acquire();

    if( FAILED( hr ) )
	{
        return;
	}

	DIDEVCAPS diDevCaps;
	Q_memset( &diDevCaps, 0, sizeof( diDevCaps ) );
	diDevCaps.dwSize = sizeof( diDevCaps );

	hr = m_pFF->m_pIJoystick->GetCapabilities( &diDevCaps );

	if ( FAILED( hr ) )
	{
		DevMsg( "GetCapabilities failed\n" );
		return;
	}

	if ( !( diDevCaps.dwFlags & DIDC_FORCEFEEDBACK ) )
	{
		// Doesn't support FF
		return;
	}

	DIDEVICEINSTANCE diDI;
	Q_memset( &diDI, 0, sizeof( diDI ) );
	diDI.dwSize = sizeof( diDI );

	hr = m_pFF->m_pIJoystick->GetDeviceInfo( &diDI );
	if ( FAILED( hr ) )
	{
		DevMsg( "GetDeviceInfo failed\n" );
		return;
	}

	DevMsg( "Forcefeedback device found:\n" ); 

	//DevMsg( "  device '%s'\n", diDI.tszInstanceName );
	DevMsg( "  product '%s'\n", diDI.tszProductName );

	DescribeFFDevice( diDevCaps );
	
	InitEffectMap();

	LoadEffectFiles( m_pFF->m_pIJoystick );

	m_pFF->m_bForceFeedbackAvailable = true; 
}