void refreshDevices() {
	if (!diAvailable || di == NULL) {
		return;
	}
	// Poll all devices
	di->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback, NULL, DIEDFL_ATTACHEDONLY);
}
Beispiel #2
0
void initJoysticks( HWND hWnd )
{
    numJoysticks = 0;
    for ( unsigned char i = 0; i < MAX_JOYSTICKS; i++ )
        numButtons[i] = 0;
    
    din->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, &hWnd, DIEDFL_ATTACHEDONLY );
}
Beispiel #3
0
//-----------------------------------------------------------------------------
// Name: InitDirectInput()
// output: none
// Desc: very similar to microsoft directinput reference code.  I added multiple
// joystick enumeration, tho.
//-----------------------------------------------------------------------------
HRESULT InitDirectInput()
{
    HRESULT hr;

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

    // Enumerate all joysticks in the system. this proggy only can use MAXJOYSTICKS.
	if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL, 
										 EnumJoysticksCallback,
										 NULL, DIEDFL_ATTACHEDONLY ) ) )
		return hr;

    // Make sure we got at least one joystick
    if( NULL == g_pJoystick[0] )
    {
        //MessageBox( NULL, TEXT("Joystick not found. plugin will not work"),  
        //            TEXT("Joypad plugin"), 
        //            MB_ICONERROR | MB_OK );
        return DIERR_UNPLUGGED;
    }

    // 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().
	// We need to repeat this setup and enumeration for each joystick.
	for (int c = 0; (c < MAXJOYSTICKS) && (g_pJoystick[c] != NULL); c++) {
		if( FAILED( hr = g_pJoystick[c]->SetDataFormat( &c_dfDIJoystick2 ) ) )
			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( hDlg, DISCL_NONEXCLUSIVE | 
		//                                                         DISCL_BACKGROUND  ) ) )
		if( FAILED( hr = g_pJoystick[c]->SetCooperativeLevel( NULL, DISCL_NONEXCLUSIVE | 
																 DISCL_BACKGROUND  ) ) )
			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.
		// The callback is run once for each axis object for each joystick.
		// c is passed so that the callback knows which joystick to setup
		if( FAILED( hr = g_pJoystick[c]->EnumObjects( EnumObjectsCallback, 
		                                            (VOID*)(&c), DIDFT_AXIS ) ) )
		    return hr;
	}

    return S_OK;
}
Beispiel #4
0
bool initJoysticks( HWND hWnd )
{
    if ( FAILED( din->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, &hWnd, DIEDFL_ATTACHEDONLY ) ) )
    {
        logg( "    ERROR: Unable to enumerate joysticks." );
        return ( false );
    }
    
    return ( true );
}
Beispiel #5
0
int GutInputInit(void)
{
	memset(g_pKeyDownFuncs, 0, sizeof(g_pKeyDownFuncs));
	memset(g_pKeyUpFuncs, 0, sizeof(g_pKeyUpFuncs));
	memset(g_pKeyPressedFuncs, 0, sizeof(g_pKeyPressedFuncs));

	int hr;
	HWND hwnd = GutGetWindowHandleWin32();
	HINSTANCE hinst = GutGetWindowInstanceWin32();
	hr = DirectInput8Create( hinst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&g_pDI, NULL);
	if ( FAILED(hr) )
		return 0;

	// create keyboard device
	hr = g_pDI->CreateDevice( GUID_SysKeyboard, &g_pKeyboard, NULL );
	if ( FAILED(hr) )
		return 0;

	if ( g_pKeyboard )
	{
		g_pKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE );
		g_pKeyboard->SetDataFormat(&c_dfDIKeyboard);
		g_pKeyboard->Acquire();
	}

	// create mouse device
	hr = g_pDI->CreateDevice(GUID_SysMouse, &g_pMouse, NULL);
	if ( FAILED(hr) )
		return 0;

	if ( g_pMouse )
	{
		g_pMouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE );
		g_pMouse->SetDataFormat(&c_dfDIMouse2);
		g_pMouse->Acquire();
	}

	GetCursorPos(&g_op);
	ScreenToClient(hwnd, &g_op);
	g_mouse = g_op;

	// create joystick device
	hr = g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, NULL, DIEDFL_ATTACHEDONLY);
	if ( FAILED(hr) )
		return 0;

	if ( g_pJoystick )
	{
		g_pJoystick->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE );
		g_pJoystick->SetDataFormat(&c_dfDIJoystick);
		g_pJoystick->Acquire();
	}

	return 1;
}
Beispiel #6
0
//-----------------------------------------------------------------------------
// Name: InitDirectInput()
// Desc: Initialize the DirectInput variables.
//-----------------------------------------------------------------------------
HRESULT InitDirectInput( HWND hDlg )
{
    HRESULT hr;

    // 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 ) ) )
        return hr;

    // Get the first enumerated force feedback device
    if( FAILED( hr = g_pDI->EnumDevices( 0, EnumFFDevicesCallback, 0, 
                                         DIEDFL_ATTACHEDONLY | 
                                         DIEDFL_FORCEFEEDBACK ) ) )
        return hr;
    
    if( g_pFFDevice == NULL )
    {
        MessageBox( hDlg, _T("No force feedback device found.  ")
                          _T("The sample will now exit."), 
                          _T("ReadFFE"), MB_ICONERROR | MB_OK );
        EndDialog( hDlg, 0 );
        return S_OK;
    }

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

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

    // Disable auto-centering spring
    DIPROPDWORD dipdw;
    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;

    // Acquire the device
    if( FAILED( hr = g_pFFDevice->Acquire() ) )
        return hr;

    return S_OK;
}
int main()
{
    HRESULT hr;

    hr=DirectInput8Create
       (GetModuleHandle (NULL), DIRECTINPUT_VERSION, IID_IDirectInput8A,
       (VOID**)&gp_DI, NULL);

    printf("Devices\n-----------------\n");
    hr = gp_DI->EnumDevices(DI8DEVCLASS_ALL,EnumDevicesCallback, NULL, DIEDFL_ALLDEVICES);


    memset(&g_ActionFormat, 0, sizeof(g_ActionFormat));
    g_ActionFormat.dwSize = sizeof(g_ActionFormat);
    g_ActionFormat.dwActionSize = sizeof(DIACTION);
    g_ActionFormat.dwNumActions = ARRAYSIZE(g_commands_space);
    g_ActionFormat.dwDataSize = 4 * g_ActionFormat.dwNumActions;
    g_ActionFormat.rgoAction = g_commands_space;
    g_ActionFormat.guidActionMap = ACTIONMAP_GUID;
    g_ActionFormat.dwBufferSize = 32;
    g_ActionFormat.dwGenre = DIVIRTUAL_SPACESIM;

    printf("Space combat enumeration\n------------\n");
    hr=gp_DI->EnumDevicesBySemantics
       (NULL, &g_ActionFormat, EnumSemanticsCallback, NULL, DIEDBSFL_AVAILABLEDEVICES );

//    if(FAILED(hr)) printf("Failed?\n");

//    g_ActionFormat.dwNumActions = ARRAYSIZE(g_commands_driving);
//    g_ActionFormat.dwDataSize = 4 * g_ActionFormat.dwNumActions;
//    g_ActionFormat.rgoAction = g_commands_driving;
//    g_ActionFormat.dwGenre = DIVIRTUAL_DRIVING_RACE;

//    printf("Driving race enumeration\n------------\n");
//    hr=gp_DI->EnumDevicesBySemantics
//       (NULL, &g_ActionFormat, EnumSemanticsCallback, NULL, DIEDBSFL_AVAILABLEDEVICES);

//    if(FAILED(hr)) printf("Failed?\n");

//    g_ActionFormat.dwNumActions = ARRAYSIZE(g_commands_fps);
//    g_ActionFormat.dwDataSize = 4 * g_ActionFormat.dwNumActions;
//    g_ActionFormat.rgoAction = g_commands_fps;
//    g_ActionFormat.dwGenre = DIVIRTUAL_FIGHTING_FPS;

//    printf("First person shooter enumeration\n------------\n");
//    hr=gp_DI->EnumDevicesBySemantics
//       (NULL, &g_ActionFormat, EnumSemanticsCallback, NULL, DIEDBSFL_AVAILABLEDEVICES);

//    if(FAILED(hr)) printf("Failed?\n");

    return 0;
}
Beispiel #8
0
void Init_DInput( HINSTANCE hInstance, HWND hWnd )
{
	di_enum_hwnd = hWnd;


	if( FAILED( DirectInput8Create( hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8,
		(void**) &dinput, NULL)) ) {
		return;
	}


	if( hidmouse_api == HIDMOUSE_API_DIRECTINPUT )
	{
		di_mouse_count = 0;

		dinput->EnumDevices( DI8DEVCLASS_POINTER, DInput_Mouse_EnumCallback, NULL, DIEDFL_ATTACHEDONLY );
	}




	di_joystick_count = 0;

	dinput->EnumDevices( DI8DEVCLASS_GAMECTRL, DInput_Joystick_EnumCallback, NULL, DIEDFL_ATTACHEDONLY );




	// XP = system keyboard only (!)
	if( FAILED( dinput->CreateDevice( GUID_SysKeyboard, &di_keyboard, NULL)) )
		return;

	if( FAILED( di_keyboard->SetDataFormat( &c_dfDIKeyboard )) )
		return;

	if( FAILED( di_keyboard->SetCooperativeLevel( hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND )) )
		return;
}
Beispiel #9
0
LPDIRECTINPUTDEVICE8 DI_CLASS::EnumDevices(LPDIRECTINPUT8 pDI)
{
	tmp_pDI = pDI;
	tmp_Feedback = FALSE;
	memset(tmp_device_name, 0, 255);
	if( FAILED( pDI->EnumDevices(DI8DEVCLASS_GAMECTRL,
									::EnumCallback,
									NULL,
									DIEDFL_ATTACHEDONLY) ) )
			return NULL;
	Feedback = tmp_Feedback;
	strcpy(JoystickName, tmp_device_name);
	return tmp_Device;
}
Beispiel #10
0
int _tmain(int argc, _TCHAR* argv[])
{
	LogFile("ditool.txt");

	setlocale(LC_ALL, "");
	hInst = GetModuleHandle(NULL);
	HRESULT hr = DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI, NULL);

	if (SUCCEEDED(hr)) g_pDI->EnumDevices(DI8DEVCLASS_ALL, EnumDevicesCallback, NULL, DIEDFL_ATTACHEDONLY);

	_getch();

	return 0;
}
Beispiel #11
0
bool CG27::InitializeG27()  
{  
    HRESULT hr;  
  
    // Register with the DirectInput subsystem and get a pointer to a IDirectInput interface we can use.  
    // Create a DInput object  
  
    //initialize directinput library  
    if( FAILED( hr = DirectInput8Create( GetModuleHandle( NULL ), DIRECTINPUT_VERSION,  
        IID_IDirectInput8, ( VOID** )&g_pDI, NULL ) ) )  
        return false;  
  
  
    LPDIRECTINPUTDEVICE8 joystick;  
  
    // Look for the first simple joystick we can find.  
    if (FAILED(hr = g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback,  
        NULL, DIEDFL_ATTACHEDONLY))) {  
            return false;  
    }  
  
    if (g_pJoystick == NULL)    
    {  
//        ShowMessageBox("g27 not found, please check the connection, exiting........");  
		qDebug() << "fucklrl";
        return false;  
    }  
  
    if (FAILED(hr = g_pJoystick->SetDataFormat(&c_dfDIJoystick2)))  
    {  
//        ShowMessageBox(" set g27 data format error, exiting.......");  
		qDebug() << "fuckld";
        return false;  
    }  
  
    g_pJoystick->SetCooperativeLevel(NULL, DISCL_EXCLUSIVE|DISCL_FOREGROUND);  
  
    DIDEVCAPS capabilities;  
    capabilities.dwSize = sizeof(DIDEVCAPS);  
  
    g_pJoystick->GetCapabilities(&capabilities);  
  
    if (FAILED(hr=g_pJoystick->EnumObjects(enumAxesCallback, NULL, DIDFT_AXIS)))  
    {  
  
    }  
	qDebug() << "initializing succeeded";
    return true;  
}  
void InitJoystick()
{
    if(FAILED(DirectInput8Create ( GetModuleHandle(NULL), DIRECTINPUT_VERSION,
                                   IID_IDirectInput8, (VOID**)&gDirectInput, NULL ) ) )
        return;

    if(FAILED(gDirectInput->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback,
                                         NULL, DIEDFL_ATTACHEDONLY ) ) )
        return;

    if(!gJoystick)
        return;

    if( FAILED(gJoystick->SetDataFormat( &c_dfDIJoystick2 ) ) )
        return;
}
unsigned int
Joystick::deviceCount()
{
    unsigned int counter = 0;
    LPDIRECTINPUT8 di = NULL;
    HRESULT hr;

    if (SUCCEEDED(hr = DirectInput8Create(GetModuleHandle(NULL),
                                          DIRECTINPUT_VERSION, 
                                          IID_IDirectInput8,
                                          (VOID**)&di, NULL))) {
        di->EnumDevices(DI8DEVCLASS_GAMECTRL, ::countCallback,
                        &counter, DIEDFL_ATTACHEDONLY);
    }

    return counter;
}
Beispiel #14
0
//=============================================================================
// ジョイパッドの初期化
//=============================================================================
HRESULT InitJoypad(HINSTANCE hInstance, HWND hWnd)
{
	int nLoop;

	HRESULT hr;

	// 入力処理の初期化
	hr = InitInput(hInstance, hWnd);
	if(FAILED(hr))
	{
		MessageBox(hWnd, "DirectInputオブジェクトが作れねぇ!", "警告!", MB_ICONWARNING);
		return hr;
	}

	// 初期化
	for(nLoop = 0; nLoop < MAX_CONTROLER; nLoop++)
		g_pDIDevJoypad[nLoop] = NULL;

	// デバイスオブジェクトを作成(接続されているジョイパッドを列挙する)
	if(FAILED(g_pInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoyCallback, NULL, DIEDFL_ATTACHEDONLY)))
		return E_FAIL;

	// ジョイパッドの数だけ処理
	for(nLoop = 0; nLoop < MAX_CONTROLER; nLoop++)
	{
		// ジョイパッドがない場合はすっ飛ばす
		if(g_pDIDevJoypad[nLoop] == NULL)
			continue;

		// データフォーマットの設定
		if(FAILED(g_pDIDevJoypad[nLoop]->SetDataFormat(&c_dfDIJoystick)))
			return E_FAIL;

		// 協調レベルの設定
		if(FAILED(g_pDIDevJoypad[nLoop]->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)))
			return E_FAIL;

		// デバイスへの入力制御開始
		g_pDIDevJoypad[nLoop]->Acquire();	
	}

	return S_OK;
}
Beispiel #15
0
int HasFFEffects(const CKBehaviorContext& behcontext)
{
	CKBehavior* beh = behcontext.Behavior;
	CKContext* ctx = behcontext.Context;

	HWND mWin = (HWND )ctx->GetMainWindow();

	DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI2, NULL )  ;

    // Get the first enumerated force feedback device
    g_pDI2->EnumDevices( 0, EnumFFDevicesCallback0, 0, DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK );

	if( g_pFFDevice2 == NULL )
          beh->ActivateOutput(1);
	else
		beh->ActivateOutput(0);
	
	FreeDirectInput0();
	return CKBR_OK;
}
Beispiel #16
0
	// コンストラクタ
	Gamepad::Gamepad(LPDIRECTINPUT8 dInput, HWND hWnd)
	{
		if (FAILED(dInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumGamepad, nullptr, DIEDFL_ATTACHEDONLY)))
		{
			return;
		}

		if (FAILED(dpad->SetDataFormat(&c_dfDIJoystick2)))
		{
			return;
		}

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

		if (FAILED(dpad->EnumObjects(EnumAxis, nullptr, DIDFT_AXIS)))
		{
			return;
		}
	}
int main()
{
	// Create a DirectInput device
	if (FAILED(hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, 
		IID_IDirectInput8, (VOID**)&di, NULL))) {
			return hr;
	}

	// Look for the first simple joystick we can find.
	if (FAILED(hr = di->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback,
		NULL, DIEDFL_ATTACHEDONLY))) {
			return hr;
	}

	// Make sure we got a joystick
	if (joystick == NULL) {
		printf("Joystick not found.\n");
		return E_FAIL;
	}

	if (FAILED(hr = joystick->SetDataFormat(&c_dfDIJoystick2))) {
		return hr;
	}

	if (FAILED(hr = joystick->SetCooperativeLevel(NULL, DISCL_EXCLUSIVE |
		DISCL_FOREGROUND))) {
			return hr;
	}

	capabilities.dwSize = sizeof(DIDEVCAPS);
	if (FAILED(hr = joystick->GetCapabilities(&capabilities))) {
		return hr;
	}

	system("pause");
	return 0;
}
Beispiel #18
0
int DInput_Init_Joystick(int min_x, int max_x, int min_y, int max_y, int dead_zone)
{
// this function initializes the joystick, it allows you to set
// the minimum and maximum x-y ranges 

// first find the f*****g GUID of your particular joystick
lpdi->EnumDevices(DI8DEVCLASS_GAMECTRL, 
                  DInput_Enum_Joysticks, 
                  &joystickGUID, 
                  DIEDFL_ATTACHEDONLY); 

// create a temporary IDIRECTINPUTDEVICE (1.0) interface, so we query for 2
LPDIRECTINPUTDEVICE lpdijoy_temp = NULL;

if (lpdi->CreateDevice(joystickGUID, &lpdijoy, NULL)!=DI_OK)
   return(0);

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

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

// set the range of the joystick
DIPROPRANGE joy_axis_range;

// first x axis
joy_axis_range.lMin = min_x;
joy_axis_range.lMax = max_x;

joy_axis_range.diph.dwSize       = sizeof(DIPROPRANGE); 
joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
joy_axis_range.diph.dwObj        = DIJOFS_X;
joy_axis_range.diph.dwHow        = DIPH_BYOFFSET;

lpdijoy->SetProperty(DIPROP_RANGE,&joy_axis_range.diph);

// now y-axis
joy_axis_range.lMin = min_y;
joy_axis_range.lMax = max_y;

joy_axis_range.diph.dwSize       = sizeof(DIPROPRANGE); 
joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
joy_axis_range.diph.dwObj        = DIJOFS_Y;
joy_axis_range.diph.dwHow        = DIPH_BYOFFSET;

lpdijoy->SetProperty(DIPROP_RANGE,&joy_axis_range.diph);


// and now the dead band
DIPROPDWORD dead_band; // here's our property word

// scale dead zone by 100
dead_zone*=100;

dead_band.diph.dwSize       = sizeof(dead_band);
dead_band.diph.dwHeaderSize = sizeof(dead_band.diph);
dead_band.diph.dwObj        = DIJOFS_X;
dead_band.diph.dwHow        = DIPH_BYOFFSET;

// deadband will be used on both sides of the range +/-
dead_band.dwData            = dead_zone;

// finally set the property
lpdijoy->SetProperty(DIPROP_DEADZONE,&dead_band.diph);

dead_band.diph.dwSize       = sizeof(dead_band);
dead_band.diph.dwHeaderSize = sizeof(dead_band.diph);
dead_band.diph.dwObj        = DIJOFS_Y;
dead_band.diph.dwHow        = DIPH_BYOFFSET;

// deadband will be used on both sides of the range +/-
dead_band.dwData            = dead_zone;


// finally set the property
lpdijoy->SetProperty(DIPROP_DEADZONE,&dead_band.diph);

// acquire the joystick
if (lpdijoy->Acquire()!=DI_OK)
   return(0);

// set found flag
joystick_found = 1;

// return success
return(1);

} // end DInput_Init_Joystick
Beispiel #19
0
//---------------------------------------- 初期化
HRESULT InitializePad(void)			// パッド初期化
{
	HRESULT		result;
	int			i;

	padCount = 0;
	// ジョイパッドを探す
	g_pDInput->EnumDevices(DI8DEVCLASS_GAMECTRL, (LPDIENUMDEVICESCALLBACK)SearchGamePadCallback, NULL, DIEDFL_ATTACHEDONLY);
	// セットしたコールバック関数が、パッドを発見した数だけ呼ばれる。

	for (i=0 ; i<padCount ; i++) {
		// ジョイスティック用のデータ・フォーマットを設定
		result = pGamePad[i]->SetDataFormat(&c_dfDIJoystick);
		if (FAILED(result))
			return false; // データフォーマットの設定に失敗

		// モードを設定(フォアグラウンド&非排他モード)
//		result = pGamePad[i]->SetCooperativeLevel(hWindow, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
//		if (FAILED(result))
//			return false; // モードの設定に失敗

		// 軸の値の範囲を設定
		// X軸、Y軸のそれぞれについて、オブジェクトが報告可能な値の範囲をセットする。
		// (max-min)は、最大10,000(?)。(max-min)/2が中央値になる。
		// 差を大きくすれば、アナログ値の細かな動きを捕らえられる。(パッドの性能による)
		DIPROPRANGE				diprg;
		ZeroMemory(&diprg, sizeof(diprg));
		diprg.diph.dwSize		= sizeof(diprg); 
		diprg.diph.dwHeaderSize	= sizeof(diprg.diph); 
		diprg.diph.dwHow		= DIPH_BYOFFSET; 
		diprg.lMin				= RANGE_MIN;
		diprg.lMax				= RANGE_MAX;
		// X軸の範囲を設定
		diprg.diph.dwObj		= DIJOFS_X; 
		pGamePad[i]->SetProperty(DIPROP_RANGE, &diprg.diph);
		// Y軸の範囲を設定
		diprg.diph.dwObj		= DIJOFS_Y;
		pGamePad[i]->SetProperty(DIPROP_RANGE, &diprg.diph);

		// 各軸ごとに、無効のゾーン値を設定する。
		// 無効ゾーンとは、中央からの微少なジョイスティックの動きを無視する範囲のこと。
		// 指定する値は、10000に対する相対値(2000なら20パーセント)。
		DIPROPDWORD				dipdw;
		dipdw.diph.dwSize		= sizeof(DIPROPDWORD);
		dipdw.diph.dwHeaderSize	= sizeof(dipdw.diph);
		dipdw.diph.dwHow		= DIPH_BYOFFSET;
		dipdw.dwData			= DEADZONE;
		//X軸の無効ゾーンを設定
		dipdw.diph.dwObj		= DIJOFS_X;
		pGamePad[i]->SetProperty(DIPROP_DEADZONE, &dipdw.diph);
		//Y軸の無効ゾーンを設定
		dipdw.diph.dwObj		= DIJOFS_Y;
		pGamePad[i]->SetProperty(DIPROP_DEADZONE, &dipdw.diph);
			
		//ジョイスティック入力制御開始
		pGamePad[i]->Acquire();
	}
		
	return true;

}
Beispiel #20
0
HRESULT InitDirectInput( HWND hDlg )
{
    HRESULT hr;

    // 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( 0, EnumFFDevicesCallback, 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) ;



    // Disable auto-centering spring
    DIPROPDWORD dipdw;
    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;

    // Acquire the device
    if( FAILED( hr = g_pFFDevice->Acquire() ) )
        return hr;


	int op = 2;
	
    return S_OK;
}
Beispiel #21
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;
}
Beispiel #22
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;
}
Beispiel #23
0
BOOL JoystickInit (HWND hWindow, int iMin, int iMax,
                            int iDeadZone)
{
	if(JOY)
	{
	    /* Find first available joystick */
		if (FAILED (m_lpkDInput->EnumDevices (
				 DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, &m_lpkDIDevice, 
				 DIEDFL_ATTACHEDONLY)) )
		{
			return FALSE;
		}
 
		/* Set joystick data format */
		if(m_lpkDIDevice == NULL)
		{
			return FALSE;
		}

		if (FAILED(m_lpkDIDevice->SetDataFormat (&c_dfDIJoystick2)))
		{
			return FALSE;
		}
 
	  /* Set joystick cooperative level */
		if (FAILED(m_lpkDIDevice->SetCooperativeLevel (hWindow, 
				DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
		{
			return FALSE;
		}
 
	  /* Set joystick axis ranges */
		DIPROPRANGE kDIRange; 
 
		kDIRange.diph.dwSize       = sizeof(DIPROPRANGE); 
		kDIRange.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
		kDIRange.diph.dwHow        = 0; 
		kDIRange.diph.dwObj        = DIPH_DEVICE; 
		kDIRange.lMin              = iMin; 
		kDIRange.lMax              = iMax; 
 
		if (FAILED(m_lpkDIDevice->SetProperty (DIPROP_RANGE, &kDIRange.diph)))
		{
			return FALSE;
		}

	  /* Set joystick dead zone */
		DIPROPDWORD kDIDeadZone; 
 
		kDIDeadZone.diph.dwSize       = sizeof(DIPROPDWORD); 
		kDIDeadZone.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
		kDIDeadZone.diph.dwHow        = 0; 
		kDIDeadZone.diph.dwObj        = DIPH_DEVICE; 
		kDIDeadZone.dwData            = iDeadZone * 100; 
 
		if (FAILED (m_lpkDIDevice->SetProperty (DIPROP_DEADZONE,
											 &kDIDeadZone.diph)) )
		{
			return FALSE;
		}
 
	  /* Acquire joystick */
		HRESULT hRet = m_lpkDIDevice->Poll (); 
		if (FAILED (hRet)) 
		{
			hRet = m_lpkDIDevice->Acquire ();
  
			while (hRet == DIERR_INPUTLOST) 
			{
				hRet = m_lpkDIDevice->Acquire ();
			}
		}
		return TRUE;
	}
	else
	{
		if (FAILED(m_lpkDInput->CreateDevice (
			GUID_SysKeyboard, &m_lpkDIDevice, NULL)) )
		{
			return FALSE;
		}
		
		if (FAILED(m_lpkDIDevice->SetDataFormat (&c_dfDIKeyboard)))
		{
			return FALSE;
		}
 
		/* Set joystick cooperative level */
		if (FAILED(m_lpkDIDevice->SetCooperativeLevel (hWindow, 
				DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
		{
			return FALSE;
		}

		/* Acquire joystick */
		HRESULT hRet = m_lpkDIDevice->Poll (); 
		if (FAILED (hRet)) 
		{
			hRet = m_lpkDIDevice->Acquire ();
  
			while (hRet == DIERR_INPUTLOST) 
			{
				hRet = m_lpkDIDevice->Acquire ();
			}
		}
		return TRUE;
	}
}
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

// start up DirectDraw (replace the parms as you desire)
DDraw_Init(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP);

// joystick creation section ////////////////////////////////

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

// first find the f*****g GUID of your particular joystick
lpdi->EnumDevices(DI8DEVCLASS_GAMECTRL, 
                  DI_Enum_Joysticks, 
                  &joystickGUID, 
                  DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK); 

if (lpdi->CreateDevice(joystickGUID, &lpdijoy, NULL)!=DI_OK)
   return(0);

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

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

// set the range of the joystick
DIPROPRANGE joy_axis_range;

// first x axis
joy_axis_range.lMin = -32;
joy_axis_range.lMax = 32;

joy_axis_range.diph.dwSize       = sizeof(DIPROPRANGE); 
joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
joy_axis_range.diph.dwObj        = DIJOFS_X;
joy_axis_range.diph.dwHow        = DIPH_BYOFFSET;

lpdijoy->SetProperty(DIPROP_RANGE,&joy_axis_range.diph);

// now y-axis
joy_axis_range.lMin = -32;
joy_axis_range.lMax = 32;

joy_axis_range.diph.dwSize       = sizeof(DIPROPRANGE); 
joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
joy_axis_range.diph.dwObj        = DIJOFS_Y;
joy_axis_range.diph.dwHow        = DIPH_BYOFFSET;

lpdijoy->SetProperty(DIPROP_RANGE,&joy_axis_range.diph);

// and now the dead band

DIPROPDWORD dead_band; // here's our property word

dead_band.diph.dwSize       = sizeof(dead_band);
dead_band.diph.dwHeaderSize = sizeof(dead_band.diph);
dead_band.diph.dwObj        = DIJOFS_X;
dead_band.diph.dwHow        = DIPH_BYOFFSET;

// 4 will be used on both sides of the range +/-
dead_band.dwData            = 1000;

// finally set the property
lpdijoy->SetProperty(DIPROP_DEADZONE,&dead_band.diph);

dead_band.diph.dwSize       = sizeof(dead_band);
dead_band.diph.dwHeaderSize = sizeof(dead_band.diph);
dead_band.diph.dwObj        = DIJOFS_Y;
dead_band.diph.dwHow        = DIPH_BYOFFSET;

// 4 will be used on both sides of the range +/-
dead_band.dwData            = 1000;

// finally set the property
lpdijoy->SetProperty(DIPROP_DEADZONE,&dead_band.diph);


// acquire the joystick
if (lpdijoy->Acquire()!=DI_OK)
   return(0);


// force feedback setup
DWORD      dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG       lDirection[2] = { 0, 0 };


DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

// setup the periodic structure
diPeriodic.dwMagnitude = DI_FFNOMINALMAX; 
diPeriodic.lOffset = 0; 
diPeriodic.dwPhase = 0; 
diPeriodic.dwPeriod = (DWORD) (0.05 * DI_SECONDS); 

// set the modulation envelope 
diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0; 
diEnvelope.dwAttackTime = (DWORD) (0.01 * DI_SECONDS); 
diEnvelope.dwFadeLevel = 0; 
diEnvelope.dwFadeTime = (DWORD) (3.0 * DI_SECONDS); 
 
// set up the effect structure itself
diEffect.dwSize = sizeof(DIEFFECT); 
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS; 
diEffect.dwDuration = (DWORD) INFINITE; // (1 * DI_SECONDS);
 
// set up details of effect
diEffect.dwSamplePeriod = 0;               // = default 
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0; // connect effect to trigger button
diEffect.dwTriggerRepeatInterval = 0;      
diEffect.cAxes = 2; 
diEffect.rgdwAxes = dwAxes; 
diEffect.rglDirection = &lDirection[0]; 
diEffect.lpEnvelope = &diEnvelope; 
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;  
 
// create the effect and get the interface to it 
lpdijoy->CreateEffect(GUID_Square,  // standard GUID 
                     &diEffect,      // where the data is
                     &lpdieffect,    // where to put interface pointer
                     NULL);          // no aggregation


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

// load the background
Load_Bitmap_File(&bitmap16bit, "MUSH_24.BMP");

// load in the four frames of the mushroom
for (index=0; index<4; index++)
    {
    // create mushroom bitmaps
    Create_Bitmap(&mushrooms[index],0,0,32,32,16);
    Load_Image_Bitmap16(&mushrooms[index],&bitmap16bit,index,0,BITMAP_EXTRACT_MODE_CELL);  
    } // end for index

// now create the bug blaster bob
Create_BOB(&blaster,0,0,32,32,3,
           BOB_ATTR_VISIBLE | BOB_ATTR_MULTI_ANIM | BOB_ATTR_ANIM_ONE_SHOT,
           DDSCAPS_SYSTEMMEMORY,0,16);

// load in the four frames of the mushroom
for (index=0; index<3; index++)
     Load_Frame_BOB16(&blaster,&bitmap16bit,index,index,1,BITMAP_EXTRACT_MODE_CELL);  

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

// set the animation sequences for bug blaster
Load_Animation_BOB(&blaster,0,5,blaster_anim);

// set up stating state of bug blaster
Set_Pos_BOB(&blaster,320, 400);
Set_Anim_Speed_BOB(&blaster,3);

// create mushroom playfield bitmap
Create_Bitmap(&playfield,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,16);
playfield.attr |= BITMAP_ATTR_LOADED;

// fill in the background
Load_Bitmap_File(&bitmap16bit, "GRASS_24.BMP");

// load the grass bitmap image
Load_Image_Bitmap16(&playfield,&bitmap16bit,0,0,BITMAP_EXTRACT_MODE_ABS);
Unload_Bitmap_File(&bitmap16bit);

// seed random number generator
srand(Start_Clock());

// create the random mushroom patch
for (index=0; index<50; index++)
    {
    // select a mushroom
    int mush = rand()%4;

    // set mushroom to random position
    mushrooms[mush].x = rand()%(SCREEN_WIDTH-32);
    mushrooms[mush].y = rand()%(SCREEN_HEIGHT-128);

    // now draw the mushroom into playfield
    Draw_Bitmap16(&mushrooms[mush], playfield.buffer, playfield.width*2,1);

    } // end for

// hide the mouse
if (!WINDOWED_APP)
   ShowCursor(FALSE);

// return success
return(1);

} // end Game_Init
Beispiel #25
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;
    }
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!");
}
 HRESULT _stdcall EnumDevices(DWORD a,LPDIENUMDEVICESCALLBACKW b,LPVOID c,DWORD d)
 {
     return RealInput->EnumDevices(a,b,c,d);
 }
Beispiel #28
0
// **if passed an existing DirectInputDevice which matches gGuid
//		unacquires it, and sets its cooperative level (reinitialize)
// **if the existing device does not match the passed gGuid, the existing device is released
// **if no device was passed or gGuid did not match
//		searches for the controller matching gGuid in connected and available devices
//		creates a DirectInputDevice
//		sets its data format
//		sets its cooperative level
//		for joysticks, calls EnumSetObjectsAxis for each axis
// GetInputDevice always leaves the returned device in an UNACQUIRED state.
bool GetInputDevice( HWND hWnd, LPDIRECTINPUTDEVICE8 &lpDirectInputDevice, GUID gGuid, DWORD dwDevType, DWORD dwCooperativeLevel )
{
	DebugWriteA("GetInputDevice: gGuid is {%08.8lX-%04.4hX-%04.4hX-%02.2X%02.2X-%02.2X%02.2X%02.2X%02.2X%02.2X%02.2X}\n", gGuid.Data1, gGuid.Data2, gGuid.Data3, gGuid.Data4[0], gGuid.Data4[1], gGuid.Data4[2], gGuid.Data4[3], gGuid.Data4[4], gGuid.Data4[5], gGuid.Data4[6], gGuid.Data4[7]);
	if( lpDirectInputDevice != NULL)
	{
		DIDEVICEINSTANCE didDev;
		didDev.dwSize = sizeof(DIDEVICEINSTANCE);
		lpDirectInputDevice->GetDeviceInfo( &didDev );

		if( didDev.guidInstance == gGuid )
		{	// we've already gotten this device; unacquire it and initialize
			DebugWriteA("GetInputDevice: already created, attempting to reinit\n");
			lpDirectInputDevice->Unacquire();
			lpDirectInputDevice->SetCooperativeLevel( hWnd, dwCooperativeLevel );
			return true;
		}
		else
			ReleaseDevice( lpDirectInputDevice );
	}

	HRESULT hResult;
	
	LPCDIDATAFORMAT ppDiDataFormat = NULL;
	bool Success = false;

	switch( LOBYTE(dwDevType) )
	{
	case DI8DEVTYPE_KEYBOARD:
		ppDiDataFormat = &c_dfDIKeyboard;
		break;

	case DI8DEVTYPE_MOUSE:
		ppDiDataFormat = &c_dfDIMouse2;
		break;

	//case DI8DEVTYPE_GAMEPAD:
	//case DI8DEVTYPE_JOYSTICK:
	//case DI8DEVTYPE_DRIVING:
	//case DI8DEVTYPE_1STPERSON:
	//case DI8DEVTYPE_FLIGHT:
	default: // assume everything else is a gamepad; probably not the best idea but it works
		ppDiDataFormat = &c_dfDIJoystick;
		break;
	}

	bool bDeviceAvailable = false;
		
	VOID* aRef[2] = { &gGuid, &bDeviceAvailable };
		
	// for each available device in our dwDevType category, run EnumIsDeviceAvailable with params "aRef"
	g_pDIHandle->EnumDevices( DI8DEVCLASS_ALL, EnumIsDeviceAvailable, (LPVOID)aRef, DIEDFL_ATTACHEDONLY );
		
	if( !bDeviceAvailable )
	{
		DebugWriteA("GetInputDevice: Device does not appear available\n");
		return false;
	}
		
	hResult = g_pDIHandle->CreateDevice( gGuid, &lpDirectInputDevice, NULL );
	
	if( SUCCEEDED( hResult ))
	{
		hResult = lpDirectInputDevice->SetDataFormat( ppDiDataFormat );
		hResult = lpDirectInputDevice->SetCooperativeLevel( hWnd, dwCooperativeLevel );
		
		Success = SUCCEEDED( hResult );
		if (!Success)
		{
			DebugWriteA("GetInputDevice: SetCooperativeLevel failed\n");
		}
	}
	else
		DebugWriteA("GetInputDevice: CreateDevice failed\n");

	if( Success && ( ppDiDataFormat == &c_dfDIJoystick ))
		lpDirectInputDevice->EnumObjects( EnumSetObjectsAxis, lpDirectInputDevice, DIDFT_AXIS );

	return Success;
}