SDL_hidapi_steam.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../../SDL_internal.h"
  19. #ifdef SDL_JOYSTICK_HIDAPI
  20. #include "SDL_hints.h"
  21. #include "SDL_events.h"
  22. #include "SDL_timer.h"
  23. #include "SDL_joystick.h"
  24. #include "SDL_gamecontroller.h"
  25. #include "../SDL_sysjoystick.h"
  26. #include "SDL_hidapijoystick_c.h"
  27. #ifdef SDL_JOYSTICK_HIDAPI_STEAM
  28. /*****************************************************************************************************/
  29. #include <stdint.h>
  30. typedef enum
  31. {
  32. false,
  33. true
  34. } bool;
  35. typedef uint32_t uint32;
  36. typedef uint64_t uint64;
  37. #include "steam/controller_constants.h"
  38. #include "steam/controller_structs.h"
  39. typedef struct SteamControllerStateInternal_t
  40. {
  41. // Controller Type for this Controller State
  42. uint32 eControllerType;
  43. // If packet num matches that on your prior call, then the controller state hasn't been changed since
  44. // your last call and there is no need to process it
  45. uint32 unPacketNum;
  46. // bit flags for each of the buttons
  47. uint64 ulButtons;
  48. // Left pad coordinates
  49. short sLeftPadX;
  50. short sLeftPadY;
  51. // Right pad coordinates
  52. short sRightPadX;
  53. short sRightPadY;
  54. // Center pad coordinates
  55. short sCenterPadX;
  56. short sCenterPadY;
  57. // Left analog stick coordinates
  58. short sLeftStickX;
  59. short sLeftStickY;
  60. // Right analog stick coordinates
  61. short sRightStickX;
  62. short sRightStickY;
  63. unsigned short sTriggerL;
  64. unsigned short sTriggerR;
  65. short sAccelX;
  66. short sAccelY;
  67. short sAccelZ;
  68. short sGyroX;
  69. short sGyroY;
  70. short sGyroZ;
  71. float sGyroQuatW;
  72. float sGyroQuatX;
  73. float sGyroQuatY;
  74. float sGyroQuatZ;
  75. short sGyroSteeringAngle;
  76. unsigned short sBatteryLevel;
  77. // Pressure sensor data.
  78. unsigned short sPressurePadLeft;
  79. unsigned short sPressurePadRight;
  80. unsigned short sPressureBumperLeft;
  81. unsigned short sPressureBumperRight;
  82. // Internal state data
  83. short sPrevLeftPad[2];
  84. short sPrevLeftStick[2];
  85. } SteamControllerStateInternal_t;
  86. /* Defines for ulButtons in SteamControllerStateInternal_t */
  87. #define STEAM_RIGHT_TRIGGER_MASK 0x00000001
  88. #define STEAM_LEFT_TRIGGER_MASK 0x00000002
  89. #define STEAM_RIGHT_BUMPER_MASK 0x00000004
  90. #define STEAM_LEFT_BUMPER_MASK 0x00000008
  91. #define STEAM_BUTTON_0_MASK 0x00000010 /* Y */
  92. #define STEAM_BUTTON_1_MASK 0x00000020 /* B */
  93. #define STEAM_BUTTON_2_MASK 0x00000040 /* X */
  94. #define STEAM_BUTTON_3_MASK 0x00000080 /* A */
  95. #define STEAM_TOUCH_0_MASK 0x00000100 /* DPAD UP */
  96. #define STEAM_TOUCH_1_MASK 0x00000200 /* DPAD RIGHT */
  97. #define STEAM_TOUCH_2_MASK 0x00000400 /* DPAD LEFT */
  98. #define STEAM_TOUCH_3_MASK 0x00000800 /* DPAD DOWN */
  99. #define STEAM_BUTTON_MENU_MASK 0x00001000 /* SELECT */
  100. #define STEAM_BUTTON_STEAM_MASK 0x00002000 /* GUIDE */
  101. #define STEAM_BUTTON_ESCAPE_MASK 0x00004000 /* START */
  102. #define STEAM_BUTTON_BACK_LEFT_MASK 0x00008000
  103. #define STEAM_BUTTON_BACK_RIGHT_MASK 0x00010000
  104. #define STEAM_BUTTON_LEFTPAD_CLICKED_MASK 0x00020000
  105. #define STEAM_BUTTON_RIGHTPAD_CLICKED_MASK 0x00040000
  106. #define STEAM_LEFTPAD_FINGERDOWN_MASK 0x00080000
  107. #define STEAM_RIGHTPAD_FINGERDOWN_MASK 0x00100000
  108. #define STEAM_JOYSTICK_BUTTON_MASK 0x00400000
  109. #define STEAM_LEFTPAD_AND_JOYSTICK_MASK 0x00800000
  110. // Look for report version 0x0001, type WIRELESS (3), length >= 1 byte
  111. #define D0G_IS_VALID_WIRELESS_EVENT(data, len) ((len) >= 5 && (data)[0] == 1 && (data)[1] == 0 && (data)[2] == 3 && (data)[3] >= 1)
  112. #define D0G_GET_WIRELESS_EVENT_TYPE(data) ((data)[4])
  113. #define D0G_WIRELESS_DISCONNECTED 1
  114. #define D0G_WIRELESS_ESTABLISHED 2
  115. #define D0G_WIRELESS_NEWLYPAIRED 3
  116. #define D0G_IS_WIRELESS_DISCONNECT(data, len) ( D0G_IS_VALID_WIRELESS_EVENT(data,len) && D0G_GET_WIRELESS_EVENT_TYPE(data) == D0G_WIRELESS_DISCONNECTED )
  117. #define MAX_REPORT_SEGMENT_PAYLOAD_SIZE 18
  118. /*
  119. * SteamControllerPacketAssembler has to be used when reading output repots from controllers.
  120. */
  121. typedef struct
  122. {
  123. uint8_t uBuffer[ MAX_REPORT_SEGMENT_PAYLOAD_SIZE * 8 + 1 ];
  124. int nExpectedSegmentNumber;
  125. bool bIsBle;
  126. } SteamControllerPacketAssembler;
  127. #undef clamp
  128. #define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val)))
  129. #undef offsetof
  130. #define offsetof(s,m) (size_t)&(((s *)0)->m)
  131. #ifdef DEBUG_STEAM_CONTROLLER
  132. #define DPRINTF(format, ...) printf(format, ##__VA_ARGS__)
  133. #define HEXDUMP(ptr, len) hexdump(ptr, len)
  134. #else
  135. #define DPRINTF(format, ...)
  136. #define HEXDUMP(ptr, len)
  137. #endif
  138. #define printf SDL_Log
  139. #define MAX_REPORT_SEGMENT_SIZE ( MAX_REPORT_SEGMENT_PAYLOAD_SIZE + 2 )
  140. #define CALC_REPORT_SEGMENT_NUM(index) ( ( index / MAX_REPORT_SEGMENT_PAYLOAD_SIZE ) & 0x07 )
  141. #define REPORT_SEGMENT_DATA_FLAG 0x80
  142. #define REPORT_SEGMENT_LAST_FLAG 0x40
  143. #define BLE_REPORT_NUMBER 0x03
  144. #define STEAMCONTROLLER_TRIGGER_MAX_ANALOG 26000
  145. // Enable mouse mode when using the Steam Controller locally
  146. #undef ENABLE_MOUSE_MODE
  147. // Wireless firmware quirk: the firmware intentionally signals "failure" when performing
  148. // SET_FEATURE / GET_FEATURE when it actually means "pending radio round-trip". The only
  149. // way to make SET_FEATURE / GET_FEATURE work is to loop several times with a sleep. If
  150. // it takes more than 50ms to get the response for SET_FEATURE / GET_FEATURE, we assume
  151. // that the controller has failed.
  152. #define RADIO_WORKAROUND_SLEEP_ATTEMPTS 50
  153. #define RADIO_WORKAROUND_SLEEP_DURATION_US 500
  154. // This was defined by experimentation. 2000 seemed to work but to give that extra bit of margin, set to 3ms.
  155. #define CONTROLLER_CONFIGURATION_DELAY_US 3000
  156. static uint8_t GetSegmentHeader( int nSegmentNumber, bool bLastPacket )
  157. {
  158. uint8_t header = REPORT_SEGMENT_DATA_FLAG;
  159. header |= nSegmentNumber;
  160. if ( bLastPacket )
  161. header |= REPORT_SEGMENT_LAST_FLAG;
  162. return header;
  163. }
  164. static void hexdump( const uint8_t *ptr, int len )
  165. {
  166. int i;
  167. for ( i = 0; i < len ; ++i )
  168. printf("%02x ", ptr[i]);
  169. printf("\n");
  170. }
  171. static void ResetSteamControllerPacketAssembler( SteamControllerPacketAssembler *pAssembler )
  172. {
  173. memset( pAssembler->uBuffer, 0, sizeof( pAssembler->uBuffer ) );
  174. pAssembler->nExpectedSegmentNumber = 0;
  175. }
  176. static void InitializeSteamControllerPacketAssembler( SteamControllerPacketAssembler *pAssembler )
  177. {
  178. /* We only support BLE devices right now */
  179. pAssembler->bIsBle = true;
  180. ResetSteamControllerPacketAssembler( pAssembler );
  181. }
  182. // Returns:
  183. // <0 on error
  184. // 0 on not ready
  185. // Complete packet size on completion
  186. static int WriteSegmentToSteamControllerPacketAssembler( SteamControllerPacketAssembler *pAssembler, const uint8_t *pSegment, int nSegmentLength )
  187. {
  188. if ( pAssembler->bIsBle )
  189. {
  190. HEXDUMP( pSegment, nSegmentLength );
  191. if ( pSegment[ 0 ] != BLE_REPORT_NUMBER )
  192. {
  193. // We may get keyboard/mouse input events until controller stops sending them
  194. return 0;
  195. }
  196. if ( nSegmentLength != MAX_REPORT_SEGMENT_SIZE )
  197. {
  198. printf( "Bad segment size! %d\n", (int)nSegmentLength );
  199. hexdump( pSegment, nSegmentLength );
  200. ResetSteamControllerPacketAssembler( pAssembler );
  201. return -1;
  202. }
  203. uint8_t uSegmentHeader = pSegment[ 1 ];
  204. DPRINTF("GOT PACKET HEADER = 0x%x\n", uSegmentHeader);
  205. if ( ( uSegmentHeader & REPORT_SEGMENT_DATA_FLAG ) == 0 )
  206. {
  207. // We get empty segments, just ignore them
  208. return 0;
  209. }
  210. int nSegmentNumber = uSegmentHeader & 0x07;
  211. if ( nSegmentNumber != pAssembler->nExpectedSegmentNumber )
  212. {
  213. ResetSteamControllerPacketAssembler( pAssembler );
  214. if ( nSegmentNumber )
  215. {
  216. // This happens occasionally
  217. DPRINTF("Bad segment number, got %d, expected %d\n",
  218. nSegmentNumber, pAssembler->nExpectedSegmentNumber );
  219. return -1;
  220. }
  221. }
  222. memcpy( pAssembler->uBuffer + nSegmentNumber * MAX_REPORT_SEGMENT_PAYLOAD_SIZE,
  223. pSegment + 2, // ignore header and report number
  224. MAX_REPORT_SEGMENT_PAYLOAD_SIZE );
  225. if ( uSegmentHeader & REPORT_SEGMENT_LAST_FLAG )
  226. {
  227. pAssembler->nExpectedSegmentNumber = 0;
  228. return ( nSegmentNumber + 1 ) * MAX_REPORT_SEGMENT_PAYLOAD_SIZE;
  229. }
  230. pAssembler->nExpectedSegmentNumber++;
  231. }
  232. else
  233. {
  234. // Just pass through
  235. memcpy( pAssembler->uBuffer,
  236. pSegment,
  237. nSegmentLength );
  238. return nSegmentLength;
  239. }
  240. return 0;
  241. }
  242. #define BLE_MAX_READ_RETRIES 8
  243. static int SetFeatureReport( hid_device *dev, unsigned char uBuffer[65], int nActualDataLen )
  244. {
  245. DPRINTF("SetFeatureReport %p %p %d\n", dev, uBuffer, nActualDataLen);
  246. int nRet = -1;
  247. bool bBle = true; // only wireless/BLE for now, though macOS could do wired in the future
  248. if ( bBle )
  249. {
  250. if ( nActualDataLen < 1 )
  251. return -1;
  252. int nSegmentNumber = 0;
  253. uint8_t uPacketBuffer[ MAX_REPORT_SEGMENT_SIZE ];
  254. // Skip report number in data
  255. unsigned char *pBufferPtr = uBuffer + 1;
  256. nActualDataLen--;
  257. while ( nActualDataLen > 0 )
  258. {
  259. int nBytesInPacket = nActualDataLen > MAX_REPORT_SEGMENT_PAYLOAD_SIZE ? MAX_REPORT_SEGMENT_PAYLOAD_SIZE : nActualDataLen;
  260. nActualDataLen -= nBytesInPacket;
  261. // Construct packet
  262. memset( uPacketBuffer, 0, sizeof( uPacketBuffer ) );
  263. uPacketBuffer[ 0 ] = BLE_REPORT_NUMBER;
  264. uPacketBuffer[ 1 ] = GetSegmentHeader( nSegmentNumber, nActualDataLen == 0 );
  265. memcpy( &uPacketBuffer[ 2 ], pBufferPtr, nBytesInPacket );
  266. pBufferPtr += nBytesInPacket;
  267. nSegmentNumber++;
  268. nRet = hid_send_feature_report( dev, uPacketBuffer, sizeof( uPacketBuffer ) );
  269. DPRINTF("SetFeatureReport() ret = %d\n", nRet);
  270. }
  271. }
  272. return nRet;
  273. }
  274. static int GetFeatureReport( hid_device *dev, unsigned char uBuffer[65] )
  275. {
  276. DPRINTF("GetFeatureReport( %p %p )\n", dev, uBuffer );
  277. int nRet = -1;
  278. bool bBle = true;
  279. if ( bBle )
  280. {
  281. SteamControllerPacketAssembler assembler;
  282. InitializeSteamControllerPacketAssembler( &assembler );
  283. int nRetries = 0;
  284. uint8_t uSegmentBuffer[ MAX_REPORT_SEGMENT_SIZE ];
  285. while( nRetries < BLE_MAX_READ_RETRIES )
  286. {
  287. memset( uSegmentBuffer, 0, sizeof( uSegmentBuffer ) );
  288. uSegmentBuffer[ 0 ] = BLE_REPORT_NUMBER;
  289. nRet = hid_get_feature_report( dev, uSegmentBuffer, sizeof( uSegmentBuffer ) );
  290. DPRINTF( "GetFeatureReport ble ret=%d\n", nRet );
  291. HEXDUMP( uSegmentBuffer, nRet );
  292. // Zero retry counter if we got data
  293. if ( nRet > 2 && ( uSegmentBuffer[ 1 ] & REPORT_SEGMENT_DATA_FLAG ) )
  294. nRetries = 0;
  295. else
  296. nRetries++;
  297. if ( nRet > 0 )
  298. {
  299. int nPacketLength = WriteSegmentToSteamControllerPacketAssembler( &assembler,
  300. uSegmentBuffer,
  301. nRet );
  302. if ( nPacketLength > 0 && nPacketLength < 65 )
  303. {
  304. // Leave space for "report number"
  305. uBuffer[ 0 ] = 0;
  306. memcpy( uBuffer + 1, assembler.uBuffer, nPacketLength );
  307. return nPacketLength;
  308. }
  309. }
  310. }
  311. printf("Could not get a full ble packet after %d retries\n", nRetries );
  312. return -1;
  313. }
  314. return nRet;
  315. }
  316. static int ReadResponse( hid_device *dev, uint8_t uBuffer[65], int nExpectedResponse )
  317. {
  318. DPRINTF("ReadResponse( %p %p %d )\n", dev, uBuffer, nExpectedResponse );
  319. int nRet = GetFeatureReport( dev, uBuffer );
  320. if ( nRet < 0 )
  321. return nRet;
  322. DPRINTF("ReadResponse got %d bytes of data: ", nRet );
  323. HEXDUMP( uBuffer, nRet );
  324. if ( uBuffer[1] != nExpectedResponse )
  325. return -1;
  326. return nRet;
  327. }
  328. //---------------------------------------------------------------------------
  329. // Reset steam controller (unmap buttons and pads) and re-fetch capability bits
  330. //---------------------------------------------------------------------------
  331. static bool ResetSteamController( hid_device *dev, bool bSuppressErrorSpew )
  332. {
  333. DPRINTF( "ResetSteamController hid=%p\n", dev );
  334. // Firmware quirk: Set Feature and Get Feature requests always require a 65-byte buffer.
  335. unsigned char buf[65];
  336. int res = -1;
  337. buf[0] = 0;
  338. buf[1] = ID_GET_ATTRIBUTES_VALUES;
  339. res = SetFeatureReport( dev, buf, 2 );
  340. if ( res < 0 )
  341. {
  342. if ( !bSuppressErrorSpew )
  343. printf( "GET_ATTRIBUTES_VALUES failed for controller %p\n", dev );
  344. return false;
  345. }
  346. // Retrieve GET_ATTRIBUTES_VALUES result
  347. // Wireless controller endpoints without a connected controller will return nAttrs == 0
  348. res = ReadResponse( dev, buf, ID_GET_ATTRIBUTES_VALUES );
  349. if ( res < 0 || buf[1] != ID_GET_ATTRIBUTES_VALUES )
  350. {
  351. HEXDUMP(buf, res);
  352. if ( !bSuppressErrorSpew )
  353. printf( "Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev );
  354. return false;
  355. }
  356. int nAttributesLength = buf[ 2 ];
  357. if ( nAttributesLength > res )
  358. {
  359. if ( !bSuppressErrorSpew )
  360. printf( "Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev );
  361. return false;
  362. }
  363. // Clear digital button mappings
  364. buf[0] = 0;
  365. buf[1] = ID_CLEAR_DIGITAL_MAPPINGS;
  366. res = SetFeatureReport( dev, buf, 2 );
  367. if ( res < 0 )
  368. {
  369. if ( !bSuppressErrorSpew )
  370. printf( "CLEAR_DIGITAL_MAPPINGS failed for controller %p\n", dev );
  371. return false;
  372. }
  373. // Reset the default settings
  374. memset( buf, 0, 65 );
  375. buf[1] = ID_LOAD_DEFAULT_SETTINGS;
  376. buf[2] = 0;
  377. res = SetFeatureReport( dev, buf, 3 );
  378. if ( res < 0 )
  379. {
  380. if ( !bSuppressErrorSpew )
  381. printf( "LOAD_DEFAULT_SETTINGS failed for controller %p\n", dev );
  382. return false;
  383. }
  384. // Apply custom settings - clear trackpad modes (cancel mouse emulation), etc
  385. int nSettings = 0;
  386. #define ADD_SETTING(SETTING, VALUE) \
  387. buf[3+nSettings*3] = SETTING; \
  388. buf[3+nSettings*3+1] = ((uint16_t)VALUE)&0xFF; \
  389. buf[3+nSettings*3+2] = ((uint16_t)VALUE)>>8; \
  390. ++nSettings;
  391. memset( buf, 0, 65 );
  392. buf[1] = ID_SET_SETTINGS_VALUES;
  393. ADD_SETTING( SETTING_WIRELESS_PACKET_VERSION, 2 );
  394. ADD_SETTING( SETTING_LEFT_TRACKPAD_MODE, TRACKPAD_NONE );
  395. #ifdef ENABLE_MOUSE_MODE
  396. ADD_SETTING( SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE );
  397. ADD_SETTING( SETTING_SMOOTH_ABSOLUTE_MOUSE, 1 );
  398. ADD_SETTING( SETTING_MOMENTUM_MAXIMUM_VELOCITY, 20000 ); // [0-20000] default 8000
  399. ADD_SETTING( SETTING_MOMENTUM_DECAY_AMMOUNT, 50 ); // [0-50] default 5
  400. #else
  401. ADD_SETTING( SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_NONE );
  402. ADD_SETTING( SETTING_SMOOTH_ABSOLUTE_MOUSE, 0 );
  403. #endif
  404. buf[2] = nSettings*3;
  405. res = SetFeatureReport( dev, buf, 3+nSettings*3 );
  406. if ( res < 0 )
  407. {
  408. if ( !bSuppressErrorSpew )
  409. printf( "SET_SETTINGS failed for controller %p\n", dev );
  410. return false;
  411. }
  412. #ifdef ENABLE_MOUSE_MODE
  413. // Wait for ID_CLEAR_DIGITAL_MAPPINGS to be processed on the controller
  414. bool bMappingsCleared = false;
  415. int iRetry;
  416. for ( iRetry = 0; iRetry < 2; ++iRetry )
  417. {
  418. memset( buf, 0, 65 );
  419. buf[1] = ID_GET_DIGITAL_MAPPINGS;
  420. buf[2] = 1; // one byte - requesting from index 0
  421. buf[3] = 0;
  422. res = SetFeatureReport( dev, buf, 4 );
  423. if ( res < 0 )
  424. {
  425. printf( "GET_DIGITAL_MAPPINGS failed for controller %p\n", dev );
  426. return false;
  427. }
  428. res = ReadResponse( dev, buf, ID_GET_DIGITAL_MAPPINGS );
  429. if ( res < 0 || buf[1] != ID_GET_DIGITAL_MAPPINGS )
  430. {
  431. printf( "Bad GET_DIGITAL_MAPPINGS response for controller %p\n", dev );
  432. return false;
  433. }
  434. // If the length of the digital mappings result is not 1 (index byte, no mappings) then clearing hasn't executed
  435. if ( buf[2] == 1 && buf[3] == 0xFF )
  436. {
  437. bMappingsCleared = true;
  438. break;
  439. }
  440. usleep( CONTROLLER_CONFIGURATION_DELAY_US );
  441. }
  442. if ( !bMappingsCleared && !bSuppressErrorSpew )
  443. {
  444. printf( "Warning: CLEAR_DIGITAL_MAPPINGS never completed for controller %p\n", dev );
  445. }
  446. // Set our new mappings
  447. memset( buf, 0, 65 );
  448. buf[1] = ID_SET_DIGITAL_MAPPINGS;
  449. buf[2] = 6; // 2 settings x 3 bytes
  450. buf[3] = IO_DIGITAL_BUTTON_RIGHT_TRIGGER;
  451. buf[4] = DEVICE_MOUSE;
  452. buf[5] = MOUSE_BTN_LEFT;
  453. buf[6] = IO_DIGITAL_BUTTON_LEFT_TRIGGER;
  454. buf[7] = DEVICE_MOUSE;
  455. buf[8] = MOUSE_BTN_RIGHT;
  456. res = SetFeatureReport( dev, buf, 9 );
  457. if ( res < 0 )
  458. {
  459. if ( !bSuppressErrorSpew )
  460. printf( "SET_DIGITAL_MAPPINGS failed for controller %p\n", dev );
  461. return false;
  462. }
  463. #endif // ENABLE_MOUSE_MODE
  464. return true;
  465. }
  466. //---------------------------------------------------------------------------
  467. // Read from a Steam Controller
  468. //---------------------------------------------------------------------------
  469. static int ReadSteamController( hid_device *dev, uint8_t *pData, int nDataSize )
  470. {
  471. memset( pData, 0, nDataSize );
  472. pData[ 0 ] = BLE_REPORT_NUMBER; // hid_read will also overwrite this with the same value, 0x03
  473. return hid_read( dev, pData, nDataSize );
  474. }
  475. //---------------------------------------------------------------------------
  476. // Close a Steam Controller
  477. //---------------------------------------------------------------------------
  478. static void CloseSteamController( hid_device *dev )
  479. {
  480. // Switch the Steam Controller back to lizard mode so it works with the OS
  481. unsigned char buf[65];
  482. int nSettings = 0;
  483. // Reset digital button mappings
  484. memset( buf, 0, 65 );
  485. buf[1] = ID_SET_DEFAULT_DIGITAL_MAPPINGS;
  486. SetFeatureReport( dev, buf, 2 );
  487. // Reset the default settings
  488. memset( buf, 0, 65 );
  489. buf[1] = ID_LOAD_DEFAULT_SETTINGS;
  490. buf[2] = 0;
  491. SetFeatureReport( dev, buf, 3 );
  492. // Reset mouse mode for lizard mode
  493. memset( buf, 0, 65 );
  494. buf[1] = ID_SET_SETTINGS_VALUES;
  495. ADD_SETTING( SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE );
  496. buf[2] = nSettings*3;
  497. SetFeatureReport( dev, buf, 3+nSettings*3 );
  498. }
  499. //---------------------------------------------------------------------------
  500. // Scale and clamp values to a range
  501. //---------------------------------------------------------------------------
  502. static float RemapValClamped( float val, float A, float B, float C, float D)
  503. {
  504. if ( A == B )
  505. {
  506. return ( val - B ) >= 0.0f ? D : C;
  507. }
  508. else
  509. {
  510. float cVal = (val - A) / (B - A);
  511. cVal = clamp( cVal, 0.0f, 1.0f );
  512. return C + (D - C) * cVal;
  513. }
  514. }
  515. //---------------------------------------------------------------------------
  516. // Rotate the pad coordinates
  517. //---------------------------------------------------------------------------
  518. static void RotatePad( int *pX, int *pY, float flAngleInRad )
  519. {
  520. short int origX = *pX, origY = *pY;
  521. *pX = (int)( SDL_cosf( flAngleInRad ) * origX - SDL_sinf( flAngleInRad ) * origY );
  522. *pY = (int)( SDL_sinf( flAngleInRad ) * origX + SDL_cosf( flAngleInRad ) * origY );
  523. }
  524. static void RotatePadShort( short *pX, short *pY, float flAngleInRad )
  525. {
  526. short int origX = *pX, origY = *pY;
  527. *pX = (short)( SDL_cosf( flAngleInRad ) * origX - SDL_sinf( flAngleInRad ) * origY );
  528. *pY = (short)( SDL_sinf( flAngleInRad ) * origX + SDL_cosf( flAngleInRad ) * origY );
  529. }
  530. //---------------------------------------------------------------------------
  531. // Format the first part of the state packet
  532. //---------------------------------------------------------------------------
  533. static void FormatStatePacketUntilGyro( SteamControllerStateInternal_t *pState, ValveControllerStatePacket_t *pStatePacket )
  534. {
  535. memset(pState, 0, offsetof(SteamControllerStateInternal_t, sBatteryLevel));
  536. //pState->eControllerType = m_eControllerType;
  537. pState->eControllerType = 2; // k_eControllerType_SteamController;
  538. pState->unPacketNum = pStatePacket->unPacketNum;
  539. // We have a chunk of trigger data in the packet format here, so zero it out afterwards
  540. memcpy(&pState->ulButtons, &pStatePacket->ButtonTriggerData.ulButtons, 8);
  541. pState->ulButtons &= ~0xFFFF000000LL;
  542. // The firmware uses this bit to tell us what kind of data is packed into the left two axises
  543. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK)
  544. {
  545. // Finger-down bit not set; "left pad" is actually trackpad
  546. pState->sLeftPadX = pState->sPrevLeftPad[0] = pStatePacket->sLeftPadX;
  547. pState->sLeftPadY = pState->sPrevLeftPad[1] = pStatePacket->sLeftPadY;
  548. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK)
  549. {
  550. // The controller is interleaving both stick and pad data, both are active
  551. pState->sLeftStickX = pState->sPrevLeftStick[0];
  552. pState->sLeftStickY = pState->sPrevLeftStick[1];
  553. }
  554. else
  555. {
  556. // The stick is not active
  557. pState->sPrevLeftStick[0] = 0;
  558. pState->sPrevLeftStick[1] = 0;
  559. }
  560. }
  561. else
  562. {
  563. // Finger-down bit not set; "left pad" is actually joystick
  564. // XXX there's a firmware bug where sometimes padX is 0 and padY is a large number (acutally the battery voltage)
  565. // If that happens skip this packet and report last frames stick
  566. /*
  567. if ( m_eControllerType == k_eControllerType_SteamControllerV2 && pStatePacket->sLeftPadY > 900 )
  568. {
  569. pState->sLeftStickX = pState->sPrevLeftStick[0];
  570. pState->sLeftStickY = pState->sPrevLeftStick[1];
  571. }
  572. else
  573. */
  574. {
  575. pState->sPrevLeftStick[0] = pState->sLeftStickX = pStatePacket->sLeftPadX;
  576. pState->sPrevLeftStick[1] = pState->sLeftStickY = pStatePacket->sLeftPadY;
  577. }
  578. /*
  579. if (m_eControllerType == k_eControllerType_SteamControllerV2)
  580. {
  581. UpdateV2JoystickCap(&state);
  582. }
  583. */
  584. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK)
  585. {
  586. // The controller is interleaving both stick and pad data, both are active
  587. pState->sLeftPadX = pState->sPrevLeftPad[0];
  588. pState->sLeftPadY = pState->sPrevLeftPad[1];
  589. }
  590. else
  591. {
  592. // The trackpad is not active
  593. pState->sPrevLeftPad[0] = 0;
  594. pState->sPrevLeftPad[1] = 0;
  595. // Old controllers send trackpad click for joystick button when trackpad is not active
  596. if (pState->ulButtons & STEAM_BUTTON_LEFTPAD_CLICKED_MASK)
  597. {
  598. pState->ulButtons &= ~STEAM_BUTTON_LEFTPAD_CLICKED_MASK;
  599. pState->ulButtons |= STEAM_JOYSTICK_BUTTON_MASK;
  600. }
  601. }
  602. }
  603. // Fingerdown bit indicates if the packed left axis data was joystick or pad,
  604. // but if we are interleaving both, the left finger is definitely on the pad.
  605. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK)
  606. pState->ulButtons |= STEAM_LEFTPAD_FINGERDOWN_MASK;
  607. pState->sRightPadX = pStatePacket->sRightPadX;
  608. pState->sRightPadY = pStatePacket->sRightPadY;
  609. int nLeftPadX = pState->sLeftPadX;
  610. int nLeftPadY = pState->sLeftPadY;
  611. int nRightPadX = pState->sRightPadX;
  612. int nRightPadY = pState->sRightPadY;
  613. // 15 degrees in rad
  614. const float flRotationAngle = 0.261799f;
  615. RotatePad(&nLeftPadX, &nLeftPadY, -flRotationAngle);
  616. RotatePad(&nRightPadX, &nRightPadY, flRotationAngle);
  617. int nPadOffset;
  618. if (pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK)
  619. nPadOffset = 1000;
  620. else
  621. nPadOffset = 0;
  622. pState->sLeftPadX = clamp(nLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  623. pState->sLeftPadY = clamp(nLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  624. nPadOffset = 0;
  625. if (pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK)
  626. nPadOffset = 1000;
  627. else
  628. nPadOffset = 0;
  629. pState->sRightPadX = clamp(nRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  630. pState->sRightPadY = clamp(nRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  631. pState->sTriggerL = (unsigned short)RemapValClamped( (pStatePacket->ButtonTriggerData.Triggers.nLeft << 7) | pStatePacket->ButtonTriggerData.Triggers.nLeft, 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 );
  632. pState->sTriggerR = (unsigned short)RemapValClamped( (pStatePacket->ButtonTriggerData.Triggers.nRight << 7) | pStatePacket->ButtonTriggerData.Triggers.nRight, 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 );
  633. }
  634. //---------------------------------------------------------------------------
  635. // Update Steam Controller state from a BLE data packet, returns true if it parsed data
  636. //---------------------------------------------------------------------------
  637. static bool UpdateBLESteamControllerState( const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState )
  638. {
  639. const float flRotationAngle = 0.261799f;
  640. uint32_t ucOptionDataMask;
  641. pState->unPacketNum++;
  642. ucOptionDataMask = ( *pData++ & 0xF0 );
  643. ucOptionDataMask |= (uint32_t)(*pData++) << 8;
  644. if ( ucOptionDataMask & k_EBLEButtonChunk1 )
  645. {
  646. memcpy( &pState->ulButtons, pData, 3 );
  647. pData += 3;
  648. }
  649. if ( ucOptionDataMask & k_EBLEButtonChunk2 )
  650. {
  651. // The middle 2 bytes of the button bits over the wire are triggers when over the wire and non-SC buttons in the internal controller state packet
  652. pState->sTriggerL = (unsigned short)RemapValClamped( ( pData[ 0 ] << 7 ) | pData[ 0 ], 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 );
  653. pState->sTriggerR = (unsigned short)RemapValClamped( ( pData[ 1 ] << 7 ) | pData[ 1 ], 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16 );
  654. pData += 2;
  655. }
  656. if ( ucOptionDataMask & k_EBLEButtonChunk3 )
  657. {
  658. uint8_t *pButtonByte = (uint8_t *)&pState->ulButtons;
  659. pButtonByte[ 5 ] = *pData++;
  660. pButtonByte[ 6 ] = *pData++;
  661. pButtonByte[ 7 ] = *pData++;
  662. }
  663. if ( ucOptionDataMask & k_EBLELeftJoystickChunk )
  664. {
  665. // This doesn't handle any of the special headcrab stuff for raw joystick which is OK for now since that FW doesn't support
  666. // this protocol yet either
  667. int nLength = sizeof( pState->sLeftStickX ) + sizeof( pState->sLeftStickY );
  668. memcpy( &pState->sLeftStickX, pData, nLength );
  669. pData += nLength;
  670. }
  671. if ( ucOptionDataMask & k_EBLELeftTrackpadChunk )
  672. {
  673. int nLength = sizeof( pState->sLeftPadX ) + sizeof( pState->sLeftPadY );
  674. int nPadOffset;
  675. memcpy( &pState->sLeftPadX, pData, nLength );
  676. if ( pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK )
  677. nPadOffset = 1000;
  678. else
  679. nPadOffset = 0;
  680. RotatePadShort( &pState->sLeftPadX, &pState->sLeftPadY, -flRotationAngle );
  681. pState->sLeftPadX = clamp( pState->sLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 );
  682. pState->sLeftPadY = clamp( pState->sLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 );
  683. pData += nLength;
  684. }
  685. if ( ucOptionDataMask & k_EBLERightTrackpadChunk )
  686. {
  687. int nLength = sizeof( pState->sRightPadX ) + sizeof( pState->sRightPadY );
  688. int nPadOffset = 0;
  689. memcpy( &pState->sRightPadX, pData, nLength );
  690. if ( pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK )
  691. nPadOffset = 1000;
  692. else
  693. nPadOffset = 0;
  694. RotatePadShort( &pState->sRightPadX, &pState->sRightPadY, flRotationAngle );
  695. pState->sRightPadX = clamp( pState->sRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 );
  696. pState->sRightPadY = clamp( pState->sRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16 );
  697. pData += nLength;
  698. }
  699. if ( ucOptionDataMask & k_EBLEIMUAccelChunk )
  700. {
  701. int nLength = sizeof( pState->sAccelX ) + sizeof( pState->sAccelY ) + sizeof( pState->sAccelZ );
  702. memcpy( &pState->sAccelX, pData, nLength );
  703. pData += nLength;
  704. }
  705. if ( ucOptionDataMask & k_EBLEIMUGyroChunk )
  706. {
  707. int nLength = sizeof( pState->sAccelX ) + sizeof( pState->sAccelY ) + sizeof( pState->sAccelZ );
  708. memcpy( &pState->sGyroX, pData, nLength );
  709. pData += nLength;
  710. }
  711. if ( ucOptionDataMask & k_EBLEIMUQuatChunk )
  712. {
  713. int nLength = sizeof( pState->sGyroQuatW ) + sizeof( pState->sGyroQuatX ) + sizeof( pState->sGyroQuatY ) + sizeof( pState->sGyroQuatZ );
  714. memcpy( &pState->sGyroQuatW, pData, nLength );
  715. pData += nLength;
  716. }
  717. return true;
  718. }
  719. //---------------------------------------------------------------------------
  720. // Update Steam Controller state from a data packet, returns true if it parsed data
  721. //---------------------------------------------------------------------------
  722. static bool UpdateSteamControllerState( const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState )
  723. {
  724. ValveInReport_t *pInReport = (ValveInReport_t*)pData;
  725. if ( pInReport->header.unReportVersion != k_ValveInReportMsgVersion )
  726. {
  727. if ( ( pData[ 0 ] & 0x0F ) == k_EBLEReportState )
  728. {
  729. return UpdateBLESteamControllerState( pData, nDataSize, pState );
  730. }
  731. return false;
  732. }
  733. if ( ( pInReport->header.ucType != ID_CONTROLLER_STATE ) &&
  734. ( pInReport->header.ucType != ID_CONTROLLER_BLE_STATE ) )
  735. {
  736. return false;
  737. }
  738. if ( pInReport->header.ucType == ID_CONTROLLER_STATE )
  739. {
  740. ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState;
  741. // No new data to process; indicate that we received a state packet, but otherwise do nothing.
  742. if ( pState->unPacketNum == pStatePacket->unPacketNum )
  743. return true;
  744. FormatStatePacketUntilGyro( pState, pStatePacket );
  745. pState->sAccelX = pStatePacket->sAccelX;
  746. pState->sAccelY = pStatePacket->sAccelY;
  747. pState->sAccelZ = pStatePacket->sAccelZ;
  748. pState->sGyroQuatW = pStatePacket->sGyroQuatW;
  749. pState->sGyroQuatX = pStatePacket->sGyroQuatX;
  750. pState->sGyroQuatY = pStatePacket->sGyroQuatY;
  751. pState->sGyroQuatZ = pStatePacket->sGyroQuatZ;
  752. pState->sGyroX = pStatePacket->sGyroX;
  753. pState->sGyroY = pStatePacket->sGyroY;
  754. pState->sGyroZ = pStatePacket->sGyroZ;
  755. }
  756. else if ( pInReport->header.ucType == ID_CONTROLLER_BLE_STATE )
  757. {
  758. ValveControllerBLEStatePacket_t *pBLEStatePacket = &pInReport->payload.controllerBLEState;
  759. ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState;
  760. // No new data to process; indicate that we received a state packet, but otherwise do nothing.
  761. if ( pState->unPacketNum == pStatePacket->unPacketNum )
  762. return true;
  763. FormatStatePacketUntilGyro( pState, pStatePacket );
  764. switch ( pBLEStatePacket->ucGyroDataType )
  765. {
  766. case 1:
  767. pState->sGyroQuatW = (( float ) pBLEStatePacket->sGyro[0]);
  768. pState->sGyroQuatX = (( float ) pBLEStatePacket->sGyro[1]);
  769. pState->sGyroQuatY = (( float ) pBLEStatePacket->sGyro[2]);
  770. pState->sGyroQuatZ = (( float ) pBLEStatePacket->sGyro[3]);
  771. break;
  772. case 2:
  773. pState->sAccelX = pBLEStatePacket->sGyro[0];
  774. pState->sAccelY = pBLEStatePacket->sGyro[1];
  775. pState->sAccelZ = pBLEStatePacket->sGyro[2];
  776. break;
  777. case 3:
  778. pState->sGyroX = pBLEStatePacket->sGyro[0];
  779. pState->sGyroY = pBLEStatePacket->sGyro[1];
  780. pState->sGyroZ = pBLEStatePacket->sGyro[2];
  781. break;
  782. default:
  783. break;
  784. }
  785. }
  786. return true;
  787. }
  788. /*****************************************************************************************************/
  789. typedef struct {
  790. SteamControllerPacketAssembler m_assembler;
  791. SteamControllerStateInternal_t m_state;
  792. SteamControllerStateInternal_t m_last_state;
  793. } SDL_DriverSteam_Context;
  794. static SDL_bool
  795. HIDAPI_DriverSteam_IsSupportedDevice(const char *name, SDL_GameControllerType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  796. {
  797. return SDL_IsJoystickSteamController(vendor_id, product_id);
  798. }
  799. static const char *
  800. HIDAPI_DriverSteam_GetDeviceName(Uint16 vendor_id, Uint16 product_id)
  801. {
  802. return "Steam Controller";
  803. }
  804. static SDL_bool
  805. HIDAPI_DriverSteam_InitDevice(SDL_HIDAPI_Device *device)
  806. {
  807. return HIDAPI_JoystickConnected(device, NULL, SDL_FALSE);
  808. }
  809. static int
  810. HIDAPI_DriverSteam_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id)
  811. {
  812. return -1;
  813. }
  814. static void
  815. HIDAPI_DriverSteam_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index)
  816. {
  817. }
  818. static SDL_bool
  819. HIDAPI_DriverSteam_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  820. {
  821. SDL_DriverSteam_Context *ctx;
  822. ctx = (SDL_DriverSteam_Context *)SDL_calloc(1, sizeof(*ctx));
  823. if (!ctx) {
  824. SDL_OutOfMemory();
  825. goto error;
  826. }
  827. device->context = ctx;
  828. device->dev = hid_open_path(device->path, 0);
  829. if (!device->dev) {
  830. SDL_SetError("Couldn't open %s", device->path);
  831. goto error;
  832. }
  833. if (!ResetSteamController(device->dev, false)) {
  834. goto error;
  835. }
  836. InitializeSteamControllerPacketAssembler(&ctx->m_assembler);
  837. /* Initialize the joystick capabilities */
  838. joystick->nbuttons = SDL_CONTROLLER_BUTTON_MAX;
  839. joystick->naxes = SDL_CONTROLLER_AXIS_MAX;
  840. return SDL_TRUE;
  841. error:
  842. if (device->dev) {
  843. hid_close(device->dev);
  844. device->dev = NULL;
  845. }
  846. if (device->context) {
  847. SDL_free(device->context);
  848. device->context = NULL;
  849. }
  850. return SDL_FALSE;
  851. }
  852. static int
  853. HIDAPI_DriverSteam_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  854. {
  855. /* You should use the full Steam Input API for rumble support */
  856. return SDL_Unsupported();
  857. }
  858. static int
  859. HIDAPI_DriverSteam_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  860. {
  861. /* You should use the full Steam Input API for LED support */
  862. return SDL_Unsupported();
  863. }
  864. static SDL_bool
  865. HIDAPI_DriverSteam_UpdateDevice(SDL_HIDAPI_Device *device)
  866. {
  867. SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context;
  868. SDL_Joystick *joystick = NULL;
  869. if (device->num_joysticks > 0) {
  870. joystick = SDL_JoystickFromInstanceID(device->joysticks[0]);
  871. }
  872. if (!joystick) {
  873. return SDL_FALSE;
  874. }
  875. for (;;)
  876. {
  877. uint8_t data[128];
  878. int r, nPacketLength;
  879. const Uint8 *pPacket;
  880. r = ReadSteamController(device->dev, data, sizeof(data));
  881. if (r == 0)
  882. {
  883. break;
  884. }
  885. nPacketLength = 0;
  886. if (r > 0) {
  887. nPacketLength = WriteSegmentToSteamControllerPacketAssembler(&ctx->m_assembler, data, r);
  888. }
  889. pPacket = ctx->m_assembler.uBuffer;
  890. if (nPacketLength > 0 && UpdateSteamControllerState(pPacket, nPacketLength, &ctx->m_state)) {
  891. if (ctx->m_state.ulButtons != ctx->m_last_state.ulButtons) {
  892. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_A,
  893. (ctx->m_state.ulButtons & STEAM_BUTTON_3_MASK) ? SDL_PRESSED : SDL_RELEASED);
  894. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_B,
  895. (ctx->m_state.ulButtons & STEAM_BUTTON_1_MASK) ? SDL_PRESSED : SDL_RELEASED);
  896. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_X,
  897. (ctx->m_state.ulButtons & STEAM_BUTTON_2_MASK) ? SDL_PRESSED : SDL_RELEASED);
  898. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_Y,
  899. (ctx->m_state.ulButtons & STEAM_BUTTON_0_MASK) ? SDL_PRESSED : SDL_RELEASED);
  900. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
  901. (ctx->m_state.ulButtons & STEAM_LEFT_BUMPER_MASK) ? SDL_PRESSED : SDL_RELEASED);
  902. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
  903. (ctx->m_state.ulButtons & STEAM_RIGHT_BUMPER_MASK) ? SDL_PRESSED : SDL_RELEASED);
  904. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_BACK,
  905. (ctx->m_state.ulButtons & STEAM_BUTTON_MENU_MASK) ? SDL_PRESSED : SDL_RELEASED);
  906. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_START,
  907. (ctx->m_state.ulButtons & STEAM_BUTTON_ESCAPE_MASK) ? SDL_PRESSED : SDL_RELEASED);
  908. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_GUIDE,
  909. (ctx->m_state.ulButtons & STEAM_BUTTON_STEAM_MASK) ? SDL_PRESSED : SDL_RELEASED);
  910. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_LEFTSTICK,
  911. (ctx->m_state.ulButtons & STEAM_JOYSTICK_BUTTON_MASK) ? SDL_PRESSED : SDL_RELEASED);
  912. }
  913. {
  914. /* Minimum distance from center of pad to register a direction */
  915. const int kPadDeadZone = 10000;
  916. /* Pad coordinates are like math grid coordinates: negative is bottom left */
  917. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP,
  918. (ctx->m_state.sLeftPadY > kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  919. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN,
  920. (ctx->m_state.sLeftPadY < -kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  921. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT,
  922. (ctx->m_state.sLeftPadX < -kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  923. SDL_PrivateJoystickButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
  924. (ctx->m_state.sLeftPadX > kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  925. }
  926. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERLEFT, (int)ctx->m_state.sTriggerL * 2 - 32768);
  927. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, (int)ctx->m_state.sTriggerR * 2 - 32768);
  928. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTX, ctx->m_state.sLeftStickX);
  929. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_LEFTY, ~ctx->m_state.sLeftStickY);
  930. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTX, ctx->m_state.sRightPadX);
  931. SDL_PrivateJoystickAxis(joystick, SDL_CONTROLLER_AXIS_RIGHTY, ~ctx->m_state.sRightPadY);
  932. ctx->m_last_state = ctx->m_state;
  933. }
  934. if (r <= 0) {
  935. /* Failed to read from controller */
  936. HIDAPI_JoystickDisconnected(device, device->joysticks[0], SDL_FALSE);
  937. return SDL_FALSE;
  938. }
  939. }
  940. return SDL_TRUE;
  941. }
  942. static void
  943. HIDAPI_DriverSteam_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  944. {
  945. CloseSteamController(device->dev);
  946. hid_close(device->dev);
  947. device->dev = NULL;
  948. SDL_free(device->context);
  949. device->context = NULL;
  950. }
  951. static void
  952. HIDAPI_DriverSteam_FreeDevice(SDL_HIDAPI_Device *device)
  953. {
  954. }
  955. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteam =
  956. {
  957. SDL_HINT_JOYSTICK_HIDAPI_STEAM,
  958. SDL_TRUE,
  959. HIDAPI_DriverSteam_IsSupportedDevice,
  960. HIDAPI_DriverSteam_GetDeviceName,
  961. HIDAPI_DriverSteam_InitDevice,
  962. HIDAPI_DriverSteam_GetDevicePlayerIndex,
  963. HIDAPI_DriverSteam_SetDevicePlayerIndex,
  964. HIDAPI_DriverSteam_UpdateDevice,
  965. HIDAPI_DriverSteam_OpenJoystick,
  966. HIDAPI_DriverSteam_RumbleJoystick,
  967. HIDAPI_DriverSteam_SetJoystickLED,
  968. HIDAPI_DriverSteam_CloseJoystick,
  969. HIDAPI_DriverSteam_FreeDevice,
  970. NULL
  971. };
  972. #endif /* SDL_JOYSTICK_HIDAPI_STEAM */
  973. #endif /* SDL_JOYSTICK_HIDAPI */
  974. /* vi: set ts=4 sw=4 expandtab: */