SDL_rawinputjoystick.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 2019 Sam Lantinga <slouken@libsdl.org>
  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. /*
  19. RAWINPUT Joystick API for better handling XInput-capable devices on Windows.
  20. XInput is limited to 4 devices.
  21. Windows.Gaming.Input does not get inputs from XBox One controllers when not in the foreground.
  22. DirectInput does not get inputs from XBox One controllers when not in the foreground, nor rumble or accurate triggers.
  23. RawInput does not get rumble or accurate triggers.
  24. So, combine them as best we can!
  25. */
  26. #include "../../SDL_internal.h"
  27. #if SDL_JOYSTICK_RAWINPUT
  28. #include "SDL_assert.h"
  29. #include "SDL_endian.h"
  30. #include "SDL_events.h"
  31. #include "SDL_hints.h"
  32. #include "SDL_timer.h"
  33. #include "../usb_ids.h"
  34. #include "../SDL_sysjoystick.h"
  35. #include "../../core/windows/SDL_windows.h"
  36. #include "../../core/windows/SDL_hid.h"
  37. #include "../hidapi/SDL_hidapijoystick_c.h"
  38. #define SDL_JOYSTICK_RAWINPUT_XINPUT
  39. #ifdef SDL_WINDOWS10_SDK
  40. #define SDL_JOYSTICK_RAWINPUT_WGI
  41. #endif
  42. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  43. #include "../../core/windows/SDL_xinput.h"
  44. #endif
  45. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  46. #include "../../core/windows/SDL_windows.h"
  47. typedef struct WindowsGamingInputGamepadState WindowsGamingInputGamepadState;
  48. #define GamepadButtons_GUIDE 0x40000000
  49. #define COBJMACROS
  50. #include "windows.gaming.input.h"
  51. #endif
  52. #if defined(SDL_JOYSTICK_RAWINPUT_XINPUT) || defined(SDL_JOYSTICK_RAWINPUT_WGI)
  53. #define SDL_JOYSTICK_RAWINPUT_MATCHING
  54. #endif
  55. /*#define DEBUG_RAWINPUT*/
  56. #ifndef RIDEV_EXINPUTSINK
  57. #define RIDEV_EXINPUTSINK 0x00001000
  58. #define RIDEV_DEVNOTIFY 0x00002000
  59. #endif
  60. #ifndef WM_INPUT_DEVICE_CHANGE
  61. #define WM_INPUT_DEVICE_CHANGE 0x00FE
  62. #endif
  63. #ifndef WM_INPUT
  64. #define WM_INPUT 0x00FF
  65. #endif
  66. #ifndef GIDC_ARRIVAL
  67. #define GIDC_ARRIVAL 1
  68. #define GIDC_REMOVAL 2
  69. #endif
  70. /* external variables referenced. */
  71. extern HWND SDL_HelperWindow;
  72. static SDL_bool SDL_RAWINPUT_inited = SDL_FALSE;
  73. static int SDL_RAWINPUT_numjoysticks = 0;
  74. static void RAWINPUT_JoystickClose(SDL_Joystick *joystick);
  75. typedef struct _SDL_RAWINPUT_Device
  76. {
  77. SDL_atomic_t refcount;
  78. char *name;
  79. Uint16 vendor_id;
  80. Uint16 product_id;
  81. Uint16 version;
  82. SDL_JoystickGUID guid;
  83. SDL_bool is_xinput;
  84. PHIDP_PREPARSED_DATA preparsed_data;
  85. HANDLE hDevice;
  86. SDL_Joystick *joystick;
  87. SDL_JoystickID joystick_id;
  88. struct _SDL_RAWINPUT_Device *next;
  89. } SDL_RAWINPUT_Device;
  90. struct joystick_hwdata
  91. {
  92. SDL_bool is_xinput;
  93. PHIDP_PREPARSED_DATA preparsed_data;
  94. ULONG max_data_length;
  95. HIDP_DATA *data;
  96. USHORT *button_indices;
  97. USHORT *axis_indices;
  98. USHORT *hat_indices;
  99. SDL_bool guide_hack;
  100. SDL_bool trigger_hack;
  101. USHORT trigger_hack_index;
  102. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  103. Uint32 match_state; /* Low 16 bits for button states, high 16 for 4 4bit axes */
  104. Uint32 last_state_packet;
  105. #endif
  106. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  107. SDL_bool xinput_enabled;
  108. SDL_bool xinput_correlated;
  109. Uint8 xinput_correlation_id;
  110. Uint8 xinput_correlation_count;
  111. Uint8 xinput_uncorrelate_count;
  112. Uint8 xinput_slot;
  113. #endif
  114. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  115. SDL_bool wgi_correlated;
  116. Uint8 wgi_correlation_id;
  117. Uint8 wgi_correlation_count;
  118. Uint8 wgi_uncorrelate_count;
  119. WindowsGamingInputGamepadState *wgi_slot;
  120. #endif
  121. SDL_RAWINPUT_Device *device;
  122. };
  123. typedef struct joystick_hwdata RAWINPUT_DeviceContext;
  124. SDL_RAWINPUT_Device *SDL_RAWINPUT_devices;
  125. static const Uint16 subscribed_devices[] = {
  126. USB_USAGE_GENERIC_GAMEPAD,
  127. /* Don't need Joystick for any devices we're handling here (XInput-capable)
  128. USB_USAGE_GENERIC_JOYSTICK,
  129. USB_USAGE_GENERIC_MULTIAXISCONTROLLER,
  130. */
  131. };
  132. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  133. static struct {
  134. Uint32 last_state_packet;
  135. SDL_Joystick *joystick;
  136. SDL_Joystick *last_joystick;
  137. } guide_button_candidate;
  138. typedef struct WindowsMatchState {
  139. SHORT match_axes[4];
  140. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  141. WORD xinput_buttons;
  142. #endif
  143. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  144. Uint32 wgi_buttons;
  145. #endif
  146. SDL_bool any_data;
  147. } WindowsMatchState;
  148. static void RAWINPUT_FillMatchState(WindowsMatchState *state, Uint32 match_state)
  149. {
  150. int ii;
  151. state->any_data = SDL_FALSE;
  152. /* SHORT state->match_axes[4] = {
  153. (match_state & 0x000F0000) >> 4,
  154. (match_state & 0x00F00000) >> 8,
  155. (match_state & 0x0F000000) >> 12,
  156. (match_state & 0xF0000000) >> 16,
  157. }; */
  158. for (ii = 0; ii < 4; ii++) {
  159. state->match_axes[ii] = (match_state & (0x000F0000 << (ii * 4))) >> (4 + ii * 4);
  160. if ((Uint32)(state->match_axes[ii] + 0x1000) > 0x2000) { /* match_state bit is not 0xF, 0x1, or 0x2 */
  161. state->any_data = SDL_TRUE;
  162. }
  163. }
  164. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  165. /* Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less */
  166. #define XInputAxesMatch(gamepad) (\
  167. (Uint32)(gamepad.sThumbLX - state->match_axes[0] + 0x1000) <= 0x2fff && \
  168. (Uint32)(~gamepad.sThumbLY - state->match_axes[1] + 0x1000) <= 0x2fff && \
  169. (Uint32)(gamepad.sThumbRX - state->match_axes[2] + 0x1000) <= 0x2fff && \
  170. (Uint32)(~gamepad.sThumbRY - state->match_axes[3] + 0x1000) <= 0x2fff)
  171. /* Explicit
  172. #define XInputAxesMatch(gamepad) (\
  173. SDL_abs((Sint8)((gamepad.sThumbLX & 0xF000) >> 8) - ((match_state & 0x000F0000) >> 12)) <= 0x10 && \
  174. SDL_abs((Sint8)((~gamepad.sThumbLY & 0xF000) >> 8) - ((match_state & 0x00F00000) >> 16)) <= 0x10 && \
  175. SDL_abs((Sint8)((gamepad.sThumbRX & 0xF000) >> 8) - ((match_state & 0x0F000000) >> 20)) <= 0x10 && \
  176. SDL_abs((Sint8)((~gamepad.sThumbRY & 0xF000) >> 8) - ((match_state & 0xF0000000) >> 24)) <= 0x10) */
  177. state->xinput_buttons =
  178. /* Bitwise map .RLDUWVQTS.KYXBA -> YXBA..WVQTKSRLDU */
  179. match_state << 12 | (match_state & 0x0780) >> 1 | (match_state & 0x0010) << 1 | (match_state & 0x0040) >> 2 | (match_state & 0x7800) >> 11;
  180. /* Explicit
  181. ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? XINPUT_GAMEPAD_A : 0) |
  182. ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? XINPUT_GAMEPAD_B : 0) |
  183. ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? XINPUT_GAMEPAD_X : 0) |
  184. ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? XINPUT_GAMEPAD_Y : 0) |
  185. ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? XINPUT_GAMEPAD_BACK : 0) |
  186. ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? XINPUT_GAMEPAD_START : 0) |
  187. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? XINPUT_GAMEPAD_LEFT_THUMB : 0) |
  188. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? XINPUT_GAMEPAD_RIGHT_THUMB: 0) |
  189. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? XINPUT_GAMEPAD_LEFT_SHOULDER : 0) |
  190. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? XINPUT_GAMEPAD_RIGHT_SHOULDER : 0) |
  191. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? XINPUT_GAMEPAD_DPAD_UP : 0) |
  192. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? XINPUT_GAMEPAD_DPAD_DOWN : 0) |
  193. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? XINPUT_GAMEPAD_DPAD_LEFT : 0) |
  194. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? XINPUT_GAMEPAD_DPAD_RIGHT : 0);
  195. */
  196. if (state->xinput_buttons)
  197. state->any_data = SDL_TRUE;
  198. #endif
  199. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  200. /* Match axes by checking if the distance between the high 4 bits of axis and the 4 bits from match_state is 1 or less */
  201. #define WindowsGamingInputAxesMatch(gamepad) (\
  202. (Uint16)(((Sint16)(gamepad.LeftThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[0] + 0x1000) <= 0x2fff && \
  203. (Uint16)((~(Sint16)(gamepad.LeftThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[1] + 0x1000) <= 0x2fff && \
  204. (Uint16)(((Sint16)(gamepad.RightThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[2] + 0x1000) <= 0x2fff && \
  205. (Uint16)((~(Sint16)(gamepad.RightThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[3] + 0x1000) <= 0x2fff)
  206. state->wgi_buttons =
  207. /* Bitwise map .RLD UWVQ TS.K YXBA -> ..QT WVRL DUYX BAKS */
  208. /* RStick/LStick (QT) RShould/LShould (WV) DPad R/L/D/U YXBA bac(K) (S)tart */
  209. (match_state & 0x0180) << 5 | (match_state & 0x0600) << 1 | (match_state & 0x7800) >> 5 | (match_state & 0x000F) << 2 | (match_state & 0x0010) >> 3 | (match_state & 0x0040) >> 6;
  210. /* Explicit
  211. ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? GamepadButtons_A : 0) |
  212. ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? GamepadButtons_B : 0) |
  213. ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? GamepadButtons_X : 0) |
  214. ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? GamepadButtons_Y : 0) |
  215. ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? GamepadButtons_View : 0) |
  216. ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? GamepadButtons_Menu : 0) |
  217. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? GamepadButtons_LeftThumbstick : 0) |
  218. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? GamepadButtons_RightThumbstick: 0) |
  219. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? GamepadButtons_LeftShoulder: 0) |
  220. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? GamepadButtons_RightShoulder: 0) |
  221. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? GamepadButtons_DPadUp : 0) |
  222. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? GamepadButtons_DPadDown : 0) |
  223. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? GamepadButtons_DPadLeft : 0) |
  224. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? GamepadButtons_DPadRight : 0); */
  225. if (state->wgi_buttons)
  226. state->any_data = SDL_TRUE;
  227. #endif
  228. }
  229. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  230. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  231. static struct {
  232. XINPUT_STATE_EX state;
  233. SDL_bool connected; /* Currently has an active XInput device */
  234. SDL_bool used; /* Is currently mapped to an SDL device */
  235. Uint8 correlation_id;
  236. } xinput_state[XUSER_MAX_COUNT];
  237. static SDL_bool xinput_device_change = SDL_TRUE;
  238. static SDL_bool xinput_state_dirty = SDL_TRUE;
  239. static void
  240. RAWINPUT_UpdateXInput()
  241. {
  242. DWORD user_index;
  243. if (xinput_device_change) {
  244. for (user_index = 0; user_index < XUSER_MAX_COUNT; user_index++) {
  245. XINPUT_CAPABILITIES capabilities;
  246. xinput_state[user_index].connected = (XINPUTGETCAPABILITIES(user_index, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS) ? SDL_TRUE : SDL_FALSE;
  247. }
  248. xinput_device_change = SDL_FALSE;
  249. xinput_state_dirty = SDL_TRUE;
  250. }
  251. if (xinput_state_dirty) {
  252. xinput_state_dirty = SDL_FALSE;
  253. for (user_index = 0; user_index < SDL_arraysize(xinput_state); ++user_index) {
  254. if (xinput_state[user_index].connected) {
  255. if (XINPUTGETSTATE(user_index, &xinput_state[user_index].state) != ERROR_SUCCESS) {
  256. xinput_state[user_index].connected = SDL_FALSE;
  257. }
  258. }
  259. }
  260. }
  261. }
  262. static void
  263. RAWINPUT_MarkXInputSlotUsed(Uint8 xinput_slot)
  264. {
  265. if (xinput_slot != XUSER_INDEX_ANY) {
  266. xinput_state[xinput_slot].used = SDL_TRUE;
  267. }
  268. }
  269. static void
  270. RAWINPUT_MarkXInputSlotFree(Uint8 xinput_slot)
  271. {
  272. if (xinput_slot != XUSER_INDEX_ANY) {
  273. xinput_state[xinput_slot].used = SDL_FALSE;
  274. }
  275. }
  276. static SDL_bool
  277. RAWINPUT_MissingXInputSlot()
  278. {
  279. int ii;
  280. for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) {
  281. if (xinput_state[ii].connected && !xinput_state[ii].used) {
  282. return SDL_TRUE;
  283. }
  284. }
  285. return SDL_FALSE;
  286. }
  287. static SDL_bool
  288. RAWINPUT_XInputSlotMatches(const WindowsMatchState *state, Uint8 slot_idx)
  289. {
  290. if (xinput_state[slot_idx].connected) {
  291. WORD xinput_buttons = xinput_state[slot_idx].state.Gamepad.wButtons;
  292. if ((xinput_buttons & ~XINPUT_GAMEPAD_GUIDE) == state->xinput_buttons && XInputAxesMatch(xinput_state[slot_idx].state.Gamepad)) {
  293. return SDL_TRUE;
  294. }
  295. }
  296. return SDL_FALSE;
  297. }
  298. static SDL_bool
  299. RAWINPUT_GuessXInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, Uint8 *slot_idx)
  300. {
  301. int user_index;
  302. int match_count;
  303. *slot_idx = 0;
  304. match_count = 0;
  305. for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) {
  306. if (!xinput_state[user_index].used && RAWINPUT_XInputSlotMatches(state, user_index)) {
  307. ++match_count;
  308. *slot_idx = (Uint8)user_index;
  309. /* Incrementing correlation_id for any match, as negative evidence for others being correlated */
  310. *correlation_id = ++xinput_state[user_index].correlation_id;
  311. }
  312. }
  313. /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched.
  314. Note that we're still invalidating *other* potential correlations if we have more than one match or we have no
  315. data. */
  316. if (match_count == 1 && state->any_data) {
  317. return SDL_TRUE;
  318. }
  319. return SDL_FALSE;
  320. }
  321. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  322. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  323. typedef struct WindowsGamingInputGamepadState {
  324. __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  325. struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state;
  326. RAWINPUT_DeviceContext *correlated_context;
  327. SDL_bool used; /* Is currently mapped to an SDL device */
  328. SDL_bool connected; /* Just used during update to track disconnected */
  329. Uint8 correlation_id;
  330. struct __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration;
  331. } WindowsGamingInputGamepadState;
  332. static struct {
  333. WindowsGamingInputGamepadState **per_gamepad;
  334. int per_gamepad_count;
  335. SDL_bool initialized;
  336. SDL_bool dirty;
  337. SDL_bool need_device_list_update;
  338. int ref_count;
  339. __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics;
  340. } wgi_state;
  341. static void
  342. RAWINPUT_MarkWindowsGamingInputSlotUsed(WindowsGamingInputGamepadState *wgi_slot, RAWINPUT_DeviceContext *ctx)
  343. {
  344. wgi_slot->used = SDL_TRUE;
  345. wgi_slot->correlated_context = ctx;
  346. }
  347. static void
  348. RAWINPUT_MarkWindowsGamingInputSlotFree(WindowsGamingInputGamepadState *wgi_slot)
  349. {
  350. wgi_slot->used = SDL_FALSE;
  351. wgi_slot->correlated_context = NULL;
  352. }
  353. static SDL_bool
  354. RAWINPUT_MissingWindowsGamingInputSlot()
  355. {
  356. int ii;
  357. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  358. if (!wgi_state.per_gamepad[ii]->used) {
  359. return SDL_TRUE;
  360. }
  361. }
  362. return SDL_FALSE;
  363. }
  364. static void
  365. RAWINPUT_UpdateWindowsGamingInput()
  366. {
  367. int ii;
  368. if (!wgi_state.gamepad_statics)
  369. return;
  370. if (!wgi_state.dirty)
  371. return;
  372. wgi_state.dirty = SDL_FALSE;
  373. if (wgi_state.need_device_list_update) {
  374. wgi_state.need_device_list_update = SDL_FALSE;
  375. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  376. wgi_state.per_gamepad[ii]->connected = SDL_FALSE;
  377. }
  378. HRESULT hr;
  379. __FIVectorView_1_Windows__CGaming__CInput__CGamepad *gamepads;
  380. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_get_Gamepads(wgi_state.gamepad_statics, &gamepads);
  381. if (SUCCEEDED(hr)) {
  382. unsigned int num_gamepads;
  383. hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_get_Size(gamepads, &num_gamepads);
  384. if (SUCCEEDED(hr)) {
  385. unsigned int i;
  386. for (i = 0; i < num_gamepads; ++i) {
  387. __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  388. hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, i, &gamepad);
  389. if (SUCCEEDED(hr)) {
  390. SDL_bool found = SDL_FALSE;
  391. int jj;
  392. for (jj = 0; jj < wgi_state.per_gamepad_count ; jj++) {
  393. if (wgi_state.per_gamepad[jj]->gamepad == gamepad) {
  394. found = SDL_TRUE;
  395. wgi_state.per_gamepad[jj]->connected = SDL_TRUE;
  396. break;
  397. }
  398. }
  399. if (!found) {
  400. /* New device, add it */
  401. wgi_state.per_gamepad_count++;
  402. wgi_state.per_gamepad = SDL_realloc(wgi_state.per_gamepad, sizeof(wgi_state.per_gamepad[0]) * wgi_state.per_gamepad_count);
  403. if (!wgi_state.per_gamepad) {
  404. SDL_OutOfMemory();
  405. return;
  406. }
  407. WindowsGamingInputGamepadState *gamepad_state = SDL_calloc(1, sizeof(*gamepad_state));
  408. if (!gamepad_state) {
  409. SDL_OutOfMemory();
  410. return;
  411. }
  412. wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1] = gamepad_state;
  413. gamepad_state->gamepad = gamepad;
  414. gamepad_state->connected = SDL_TRUE;
  415. } else {
  416. /* Already tracked */
  417. __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad);
  418. }
  419. }
  420. }
  421. for (ii = wgi_state.per_gamepad_count - 1; ii >= 0; ii--) {
  422. WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii];
  423. if (!gamepad_state->connected) {
  424. /* Device missing, must be disconnected */
  425. if (gamepad_state->correlated_context) {
  426. gamepad_state->correlated_context->wgi_correlated = SDL_FALSE;
  427. gamepad_state->correlated_context->wgi_slot = NULL;
  428. }
  429. __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad_state->gamepad);
  430. SDL_free(gamepad_state);
  431. wgi_state.per_gamepad[ii] = wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1];
  432. --wgi_state.per_gamepad_count;
  433. }
  434. }
  435. }
  436. __FIVectorView_1_Windows__CGaming__CInput__CGamepad_Release(gamepads);
  437. }
  438. } /* need_device_list_update */
  439. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  440. HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(wgi_state.per_gamepad[ii]->gamepad, &wgi_state.per_gamepad[ii]->state);
  441. if (!SUCCEEDED(hr)) {
  442. wgi_state.per_gamepad[ii]->connected = SDL_FALSE; /* Not used by anything, currently */
  443. }
  444. }
  445. }
  446. static void
  447. RAWINPUT_InitWindowsGamingInput(RAWINPUT_DeviceContext *ctx)
  448. {
  449. wgi_state.need_device_list_update = SDL_TRUE;
  450. wgi_state.ref_count++;
  451. if (!wgi_state.initialized) {
  452. /* I think this takes care of RoInitialize() in a way that is compatible with the rest of SDL */
  453. if (FAILED(WIN_CoInitialize())) {
  454. return;
  455. }
  456. wgi_state.initialized = SDL_TRUE;
  457. wgi_state.dirty = SDL_TRUE;
  458. static const IID SDL_IID_IGamepadStatics = { 0x8BBCE529, 0xD49C, 0x39E9, { 0x95, 0x60, 0xE4, 0x7D, 0xDE, 0x96, 0xB7, 0xC8 } };
  459. HRESULT hr;
  460. HMODULE hModule = LoadLibraryA("combase.dll");
  461. if (hModule != NULL) {
  462. typedef HRESULT (WINAPI *WindowsCreateString_t)(PCNZWCH sourceString, UINT32 length, HSTRING* string);
  463. typedef HRESULT (WINAPI *WindowsDeleteString_t)(HSTRING string);
  464. typedef HRESULT (WINAPI *RoGetActivationFactory_t)(HSTRING activatableClassId, REFIID iid, void** factory);
  465. WindowsCreateString_t WindowsCreateStringFunc = (WindowsCreateString_t)GetProcAddress(hModule, "WindowsCreateString");
  466. WindowsDeleteString_t WindowsDeleteStringFunc = (WindowsDeleteString_t)GetProcAddress(hModule, "WindowsDeleteString");
  467. RoGetActivationFactory_t RoGetActivationFactoryFunc = (RoGetActivationFactory_t)GetProcAddress(hModule, "RoGetActivationFactory");
  468. if (WindowsCreateStringFunc && WindowsDeleteStringFunc && RoGetActivationFactoryFunc) {
  469. LPTSTR pNamespace = L"Windows.Gaming.Input.Gamepad";
  470. HSTRING hNamespaceString;
  471. hr = WindowsCreateStringFunc(pNamespace, SDL_wcslen(pNamespace), &hNamespaceString);
  472. if (SUCCEEDED(hr)) {
  473. RoGetActivationFactoryFunc(hNamespaceString, &SDL_IID_IGamepadStatics, &wgi_state.gamepad_statics);
  474. WindowsDeleteStringFunc(hNamespaceString);
  475. }
  476. }
  477. FreeLibrary(hModule);
  478. }
  479. }
  480. }
  481. static SDL_bool
  482. RAWINPUT_WindowsGamingInputSlotMatches(const WindowsMatchState *state, WindowsGamingInputGamepadState *slot)
  483. {
  484. Uint32 wgi_buttons = slot->state.Buttons;
  485. if ((wgi_buttons & 0x3FFF) == state->wgi_buttons && WindowsGamingInputAxesMatch(slot->state)) {
  486. return SDL_TRUE;
  487. }
  488. return SDL_FALSE;
  489. }
  490. static SDL_bool
  491. RAWINPUT_GuessWindowsGamingInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, WindowsGamingInputGamepadState **slot)
  492. {
  493. int match_count;
  494. match_count = 0;
  495. for (int user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) {
  496. WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[user_index];
  497. if (RAWINPUT_WindowsGamingInputSlotMatches(state, gamepad_state)) {
  498. ++match_count;
  499. *slot = gamepad_state;
  500. /* Incrementing correlation_id for any match, as negative evidence for others being correlated */
  501. *correlation_id = ++gamepad_state->correlation_id;
  502. }
  503. }
  504. /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched.
  505. Note that we're still invalidating *other* potential correlations if we have more than one match or we have no
  506. data. */
  507. if (match_count == 1 && state->any_data) {
  508. return SDL_TRUE;
  509. }
  510. return SDL_FALSE;
  511. }
  512. static void
  513. RAWINPUT_QuitWindowsGamingInput(RAWINPUT_DeviceContext *ctx)
  514. {
  515. wgi_state.need_device_list_update = SDL_TRUE;
  516. --wgi_state.ref_count;
  517. if (!wgi_state.ref_count && wgi_state.initialized) {
  518. for (int ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  519. __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(wgi_state.per_gamepad[ii]->gamepad);
  520. }
  521. if (wgi_state.per_gamepad) {
  522. SDL_free(wgi_state.per_gamepad);
  523. wgi_state.per_gamepad = NULL;
  524. }
  525. wgi_state.per_gamepad_count = 0;
  526. if (wgi_state.gamepad_statics) {
  527. __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(wgi_state.gamepad_statics);
  528. wgi_state.gamepad_statics = NULL;
  529. }
  530. WIN_CoUninitialize();
  531. wgi_state.initialized = SDL_FALSE;
  532. }
  533. }
  534. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  535. /* Most of the time the raw input messages will get dispatched in the main event loop,
  536. * but sometimes we want to get any pending device change messages immediately.
  537. */
  538. static void
  539. RAWINPUT_GetPendingDeviceChanges(void)
  540. {
  541. MSG msg;
  542. while (PeekMessage(&msg, SDL_HelperWindow, WM_INPUT_DEVICE_CHANGE, WM_INPUT_DEVICE_CHANGE, PM_REMOVE)) {
  543. TranslateMessage(&msg);
  544. DispatchMessage(&msg);
  545. }
  546. }
  547. static int
  548. RAWINPUT_JoystickInit(void)
  549. {
  550. int ii;
  551. RAWINPUTDEVICE rid[SDL_arraysize(subscribed_devices)];
  552. SDL_assert(!SDL_RAWINPUT_inited);
  553. SDL_assert(SDL_HelperWindow);
  554. if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT, SDL_TRUE)) {
  555. return -1;
  556. }
  557. if (WIN_LoadHIDDLL() < 0) {
  558. return -1;
  559. }
  560. for (ii = 0; ii < SDL_arraysize(subscribed_devices); ii++) {
  561. rid[ii].usUsagePage = USB_USAGEPAGE_GENERIC_DESKTOP;
  562. rid[ii].usUsage = subscribed_devices[ii];
  563. rid[ii].dwFlags = RIDEV_DEVNOTIFY | RIDEV_INPUTSINK; /* Receive messages when in background, including device add/remove */
  564. rid[ii].hwndTarget = SDL_HelperWindow;
  565. }
  566. if (!RegisterRawInputDevices(rid, SDL_arraysize(rid), sizeof(RAWINPUTDEVICE))) {
  567. SDL_SetError("Couldn't initialize RAWINPUT");
  568. WIN_UnloadHIDDLL();
  569. return -1;
  570. }
  571. SDL_RAWINPUT_inited = SDL_TRUE;
  572. /* Get initial controller connect messages */
  573. RAWINPUT_GetPendingDeviceChanges();
  574. return 0;
  575. }
  576. static int
  577. RAWINPUT_JoystickGetCount(void)
  578. {
  579. return SDL_RAWINPUT_numjoysticks;
  580. }
  581. static SDL_RAWINPUT_Device *
  582. RAWINPUT_AcquireDevice(SDL_RAWINPUT_Device *device)
  583. {
  584. SDL_AtomicIncRef(&device->refcount);
  585. return device;
  586. }
  587. static void
  588. RAWINPUT_ReleaseDevice(SDL_RAWINPUT_Device *device)
  589. {
  590. if (SDL_AtomicDecRef(&device->refcount)) {
  591. if (device->preparsed_data) {
  592. SDL_HidD_FreePreparsedData(device->preparsed_data);
  593. }
  594. SDL_free(device->name);
  595. SDL_free(device);
  596. }
  597. }
  598. static SDL_RAWINPUT_Device *
  599. RAWINPUT_DeviceFromHandle(HANDLE hDevice)
  600. {
  601. SDL_RAWINPUT_Device *curr;
  602. for (curr = SDL_RAWINPUT_devices; curr; curr = curr->next) {
  603. if (curr->hDevice == hDevice)
  604. return curr;
  605. }
  606. return NULL;
  607. }
  608. static void
  609. RAWINPUT_AddDevice(HANDLE hDevice)
  610. {
  611. #define CHECK(exp) { if(!(exp)) goto err; }
  612. SDL_RAWINPUT_Device *device = NULL;
  613. SDL_RAWINPUT_Device *curr, *last;
  614. RID_DEVICE_INFO rdi;
  615. UINT rdi_size = sizeof(rdi);
  616. char dev_name[MAX_PATH];
  617. UINT name_size = SDL_arraysize(dev_name);
  618. HANDLE hFile = INVALID_HANDLE_VALUE;
  619. /* Make sure we're not trying to add the same device twice */
  620. if (RAWINPUT_DeviceFromHandle(hDevice)) {
  621. return;
  622. }
  623. /* Figure out what kind of device it is */
  624. CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_DEVICEINFO, &rdi, &rdi_size) != (UINT)-1);
  625. CHECK(rdi.dwType == RIM_TYPEHID);
  626. /* Get the device "name" (HID Path) */
  627. CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_DEVICENAME, dev_name, &name_size) != (UINT)-1);
  628. /* Only take XInput-capable devices */
  629. CHECK(SDL_strstr(dev_name, "IG_") != NULL);
  630. #ifdef SDL_JOYSTICK_HIDAPI
  631. /* Don't take devices handled by HIDAPI */
  632. CHECK(!HIDAPI_IsDevicePresent((Uint16)rdi.hid.dwVendorId, (Uint16)rdi.hid.dwProductId, (Uint16)rdi.hid.dwVersionNumber, ""));
  633. #endif
  634. CHECK(device = (SDL_RAWINPUT_Device *)SDL_calloc(1, sizeof(SDL_RAWINPUT_Device)));
  635. device->hDevice = hDevice;
  636. device->vendor_id = (Uint16)rdi.hid.dwVendorId;
  637. device->product_id = (Uint16)rdi.hid.dwProductId;
  638. device->version = (Uint16)rdi.hid.dwVersionNumber;
  639. device->is_xinput = SDL_TRUE;
  640. {
  641. const Uint16 vendor = device->vendor_id;
  642. const Uint16 product = device->product_id;
  643. const Uint16 version = device->version;
  644. Uint16 *guid16 = (Uint16 *)device->guid.data;
  645. *guid16++ = SDL_SwapLE16(SDL_HARDWARE_BUS_USB);
  646. *guid16++ = 0;
  647. *guid16++ = SDL_SwapLE16(vendor);
  648. *guid16++ = 0;
  649. *guid16++ = SDL_SwapLE16(product);
  650. *guid16++ = 0;
  651. *guid16++ = SDL_SwapLE16(version);
  652. *guid16++ = 0;
  653. /* Note that this is a RAWINPUT device for special handling elsewhere */
  654. device->guid.data[14] = 'r';
  655. device->guid.data[15] = 0;
  656. }
  657. hFile = CreateFileA(dev_name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  658. CHECK(hFile != INVALID_HANDLE_VALUE);
  659. {
  660. char *manufacturer_string = NULL;
  661. char *product_string = NULL;
  662. WCHAR string[128];
  663. if (SDL_HidD_GetManufacturerString(hFile, string, sizeof(string))) {
  664. manufacturer_string = WIN_StringToUTF8(string);
  665. }
  666. if (SDL_HidD_GetProductString(hFile, string, sizeof(string))) {
  667. product_string = WIN_StringToUTF8(string);
  668. }
  669. device->name = SDL_CreateJoystickName(device->vendor_id, device->product_id, manufacturer_string, product_string);
  670. if (manufacturer_string) {
  671. SDL_free(manufacturer_string);
  672. }
  673. if (product_string) {
  674. SDL_free(product_string);
  675. }
  676. }
  677. CHECK(SDL_HidD_GetPreparsedData(hFile, &device->preparsed_data));
  678. CloseHandle(hFile);
  679. hFile = INVALID_HANDLE_VALUE;
  680. device->joystick_id = SDL_GetNextJoystickInstanceID();
  681. #ifdef DEBUG_RAWINPUT
  682. SDL_Log("Adding RAWINPUT device '%s' VID 0x%.4x, PID 0x%.4x, version %d, handle 0x%.8x\n", device->name, device->vendor_id, device->product_id, device->version, device->hDevice);
  683. #endif
  684. /* Add it to the list */
  685. RAWINPUT_AcquireDevice(device);
  686. for (curr = SDL_RAWINPUT_devices, last = NULL; curr; last = curr, curr = curr->next) {
  687. continue;
  688. }
  689. if (last) {
  690. last->next = device;
  691. } else {
  692. SDL_RAWINPUT_devices = device;
  693. }
  694. ++SDL_RAWINPUT_numjoysticks;
  695. SDL_PrivateJoystickAdded(device->joystick_id);
  696. return;
  697. err:
  698. if (hFile != INVALID_HANDLE_VALUE) {
  699. CloseHandle(hFile);
  700. }
  701. if (device) {
  702. if (device->name)
  703. SDL_free(device->name);
  704. SDL_free(device);
  705. }
  706. #undef CHECK
  707. }
  708. static void
  709. RAWINPUT_DelDevice(SDL_RAWINPUT_Device *device, SDL_bool send_event)
  710. {
  711. SDL_RAWINPUT_Device *curr, *last;
  712. for (curr = SDL_RAWINPUT_devices, last = NULL; curr; last = curr, curr = curr->next) {
  713. if (curr == device) {
  714. if (last) {
  715. last->next = curr->next;
  716. } else {
  717. SDL_RAWINPUT_devices = curr->next;
  718. }
  719. --SDL_RAWINPUT_numjoysticks;
  720. SDL_PrivateJoystickRemoved(device->joystick_id);
  721. #ifdef DEBUG_RAWINPUT
  722. SDL_Log("Removing RAWINPUT device '%s' VID 0x%.4x, PID 0x%.4x, version %d, handle 0x%.8x\n", device->name, device->vendor_id, device->product_id, device->version, device->hDevice);
  723. #endif
  724. RAWINPUT_ReleaseDevice(device);
  725. return;
  726. }
  727. }
  728. }
  729. static void
  730. RAWINPUT_PostUpdate(void)
  731. {
  732. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  733. SDL_bool unmapped_guide_pressed = SDL_FALSE;
  734. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  735. if (!wgi_state.dirty) {
  736. int ii;
  737. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  738. WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii];
  739. if (!gamepad_state->used && (gamepad_state->state.Buttons & GamepadButtons_GUIDE)) {
  740. unmapped_guide_pressed = SDL_TRUE;
  741. break;
  742. }
  743. }
  744. }
  745. wgi_state.dirty = SDL_TRUE;
  746. #endif
  747. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  748. if (!xinput_state_dirty) {
  749. int ii;
  750. for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) {
  751. if (xinput_state[ii].connected && !xinput_state[ii].used && (xinput_state[ii].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE)) {
  752. unmapped_guide_pressed = SDL_TRUE;
  753. break;
  754. }
  755. }
  756. }
  757. xinput_state_dirty = SDL_TRUE;
  758. #endif
  759. if (unmapped_guide_pressed) {
  760. if (guide_button_candidate.joystick && !guide_button_candidate.last_joystick) {
  761. SDL_Joystick *joystick = guide_button_candidate.joystick;
  762. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  763. if (ctx->guide_hack) {
  764. int guide_button = joystick->nbuttons - 1;
  765. SDL_PrivateJoystickButton(guide_button_candidate.joystick, guide_button, SDL_PRESSED);
  766. }
  767. guide_button_candidate.last_joystick = guide_button_candidate.joystick;
  768. }
  769. } else if (guide_button_candidate.last_joystick) {
  770. SDL_Joystick *joystick = guide_button_candidate.last_joystick;
  771. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  772. if (ctx->guide_hack) {
  773. int guide_button = joystick->nbuttons - 1;
  774. SDL_PrivateJoystickButton(joystick, guide_button, SDL_RELEASED);
  775. }
  776. guide_button_candidate.last_joystick = NULL;
  777. }
  778. guide_button_candidate.joystick = NULL;
  779. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  780. }
  781. SDL_bool
  782. RAWINPUT_IsEnabled()
  783. {
  784. return SDL_RAWINPUT_inited;
  785. }
  786. SDL_bool
  787. RAWINPUT_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version)
  788. {
  789. SDL_RAWINPUT_Device *device;
  790. /* Make sure the device list is completely up to date when we check for device presence */
  791. RAWINPUT_GetPendingDeviceChanges();
  792. device = SDL_RAWINPUT_devices;
  793. while (device) {
  794. if (device->vendor_id == vendor_id && device->product_id == product_id) {
  795. return SDL_TRUE;
  796. }
  797. device = device->next;
  798. }
  799. return SDL_FALSE;
  800. }
  801. static void
  802. RAWINPUT_JoystickDetect(void)
  803. {
  804. RAWINPUT_PostUpdate();
  805. }
  806. static SDL_RAWINPUT_Device *
  807. RAWINPUT_GetDeviceByIndex(int device_index)
  808. {
  809. SDL_RAWINPUT_Device *device = SDL_RAWINPUT_devices;
  810. while (device) {
  811. if (device_index == 0) {
  812. break;
  813. }
  814. --device_index;
  815. device = device->next;
  816. }
  817. return device;
  818. }
  819. static const char *
  820. RAWINPUT_JoystickGetDeviceName(int device_index)
  821. {
  822. return RAWINPUT_GetDeviceByIndex(device_index)->name;
  823. }
  824. static int
  825. RAWINPUT_JoystickGetDevicePlayerIndex(int device_index)
  826. {
  827. return -1;
  828. }
  829. static void
  830. RAWINPUT_JoystickSetDevicePlayerIndex(int device_index, int player_index)
  831. {
  832. }
  833. static SDL_JoystickGUID
  834. RAWINPUT_JoystickGetDeviceGUID(int device_index)
  835. {
  836. return RAWINPUT_GetDeviceByIndex(device_index)->guid;
  837. }
  838. static SDL_JoystickID
  839. RAWINPUT_JoystickGetDeviceInstanceID(int device_index)
  840. {
  841. return RAWINPUT_GetDeviceByIndex(device_index)->joystick_id;
  842. }
  843. static int
  844. RAWINPUT_JoystickOpen(SDL_Joystick *joystick, int device_index)
  845. {
  846. SDL_RAWINPUT_Device *device = RAWINPUT_GetDeviceByIndex(device_index);
  847. RAWINPUT_DeviceContext *ctx;
  848. HIDP_CAPS caps;
  849. HIDP_BUTTON_CAPS *button_caps;
  850. HIDP_VALUE_CAPS *value_caps;
  851. ULONG i;
  852. ctx = (RAWINPUT_DeviceContext *)SDL_calloc(1, sizeof(RAWINPUT_DeviceContext));
  853. if (!ctx) {
  854. return SDL_OutOfMemory();
  855. }
  856. joystick->hwdata = ctx;
  857. ctx->device = RAWINPUT_AcquireDevice(device);
  858. device->joystick = joystick;
  859. if (device->is_xinput) {
  860. /* We'll try to get guide button and trigger axes from XInput */
  861. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  862. xinput_device_change = SDL_TRUE;
  863. ctx->xinput_enabled = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT, SDL_TRUE);
  864. if (ctx->xinput_enabled && (WIN_LoadXInputDLL() < 0 || !XINPUTGETSTATE)) {
  865. ctx->xinput_enabled = SDL_FALSE;
  866. }
  867. ctx->xinput_slot = XUSER_INDEX_ANY;
  868. #endif
  869. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  870. RAWINPUT_InitWindowsGamingInput(ctx);
  871. #endif
  872. }
  873. ctx->is_xinput = device->is_xinput;
  874. ctx->preparsed_data = device->preparsed_data;
  875. ctx->max_data_length = SDL_HidP_MaxDataListLength(HidP_Input, ctx->preparsed_data);
  876. ctx->data = (HIDP_DATA *)SDL_malloc(ctx->max_data_length * sizeof(*ctx->data));
  877. if (!ctx->data) {
  878. RAWINPUT_JoystickClose(joystick);
  879. return SDL_OutOfMemory();
  880. }
  881. if (SDL_HidP_GetCaps(ctx->preparsed_data, &caps) != HIDP_STATUS_SUCCESS) {
  882. RAWINPUT_JoystickClose(joystick);
  883. return SDL_SetError("Couldn't get device capabilities");
  884. }
  885. button_caps = SDL_stack_alloc(HIDP_BUTTON_CAPS, caps.NumberInputButtonCaps);
  886. if (SDL_HidP_GetButtonCaps(HidP_Input, button_caps, &caps.NumberInputButtonCaps, ctx->preparsed_data) != HIDP_STATUS_SUCCESS) {
  887. RAWINPUT_JoystickClose(joystick);
  888. return SDL_SetError("Couldn't get device button capabilities");
  889. }
  890. value_caps = SDL_stack_alloc(HIDP_VALUE_CAPS, caps.NumberInputValueCaps);
  891. if (SDL_HidP_GetValueCaps(HidP_Input, value_caps, &caps.NumberInputValueCaps, ctx->preparsed_data) != HIDP_STATUS_SUCCESS) {
  892. RAWINPUT_JoystickClose(joystick);
  893. return SDL_SetError("Couldn't get device value capabilities");
  894. }
  895. for (i = 0; i < caps.NumberInputButtonCaps; ++i) {
  896. HIDP_BUTTON_CAPS *cap = &button_caps[i];
  897. if (cap->UsagePage == USB_USAGEPAGE_BUTTON) {
  898. int count;
  899. if (cap->IsRange) {
  900. count = 1 + (cap->Range.DataIndexMax - cap->Range.DataIndexMin);
  901. } else {
  902. count = 1;
  903. }
  904. joystick->nbuttons += count;
  905. }
  906. }
  907. if (joystick->nbuttons > 0) {
  908. int button_index = 0;
  909. ctx->button_indices = (USHORT *)SDL_malloc(joystick->nbuttons * sizeof(*ctx->button_indices));
  910. if (!ctx->button_indices) {
  911. RAWINPUT_JoystickClose(joystick);
  912. return SDL_OutOfMemory();
  913. }
  914. for (i = 0; i < caps.NumberInputButtonCaps; ++i) {
  915. HIDP_BUTTON_CAPS *cap = &button_caps[i];
  916. if (cap->UsagePage == USB_USAGEPAGE_BUTTON) {
  917. if (cap->IsRange) {
  918. int j, count = 1 + (cap->Range.DataIndexMax - cap->Range.DataIndexMin);
  919. for (j = 0; j < count; ++j) {
  920. ctx->button_indices[button_index++] = cap->Range.DataIndexMin + j;
  921. }
  922. } else {
  923. ctx->button_indices[button_index++] = cap->NotRange.DataIndex;
  924. }
  925. }
  926. }
  927. }
  928. if (ctx->is_xinput && joystick->nbuttons == 10) {
  929. ctx->guide_hack = SDL_TRUE;
  930. joystick->nbuttons += 1;
  931. }
  932. for (i = 0; i < caps.NumberInputValueCaps; ++i) {
  933. HIDP_VALUE_CAPS *cap = &value_caps[i];
  934. if (cap->IsRange) {
  935. continue;
  936. }
  937. if (ctx->trigger_hack && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) {
  938. continue;
  939. }
  940. if (cap->NotRange.Usage == USB_USAGE_GENERIC_HAT) {
  941. joystick->nhats += 1;
  942. continue;
  943. }
  944. if (ctx->is_xinput && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) {
  945. continue;
  946. }
  947. joystick->naxes += 1;
  948. }
  949. if (joystick->naxes > 0) {
  950. int axis_index = 0;
  951. ctx->axis_indices = (USHORT *)SDL_malloc(joystick->naxes * sizeof(*ctx->axis_indices));
  952. if (!ctx->axis_indices) {
  953. RAWINPUT_JoystickClose(joystick);
  954. return SDL_OutOfMemory();
  955. }
  956. for (i = 0; i < caps.NumberInputValueCaps; ++i) {
  957. HIDP_VALUE_CAPS *cap = &value_caps[i];
  958. if (cap->IsRange) {
  959. continue;
  960. }
  961. if (cap->NotRange.Usage == USB_USAGE_GENERIC_HAT) {
  962. continue;
  963. }
  964. if (ctx->is_xinput && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) {
  965. ctx->trigger_hack = SDL_TRUE;
  966. ctx->trigger_hack_index = cap->NotRange.DataIndex;
  967. continue;
  968. }
  969. ctx->axis_indices[axis_index++] = cap->NotRange.DataIndex;
  970. }
  971. }
  972. if (ctx->trigger_hack) {
  973. joystick->naxes += 2;
  974. }
  975. if (joystick->nhats > 0) {
  976. int hat_index = 0;
  977. ctx->hat_indices = (USHORT *)SDL_malloc(joystick->nhats * sizeof(*ctx->hat_indices));
  978. if (!ctx->hat_indices) {
  979. RAWINPUT_JoystickClose(joystick);
  980. return SDL_OutOfMemory();
  981. }
  982. for (i = 0; i < caps.NumberInputValueCaps; ++i) {
  983. HIDP_VALUE_CAPS *cap = &value_caps[i];
  984. if (cap->IsRange) {
  985. continue;
  986. }
  987. if (cap->NotRange.Usage != USB_USAGE_GENERIC_HAT) {
  988. continue;
  989. }
  990. ctx->hat_indices[hat_index++] = cap->NotRange.DataIndex;
  991. }
  992. }
  993. joystick->epowerlevel = SDL_JOYSTICK_POWER_WIRED;
  994. return 0;
  995. }
  996. static int
  997. RAWINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  998. {
  999. #if defined(SDL_JOYSTICK_RAWINPUT_WGI) || defined(SDL_JOYSTICK_RAWINPUT_XINPUT)
  1000. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1001. #endif
  1002. SDL_bool rumbled = SDL_FALSE;
  1003. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1004. if (!rumbled && ctx->wgi_correlated) {
  1005. WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot;
  1006. HRESULT hr;
  1007. gamepad_state->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16;
  1008. gamepad_state->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16;
  1009. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, gamepad_state->vibration);
  1010. if (SUCCEEDED(hr)) {
  1011. rumbled = SDL_TRUE;
  1012. }
  1013. }
  1014. #endif
  1015. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1016. if (!rumbled && ctx->xinput_correlated) {
  1017. XINPUT_VIBRATION XVibration;
  1018. if (!XINPUTSETSTATE) {
  1019. return SDL_Unsupported();
  1020. }
  1021. XVibration.wLeftMotorSpeed = low_frequency_rumble;
  1022. XVibration.wRightMotorSpeed = high_frequency_rumble;
  1023. if (XINPUTSETSTATE(ctx->xinput_slot, &XVibration) == ERROR_SUCCESS) {
  1024. rumbled = SDL_TRUE;
  1025. } else {
  1026. return SDL_SetError("XInputSetState() failed");
  1027. }
  1028. }
  1029. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1030. return 0;
  1031. }
  1032. static int
  1033. RAWINPUT_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  1034. {
  1035. #if defined(SDL_JOYSTICK_RAWINPUT_WGI)
  1036. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1037. if (ctx->wgi_correlated) {
  1038. WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot;
  1039. HRESULT hr;
  1040. gamepad_state->vibration.LeftTrigger = (DOUBLE)left_rumble / SDL_MAX_UINT16;
  1041. gamepad_state->vibration.RightTrigger = (DOUBLE)right_rumble / SDL_MAX_UINT16;
  1042. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, gamepad_state->vibration);
  1043. if (!SUCCEEDED(hr)) {
  1044. return SDL_SetError("Setting vibration failed: 0x%x\n", hr);
  1045. }
  1046. }
  1047. return 0;
  1048. #else
  1049. return SDL_Unsupported();
  1050. #endif
  1051. }
  1052. static SDL_bool
  1053. RAWINPUT_JoystickHasLED(SDL_Joystick *joystick)
  1054. {
  1055. return SDL_FALSE;
  1056. }
  1057. static int
  1058. RAWINPUT_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  1059. {
  1060. return SDL_Unsupported();
  1061. }
  1062. static int
  1063. RAWINPUT_JoystickSetSensorsEnabled(SDL_Joystick *joystick, SDL_bool enabled)
  1064. {
  1065. return SDL_Unsupported();
  1066. }
  1067. static HIDP_DATA *GetData(USHORT index, HIDP_DATA *data, ULONG length)
  1068. {
  1069. ULONG i;
  1070. /* Check to see if the data is at the expected offset */
  1071. if (index < length && data[index].DataIndex == index) {
  1072. return &data[index];
  1073. }
  1074. /* Loop through the data to find it */
  1075. for (i = 0; i < length; ++i) {
  1076. if (data[i].DataIndex == index) {
  1077. return &data[i];
  1078. }
  1079. }
  1080. return NULL;
  1081. }
  1082. /* This is the packet format for Xbox 360 and Xbox One controllers on Windows,
  1083. however with this interface there is no rumble support, no guide button,
  1084. and the left and right triggers are tied together as a single axis.
  1085. We use XInput and Windows.Gaming.Input to make up for these shortcomings.
  1086. */
  1087. static void
  1088. RAWINPUT_HandleStatePacket(SDL_Joystick *joystick, Uint8 *data, int size)
  1089. {
  1090. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1091. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1092. /* Map new buttons and axes into game controller controls */
  1093. static int axis_map[] = {
  1094. SDL_CONTROLLER_AXIS_LEFTY,
  1095. SDL_CONTROLLER_AXIS_LEFTX,
  1096. SDL_CONTROLLER_AXIS_RIGHTY,
  1097. SDL_CONTROLLER_AXIS_RIGHTX
  1098. };
  1099. static int button_map[] = {
  1100. SDL_CONTROLLER_BUTTON_A,
  1101. SDL_CONTROLLER_BUTTON_B,
  1102. SDL_CONTROLLER_BUTTON_X,
  1103. SDL_CONTROLLER_BUTTON_Y,
  1104. SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
  1105. SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
  1106. SDL_CONTROLLER_BUTTON_BACK,
  1107. SDL_CONTROLLER_BUTTON_START,
  1108. SDL_CONTROLLER_BUTTON_LEFTSTICK,
  1109. SDL_CONTROLLER_BUTTON_RIGHTSTICK
  1110. };
  1111. Uint32 match_state = ctx->match_state;
  1112. /* Update match_state with button bit, then fall through */
  1113. #define SDL_PrivateJoystickButton(joystick, button, state) if (button < SDL_arraysize(button_map)) { if (state) match_state |= 1 << button_map[button]; else match_state &= ~(1 << button_map[button]); } SDL_PrivateJoystickButton(joystick, button, state)
  1114. /* Grab high 4 bits of value, then fall through */
  1115. #define SDL_PrivateJoystickAxis(joystick, axis, value) if (axis < SDL_arraysize(axis_map)) match_state = (match_state & ~(0xF << (4 * axis_map[axis] + 16))) | ((value) & 0xF000) << (4 * axis_map[axis] + 4); SDL_PrivateJoystickAxis(joystick, axis, value)
  1116. #endif
  1117. ULONG data_length = ctx->max_data_length;
  1118. int i;
  1119. int nbuttons = joystick->nbuttons - (ctx->guide_hack * 1);
  1120. int naxes = joystick->naxes - (ctx->trigger_hack * 2);
  1121. int nhats = joystick->nhats;
  1122. Uint32 button_mask = 0;
  1123. if (SDL_HidP_GetData(HidP_Input, ctx->data, &data_length, ctx->preparsed_data, (PCHAR)data, size) != HIDP_STATUS_SUCCESS) {
  1124. return;
  1125. }
  1126. for (i = 0; i < nbuttons; ++i) {
  1127. HIDP_DATA *item = GetData(ctx->button_indices[i], ctx->data, data_length);
  1128. if (item && item->On) {
  1129. button_mask |= (1 << i);
  1130. }
  1131. }
  1132. for (i = 0; i < nbuttons; ++i) {
  1133. SDL_PrivateJoystickButton(joystick, i, (button_mask & (1 << i)) ? SDL_PRESSED : SDL_RELEASED);
  1134. }
  1135. for (i = 0; i < naxes; ++i) {
  1136. HIDP_DATA *item = GetData(ctx->axis_indices[i], ctx->data, data_length);
  1137. if (item) {
  1138. Sint16 axis = (int)(Uint16)item->RawValue - 0x8000;
  1139. SDL_PrivateJoystickAxis(joystick, i, axis);
  1140. }
  1141. }
  1142. for (i = 0; i < nhats; ++i) {
  1143. HIDP_DATA *item = GetData(ctx->hat_indices[i], ctx->data, data_length);
  1144. if (item) {
  1145. #define HAT_MASK ((1 << SDL_CONTROLLER_BUTTON_DPAD_UP) | (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN) | (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT) | (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
  1146. const int hat_map[] = {
  1147. 0,
  1148. (1 << SDL_CONTROLLER_BUTTON_DPAD_UP),
  1149. (1 << SDL_CONTROLLER_BUTTON_DPAD_UP) | (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT),
  1150. (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT),
  1151. (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN) | (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT),
  1152. (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN),
  1153. (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN) | (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT),
  1154. (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT),
  1155. (1 << SDL_CONTROLLER_BUTTON_DPAD_UP) | (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT),
  1156. };
  1157. const Uint8 hat_states[] = {
  1158. SDL_HAT_CENTERED,
  1159. SDL_HAT_UP,
  1160. SDL_HAT_UP | SDL_HAT_RIGHT,
  1161. SDL_HAT_RIGHT,
  1162. SDL_HAT_DOWN | SDL_HAT_RIGHT,
  1163. SDL_HAT_DOWN,
  1164. SDL_HAT_DOWN | SDL_HAT_LEFT,
  1165. SDL_HAT_LEFT,
  1166. SDL_HAT_UP | SDL_HAT_LEFT,
  1167. };
  1168. ULONG state = item->RawValue;
  1169. if (state < SDL_arraysize(hat_states)) {
  1170. match_state = (match_state & ~HAT_MASK) | hat_map[state];
  1171. SDL_PrivateJoystickHat(joystick, i, hat_states[state]);
  1172. }
  1173. }
  1174. }
  1175. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1176. #undef SDL_PrivateJoystickButton
  1177. #undef SDL_PrivateJoystickAxis
  1178. #endif
  1179. if (ctx->trigger_hack) {
  1180. SDL_bool has_trigger_data = SDL_FALSE;
  1181. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1182. /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */
  1183. if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) {
  1184. has_trigger_data = SDL_TRUE;
  1185. }
  1186. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1187. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1188. if (!has_trigger_data && ctx->wgi_correlated) {
  1189. has_trigger_data = SDL_TRUE;
  1190. }
  1191. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  1192. if (!has_trigger_data) {
  1193. HIDP_DATA *item = GetData(ctx->trigger_hack_index, ctx->data, data_length);
  1194. if (item) {
  1195. int left_trigger = joystick->naxes - 2;
  1196. int right_trigger = joystick->naxes - 1;
  1197. Sint16 value = (int)(Uint16)item->RawValue - 0x8000;
  1198. if (value < 0) {
  1199. value = -value * 2 - 32769;
  1200. SDL_PrivateJoystickAxis(joystick, left_trigger, SDL_MIN_SINT16);
  1201. SDL_PrivateJoystickAxis(joystick, right_trigger, value);
  1202. } else if (value > 0) {
  1203. value = value * 2 - 32767;
  1204. SDL_PrivateJoystickAxis(joystick, left_trigger, value);
  1205. SDL_PrivateJoystickAxis(joystick, right_trigger, SDL_MIN_SINT16);
  1206. } else {
  1207. SDL_PrivateJoystickAxis(joystick, left_trigger, SDL_MIN_SINT16);
  1208. SDL_PrivateJoystickAxis(joystick, right_trigger, SDL_MIN_SINT16);
  1209. }
  1210. }
  1211. }
  1212. }
  1213. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1214. if (ctx->is_xinput) {
  1215. ctx->match_state = match_state;
  1216. ctx->last_state_packet = SDL_GetTicks();
  1217. }
  1218. #endif
  1219. }
  1220. static void
  1221. RAWINPUT_UpdateOtherAPIs(SDL_Joystick *joystick)
  1222. {
  1223. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1224. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1225. SDL_bool has_trigger_data = SDL_FALSE;
  1226. SDL_bool correlated = SDL_FALSE;
  1227. WindowsMatchState match_state_xinput;
  1228. int guide_button = joystick->nbuttons - 1;
  1229. int left_trigger = joystick->naxes - 2;
  1230. int right_trigger = joystick->naxes - 1;
  1231. RAWINPUT_FillMatchState(&match_state_xinput, ctx->match_state);
  1232. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1233. /* Parallel logic to WINDOWS_XINPUT below */
  1234. RAWINPUT_UpdateWindowsGamingInput();
  1235. if (ctx->wgi_correlated) {
  1236. /* We have been previously correlated, ensure we are still matching, see comments in XINPUT section */
  1237. if (RAWINPUT_WindowsGamingInputSlotMatches(&match_state_xinput, ctx->wgi_slot)) {
  1238. ctx->wgi_uncorrelate_count = 0;
  1239. } else {
  1240. ++ctx->wgi_uncorrelate_count;
  1241. /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event
  1242. pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but
  1243. let's set it to 3 to be safe. An incorrect un-correlation will simply result in lower precision
  1244. triggers for a frame. */
  1245. if (ctx->wgi_uncorrelate_count >= 3) {
  1246. #ifdef DEBUG_JOYSTICK
  1247. SDL_Log("UN-Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, ctx->wgi_slot);
  1248. #endif
  1249. RAWINPUT_MarkWindowsGamingInputSlotFree(ctx->wgi_slot);
  1250. ctx->wgi_correlated = SDL_FALSE;
  1251. ctx->wgi_correlation_count = 0;
  1252. /* Force release of Guide button, it can't possibly be down on this device now. */
  1253. /* It gets left down if we were actually correlated incorrectly and it was released on the WindowsGamingInput
  1254. device but we didn't get a state packet. */
  1255. if (ctx->guide_hack) {
  1256. SDL_PrivateJoystickButton(joystick, guide_button, SDL_RELEASED);
  1257. }
  1258. }
  1259. }
  1260. }
  1261. if (!ctx->wgi_correlated) {
  1262. SDL_bool new_correlation_count = 0;
  1263. if (RAWINPUT_MissingWindowsGamingInputSlot()) {
  1264. Uint8 correlation_id;
  1265. WindowsGamingInputGamepadState *slot_idx;
  1266. if (RAWINPUT_GuessWindowsGamingInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) {
  1267. /* we match exactly one WindowsGamingInput device */
  1268. /* Probably can do without wgi_correlation_count, just check and clear wgi_slot to NULL, unless we need
  1269. even more frames to be sure. */
  1270. if (ctx->wgi_correlation_count && ctx->wgi_slot == slot_idx) {
  1271. /* was correlated previously, and still the same device */
  1272. if (ctx->wgi_correlation_id + 1 == correlation_id) {
  1273. /* no one else was correlated in the meantime */
  1274. new_correlation_count = ctx->wgi_correlation_count + 1;
  1275. if (new_correlation_count == 2) {
  1276. /* correlation stayed steady and uncontested across multiple frames, guaranteed match */
  1277. ctx->wgi_correlated = SDL_TRUE;
  1278. #ifdef DEBUG_JOYSTICK
  1279. SDL_Log("Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, slot_idx);
  1280. #endif
  1281. correlated = SDL_TRUE;
  1282. RAWINPUT_MarkWindowsGamingInputSlotUsed(ctx->wgi_slot, ctx);
  1283. /* If the generalized Guide button was using us, it doesn't need to anymore */
  1284. if (guide_button_candidate.joystick == joystick)
  1285. guide_button_candidate.joystick = NULL;
  1286. if (guide_button_candidate.last_joystick == joystick)
  1287. guide_button_candidate.last_joystick = NULL;
  1288. }
  1289. } else {
  1290. /* someone else also possibly correlated to this device, start over */
  1291. new_correlation_count = 1;
  1292. }
  1293. } else {
  1294. /* new possible correlation */
  1295. new_correlation_count = 1;
  1296. ctx->wgi_slot = slot_idx;
  1297. }
  1298. ctx->wgi_correlation_id = correlation_id;
  1299. } else {
  1300. /* Match multiple WindowsGamingInput devices, or none (possibly due to no buttons pressed) */
  1301. }
  1302. }
  1303. ctx->wgi_correlation_count = new_correlation_count;
  1304. } else {
  1305. correlated = SDL_TRUE;
  1306. }
  1307. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  1308. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1309. /* Parallel logic to WINDOWS_GAMING_INPUT above */
  1310. if (ctx->xinput_enabled) {
  1311. RAWINPUT_UpdateXInput();
  1312. if (ctx->xinput_correlated) {
  1313. /* We have been previously correlated, ensure we are still matching */
  1314. /* This is required to deal with two (mostly) un-preventable mis-correlation situations:
  1315. A) Since the HID data stream does not provide an initial state (but polling XInput does), if we open
  1316. 5 controllers (#1-4 XInput mapped, #5 is not), and controller 1 had the A button down (and we don't
  1317. know), and the user presses A on controller #5, we'll see exactly 1 controller with A down (#5) and
  1318. exactly 1 XInput device with A down (#1), and incorrectly correlate. This code will then un-correlate
  1319. when A is released from either controller #1 or #5.
  1320. B) Since the app may not open all controllers, we could have a similar situation where only controller #5
  1321. is opened, and the user holds A on controllers #1 and #5 simultaneously - again we see only 1 controller
  1322. with A down and 1 XInput device with A down, and incorrectly correlate. This should be very unusual
  1323. (only when apps do not open all controllers, yet are listening to Guide button presses, yet
  1324. for some reason want to ignore guide button presses on the un-opened controllers, yet users are
  1325. pressing buttons on the unopened controllers), and will resolve itself when either button is released
  1326. and we un-correlate. We could prevent this by processing the state packets for *all* controllers,
  1327. even un-opened ones, as that would allow more precise correlation.
  1328. */
  1329. if (RAWINPUT_XInputSlotMatches(&match_state_xinput, ctx->xinput_slot)) {
  1330. ctx->xinput_uncorrelate_count = 0;
  1331. } else {
  1332. ++ctx->xinput_uncorrelate_count;
  1333. /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event
  1334. pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but
  1335. let's set it to 3 to be safe. An incorrect un-correlation will simply result in lower precision
  1336. triggers for a frame. */
  1337. if (ctx->xinput_uncorrelate_count >= 3) {
  1338. #ifdef DEBUG_JOYSTICK
  1339. SDL_Log("UN-Correlated joystick %d to XInput device #%d\n", joystick->instance_id, ctx->xinput_slot);
  1340. #endif
  1341. RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot);
  1342. ctx->xinput_correlated = SDL_FALSE;
  1343. ctx->xinput_correlation_count = 0;
  1344. /* Force release of Guide button, it can't possibly be down on this device now. */
  1345. /* It gets left down if we were actually correlated incorrectly and it was released on the XInput
  1346. device but we didn't get a state packet. */
  1347. if (ctx->guide_hack) {
  1348. SDL_PrivateJoystickButton(joystick, guide_button, SDL_RELEASED);
  1349. }
  1350. }
  1351. }
  1352. }
  1353. if (!ctx->xinput_correlated) {
  1354. Uint8 new_correlation_count = 0;
  1355. if (RAWINPUT_MissingXInputSlot()) {
  1356. Uint8 correlation_id = 0;
  1357. Uint8 slot_idx = 0;
  1358. if (RAWINPUT_GuessXInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) {
  1359. /* we match exactly one XInput device */
  1360. /* Probably can do without xinput_correlation_count, just check and clear xinput_slot to ANY, unless
  1361. we need even more frames to be sure */
  1362. if (ctx->xinput_correlation_count && ctx->xinput_slot == slot_idx) {
  1363. /* was correlated previously, and still the same device */
  1364. if (ctx->xinput_correlation_id + 1 == correlation_id) {
  1365. /* no one else was correlated in the meantime */
  1366. new_correlation_count = ctx->xinput_correlation_count + 1;
  1367. if (new_correlation_count == 2) {
  1368. /* correlation stayed steady and uncontested across multiple frames, guaranteed match */
  1369. ctx->xinput_correlated = SDL_TRUE;
  1370. #ifdef DEBUG_JOYSTICK
  1371. SDL_Log("Correlated joystick %d to XInput device #%d\n", joystick->instance_id, slot_idx);
  1372. #endif
  1373. correlated = SDL_TRUE;
  1374. RAWINPUT_MarkXInputSlotUsed(ctx->xinput_slot);
  1375. /* If the generalized Guide button was using us, it doesn't need to anymore */
  1376. if (guide_button_candidate.joystick == joystick)
  1377. guide_button_candidate.joystick = NULL;
  1378. if (guide_button_candidate.last_joystick == joystick)
  1379. guide_button_candidate.last_joystick = NULL;
  1380. }
  1381. } else {
  1382. /* someone else also possibly correlated to this device, start over */
  1383. new_correlation_count = 1;
  1384. }
  1385. } else {
  1386. /* new possible correlation */
  1387. new_correlation_count = 1;
  1388. ctx->xinput_slot = slot_idx;
  1389. }
  1390. ctx->xinput_correlation_id = correlation_id;
  1391. } else {
  1392. /* Match multiple XInput devices, or none (possibly due to no buttons pressed) */
  1393. }
  1394. }
  1395. ctx->xinput_correlation_count = new_correlation_count;
  1396. } else {
  1397. correlated = SDL_TRUE;
  1398. }
  1399. }
  1400. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1401. /* Poll for trigger data once (not per-state-packet) */
  1402. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1403. /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */
  1404. if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) {
  1405. RAWINPUT_UpdateXInput();
  1406. if (xinput_state[ctx->xinput_slot].connected) {
  1407. if (ctx->guide_hack) {
  1408. SDL_PrivateJoystickButton(joystick, guide_button, (xinput_state[ctx->xinput_slot].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  1409. }
  1410. if (ctx->trigger_hack) {
  1411. SDL_PrivateJoystickAxis(joystick, left_trigger, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bLeftTrigger * 257) - 32768);
  1412. SDL_PrivateJoystickAxis(joystick, right_trigger, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bRightTrigger * 257) - 32768);
  1413. }
  1414. has_trigger_data = SDL_TRUE;
  1415. }
  1416. }
  1417. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1418. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1419. if (!has_trigger_data && ctx->wgi_correlated) {
  1420. RAWINPUT_UpdateWindowsGamingInput(); /* May detect disconnect / cause uncorrelation */
  1421. if (ctx->wgi_correlated) { /* Still connected */
  1422. struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading *state = &ctx->wgi_slot->state;
  1423. if (ctx->guide_hack) {
  1424. SDL_PrivateJoystickButton(joystick, guide_button, (state->Buttons & GamepadButtons_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  1425. }
  1426. if (ctx->trigger_hack) {
  1427. SDL_PrivateJoystickAxis(joystick, left_trigger, ((int)(state->LeftTrigger * SDL_MAX_UINT16)) - 32768);
  1428. SDL_PrivateJoystickAxis(joystick, right_trigger, ((int)(state->RightTrigger * SDL_MAX_UINT16)) - 32768);
  1429. }
  1430. has_trigger_data = SDL_TRUE;
  1431. }
  1432. }
  1433. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  1434. if (!correlated) {
  1435. if (!guide_button_candidate.joystick ||
  1436. (ctx->last_state_packet && (
  1437. !guide_button_candidate.last_state_packet ||
  1438. SDL_TICKS_PASSED(ctx->last_state_packet, guide_button_candidate.last_state_packet)
  1439. ))
  1440. ) {
  1441. guide_button_candidate.joystick = joystick;
  1442. guide_button_candidate.last_state_packet = ctx->last_state_packet;
  1443. }
  1444. }
  1445. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  1446. }
  1447. static void
  1448. RAWINPUT_JoystickUpdate(SDL_Joystick *joystick)
  1449. {
  1450. /* The input events have been handled in the main loop message pumping */
  1451. RAWINPUT_UpdateOtherAPIs(joystick);
  1452. }
  1453. static void
  1454. RAWINPUT_JoystickClose(SDL_Joystick *joystick)
  1455. {
  1456. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1457. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1458. if (guide_button_candidate.joystick == joystick)
  1459. guide_button_candidate.joystick = NULL;
  1460. if (guide_button_candidate.last_joystick == joystick)
  1461. guide_button_candidate.last_joystick = NULL;
  1462. #endif
  1463. if (ctx) {
  1464. SDL_RAWINPUT_Device *device;
  1465. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1466. xinput_device_change = SDL_TRUE;
  1467. if (ctx->xinput_enabled) {
  1468. if (ctx->xinput_correlated) {
  1469. RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot);
  1470. }
  1471. WIN_UnloadXInputDLL();
  1472. }
  1473. #endif
  1474. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1475. RAWINPUT_QuitWindowsGamingInput(ctx);
  1476. #endif
  1477. device = ctx->device;
  1478. if (device) {
  1479. SDL_assert(device->joystick == joystick);
  1480. device->joystick = NULL;
  1481. RAWINPUT_ReleaseDevice(device);
  1482. }
  1483. SDL_free(ctx->data);
  1484. SDL_free(ctx->button_indices);
  1485. SDL_free(ctx->axis_indices);
  1486. SDL_free(ctx->hat_indices);
  1487. SDL_free(ctx);
  1488. joystick->hwdata = NULL;
  1489. }
  1490. }
  1491. LRESULT RAWINPUT_WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1492. {
  1493. if (!SDL_RAWINPUT_inited)
  1494. return -1;
  1495. switch (msg)
  1496. {
  1497. case WM_INPUT_DEVICE_CHANGE:
  1498. {
  1499. HANDLE hDevice = (HANDLE)lParam;
  1500. switch (wParam) {
  1501. case GIDC_ARRIVAL:
  1502. RAWINPUT_AddDevice(hDevice);
  1503. break;
  1504. case GIDC_REMOVAL: {
  1505. SDL_RAWINPUT_Device *device;
  1506. device = RAWINPUT_DeviceFromHandle(hDevice);
  1507. if (device) {
  1508. RAWINPUT_DelDevice(device, SDL_TRUE);
  1509. }
  1510. } break;
  1511. default:
  1512. return 0;
  1513. }
  1514. }
  1515. return 0;
  1516. case WM_INPUT:
  1517. {
  1518. Uint8 data[sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + USB_PACKET_LENGTH];
  1519. UINT buffer_size = SDL_arraysize(data);
  1520. if ((int)GetRawInputData((HRAWINPUT)lParam, RID_INPUT, data, &buffer_size, sizeof(RAWINPUTHEADER)) > 0) {
  1521. PRAWINPUT raw_input = (PRAWINPUT)data;
  1522. SDL_RAWINPUT_Device *device = RAWINPUT_DeviceFromHandle(raw_input->header.hDevice);
  1523. if (device) {
  1524. SDL_Joystick *joystick = device->joystick;
  1525. if (joystick) {
  1526. RAWINPUT_HandleStatePacket(joystick, raw_input->data.hid.bRawData, raw_input->data.hid.dwSizeHid);
  1527. }
  1528. }
  1529. }
  1530. }
  1531. return 0;
  1532. }
  1533. return -1;
  1534. }
  1535. static void
  1536. RAWINPUT_JoystickQuit(void)
  1537. {
  1538. int ii;
  1539. RAWINPUTDEVICE rid[SDL_arraysize(subscribed_devices)];
  1540. if (!SDL_RAWINPUT_inited)
  1541. return;
  1542. for (ii = 0; ii < SDL_arraysize(subscribed_devices); ii++) {
  1543. rid[ii].usUsagePage = USB_USAGEPAGE_GENERIC_DESKTOP;
  1544. rid[ii].usUsage = subscribed_devices[ii];
  1545. rid[ii].dwFlags = RIDEV_REMOVE;
  1546. rid[ii].hwndTarget = NULL;
  1547. }
  1548. if (!RegisterRawInputDevices(rid, SDL_arraysize(rid), sizeof(RAWINPUTDEVICE))) {
  1549. SDL_Log("Couldn't un-register RAWINPUT");
  1550. }
  1551. while (SDL_RAWINPUT_devices) {
  1552. RAWINPUT_DelDevice(SDL_RAWINPUT_devices, SDL_FALSE);
  1553. }
  1554. WIN_UnloadHIDDLL();
  1555. SDL_RAWINPUT_numjoysticks = 0;
  1556. SDL_RAWINPUT_inited = SDL_FALSE;
  1557. }
  1558. static SDL_bool
  1559. RAWINPUT_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out)
  1560. {
  1561. return SDL_FALSE;
  1562. }
  1563. SDL_JoystickDriver SDL_RAWINPUT_JoystickDriver =
  1564. {
  1565. RAWINPUT_JoystickInit,
  1566. RAWINPUT_JoystickGetCount,
  1567. RAWINPUT_JoystickDetect,
  1568. RAWINPUT_JoystickGetDeviceName,
  1569. RAWINPUT_JoystickGetDevicePlayerIndex,
  1570. RAWINPUT_JoystickSetDevicePlayerIndex,
  1571. RAWINPUT_JoystickGetDeviceGUID,
  1572. RAWINPUT_JoystickGetDeviceInstanceID,
  1573. RAWINPUT_JoystickOpen,
  1574. RAWINPUT_JoystickRumble,
  1575. RAWINPUT_JoystickRumbleTriggers,
  1576. RAWINPUT_JoystickHasLED,
  1577. RAWINPUT_JoystickSetLED,
  1578. RAWINPUT_JoystickSetSensorsEnabled,
  1579. RAWINPUT_JoystickUpdate,
  1580. RAWINPUT_JoystickClose,
  1581. RAWINPUT_JoystickQuit,
  1582. RAWINPUT_JoystickGetGamepadMapping
  1583. };
  1584. #endif /* SDL_JOYSTICK_RAWINPUT */
  1585. /* vi: set ts=4 sw=4 expandtab: */