SDL_rawinputjoystick.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 2024 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. #ifdef SDL_JOYSTICK_RAWINPUT
  28. #include "SDL_atomic.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. /* SDL_JOYSTICK_RAWINPUT_XINPUT is disabled because using XInput at the same time as
  39. raw input will turn off the Xbox Series X controller when it is connected via the
  40. Xbox One Wireless Adapter.
  41. */
  42. #ifdef HAVE_XINPUT_H
  43. #define SDL_JOYSTICK_RAWINPUT_XINPUT
  44. #endif
  45. #ifdef HAVE_WINDOWS_GAMING_INPUT_H
  46. #define SDL_JOYSTICK_RAWINPUT_WGI
  47. #endif
  48. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  49. #include "../../core/windows/SDL_xinput.h"
  50. #endif
  51. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  52. #include "../../core/windows/SDL_windows.h"
  53. typedef struct WindowsGamingInputGamepadState WindowsGamingInputGamepadState;
  54. #define GamepadButtons_GUIDE 0x40000000
  55. #define COBJMACROS
  56. #include "windows.gaming.input.h"
  57. #include <roapi.h>
  58. #endif
  59. #if defined(SDL_JOYSTICK_RAWINPUT_XINPUT) || defined(SDL_JOYSTICK_RAWINPUT_WGI)
  60. #define SDL_JOYSTICK_RAWINPUT_MATCHING
  61. #define SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  62. #define SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  63. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  64. #define SDL_JOYSTICK_RAWINPUT_MATCH_COUNT 6 // stick + trigger axes
  65. #else
  66. #define SDL_JOYSTICK_RAWINPUT_MATCH_COUNT 4 // stick axes
  67. #endif
  68. #endif
  69. #if 0
  70. #define DEBUG_RAWINPUT
  71. #endif
  72. #ifndef RIDEV_EXINPUTSINK
  73. #define RIDEV_EXINPUTSINK 0x00001000
  74. #define RIDEV_DEVNOTIFY 0x00002000
  75. #endif
  76. #ifndef WM_INPUT_DEVICE_CHANGE
  77. #define WM_INPUT_DEVICE_CHANGE 0x00FE
  78. #endif
  79. #ifndef WM_INPUT
  80. #define WM_INPUT 0x00FF
  81. #endif
  82. #ifndef GIDC_ARRIVAL
  83. #define GIDC_ARRIVAL 1
  84. #define GIDC_REMOVAL 2
  85. #endif
  86. extern void WINDOWS_RAWINPUTEnabledChanged(void);
  87. extern void WINDOWS_JoystickDetect(void);
  88. static SDL_bool SDL_RAWINPUT_inited = SDL_FALSE;
  89. static SDL_bool SDL_RAWINPUT_remote_desktop = SDL_FALSE;
  90. static int SDL_RAWINPUT_numjoysticks = 0;
  91. static void RAWINPUT_JoystickClose(SDL_Joystick *joystick);
  92. typedef struct _SDL_RAWINPUT_Device
  93. {
  94. SDL_atomic_t refcount;
  95. char *name;
  96. char *path;
  97. Uint16 vendor_id;
  98. Uint16 product_id;
  99. Uint16 version;
  100. SDL_JoystickGUID guid;
  101. SDL_bool is_xinput;
  102. SDL_bool is_xboxone;
  103. int steam_virtual_gamepad_slot;
  104. PHIDP_PREPARSED_DATA preparsed_data;
  105. HANDLE hDevice;
  106. SDL_Joystick *joystick;
  107. SDL_JoystickID joystick_id;
  108. struct _SDL_RAWINPUT_Device *next;
  109. } SDL_RAWINPUT_Device;
  110. struct joystick_hwdata
  111. {
  112. SDL_bool is_xinput;
  113. SDL_bool is_xboxone;
  114. PHIDP_PREPARSED_DATA preparsed_data;
  115. ULONG max_data_length;
  116. HIDP_DATA *data;
  117. USHORT *button_indices;
  118. USHORT *axis_indices;
  119. USHORT *hat_indices;
  120. SDL_bool guide_hack;
  121. SDL_bool trigger_hack;
  122. USHORT trigger_hack_index;
  123. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  124. Uint64 match_state; /* Lowest 16 bits for button states, higher 24 for 6 4bit axes */
  125. Uint32 last_state_packet;
  126. #endif
  127. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  128. SDL_bool xinput_enabled;
  129. SDL_bool xinput_correlated;
  130. Uint8 xinput_correlation_id;
  131. Uint8 xinput_correlation_count;
  132. Uint8 xinput_uncorrelate_count;
  133. Uint8 xinput_slot;
  134. #endif
  135. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  136. SDL_bool wgi_correlated;
  137. Uint8 wgi_correlation_id;
  138. Uint8 wgi_correlation_count;
  139. Uint8 wgi_uncorrelate_count;
  140. WindowsGamingInputGamepadState *wgi_slot;
  141. #endif
  142. SDL_RAWINPUT_Device *device;
  143. };
  144. typedef struct joystick_hwdata RAWINPUT_DeviceContext;
  145. SDL_RAWINPUT_Device *SDL_RAWINPUT_devices;
  146. static const Uint16 subscribed_devices[] = {
  147. USB_USAGE_GENERIC_GAMEPAD,
  148. /* Don't need Joystick for any devices we're handling here (XInput-capable)
  149. USB_USAGE_GENERIC_JOYSTICK,
  150. USB_USAGE_GENERIC_MULTIAXISCONTROLLER,
  151. */
  152. };
  153. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  154. static struct
  155. {
  156. Uint32 last_state_packet;
  157. SDL_Joystick *joystick;
  158. SDL_Joystick *last_joystick;
  159. } guide_button_candidate;
  160. typedef struct WindowsMatchState
  161. {
  162. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  163. SHORT match_axes[SDL_JOYSTICK_RAWINPUT_MATCH_COUNT];
  164. #endif
  165. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  166. WORD xinput_buttons;
  167. #endif
  168. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  169. Uint32 wgi_buttons;
  170. #endif
  171. SDL_bool any_data;
  172. } WindowsMatchState;
  173. static void RAWINPUT_FillMatchState(WindowsMatchState *state, Uint64 match_state)
  174. {
  175. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  176. int ii;
  177. #endif
  178. SDL_bool any_axes_data = SDL_FALSE;
  179. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  180. /* SHORT state->match_axes[4] = {
  181. (match_state & 0x000F0000) >> 4,
  182. (match_state & 0x00F00000) >> 8,
  183. (match_state & 0x0F000000) >> 12,
  184. (match_state & 0xF0000000) >> 16,
  185. }; */
  186. for (ii = 0; ii < 4; ii++) {
  187. state->match_axes[ii] = (SHORT)((match_state & (0x000F0000ull << (ii * 4))) >> (4 + ii * 4));
  188. any_axes_data |= ((Uint32)(state->match_axes[ii] + 0x1000) > 0x2000); /* match_state bit is not 0xF, 0x1, or 0x2 */
  189. }
  190. #endif /* SDL_JOYSTICK_RAWINPUT_MATCH_AXES */
  191. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  192. for (; ii < SDL_JOYSTICK_RAWINPUT_MATCH_COUNT; ii++) {
  193. state->match_axes[ii] = (SHORT)((match_state & (0x000F0000ull << (ii * 4))) >> (4 + ii * 4));
  194. any_axes_data |= (state->match_axes[ii] != SDL_MIN_SINT16);
  195. }
  196. #endif /* SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS */
  197. state->any_data = any_axes_data;
  198. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  199. /* 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 */
  200. #define XInputAxesMatch(gamepad) ( \
  201. (Uint32)(gamepad.sThumbLX - state->match_axes[0] + 0x1000) <= 0x2fff && \
  202. (Uint32)(~gamepad.sThumbLY - state->match_axes[1] + 0x1000) <= 0x2fff && \
  203. (Uint32)(gamepad.sThumbRX - state->match_axes[2] + 0x1000) <= 0x2fff && \
  204. (Uint32)(~gamepad.sThumbRY - state->match_axes[3] + 0x1000) <= 0x2fff)
  205. /* Explicit
  206. #define XInputAxesMatch(gamepad) (\
  207. SDL_abs((Sint8)((gamepad.sThumbLX & 0xF000) >> 8) - ((match_state & 0x000F0000) >> 12)) <= 0x10 && \
  208. SDL_abs((Sint8)((~gamepad.sThumbLY & 0xF000) >> 8) - ((match_state & 0x00F00000) >> 16)) <= 0x10 && \
  209. SDL_abs((Sint8)((gamepad.sThumbRX & 0xF000) >> 8) - ((match_state & 0x0F000000) >> 20)) <= 0x10 && \
  210. SDL_abs((Sint8)((~gamepad.sThumbRY & 0xF000) >> 8) - ((match_state & 0xF0000000) >> 24)) <= 0x10) */
  211. /* Can only match trigger values if a single trigger has a value. */
  212. #define XInputTriggersMatch(gamepad) ( \
  213. ((state->match_axes[4] == SDL_MIN_SINT16) && (state->match_axes[5] == SDL_MIN_SINT16)) || \
  214. ((gamepad.bLeftTrigger != 0) && (gamepad.bRightTrigger != 0)) || \
  215. ((Uint32)((((int)gamepad.bLeftTrigger * 257) - 32768) - state->match_axes[4]) <= 0x2fff) || \
  216. ((Uint32)((((int)gamepad.bRightTrigger * 257) - 32768) - state->match_axes[5]) <= 0x2fff))
  217. state->xinput_buttons =
  218. /* Bitwise map .RLDUWVQTS.KYXBA -> YXBA..WVQTKSRLDU */
  219. (WORD)(match_state << 12 | (match_state & 0x0780) >> 1 | (match_state & 0x0010) << 1 | (match_state & 0x0040) >> 2 | (match_state & 0x7800) >> 11);
  220. /* Explicit
  221. ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? XINPUT_GAMEPAD_A : 0) |
  222. ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? XINPUT_GAMEPAD_B : 0) |
  223. ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? XINPUT_GAMEPAD_X : 0) |
  224. ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? XINPUT_GAMEPAD_Y : 0) |
  225. ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? XINPUT_GAMEPAD_BACK : 0) |
  226. ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? XINPUT_GAMEPAD_START : 0) |
  227. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? XINPUT_GAMEPAD_LEFT_THUMB : 0) |
  228. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? XINPUT_GAMEPAD_RIGHT_THUMB: 0) |
  229. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? XINPUT_GAMEPAD_LEFT_SHOULDER : 0) |
  230. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? XINPUT_GAMEPAD_RIGHT_SHOULDER : 0) |
  231. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? XINPUT_GAMEPAD_DPAD_UP : 0) |
  232. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? XINPUT_GAMEPAD_DPAD_DOWN : 0) |
  233. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? XINPUT_GAMEPAD_DPAD_LEFT : 0) |
  234. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? XINPUT_GAMEPAD_DPAD_RIGHT : 0);
  235. */
  236. if (state->xinput_buttons) {
  237. state->any_data = SDL_TRUE;
  238. }
  239. #endif
  240. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  241. /* 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 */
  242. #define WindowsGamingInputAxesMatch(gamepad) ( \
  243. (Uint16)(((Sint16)(gamepad.LeftThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[0] + 0x1000) <= 0x2fff && \
  244. (Uint16)((~(Sint16)(gamepad.LeftThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[1] + 0x1000) <= 0x2fff && \
  245. (Uint16)(((Sint16)(gamepad.RightThumbstickX * SDL_MAX_SINT16) & 0xF000) - state->match_axes[2] + 0x1000) <= 0x2fff && \
  246. (Uint16)((~(Sint16)(gamepad.RightThumbstickY * SDL_MAX_SINT16) & 0xF000) - state->match_axes[3] + 0x1000) <= 0x2fff)
  247. #define WindowsGamingInputTriggersMatch(gamepad) ( \
  248. ((state->match_axes[4] == SDL_MIN_SINT16) && (state->match_axes[5] == SDL_MIN_SINT16)) || \
  249. ((gamepad.LeftTrigger == 0.0f) && (gamepad.RightTrigger == 0.0f)) || \
  250. ((Uint16)((((int)(gamepad.LeftTrigger * SDL_MAX_UINT16)) - 32768) - state->match_axes[4]) <= 0x2fff) || \
  251. ((Uint16)((((int)(gamepad.RightTrigger * SDL_MAX_UINT16)) - 32768) - state->match_axes[5]) <= 0x2fff))
  252. state->wgi_buttons =
  253. /* Bitwise map .RLD UWVQ TS.K YXBA -> ..QT WVRL DUYX BAKS */
  254. /* RStick/LStick (QT) RShould/LShould (WV) DPad R/L/D/U YXBA bac(K) (S)tart */
  255. (match_state & 0x0180) << 5 | (match_state & 0x0600) << 1 | (match_state & 0x7800) >> 5 | (match_state & 0x000F) << 2 | (match_state & 0x0010) >> 3 | (match_state & 0x0040) >> 6;
  256. /* Explicit
  257. ((match_state & (1<<SDL_CONTROLLER_BUTTON_A)) ? GamepadButtons_A : 0) |
  258. ((match_state & (1<<SDL_CONTROLLER_BUTTON_B)) ? GamepadButtons_B : 0) |
  259. ((match_state & (1<<SDL_CONTROLLER_BUTTON_X)) ? GamepadButtons_X : 0) |
  260. ((match_state & (1<<SDL_CONTROLLER_BUTTON_Y)) ? GamepadButtons_Y : 0) |
  261. ((match_state & (1<<SDL_CONTROLLER_BUTTON_BACK)) ? GamepadButtons_View : 0) |
  262. ((match_state & (1<<SDL_CONTROLLER_BUTTON_START)) ? GamepadButtons_Menu : 0) |
  263. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSTICK)) ? GamepadButtons_LeftThumbstick : 0) |
  264. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSTICK)) ? GamepadButtons_RightThumbstick: 0) |
  265. ((match_state & (1<<SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) ? GamepadButtons_LeftShoulder: 0) |
  266. ((match_state & (1<<SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) ? GamepadButtons_RightShoulder: 0) |
  267. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_UP)) ? GamepadButtons_DPadUp : 0) |
  268. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_DOWN)) ? GamepadButtons_DPadDown : 0) |
  269. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ? GamepadButtons_DPadLeft : 0) |
  270. ((match_state & (1<<SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ? GamepadButtons_DPadRight : 0); */
  271. if (state->wgi_buttons) {
  272. state->any_data = SDL_TRUE;
  273. }
  274. #endif
  275. }
  276. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  277. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  278. static struct
  279. {
  280. XINPUT_STATE state;
  281. XINPUT_BATTERY_INFORMATION_EX battery;
  282. SDL_bool connected; /* Currently has an active XInput device */
  283. SDL_bool used; /* Is currently mapped to an SDL device */
  284. Uint8 correlation_id;
  285. } xinput_state[XUSER_MAX_COUNT];
  286. static SDL_bool xinput_device_change = SDL_TRUE;
  287. static SDL_bool xinput_state_dirty = SDL_TRUE;
  288. static void RAWINPUT_UpdateXInput(void)
  289. {
  290. DWORD user_index;
  291. if (xinput_device_change) {
  292. for (user_index = 0; user_index < XUSER_MAX_COUNT; user_index++) {
  293. XINPUT_CAPABILITIES capabilities;
  294. xinput_state[user_index].connected = (XINPUTGETCAPABILITIES(user_index, XINPUT_FLAG_GAMEPAD, &capabilities) == ERROR_SUCCESS) ? SDL_TRUE : SDL_FALSE;
  295. }
  296. xinput_device_change = SDL_FALSE;
  297. xinput_state_dirty = SDL_TRUE;
  298. }
  299. if (xinput_state_dirty) {
  300. xinput_state_dirty = SDL_FALSE;
  301. for (user_index = 0; user_index < SDL_arraysize(xinput_state); ++user_index) {
  302. if (xinput_state[user_index].connected) {
  303. if (XINPUTGETSTATE(user_index, &xinput_state[user_index].state) != ERROR_SUCCESS) {
  304. xinput_state[user_index].connected = SDL_FALSE;
  305. }
  306. xinput_state[user_index].battery.BatteryType = BATTERY_TYPE_UNKNOWN;
  307. if (XINPUTGETBATTERYINFORMATION) {
  308. XINPUTGETBATTERYINFORMATION(user_index, BATTERY_DEVTYPE_GAMEPAD, &xinput_state[user_index].battery);
  309. }
  310. }
  311. }
  312. }
  313. }
  314. static void RAWINPUT_MarkXInputSlotUsed(Uint8 xinput_slot)
  315. {
  316. if (xinput_slot != XUSER_INDEX_ANY) {
  317. xinput_state[xinput_slot].used = SDL_TRUE;
  318. }
  319. }
  320. static void RAWINPUT_MarkXInputSlotFree(Uint8 xinput_slot)
  321. {
  322. if (xinput_slot != XUSER_INDEX_ANY) {
  323. xinput_state[xinput_slot].used = SDL_FALSE;
  324. }
  325. }
  326. static SDL_bool RAWINPUT_MissingXInputSlot(void)
  327. {
  328. int ii;
  329. for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) {
  330. if (xinput_state[ii].connected && !xinput_state[ii].used) {
  331. return SDL_TRUE;
  332. }
  333. }
  334. return SDL_FALSE;
  335. }
  336. static SDL_bool RAWINPUT_XInputSlotMatches(const WindowsMatchState *state, Uint8 slot_idx)
  337. {
  338. if (xinput_state[slot_idx].connected) {
  339. WORD xinput_buttons = xinput_state[slot_idx].state.Gamepad.wButtons;
  340. if ((xinput_buttons & ~XINPUT_GAMEPAD_GUIDE) == state->xinput_buttons
  341. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  342. && XInputAxesMatch(xinput_state[slot_idx].state.Gamepad)
  343. #endif
  344. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  345. && XInputTriggersMatch(xinput_state[slot_idx].state.Gamepad)
  346. #endif
  347. ) {
  348. return SDL_TRUE;
  349. }
  350. }
  351. return SDL_FALSE;
  352. }
  353. static SDL_bool RAWINPUT_GuessXInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, Uint8 *slot_idx)
  354. {
  355. int user_index;
  356. int match_count;
  357. /* If there is only one available slot, let's use that
  358. * That will be right most of the time, and uncorrelation will fix any bad guesses
  359. */
  360. match_count = 0;
  361. for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) {
  362. if (xinput_state[user_index].connected && !xinput_state[user_index].used) {
  363. *slot_idx = user_index;
  364. ++match_count;
  365. }
  366. }
  367. if (match_count == 1) {
  368. *correlation_id = ++xinput_state[*slot_idx].correlation_id;
  369. return SDL_TRUE;
  370. }
  371. *slot_idx = 0;
  372. match_count = 0;
  373. for (user_index = 0; user_index < XUSER_MAX_COUNT; ++user_index) {
  374. if (!xinput_state[user_index].used && RAWINPUT_XInputSlotMatches(state, user_index)) {
  375. ++match_count;
  376. *slot_idx = (Uint8)user_index;
  377. /* Incrementing correlation_id for any match, as negative evidence for others being correlated */
  378. *correlation_id = ++xinput_state[user_index].correlation_id;
  379. }
  380. }
  381. /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched.
  382. Note that we're still invalidating *other* potential correlations if we have more than one match or we have no
  383. data. */
  384. if (match_count == 1 && state->any_data) {
  385. return SDL_TRUE;
  386. }
  387. return SDL_FALSE;
  388. }
  389. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  390. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  391. typedef struct WindowsGamingInputGamepadState
  392. {
  393. __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  394. struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading state;
  395. RAWINPUT_DeviceContext *correlated_context;
  396. SDL_bool used; /* Is currently mapped to an SDL device */
  397. SDL_bool connected; /* Just used during update to track disconnected */
  398. Uint8 correlation_id;
  399. struct __x_ABI_CWindows_CGaming_CInput_CGamepadVibration vibration;
  400. } WindowsGamingInputGamepadState;
  401. static struct
  402. {
  403. WindowsGamingInputGamepadState **per_gamepad;
  404. int per_gamepad_count;
  405. SDL_bool initialized;
  406. SDL_bool dirty;
  407. SDL_bool need_device_list_update;
  408. int ref_count;
  409. __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics *gamepad_statics;
  410. EventRegistrationToken gamepad_added_token;
  411. EventRegistrationToken gamepad_removed_token;
  412. } wgi_state;
  413. typedef struct GamepadDelegate
  414. {
  415. __FIEventHandler_1_Windows__CGaming__CInput__CGamepad iface;
  416. SDL_atomic_t refcount;
  417. } GamepadDelegate;
  418. static const IID IID_IEventHandler_Gamepad = { 0x8a7639ee, 0x624a, 0x501a, { 0xbb, 0x53, 0x56, 0x2d, 0x1e, 0xc1, 0x1b, 0x52 } };
  419. static HRESULT STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_QueryInterface(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This, REFIID riid, void **ppvObject)
  420. {
  421. if (!ppvObject) {
  422. return E_INVALIDARG;
  423. }
  424. *ppvObject = NULL;
  425. if (WIN_IsEqualIID(riid, &IID_IUnknown) || WIN_IsEqualIID(riid, &IID_IAgileObject) || WIN_IsEqualIID(riid, &IID_IEventHandler_Gamepad)) {
  426. *ppvObject = This;
  427. __FIEventHandler_1_Windows__CGaming__CInput__CGamepad_AddRef(This);
  428. return S_OK;
  429. } else if (WIN_IsEqualIID(riid, &IID_IMarshal)) {
  430. /* This seems complicated. Let's hope it doesn't happen. */
  431. return E_OUTOFMEMORY;
  432. } else {
  433. return E_NOINTERFACE;
  434. }
  435. }
  436. static ULONG STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_AddRef(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This)
  437. {
  438. GamepadDelegate *self = (GamepadDelegate *)This;
  439. return SDL_AtomicAdd(&self->refcount, 1) + 1UL;
  440. }
  441. static ULONG STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_Release(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This)
  442. {
  443. GamepadDelegate *self = (GamepadDelegate *)This;
  444. int rc = SDL_AtomicAdd(&self->refcount, -1) - 1;
  445. /* Should never free the static delegate objects */
  446. SDL_assert(rc > 0);
  447. return rc;
  448. }
  449. static HRESULT STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_InvokeAdded(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This, IInspectable *sender, __x_ABI_CWindows_CGaming_CInput_CIGamepad *e)
  450. {
  451. wgi_state.need_device_list_update = SDL_TRUE;
  452. return S_OK;
  453. }
  454. static HRESULT STDMETHODCALLTYPE IEventHandler_CGamepadVtbl_InvokeRemoved(__FIEventHandler_1_Windows__CGaming__CInput__CGamepad *This, IInspectable *sender, __x_ABI_CWindows_CGaming_CInput_CIGamepad *e)
  455. {
  456. wgi_state.need_device_list_update = SDL_TRUE;
  457. return S_OK;
  458. }
  459. static __FIEventHandler_1_Windows__CGaming__CInput__CGamepadVtbl gamepad_added_vtbl = {
  460. IEventHandler_CGamepadVtbl_QueryInterface,
  461. IEventHandler_CGamepadVtbl_AddRef,
  462. IEventHandler_CGamepadVtbl_Release,
  463. IEventHandler_CGamepadVtbl_InvokeAdded
  464. };
  465. static GamepadDelegate gamepad_added = {
  466. { &gamepad_added_vtbl },
  467. { 1 }
  468. };
  469. static __FIEventHandler_1_Windows__CGaming__CInput__CGamepadVtbl gamepad_removed_vtbl = {
  470. IEventHandler_CGamepadVtbl_QueryInterface,
  471. IEventHandler_CGamepadVtbl_AddRef,
  472. IEventHandler_CGamepadVtbl_Release,
  473. IEventHandler_CGamepadVtbl_InvokeRemoved
  474. };
  475. static GamepadDelegate gamepad_removed = {
  476. { &gamepad_removed_vtbl },
  477. { 1 }
  478. };
  479. static void RAWINPUT_MarkWindowsGamingInputSlotUsed(WindowsGamingInputGamepadState *wgi_slot, RAWINPUT_DeviceContext *ctx)
  480. {
  481. wgi_slot->used = SDL_TRUE;
  482. wgi_slot->correlated_context = ctx;
  483. }
  484. static void RAWINPUT_MarkWindowsGamingInputSlotFree(WindowsGamingInputGamepadState *wgi_slot)
  485. {
  486. wgi_slot->used = SDL_FALSE;
  487. wgi_slot->correlated_context = NULL;
  488. }
  489. static SDL_bool RAWINPUT_MissingWindowsGamingInputSlot(void)
  490. {
  491. int ii;
  492. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  493. if (!wgi_state.per_gamepad[ii]->used) {
  494. return SDL_TRUE;
  495. }
  496. }
  497. return SDL_FALSE;
  498. }
  499. static void RAWINPUT_UpdateWindowsGamingInput(void)
  500. {
  501. int ii;
  502. if (!wgi_state.gamepad_statics) {
  503. return;
  504. }
  505. if (!wgi_state.dirty) {
  506. return;
  507. }
  508. wgi_state.dirty = SDL_FALSE;
  509. if (wgi_state.need_device_list_update) {
  510. HRESULT hr;
  511. __FIVectorView_1_Windows__CGaming__CInput__CGamepad *gamepads;
  512. wgi_state.need_device_list_update = SDL_FALSE;
  513. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  514. wgi_state.per_gamepad[ii]->connected = SDL_FALSE;
  515. }
  516. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_get_Gamepads(wgi_state.gamepad_statics, &gamepads);
  517. if (SUCCEEDED(hr)) {
  518. unsigned int num_gamepads;
  519. hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_get_Size(gamepads, &num_gamepads);
  520. if (SUCCEEDED(hr)) {
  521. unsigned int i;
  522. for (i = 0; i < num_gamepads; ++i) {
  523. __x_ABI_CWindows_CGaming_CInput_CIGamepad *gamepad;
  524. hr = __FIVectorView_1_Windows__CGaming__CInput__CGamepad_GetAt(gamepads, i, &gamepad);
  525. if (SUCCEEDED(hr)) {
  526. SDL_bool found = SDL_FALSE;
  527. int jj;
  528. for (jj = 0; jj < wgi_state.per_gamepad_count; jj++) {
  529. if (wgi_state.per_gamepad[jj]->gamepad == gamepad) {
  530. found = SDL_TRUE;
  531. wgi_state.per_gamepad[jj]->connected = SDL_TRUE;
  532. break;
  533. }
  534. }
  535. if (!found) {
  536. /* New device, add it */
  537. WindowsGamingInputGamepadState *gamepad_state;
  538. wgi_state.per_gamepad_count++;
  539. wgi_state.per_gamepad = SDL_realloc(wgi_state.per_gamepad, sizeof(wgi_state.per_gamepad[0]) * wgi_state.per_gamepad_count);
  540. if (!wgi_state.per_gamepad) {
  541. SDL_OutOfMemory();
  542. return;
  543. }
  544. gamepad_state = SDL_calloc(1, sizeof(*gamepad_state));
  545. if (!gamepad_state) {
  546. SDL_OutOfMemory();
  547. return;
  548. }
  549. wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1] = gamepad_state;
  550. gamepad_state->gamepad = gamepad;
  551. gamepad_state->connected = SDL_TRUE;
  552. } else {
  553. /* Already tracked */
  554. __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad);
  555. }
  556. }
  557. }
  558. for (ii = wgi_state.per_gamepad_count - 1; ii >= 0; ii--) {
  559. WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii];
  560. if (!gamepad_state->connected) {
  561. /* Device missing, must be disconnected */
  562. if (gamepad_state->correlated_context) {
  563. gamepad_state->correlated_context->wgi_correlated = SDL_FALSE;
  564. gamepad_state->correlated_context->wgi_slot = NULL;
  565. }
  566. __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(gamepad_state->gamepad);
  567. SDL_free(gamepad_state);
  568. wgi_state.per_gamepad[ii] = wgi_state.per_gamepad[wgi_state.per_gamepad_count - 1];
  569. --wgi_state.per_gamepad_count;
  570. }
  571. }
  572. }
  573. __FIVectorView_1_Windows__CGaming__CInput__CGamepad_Release(gamepads);
  574. }
  575. } /* need_device_list_update */
  576. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  577. HRESULT hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_GetCurrentReading(wgi_state.per_gamepad[ii]->gamepad, &wgi_state.per_gamepad[ii]->state);
  578. if (!SUCCEEDED(hr)) {
  579. wgi_state.per_gamepad[ii]->connected = SDL_FALSE; /* Not used by anything, currently */
  580. }
  581. }
  582. }
  583. static void RAWINPUT_InitWindowsGamingInput(RAWINPUT_DeviceContext *ctx)
  584. {
  585. if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_WGI, SDL_TRUE)) {
  586. return;
  587. }
  588. wgi_state.ref_count++;
  589. if (!wgi_state.initialized) {
  590. static const IID SDL_IID_IGamepadStatics = { 0x8BBCE529, 0xD49C, 0x39E9, { 0x95, 0x60, 0xE4, 0x7D, 0xDE, 0x96, 0xB7, 0xC8 } };
  591. HRESULT hr;
  592. if (FAILED(WIN_RoInitialize())) {
  593. return;
  594. }
  595. wgi_state.initialized = SDL_TRUE;
  596. wgi_state.dirty = SDL_TRUE;
  597. {
  598. typedef HRESULT(WINAPI * WindowsCreateStringReference_t)(PCWSTR sourceString, UINT32 length, HSTRING_HEADER * hstringHeader, HSTRING * string);
  599. typedef HRESULT(WINAPI * RoGetActivationFactory_t)(HSTRING activatableClassId, REFIID iid, void **factory);
  600. #ifdef __WINRT__
  601. WindowsCreateStringReference_t WindowsCreateStringReferenceFunc = WindowsCreateStringReference;
  602. RoGetActivationFactory_t RoGetActivationFactoryFunc = RoGetActivationFactory;
  603. #else
  604. WindowsCreateStringReference_t WindowsCreateStringReferenceFunc = (WindowsCreateStringReference_t)WIN_LoadComBaseFunction("WindowsCreateStringReference");
  605. RoGetActivationFactory_t RoGetActivationFactoryFunc = (RoGetActivationFactory_t)WIN_LoadComBaseFunction("RoGetActivationFactory");
  606. #endif
  607. if (WindowsCreateStringReferenceFunc && RoGetActivationFactoryFunc) {
  608. PCWSTR pNamespace = L"Windows.Gaming.Input.Gamepad";
  609. HSTRING_HEADER hNamespaceStringHeader;
  610. HSTRING hNamespaceString;
  611. hr = WindowsCreateStringReferenceFunc(pNamespace, (UINT32)SDL_wcslen(pNamespace), &hNamespaceStringHeader, &hNamespaceString);
  612. if (SUCCEEDED(hr)) {
  613. RoGetActivationFactoryFunc(hNamespaceString, &SDL_IID_IGamepadStatics, (void **)&wgi_state.gamepad_statics);
  614. }
  615. if (wgi_state.gamepad_statics) {
  616. wgi_state.need_device_list_update = SDL_TRUE;
  617. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_add_GamepadAdded(wgi_state.gamepad_statics, &gamepad_added.iface, &wgi_state.gamepad_added_token);
  618. if (!SUCCEEDED(hr)) {
  619. SDL_SetError("add_GamepadAdded() failed: 0x%lx\n", hr);
  620. }
  621. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_add_GamepadRemoved(wgi_state.gamepad_statics, &gamepad_removed.iface, &wgi_state.gamepad_removed_token);
  622. if (!SUCCEEDED(hr)) {
  623. SDL_SetError("add_GamepadRemoved() failed: 0x%lx\n", hr);
  624. }
  625. }
  626. }
  627. }
  628. }
  629. }
  630. static SDL_bool RAWINPUT_WindowsGamingInputSlotMatches(const WindowsMatchState *state, WindowsGamingInputGamepadState *slot, SDL_bool xinput_correlated)
  631. {
  632. Uint32 wgi_buttons = slot->state.Buttons;
  633. if ((wgi_buttons & 0x3FFF) == state->wgi_buttons
  634. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  635. && WindowsGamingInputAxesMatch(slot->state)
  636. #endif
  637. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  638. // Don't try to match WGI triggers if getting values from XInput
  639. && (xinput_correlated || WindowsGamingInputTriggersMatch(slot->state))
  640. #endif
  641. ) {
  642. return SDL_TRUE;
  643. }
  644. return SDL_FALSE;
  645. }
  646. static SDL_bool RAWINPUT_GuessWindowsGamingInputSlot(const WindowsMatchState *state, Uint8 *correlation_id, WindowsGamingInputGamepadState **slot, SDL_bool xinput_correlated)
  647. {
  648. int match_count, user_index;
  649. WindowsGamingInputGamepadState *gamepad_state = NULL;
  650. /* If there is only one available slot, let's use that
  651. * That will be right most of the time, and uncorrelation will fix any bad guesses
  652. */
  653. match_count = 0;
  654. for (user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) {
  655. gamepad_state = wgi_state.per_gamepad[user_index];
  656. if (gamepad_state->connected && !gamepad_state->used) {
  657. *slot = gamepad_state;
  658. ++match_count;
  659. }
  660. }
  661. if (match_count == 1) {
  662. *correlation_id = ++gamepad_state->correlation_id;
  663. return SDL_TRUE;
  664. }
  665. match_count = 0;
  666. for (user_index = 0; user_index < wgi_state.per_gamepad_count; ++user_index) {
  667. gamepad_state = wgi_state.per_gamepad[user_index];
  668. if (RAWINPUT_WindowsGamingInputSlotMatches(state, gamepad_state, xinput_correlated)) {
  669. ++match_count;
  670. *slot = gamepad_state;
  671. /* Incrementing correlation_id for any match, as negative evidence for others being correlated */
  672. *correlation_id = ++gamepad_state->correlation_id;
  673. }
  674. }
  675. /* Only return a match if we match exactly one, and we have some non-zero data (buttons or axes) that matched.
  676. Note that we're still invalidating *other* potential correlations if we have more than one match or we have no
  677. data. */
  678. if (match_count == 1 && state->any_data) {
  679. return SDL_TRUE;
  680. }
  681. return SDL_FALSE;
  682. }
  683. static void RAWINPUT_QuitWindowsGamingInput(RAWINPUT_DeviceContext *ctx)
  684. {
  685. --wgi_state.ref_count;
  686. if (!wgi_state.ref_count && wgi_state.initialized) {
  687. int ii;
  688. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  689. __x_ABI_CWindows_CGaming_CInput_CIGamepad_Release(wgi_state.per_gamepad[ii]->gamepad);
  690. }
  691. if (wgi_state.per_gamepad) {
  692. SDL_free(wgi_state.per_gamepad);
  693. wgi_state.per_gamepad = NULL;
  694. }
  695. wgi_state.per_gamepad_count = 0;
  696. if (wgi_state.gamepad_statics) {
  697. __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_remove_GamepadAdded(wgi_state.gamepad_statics, wgi_state.gamepad_added_token);
  698. __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_remove_GamepadRemoved(wgi_state.gamepad_statics, wgi_state.gamepad_removed_token);
  699. __x_ABI_CWindows_CGaming_CInput_CIGamepadStatics_Release(wgi_state.gamepad_statics);
  700. wgi_state.gamepad_statics = NULL;
  701. }
  702. WIN_RoUninitialize();
  703. wgi_state.initialized = SDL_FALSE;
  704. }
  705. }
  706. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  707. static SDL_RAWINPUT_Device *RAWINPUT_AcquireDevice(SDL_RAWINPUT_Device *device)
  708. {
  709. SDL_AtomicIncRef(&device->refcount);
  710. return device;
  711. }
  712. static void RAWINPUT_ReleaseDevice(SDL_RAWINPUT_Device *device)
  713. {
  714. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  715. if (device->joystick) {
  716. RAWINPUT_DeviceContext *ctx = device->joystick->hwdata;
  717. if (ctx->xinput_enabled && ctx->xinput_correlated) {
  718. RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot);
  719. ctx->xinput_correlated = SDL_FALSE;
  720. }
  721. }
  722. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  723. if (SDL_AtomicDecRef(&device->refcount)) {
  724. SDL_free(device->preparsed_data);
  725. SDL_free(device->name);
  726. SDL_free(device->path);
  727. SDL_free(device);
  728. }
  729. }
  730. static SDL_RAWINPUT_Device *RAWINPUT_DeviceFromHandle(HANDLE hDevice)
  731. {
  732. SDL_RAWINPUT_Device *curr;
  733. for (curr = SDL_RAWINPUT_devices; curr; curr = curr->next) {
  734. if (curr->hDevice == hDevice) {
  735. return curr;
  736. }
  737. }
  738. return NULL;
  739. }
  740. static int GetSteamVirtualGamepadSlot(Uint16 vendor_id, Uint16 product_id, const char *device_path)
  741. {
  742. int slot = -1;
  743. // The format for the raw input device path is documented here:
  744. // https://partner.steamgames.com/doc/features/steam_controller/steam_input_gamepad_emulation_bestpractices
  745. if (vendor_id == USB_VENDOR_VALVE &&
  746. product_id == USB_PRODUCT_STEAM_VIRTUAL_GAMEPAD) {
  747. (void)SDL_sscanf(device_path, "\\\\.\\pipe\\HID#VID_045E&PID_028E&IG_00#%*X&%*X&%*X#%d#%*u", &slot);
  748. }
  749. return slot;
  750. }
  751. static void RAWINPUT_AddDevice(HANDLE hDevice)
  752. {
  753. #define CHECK(expression) \
  754. { \
  755. if (!(expression)) \
  756. goto err; \
  757. }
  758. SDL_RAWINPUT_Device *device = NULL;
  759. SDL_RAWINPUT_Device *curr, *last;
  760. RID_DEVICE_INFO rdi;
  761. UINT size;
  762. char dev_name[MAX_PATH];
  763. HANDLE hFile = INVALID_HANDLE_VALUE;
  764. /* Make sure we're not trying to add the same device twice */
  765. if (RAWINPUT_DeviceFromHandle(hDevice)) {
  766. return;
  767. }
  768. /* Figure out what kind of device it is */
  769. size = sizeof(rdi);
  770. CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_DEVICEINFO, &rdi, &size) != (UINT)-1);
  771. CHECK(rdi.dwType == RIM_TYPEHID);
  772. /* Get the device "name" (HID Path) */
  773. size = SDL_arraysize(dev_name);
  774. CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_DEVICENAME, dev_name, &size) != (UINT)-1);
  775. /* Only take XInput-capable devices */
  776. CHECK(SDL_strstr(dev_name, "IG_") != NULL);
  777. #ifdef SDL_JOYSTICK_HIDAPI
  778. /* Don't take devices handled by HIDAPI */
  779. CHECK(!HIDAPI_IsDevicePresent((Uint16)rdi.hid.dwVendorId, (Uint16)rdi.hid.dwProductId, (Uint16)rdi.hid.dwVersionNumber, ""));
  780. #endif
  781. device = (SDL_RAWINPUT_Device *)SDL_calloc(1, sizeof(SDL_RAWINPUT_Device));
  782. CHECK(device);
  783. device->hDevice = hDevice;
  784. device->vendor_id = (Uint16)rdi.hid.dwVendorId;
  785. device->product_id = (Uint16)rdi.hid.dwProductId;
  786. device->version = (Uint16)rdi.hid.dwVersionNumber;
  787. device->is_xinput = SDL_TRUE;
  788. device->is_xboxone = SDL_IsJoystickXboxOne(device->vendor_id, device->product_id);
  789. device->steam_virtual_gamepad_slot = GetSteamVirtualGamepadSlot(device->vendor_id, device->product_id, dev_name);
  790. /* Get HID Top-Level Collection Preparsed Data */
  791. size = 0;
  792. CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_PREPARSEDDATA, NULL, &size) != (UINT)-1);
  793. device->preparsed_data = (PHIDP_PREPARSED_DATA)SDL_calloc(size, sizeof(BYTE));
  794. CHECK(device->preparsed_data);
  795. CHECK(GetRawInputDeviceInfoA(hDevice, RIDI_PREPARSEDDATA, device->preparsed_data, &size) != (UINT)-1);
  796. hFile = CreateFileA(dev_name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  797. CHECK(hFile != INVALID_HANDLE_VALUE);
  798. {
  799. char *manufacturer_string = NULL;
  800. char *product_string = NULL;
  801. WCHAR string[128];
  802. if (SDL_HidD_GetManufacturerString(hFile, string, sizeof(string))) {
  803. manufacturer_string = WIN_StringToUTF8W(string);
  804. }
  805. if (SDL_HidD_GetProductString(hFile, string, sizeof(string))) {
  806. product_string = WIN_StringToUTF8W(string);
  807. }
  808. device->name = SDL_CreateJoystickName(device->vendor_id, device->product_id, manufacturer_string, product_string);
  809. device->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_USB, device->vendor_id, device->product_id, device->version, manufacturer_string, product_string, 'r', 0);
  810. if (manufacturer_string) {
  811. SDL_free(manufacturer_string);
  812. }
  813. if (product_string) {
  814. SDL_free(product_string);
  815. }
  816. }
  817. device->path = SDL_strdup(dev_name);
  818. CloseHandle(hFile);
  819. hFile = INVALID_HANDLE_VALUE;
  820. device->joystick_id = SDL_GetNextJoystickInstanceID();
  821. #ifdef DEBUG_RAWINPUT
  822. 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);
  823. #endif
  824. /* Add it to the list */
  825. RAWINPUT_AcquireDevice(device);
  826. for (curr = SDL_RAWINPUT_devices, last = NULL; curr; last = curr, curr = curr->next) {
  827. }
  828. if (last) {
  829. last->next = device;
  830. } else {
  831. SDL_RAWINPUT_devices = device;
  832. }
  833. ++SDL_RAWINPUT_numjoysticks;
  834. SDL_PrivateJoystickAdded(device->joystick_id);
  835. return;
  836. err:
  837. if (hFile != INVALID_HANDLE_VALUE) {
  838. CloseHandle(hFile);
  839. }
  840. if (device) {
  841. if (device->name) {
  842. SDL_free(device->name);
  843. }
  844. if (device->path) {
  845. SDL_free(device->path);
  846. }
  847. SDL_free(device);
  848. }
  849. #undef CHECK
  850. }
  851. static void RAWINPUT_DelDevice(SDL_RAWINPUT_Device *device, SDL_bool send_event)
  852. {
  853. SDL_RAWINPUT_Device *curr, *last;
  854. for (curr = SDL_RAWINPUT_devices, last = NULL; curr; last = curr, curr = curr->next) {
  855. if (curr == device) {
  856. if (last) {
  857. last->next = curr->next;
  858. } else {
  859. SDL_RAWINPUT_devices = curr->next;
  860. }
  861. --SDL_RAWINPUT_numjoysticks;
  862. SDL_PrivateJoystickRemoved(device->joystick_id);
  863. #ifdef DEBUG_RAWINPUT
  864. SDL_Log("Removing RAWINPUT device '%s' VID 0x%.4x, PID 0x%.4x, version %d, handle %p\n", device->name, device->vendor_id, device->product_id, device->version, device->hDevice);
  865. #endif
  866. RAWINPUT_ReleaseDevice(device);
  867. return;
  868. }
  869. }
  870. }
  871. static void RAWINPUT_DetectDevices(void)
  872. {
  873. UINT device_count = 0;
  874. if ((GetRawInputDeviceList(NULL, &device_count, sizeof(RAWINPUTDEVICELIST)) != -1) && device_count > 0) {
  875. PRAWINPUTDEVICELIST devices = NULL;
  876. UINT i;
  877. devices = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * device_count);
  878. if (devices) {
  879. device_count = GetRawInputDeviceList(devices, &device_count, sizeof(RAWINPUTDEVICELIST));
  880. if (device_count != (UINT)-1) {
  881. for (i = 0; i < device_count; ++i) {
  882. RAWINPUT_AddDevice(devices[i].hDevice);
  883. }
  884. }
  885. SDL_free(devices);
  886. }
  887. }
  888. }
  889. static void RAWINPUT_RemoveDevices(void)
  890. {
  891. while (SDL_RAWINPUT_devices) {
  892. RAWINPUT_DelDevice(SDL_RAWINPUT_devices, SDL_FALSE);
  893. }
  894. SDL_assert(SDL_RAWINPUT_numjoysticks == 0);
  895. }
  896. static int RAWINPUT_JoystickInit(void)
  897. {
  898. SDL_assert(!SDL_RAWINPUT_inited);
  899. if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT, SDL_TRUE)) {
  900. return 0;
  901. }
  902. if (!WIN_IsWindowsVistaOrGreater()) {
  903. /* According to bug 6400, this doesn't work on Windows XP */
  904. return -1;
  905. }
  906. if (WIN_LoadHIDDLL() < 0) {
  907. return -1;
  908. }
  909. SDL_RAWINPUT_inited = SDL_TRUE;
  910. RAWINPUT_DetectDevices();
  911. return 0;
  912. }
  913. static int RAWINPUT_JoystickGetCount(void)
  914. {
  915. return SDL_RAWINPUT_numjoysticks;
  916. }
  917. SDL_bool RAWINPUT_IsEnabled(void)
  918. {
  919. return SDL_RAWINPUT_inited && !SDL_RAWINPUT_remote_desktop;
  920. }
  921. SDL_bool RAWINPUT_IsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name)
  922. {
  923. SDL_RAWINPUT_Device *device;
  924. /* If we're being asked about a device, that means another API just detected one, so rescan */
  925. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  926. xinput_device_change = SDL_TRUE;
  927. #endif
  928. device = SDL_RAWINPUT_devices;
  929. while (device) {
  930. if (vendor_id == device->vendor_id && product_id == device->product_id) {
  931. return SDL_TRUE;
  932. }
  933. /* The Xbox 360 wireless controller shows up as product 0 in WGI.
  934. Try to match it to a Raw Input device via name or known product ID. */
  935. if (vendor_id == device->vendor_id && product_id == 0 &&
  936. ((name && SDL_strstr(device->name, name) != NULL) ||
  937. (device->vendor_id == USB_VENDOR_MICROSOFT &&
  938. device->product_id == USB_PRODUCT_XBOX360_XUSB_CONTROLLER))) {
  939. return SDL_TRUE;
  940. }
  941. /* The Xbox One controller shows up as a hardcoded raw input VID/PID */
  942. if (name && SDL_strcmp(name, "Xbox One Game Controller") == 0 &&
  943. device->vendor_id == USB_VENDOR_MICROSOFT &&
  944. device->product_id == USB_PRODUCT_XBOX_ONE_XBOXGIP_CONTROLLER) {
  945. return SDL_TRUE;
  946. }
  947. device = device->next;
  948. }
  949. return SDL_FALSE;
  950. }
  951. static void RAWINPUT_PostUpdate(void)
  952. {
  953. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  954. SDL_bool unmapped_guide_pressed = SDL_FALSE;
  955. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  956. if (!wgi_state.dirty) {
  957. int ii;
  958. for (ii = 0; ii < wgi_state.per_gamepad_count; ii++) {
  959. WindowsGamingInputGamepadState *gamepad_state = wgi_state.per_gamepad[ii];
  960. if (!gamepad_state->used && (gamepad_state->state.Buttons & GamepadButtons_GUIDE)) {
  961. unmapped_guide_pressed = SDL_TRUE;
  962. break;
  963. }
  964. }
  965. }
  966. wgi_state.dirty = SDL_TRUE;
  967. #endif
  968. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  969. if (!xinput_state_dirty) {
  970. int ii;
  971. for (ii = 0; ii < SDL_arraysize(xinput_state); ii++) {
  972. if (xinput_state[ii].connected && !xinput_state[ii].used && (xinput_state[ii].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE)) {
  973. unmapped_guide_pressed = SDL_TRUE;
  974. break;
  975. }
  976. }
  977. }
  978. xinput_state_dirty = SDL_TRUE;
  979. #endif
  980. if (unmapped_guide_pressed) {
  981. if (guide_button_candidate.joystick && !guide_button_candidate.last_joystick) {
  982. SDL_Joystick *joystick = guide_button_candidate.joystick;
  983. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  984. if (ctx->guide_hack) {
  985. int guide_button = joystick->nbuttons - 1;
  986. SDL_PrivateJoystickButton(guide_button_candidate.joystick, guide_button, SDL_PRESSED);
  987. }
  988. guide_button_candidate.last_joystick = guide_button_candidate.joystick;
  989. }
  990. } else if (guide_button_candidate.last_joystick) {
  991. SDL_Joystick *joystick = guide_button_candidate.last_joystick;
  992. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  993. if (ctx->guide_hack) {
  994. int guide_button = joystick->nbuttons - 1;
  995. SDL_PrivateJoystickButton(joystick, guide_button, SDL_RELEASED);
  996. }
  997. guide_button_candidate.last_joystick = NULL;
  998. }
  999. guide_button_candidate.joystick = NULL;
  1000. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  1001. }
  1002. static void RAWINPUT_JoystickDetect(void)
  1003. {
  1004. SDL_bool remote_desktop;
  1005. if (!SDL_RAWINPUT_inited) {
  1006. return;
  1007. }
  1008. remote_desktop = GetSystemMetrics(SM_REMOTESESSION) ? SDL_TRUE : SDL_FALSE;
  1009. if (remote_desktop != SDL_RAWINPUT_remote_desktop) {
  1010. SDL_RAWINPUT_remote_desktop = remote_desktop;
  1011. WINDOWS_RAWINPUTEnabledChanged();
  1012. if (remote_desktop) {
  1013. RAWINPUT_RemoveDevices();
  1014. WINDOWS_JoystickDetect();
  1015. } else {
  1016. WINDOWS_JoystickDetect();
  1017. RAWINPUT_DetectDevices();
  1018. }
  1019. }
  1020. RAWINPUT_PostUpdate();
  1021. }
  1022. static SDL_RAWINPUT_Device *RAWINPUT_GetDeviceByIndex(int device_index)
  1023. {
  1024. SDL_RAWINPUT_Device *device = SDL_RAWINPUT_devices;
  1025. while (device) {
  1026. if (device_index == 0) {
  1027. break;
  1028. }
  1029. --device_index;
  1030. device = device->next;
  1031. }
  1032. return device;
  1033. }
  1034. static const char *RAWINPUT_JoystickGetDeviceName(int device_index)
  1035. {
  1036. return RAWINPUT_GetDeviceByIndex(device_index)->name;
  1037. }
  1038. static const char *RAWINPUT_JoystickGetDevicePath(int device_index)
  1039. {
  1040. return RAWINPUT_GetDeviceByIndex(device_index)->path;
  1041. }
  1042. static int RAWINPUT_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index)
  1043. {
  1044. return RAWINPUT_GetDeviceByIndex(device_index)->steam_virtual_gamepad_slot;
  1045. }
  1046. static int RAWINPUT_JoystickGetDevicePlayerIndex(int device_index)
  1047. {
  1048. return -1;
  1049. }
  1050. static void RAWINPUT_JoystickSetDevicePlayerIndex(int device_index, int player_index)
  1051. {
  1052. }
  1053. static SDL_JoystickGUID RAWINPUT_JoystickGetDeviceGUID(int device_index)
  1054. {
  1055. return RAWINPUT_GetDeviceByIndex(device_index)->guid;
  1056. }
  1057. static SDL_JoystickID RAWINPUT_JoystickGetDeviceInstanceID(int device_index)
  1058. {
  1059. return RAWINPUT_GetDeviceByIndex(device_index)->joystick_id;
  1060. }
  1061. static int SDLCALL RAWINPUT_SortValueCaps(const void *A, const void *B)
  1062. {
  1063. HIDP_VALUE_CAPS *capsA = (HIDP_VALUE_CAPS *)A;
  1064. HIDP_VALUE_CAPS *capsB = (HIDP_VALUE_CAPS *)B;
  1065. /* Sort by Usage for single values, or UsageMax for range of values */
  1066. return (int)capsA->NotRange.Usage - capsB->NotRange.Usage;
  1067. }
  1068. static int RAWINPUT_JoystickOpen(SDL_Joystick *joystick, int device_index)
  1069. {
  1070. SDL_RAWINPUT_Device *device = RAWINPUT_GetDeviceByIndex(device_index);
  1071. RAWINPUT_DeviceContext *ctx;
  1072. HIDP_CAPS caps;
  1073. HIDP_BUTTON_CAPS *button_caps;
  1074. HIDP_VALUE_CAPS *value_caps;
  1075. ULONG i;
  1076. ctx = (RAWINPUT_DeviceContext *)SDL_calloc(1, sizeof(RAWINPUT_DeviceContext));
  1077. if (!ctx) {
  1078. return SDL_OutOfMemory();
  1079. }
  1080. joystick->hwdata = ctx;
  1081. ctx->device = RAWINPUT_AcquireDevice(device);
  1082. device->joystick = joystick;
  1083. if (device->is_xinput) {
  1084. /* We'll try to get guide button and trigger axes from XInput */
  1085. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1086. xinput_device_change = SDL_TRUE;
  1087. ctx->xinput_enabled = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT, SDL_TRUE);
  1088. if (ctx->xinput_enabled && (WIN_LoadXInputDLL() < 0 || !XINPUTGETSTATE)) {
  1089. ctx->xinput_enabled = SDL_FALSE;
  1090. }
  1091. ctx->xinput_slot = XUSER_INDEX_ANY;
  1092. #endif
  1093. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1094. RAWINPUT_InitWindowsGamingInput(ctx);
  1095. #endif
  1096. }
  1097. ctx->is_xinput = device->is_xinput;
  1098. ctx->is_xboxone = device->is_xboxone;
  1099. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1100. ctx->match_state = 0x0000008800000000ULL; /* Trigger axes at rest */
  1101. #endif
  1102. ctx->preparsed_data = device->preparsed_data;
  1103. ctx->max_data_length = SDL_HidP_MaxDataListLength(HidP_Input, ctx->preparsed_data);
  1104. ctx->data = (HIDP_DATA *)SDL_malloc(ctx->max_data_length * sizeof(*ctx->data));
  1105. if (!ctx->data) {
  1106. RAWINPUT_JoystickClose(joystick);
  1107. return SDL_OutOfMemory();
  1108. }
  1109. if (SDL_HidP_GetCaps(ctx->preparsed_data, &caps) != HIDP_STATUS_SUCCESS) {
  1110. RAWINPUT_JoystickClose(joystick);
  1111. return SDL_SetError("Couldn't get device capabilities");
  1112. }
  1113. button_caps = SDL_stack_alloc(HIDP_BUTTON_CAPS, caps.NumberInputButtonCaps);
  1114. if (SDL_HidP_GetButtonCaps(HidP_Input, button_caps, &caps.NumberInputButtonCaps, ctx->preparsed_data) != HIDP_STATUS_SUCCESS) {
  1115. RAWINPUT_JoystickClose(joystick);
  1116. return SDL_SetError("Couldn't get device button capabilities");
  1117. }
  1118. value_caps = SDL_stack_alloc(HIDP_VALUE_CAPS, caps.NumberInputValueCaps);
  1119. if (SDL_HidP_GetValueCaps(HidP_Input, value_caps, &caps.NumberInputValueCaps, ctx->preparsed_data) != HIDP_STATUS_SUCCESS) {
  1120. RAWINPUT_JoystickClose(joystick);
  1121. SDL_stack_free(button_caps);
  1122. return SDL_SetError("Couldn't get device value capabilities");
  1123. }
  1124. /* Sort the axes by usage, so X comes before Y, etc. */
  1125. SDL_qsort(value_caps, caps.NumberInputValueCaps, sizeof(*value_caps), RAWINPUT_SortValueCaps);
  1126. for (i = 0; i < caps.NumberInputButtonCaps; ++i) {
  1127. HIDP_BUTTON_CAPS *cap = &button_caps[i];
  1128. if (cap->UsagePage == USB_USAGEPAGE_BUTTON) {
  1129. int count;
  1130. if (cap->IsRange) {
  1131. count = 1 + (cap->Range.DataIndexMax - cap->Range.DataIndexMin);
  1132. } else {
  1133. count = 1;
  1134. }
  1135. joystick->nbuttons += count;
  1136. }
  1137. }
  1138. if (joystick->nbuttons > 0) {
  1139. int button_index = 0;
  1140. ctx->button_indices = (USHORT *)SDL_malloc(joystick->nbuttons * sizeof(*ctx->button_indices));
  1141. if (!ctx->button_indices) {
  1142. RAWINPUT_JoystickClose(joystick);
  1143. SDL_stack_free(value_caps);
  1144. SDL_stack_free(button_caps);
  1145. return SDL_OutOfMemory();
  1146. }
  1147. for (i = 0; i < caps.NumberInputButtonCaps; ++i) {
  1148. HIDP_BUTTON_CAPS *cap = &button_caps[i];
  1149. if (cap->UsagePage == USB_USAGEPAGE_BUTTON) {
  1150. if (cap->IsRange) {
  1151. int j, count = 1 + (cap->Range.DataIndexMax - cap->Range.DataIndexMin);
  1152. for (j = 0; j < count; ++j) {
  1153. ctx->button_indices[button_index++] = cap->Range.DataIndexMin + j;
  1154. }
  1155. } else {
  1156. ctx->button_indices[button_index++] = cap->NotRange.DataIndex;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. if (ctx->is_xinput && joystick->nbuttons == 10) {
  1162. ctx->guide_hack = SDL_TRUE;
  1163. joystick->nbuttons += 1;
  1164. }
  1165. SDL_stack_free(button_caps);
  1166. for (i = 0; i < caps.NumberInputValueCaps; ++i) {
  1167. HIDP_VALUE_CAPS *cap = &value_caps[i];
  1168. if (cap->IsRange) {
  1169. continue;
  1170. }
  1171. if (ctx->trigger_hack && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) {
  1172. continue;
  1173. }
  1174. if (cap->NotRange.Usage == USB_USAGE_GENERIC_HAT) {
  1175. joystick->nhats += 1;
  1176. continue;
  1177. }
  1178. if (ctx->is_xinput && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) {
  1179. continue;
  1180. }
  1181. joystick->naxes += 1;
  1182. }
  1183. if (joystick->naxes > 0) {
  1184. int axis_index = 0;
  1185. ctx->axis_indices = (USHORT *)SDL_malloc(joystick->naxes * sizeof(*ctx->axis_indices));
  1186. if (!ctx->axis_indices) {
  1187. RAWINPUT_JoystickClose(joystick);
  1188. SDL_stack_free(value_caps);
  1189. return SDL_OutOfMemory();
  1190. }
  1191. for (i = 0; i < caps.NumberInputValueCaps; ++i) {
  1192. HIDP_VALUE_CAPS *cap = &value_caps[i];
  1193. if (cap->IsRange) {
  1194. continue;
  1195. }
  1196. if (cap->NotRange.Usage == USB_USAGE_GENERIC_HAT) {
  1197. continue;
  1198. }
  1199. if (ctx->is_xinput && cap->NotRange.Usage == USB_USAGE_GENERIC_Z) {
  1200. ctx->trigger_hack = SDL_TRUE;
  1201. ctx->trigger_hack_index = cap->NotRange.DataIndex;
  1202. continue;
  1203. }
  1204. ctx->axis_indices[axis_index++] = cap->NotRange.DataIndex;
  1205. }
  1206. }
  1207. if (ctx->trigger_hack) {
  1208. joystick->naxes += 2;
  1209. }
  1210. if (joystick->nhats > 0) {
  1211. int hat_index = 0;
  1212. ctx->hat_indices = (USHORT *)SDL_malloc(joystick->nhats * sizeof(*ctx->hat_indices));
  1213. if (!ctx->hat_indices) {
  1214. RAWINPUT_JoystickClose(joystick);
  1215. SDL_stack_free(value_caps);
  1216. return SDL_OutOfMemory();
  1217. }
  1218. for (i = 0; i < caps.NumberInputValueCaps; ++i) {
  1219. HIDP_VALUE_CAPS *cap = &value_caps[i];
  1220. if (cap->IsRange) {
  1221. continue;
  1222. }
  1223. if (cap->NotRange.Usage != USB_USAGE_GENERIC_HAT) {
  1224. continue;
  1225. }
  1226. ctx->hat_indices[hat_index++] = cap->NotRange.DataIndex;
  1227. }
  1228. }
  1229. SDL_stack_free(value_caps);
  1230. joystick->epowerlevel = SDL_JOYSTICK_POWER_UNKNOWN;
  1231. return 0;
  1232. }
  1233. static int RAWINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  1234. {
  1235. #if defined(SDL_JOYSTICK_RAWINPUT_WGI) || defined(SDL_JOYSTICK_RAWINPUT_XINPUT)
  1236. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1237. #endif
  1238. SDL_bool rumbled = SDL_FALSE;
  1239. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1240. /* Prefer XInput over WGI because it allows rumble in the background */
  1241. if (!rumbled && ctx->xinput_correlated) {
  1242. XINPUT_VIBRATION XVibration;
  1243. if (!XINPUTSETSTATE) {
  1244. return SDL_Unsupported();
  1245. }
  1246. XVibration.wLeftMotorSpeed = low_frequency_rumble;
  1247. XVibration.wRightMotorSpeed = high_frequency_rumble;
  1248. if (XINPUTSETSTATE(ctx->xinput_slot, &XVibration) == ERROR_SUCCESS) {
  1249. rumbled = SDL_TRUE;
  1250. } else {
  1251. return SDL_SetError("XInputSetState() failed");
  1252. }
  1253. }
  1254. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1255. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1256. if (!rumbled && ctx->wgi_correlated) {
  1257. WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot;
  1258. HRESULT hr;
  1259. gamepad_state->vibration.LeftMotor = (DOUBLE)low_frequency_rumble / SDL_MAX_UINT16;
  1260. gamepad_state->vibration.RightMotor = (DOUBLE)high_frequency_rumble / SDL_MAX_UINT16;
  1261. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, gamepad_state->vibration);
  1262. if (SUCCEEDED(hr)) {
  1263. rumbled = SDL_TRUE;
  1264. }
  1265. }
  1266. #endif
  1267. if (!rumbled) {
  1268. #if defined(SDL_JOYSTICK_RAWINPUT_WGI) || defined(SDL_JOYSTICK_RAWINPUT_XINPUT)
  1269. return SDL_SetError("Controller isn't correlated yet, try hitting a button first");
  1270. #else
  1271. return SDL_Unsupported();
  1272. #endif
  1273. }
  1274. return 0;
  1275. }
  1276. static int RAWINPUT_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  1277. {
  1278. #if defined(SDL_JOYSTICK_RAWINPUT_WGI)
  1279. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1280. if (ctx->wgi_correlated) {
  1281. WindowsGamingInputGamepadState *gamepad_state = ctx->wgi_slot;
  1282. HRESULT hr;
  1283. gamepad_state->vibration.LeftTrigger = (DOUBLE)left_rumble / SDL_MAX_UINT16;
  1284. gamepad_state->vibration.RightTrigger = (DOUBLE)right_rumble / SDL_MAX_UINT16;
  1285. hr = __x_ABI_CWindows_CGaming_CInput_CIGamepad_put_Vibration(gamepad_state->gamepad, gamepad_state->vibration);
  1286. if (!SUCCEEDED(hr)) {
  1287. return SDL_SetError("Setting vibration failed: 0x%lx\n", hr);
  1288. }
  1289. return 0;
  1290. } else {
  1291. return SDL_SetError("Controller isn't correlated yet, try hitting a button first");
  1292. }
  1293. #else
  1294. return SDL_Unsupported();
  1295. #endif
  1296. }
  1297. static Uint32 RAWINPUT_JoystickGetCapabilities(SDL_Joystick *joystick)
  1298. {
  1299. Uint32 result = 0;
  1300. #if defined(SDL_JOYSTICK_RAWINPUT_XINPUT) || defined(SDL_JOYSTICK_RAWINPUT_WGI)
  1301. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1302. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1303. if (ctx->is_xinput) {
  1304. result |= SDL_JOYCAP_RUMBLE;
  1305. }
  1306. #endif
  1307. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1308. if (ctx->is_xinput) {
  1309. result |= SDL_JOYCAP_RUMBLE;
  1310. if (ctx->is_xboxone) {
  1311. result |= SDL_JOYCAP_RUMBLE_TRIGGERS;
  1312. }
  1313. }
  1314. #endif
  1315. #endif /**/
  1316. return result;
  1317. }
  1318. static int RAWINPUT_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  1319. {
  1320. return SDL_Unsupported();
  1321. }
  1322. static int RAWINPUT_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size)
  1323. {
  1324. return SDL_Unsupported();
  1325. }
  1326. static int RAWINPUT_JoystickSetSensorsEnabled(SDL_Joystick *joystick, SDL_bool enabled)
  1327. {
  1328. return SDL_Unsupported();
  1329. }
  1330. static HIDP_DATA *GetData(USHORT index, HIDP_DATA *data, ULONG length)
  1331. {
  1332. ULONG i;
  1333. /* Check to see if the data is at the expected offset */
  1334. if (index < length && data[index].DataIndex == index) {
  1335. return &data[index];
  1336. }
  1337. /* Loop through the data to find it */
  1338. for (i = 0; i < length; ++i) {
  1339. if (data[i].DataIndex == index) {
  1340. return &data[i];
  1341. }
  1342. }
  1343. return NULL;
  1344. }
  1345. /* This is the packet format for Xbox 360 and Xbox One controllers on Windows,
  1346. however with this interface there is no rumble support, no guide button,
  1347. and the left and right triggers are tied together as a single axis.
  1348. We use XInput and Windows.Gaming.Input to make up for these shortcomings.
  1349. */
  1350. static void RAWINPUT_HandleStatePacket(SDL_Joystick *joystick, Uint8 *data, int size)
  1351. {
  1352. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1353. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1354. /* Map new buttons and axes into game controller controls */
  1355. static const int button_map[] = {
  1356. SDL_CONTROLLER_BUTTON_A,
  1357. SDL_CONTROLLER_BUTTON_B,
  1358. SDL_CONTROLLER_BUTTON_X,
  1359. SDL_CONTROLLER_BUTTON_Y,
  1360. SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
  1361. SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
  1362. SDL_CONTROLLER_BUTTON_BACK,
  1363. SDL_CONTROLLER_BUTTON_START,
  1364. SDL_CONTROLLER_BUTTON_LEFTSTICK,
  1365. SDL_CONTROLLER_BUTTON_RIGHTSTICK
  1366. };
  1367. #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))
  1368. static const int hat_map[] = {
  1369. 0,
  1370. (1 << SDL_CONTROLLER_BUTTON_DPAD_UP),
  1371. (1 << SDL_CONTROLLER_BUTTON_DPAD_UP) | (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT),
  1372. (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT),
  1373. (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN) | (1 << SDL_CONTROLLER_BUTTON_DPAD_RIGHT),
  1374. (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN),
  1375. (1 << SDL_CONTROLLER_BUTTON_DPAD_DOWN) | (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT),
  1376. (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT),
  1377. (1 << SDL_CONTROLLER_BUTTON_DPAD_UP) | (1 << SDL_CONTROLLER_BUTTON_DPAD_LEFT),
  1378. 0,
  1379. };
  1380. Uint64 match_state = ctx->match_state;
  1381. /* Update match_state with button bit, then fall through */
  1382. #define SDL_PrivateJoystickButton(joystick, button, state) \
  1383. if (button < SDL_arraysize(button_map)) { \
  1384. Uint64 button_bit = 1ull << button_map[button]; \
  1385. match_state = (match_state & ~button_bit) | (button_bit * (state)); \
  1386. } \
  1387. SDL_PrivateJoystickButton(joystick, button, state)
  1388. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_AXES
  1389. /* Grab high 4 bits of value, then fall through */
  1390. #define AddAxisToMatchState(axis, value) \
  1391. { \
  1392. match_state = (match_state & ~(0xFull << (4 * axis + 16))) | ((value)&0xF000ull) << (4 * axis + 4); \
  1393. }
  1394. #define SDL_PrivateJoystickAxis(joystick, axis, value) \
  1395. if (axis < 4) \
  1396. AddAxisToMatchState(axis, value); \
  1397. SDL_PrivateJoystickAxis(joystick, axis, value)
  1398. #endif
  1399. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  1400. ULONG data_length = ctx->max_data_length;
  1401. int i;
  1402. int nbuttons = joystick->nbuttons - (ctx->guide_hack * 1);
  1403. int naxes = joystick->naxes - (ctx->trigger_hack * 2);
  1404. int nhats = joystick->nhats;
  1405. Uint32 button_mask = 0;
  1406. if (SDL_HidP_GetData(HidP_Input, ctx->data, &data_length, ctx->preparsed_data, (PCHAR)data, size) != HIDP_STATUS_SUCCESS) {
  1407. return;
  1408. }
  1409. for (i = 0; i < nbuttons; ++i) {
  1410. HIDP_DATA *item = GetData(ctx->button_indices[i], ctx->data, data_length);
  1411. if (item && item->On) {
  1412. button_mask |= (1 << i);
  1413. }
  1414. }
  1415. for (i = 0; i < nbuttons; ++i) {
  1416. SDL_PrivateJoystickButton(joystick, i, (button_mask & (1 << i)) ? SDL_PRESSED : SDL_RELEASED);
  1417. }
  1418. for (i = 0; i < naxes; ++i) {
  1419. HIDP_DATA *item = GetData(ctx->axis_indices[i], ctx->data, data_length);
  1420. if (item) {
  1421. Sint16 axis = (int)(Uint16)item->RawValue - 0x8000;
  1422. SDL_PrivateJoystickAxis(joystick, i, axis);
  1423. }
  1424. }
  1425. for (i = 0; i < nhats; ++i) {
  1426. HIDP_DATA *item = GetData(ctx->hat_indices[i], ctx->data, data_length);
  1427. if (item) {
  1428. Uint8 hat = SDL_HAT_CENTERED;
  1429. const Uint8 hat_states[] = {
  1430. SDL_HAT_CENTERED,
  1431. SDL_HAT_UP,
  1432. SDL_HAT_UP | SDL_HAT_RIGHT,
  1433. SDL_HAT_RIGHT,
  1434. SDL_HAT_DOWN | SDL_HAT_RIGHT,
  1435. SDL_HAT_DOWN,
  1436. SDL_HAT_DOWN | SDL_HAT_LEFT,
  1437. SDL_HAT_LEFT,
  1438. SDL_HAT_UP | SDL_HAT_LEFT,
  1439. SDL_HAT_CENTERED,
  1440. };
  1441. ULONG state = item->RawValue;
  1442. if (state < SDL_arraysize(hat_states)) {
  1443. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1444. match_state = (match_state & ~HAT_MASK) | hat_map[state];
  1445. #endif
  1446. hat = hat_states[state];
  1447. }
  1448. SDL_PrivateJoystickHat(joystick, i, hat);
  1449. }
  1450. }
  1451. #ifdef SDL_PrivateJoystickButton
  1452. #undef SDL_PrivateJoystickButton
  1453. #endif
  1454. #ifdef SDL_PrivateJoystickAxis
  1455. #undef SDL_PrivateJoystickAxis
  1456. #endif
  1457. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  1458. #define AddTriggerToMatchState(axis, value) \
  1459. { \
  1460. int match_axis = axis + SDL_JOYSTICK_RAWINPUT_MATCH_COUNT - joystick->naxes; \
  1461. AddAxisToMatchState(match_axis, value); \
  1462. }
  1463. #endif /* SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS */
  1464. if (ctx->trigger_hack) {
  1465. SDL_bool has_trigger_data = SDL_FALSE;
  1466. int left_trigger = joystick->naxes - 2;
  1467. int right_trigger = joystick->naxes - 1;
  1468. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1469. /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */
  1470. if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) {
  1471. has_trigger_data = SDL_TRUE;
  1472. }
  1473. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1474. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1475. if (!has_trigger_data && ctx->wgi_correlated) {
  1476. has_trigger_data = SDL_TRUE;
  1477. }
  1478. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  1479. #ifndef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  1480. if (!has_trigger_data)
  1481. #endif
  1482. {
  1483. HIDP_DATA *item = GetData(ctx->trigger_hack_index, ctx->data, data_length);
  1484. if (item) {
  1485. Sint16 value = (int)(Uint16)item->RawValue - 0x8000;
  1486. Sint16 left_value = (value > 0) ? (value * 2 - 32767) : SDL_MIN_SINT16;
  1487. Sint16 right_value = (value < 0) ? (-value * 2 - 32769) : SDL_MIN_SINT16;
  1488. #ifdef SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS
  1489. AddTriggerToMatchState(left_trigger, left_value);
  1490. AddTriggerToMatchState(right_trigger, right_value);
  1491. if (!has_trigger_data)
  1492. #endif /* SDL_JOYSTICK_RAWINPUT_MATCH_TRIGGERS */
  1493. {
  1494. SDL_PrivateJoystickAxis(joystick, left_trigger, left_value);
  1495. SDL_PrivateJoystickAxis(joystick, right_trigger, right_value);
  1496. }
  1497. }
  1498. }
  1499. }
  1500. #ifdef AddAxisToMatchState
  1501. #undef AddAxisToMatchState
  1502. #endif
  1503. #ifdef AddTriggerToMatchState
  1504. #undef AddTriggerToMatchState
  1505. #endif
  1506. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1507. if (ctx->is_xinput) {
  1508. ctx->match_state = match_state;
  1509. ctx->last_state_packet = SDL_GetTicks();
  1510. }
  1511. #endif
  1512. }
  1513. static void RAWINPUT_UpdateOtherAPIs(SDL_Joystick *joystick)
  1514. {
  1515. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1516. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1517. SDL_bool has_trigger_data = SDL_FALSE;
  1518. SDL_bool correlated = SDL_FALSE;
  1519. WindowsMatchState match_state_xinput;
  1520. int guide_button = joystick->nbuttons - 1;
  1521. int left_trigger = joystick->naxes - 2;
  1522. int right_trigger = joystick->naxes - 1;
  1523. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1524. SDL_bool xinput_correlated;
  1525. #endif
  1526. RAWINPUT_FillMatchState(&match_state_xinput, ctx->match_state);
  1527. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1528. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1529. xinput_correlated = ctx->xinput_correlated;
  1530. #else
  1531. xinput_correlated = SDL_FALSE;
  1532. #endif
  1533. /* Parallel logic to WINDOWS_XINPUT below */
  1534. RAWINPUT_UpdateWindowsGamingInput();
  1535. if (ctx->wgi_correlated &&
  1536. !joystick->low_frequency_rumble && !joystick->high_frequency_rumble &&
  1537. !joystick->left_trigger_rumble && !joystick->right_trigger_rumble) {
  1538. /* We have been previously correlated, ensure we are still matching, see comments in XINPUT section */
  1539. if (RAWINPUT_WindowsGamingInputSlotMatches(&match_state_xinput, ctx->wgi_slot, xinput_correlated)) {
  1540. ctx->wgi_uncorrelate_count = 0;
  1541. } else {
  1542. ++ctx->wgi_uncorrelate_count;
  1543. /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event
  1544. pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but
  1545. let's set it to 5 to be safe. An incorrect un-correlation will simply result in lower precision
  1546. triggers for a frame. */
  1547. if (ctx->wgi_uncorrelate_count >= 5) {
  1548. #ifdef DEBUG_RAWINPUT
  1549. SDL_Log("UN-Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, ctx->wgi_slot);
  1550. #endif
  1551. RAWINPUT_MarkWindowsGamingInputSlotFree(ctx->wgi_slot);
  1552. ctx->wgi_correlated = SDL_FALSE;
  1553. ctx->wgi_correlation_count = 0;
  1554. /* Force release of Guide button, it can't possibly be down on this device now. */
  1555. /* It gets left down if we were actually correlated incorrectly and it was released on the WindowsGamingInput
  1556. device but we didn't get a state packet. */
  1557. if (ctx->guide_hack) {
  1558. SDL_PrivateJoystickButton(joystick, guide_button, SDL_RELEASED);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. if (!ctx->wgi_correlated) {
  1564. SDL_bool new_correlation_count = 0;
  1565. if (RAWINPUT_MissingWindowsGamingInputSlot()) {
  1566. Uint8 correlation_id = 0;
  1567. WindowsGamingInputGamepadState *slot_idx = NULL;
  1568. if (RAWINPUT_GuessWindowsGamingInputSlot(&match_state_xinput, &correlation_id, &slot_idx, xinput_correlated)) {
  1569. /* we match exactly one WindowsGamingInput device */
  1570. /* Probably can do without wgi_correlation_count, just check and clear wgi_slot to NULL, unless we need
  1571. even more frames to be sure. */
  1572. if (ctx->wgi_correlation_count && ctx->wgi_slot == slot_idx) {
  1573. /* was correlated previously, and still the same device */
  1574. if (ctx->wgi_correlation_id + 1 == correlation_id) {
  1575. /* no one else was correlated in the meantime */
  1576. new_correlation_count = ctx->wgi_correlation_count + 1;
  1577. if (new_correlation_count == 2) {
  1578. /* correlation stayed steady and uncontested across multiple frames, guaranteed match */
  1579. ctx->wgi_correlated = SDL_TRUE;
  1580. #ifdef DEBUG_RAWINPUT
  1581. SDL_Log("Correlated joystick %d to WindowsGamingInput device #%d\n", joystick->instance_id, slot_idx);
  1582. #endif
  1583. correlated = SDL_TRUE;
  1584. RAWINPUT_MarkWindowsGamingInputSlotUsed(ctx->wgi_slot, ctx);
  1585. /* If the generalized Guide button was using us, it doesn't need to anymore */
  1586. if (guide_button_candidate.joystick == joystick) {
  1587. guide_button_candidate.joystick = NULL;
  1588. }
  1589. if (guide_button_candidate.last_joystick == joystick) {
  1590. guide_button_candidate.last_joystick = NULL;
  1591. }
  1592. }
  1593. } else {
  1594. /* someone else also possibly correlated to this device, start over */
  1595. new_correlation_count = 1;
  1596. }
  1597. } else {
  1598. /* new possible correlation */
  1599. new_correlation_count = 1;
  1600. ctx->wgi_slot = slot_idx;
  1601. }
  1602. ctx->wgi_correlation_id = correlation_id;
  1603. } else {
  1604. /* Match multiple WindowsGamingInput devices, or none (possibly due to no buttons pressed) */
  1605. }
  1606. }
  1607. ctx->wgi_correlation_count = new_correlation_count;
  1608. } else {
  1609. correlated = SDL_TRUE;
  1610. }
  1611. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  1612. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1613. /* Parallel logic to WINDOWS_GAMING_INPUT above */
  1614. if (ctx->xinput_enabled) {
  1615. RAWINPUT_UpdateXInput();
  1616. if (ctx->xinput_correlated &&
  1617. !joystick->low_frequency_rumble && !joystick->high_frequency_rumble) {
  1618. /* We have been previously correlated, ensure we are still matching */
  1619. /* This is required to deal with two (mostly) un-preventable mis-correlation situations:
  1620. A) Since the HID data stream does not provide an initial state (but polling XInput does), if we open
  1621. 5 controllers (#1-4 XInput mapped, #5 is not), and controller 1 had the A button down (and we don't
  1622. know), and the user presses A on controller #5, we'll see exactly 1 controller with A down (#5) and
  1623. exactly 1 XInput device with A down (#1), and incorrectly correlate. This code will then un-correlate
  1624. when A is released from either controller #1 or #5.
  1625. B) Since the app may not open all controllers, we could have a similar situation where only controller #5
  1626. is opened, and the user holds A on controllers #1 and #5 simultaneously - again we see only 1 controller
  1627. with A down and 1 XInput device with A down, and incorrectly correlate. This should be very unusual
  1628. (only when apps do not open all controllers, yet are listening to Guide button presses, yet
  1629. for some reason want to ignore guide button presses on the un-opened controllers, yet users are
  1630. pressing buttons on the unopened controllers), and will resolve itself when either button is released
  1631. and we un-correlate. We could prevent this by processing the state packets for *all* controllers,
  1632. even un-opened ones, as that would allow more precise correlation.
  1633. */
  1634. if (RAWINPUT_XInputSlotMatches(&match_state_xinput, ctx->xinput_slot)) {
  1635. ctx->xinput_uncorrelate_count = 0;
  1636. } else {
  1637. ++ctx->xinput_uncorrelate_count;
  1638. /* Only un-correlate if this is consistent over multiple Update() calls - the timing of polling/event
  1639. pumping can easily cause this to uncorrelate for a frame. 2 seemed reliable in my testing, but
  1640. let's set it to 5 to be safe. An incorrect un-correlation will simply result in lower precision
  1641. triggers for a frame. */
  1642. if (ctx->xinput_uncorrelate_count >= 5) {
  1643. #ifdef DEBUG_RAWINPUT
  1644. SDL_Log("UN-Correlated joystick %d to XInput device #%d\n", joystick->instance_id, ctx->xinput_slot);
  1645. #endif
  1646. RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot);
  1647. ctx->xinput_correlated = SDL_FALSE;
  1648. ctx->xinput_correlation_count = 0;
  1649. /* Force release of Guide button, it can't possibly be down on this device now. */
  1650. /* It gets left down if we were actually correlated incorrectly and it was released on the XInput
  1651. device but we didn't get a state packet. */
  1652. if (ctx->guide_hack) {
  1653. SDL_PrivateJoystickButton(joystick, guide_button, SDL_RELEASED);
  1654. }
  1655. }
  1656. }
  1657. }
  1658. if (!ctx->xinput_correlated) {
  1659. Uint8 new_correlation_count = 0;
  1660. if (RAWINPUT_MissingXInputSlot()) {
  1661. Uint8 correlation_id = 0;
  1662. Uint8 slot_idx = 0;
  1663. if (RAWINPUT_GuessXInputSlot(&match_state_xinput, &correlation_id, &slot_idx)) {
  1664. /* we match exactly one XInput device */
  1665. /* Probably can do without xinput_correlation_count, just check and clear xinput_slot to ANY, unless
  1666. we need even more frames to be sure */
  1667. if (ctx->xinput_correlation_count && ctx->xinput_slot == slot_idx) {
  1668. /* was correlated previously, and still the same device */
  1669. if (ctx->xinput_correlation_id + 1 == correlation_id) {
  1670. /* no one else was correlated in the meantime */
  1671. new_correlation_count = ctx->xinput_correlation_count + 1;
  1672. if (new_correlation_count == 2) {
  1673. /* correlation stayed steady and uncontested across multiple frames, guaranteed match */
  1674. ctx->xinput_correlated = SDL_TRUE;
  1675. #ifdef DEBUG_RAWINPUT
  1676. SDL_Log("Correlated joystick %d to XInput device #%d\n", joystick->instance_id, slot_idx);
  1677. #endif
  1678. correlated = SDL_TRUE;
  1679. RAWINPUT_MarkXInputSlotUsed(ctx->xinput_slot);
  1680. /* If the generalized Guide button was using us, it doesn't need to anymore */
  1681. if (guide_button_candidate.joystick == joystick) {
  1682. guide_button_candidate.joystick = NULL;
  1683. }
  1684. if (guide_button_candidate.last_joystick == joystick) {
  1685. guide_button_candidate.last_joystick = NULL;
  1686. }
  1687. }
  1688. } else {
  1689. /* someone else also possibly correlated to this device, start over */
  1690. new_correlation_count = 1;
  1691. }
  1692. } else {
  1693. /* new possible correlation */
  1694. new_correlation_count = 1;
  1695. ctx->xinput_slot = slot_idx;
  1696. }
  1697. ctx->xinput_correlation_id = correlation_id;
  1698. } else {
  1699. /* Match multiple XInput devices, or none (possibly due to no buttons pressed) */
  1700. }
  1701. }
  1702. ctx->xinput_correlation_count = new_correlation_count;
  1703. } else {
  1704. correlated = SDL_TRUE;
  1705. }
  1706. }
  1707. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1708. /* Poll for trigger data once (not per-state-packet) */
  1709. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1710. /* Prefer XInput over WindowsGamingInput, it continues to provide data in the background */
  1711. if (!has_trigger_data && ctx->xinput_enabled && ctx->xinput_correlated) {
  1712. RAWINPUT_UpdateXInput();
  1713. if (xinput_state[ctx->xinput_slot].connected) {
  1714. XINPUT_BATTERY_INFORMATION_EX *battery_info = &xinput_state[ctx->xinput_slot].battery;
  1715. if (ctx->guide_hack) {
  1716. SDL_PrivateJoystickButton(joystick, guide_button, (xinput_state[ctx->xinput_slot].state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  1717. }
  1718. if (ctx->trigger_hack) {
  1719. SDL_PrivateJoystickAxis(joystick, left_trigger, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bLeftTrigger * 257) - 32768);
  1720. SDL_PrivateJoystickAxis(joystick, right_trigger, ((int)xinput_state[ctx->xinput_slot].state.Gamepad.bRightTrigger * 257) - 32768);
  1721. }
  1722. has_trigger_data = SDL_TRUE;
  1723. if (battery_info->BatteryType != BATTERY_TYPE_UNKNOWN &&
  1724. battery_info->BatteryType != BATTERY_TYPE_DISCONNECTED) {
  1725. SDL_JoystickPowerLevel ePowerLevel = SDL_JOYSTICK_POWER_UNKNOWN;
  1726. if (battery_info->BatteryType == BATTERY_TYPE_WIRED) {
  1727. ePowerLevel = SDL_JOYSTICK_POWER_WIRED;
  1728. } else {
  1729. switch (battery_info->BatteryLevel) {
  1730. case BATTERY_LEVEL_EMPTY:
  1731. ePowerLevel = SDL_JOYSTICK_POWER_EMPTY;
  1732. break;
  1733. case BATTERY_LEVEL_LOW:
  1734. ePowerLevel = SDL_JOYSTICK_POWER_LOW;
  1735. break;
  1736. case BATTERY_LEVEL_MEDIUM:
  1737. ePowerLevel = SDL_JOYSTICK_POWER_MEDIUM;
  1738. break;
  1739. default:
  1740. case BATTERY_LEVEL_FULL:
  1741. ePowerLevel = SDL_JOYSTICK_POWER_FULL;
  1742. break;
  1743. }
  1744. }
  1745. SDL_PrivateJoystickBatteryLevel(joystick, ePowerLevel);
  1746. }
  1747. }
  1748. }
  1749. #endif /* SDL_JOYSTICK_RAWINPUT_XINPUT */
  1750. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1751. if (!has_trigger_data && ctx->wgi_correlated) {
  1752. RAWINPUT_UpdateWindowsGamingInput(); /* May detect disconnect / cause uncorrelation */
  1753. if (ctx->wgi_correlated) { /* Still connected */
  1754. struct __x_ABI_CWindows_CGaming_CInput_CGamepadReading *state = &ctx->wgi_slot->state;
  1755. if (ctx->guide_hack) {
  1756. SDL_PrivateJoystickButton(joystick, guide_button, (state->Buttons & GamepadButtons_GUIDE) ? SDL_PRESSED : SDL_RELEASED);
  1757. }
  1758. if (ctx->trigger_hack) {
  1759. SDL_PrivateJoystickAxis(joystick, left_trigger, ((int)(state->LeftTrigger * SDL_MAX_UINT16)) - 32768);
  1760. SDL_PrivateJoystickAxis(joystick, right_trigger, ((int)(state->RightTrigger * SDL_MAX_UINT16)) - 32768);
  1761. }
  1762. has_trigger_data = SDL_TRUE;
  1763. }
  1764. }
  1765. #endif /* SDL_JOYSTICK_RAWINPUT_WGI */
  1766. if (!correlated) {
  1767. if (!guide_button_candidate.joystick ||
  1768. (ctx->last_state_packet && (!guide_button_candidate.last_state_packet ||
  1769. SDL_TICKS_PASSED(ctx->last_state_packet, guide_button_candidate.last_state_packet)))) {
  1770. guide_button_candidate.joystick = joystick;
  1771. guide_button_candidate.last_state_packet = ctx->last_state_packet;
  1772. }
  1773. }
  1774. #endif /* SDL_JOYSTICK_RAWINPUT_MATCHING */
  1775. }
  1776. static void RAWINPUT_JoystickUpdate(SDL_Joystick *joystick)
  1777. {
  1778. RAWINPUT_UpdateOtherAPIs(joystick);
  1779. }
  1780. static void RAWINPUT_JoystickClose(SDL_Joystick *joystick)
  1781. {
  1782. RAWINPUT_DeviceContext *ctx = joystick->hwdata;
  1783. #ifdef SDL_JOYSTICK_RAWINPUT_MATCHING
  1784. if (guide_button_candidate.joystick == joystick) {
  1785. guide_button_candidate.joystick = NULL;
  1786. }
  1787. if (guide_button_candidate.last_joystick == joystick) {
  1788. guide_button_candidate.last_joystick = NULL;
  1789. }
  1790. #endif
  1791. if (ctx) {
  1792. SDL_RAWINPUT_Device *device;
  1793. #ifdef SDL_JOYSTICK_RAWINPUT_XINPUT
  1794. xinput_device_change = SDL_TRUE;
  1795. if (ctx->xinput_enabled) {
  1796. if (ctx->xinput_correlated) {
  1797. RAWINPUT_MarkXInputSlotFree(ctx->xinput_slot);
  1798. }
  1799. WIN_UnloadXInputDLL();
  1800. }
  1801. #endif
  1802. #ifdef SDL_JOYSTICK_RAWINPUT_WGI
  1803. RAWINPUT_QuitWindowsGamingInput(ctx);
  1804. #endif
  1805. device = ctx->device;
  1806. if (device) {
  1807. SDL_assert(device->joystick == joystick);
  1808. device->joystick = NULL;
  1809. RAWINPUT_ReleaseDevice(device);
  1810. }
  1811. SDL_free(ctx->data);
  1812. SDL_free(ctx->button_indices);
  1813. SDL_free(ctx->axis_indices);
  1814. SDL_free(ctx->hat_indices);
  1815. SDL_free(ctx);
  1816. joystick->hwdata = NULL;
  1817. }
  1818. }
  1819. int RAWINPUT_RegisterNotifications(HWND hWnd)
  1820. {
  1821. int i;
  1822. RAWINPUTDEVICE rid[SDL_arraysize(subscribed_devices)];
  1823. if (!SDL_RAWINPUT_inited) {
  1824. return 0;
  1825. }
  1826. for (i = 0; i < SDL_arraysize(subscribed_devices); i++) {
  1827. rid[i].usUsagePage = USB_USAGEPAGE_GENERIC_DESKTOP;
  1828. rid[i].usUsage = subscribed_devices[i];
  1829. rid[i].dwFlags = RIDEV_DEVNOTIFY | RIDEV_INPUTSINK; /* Receive messages when in background, including device add/remove */
  1830. rid[i].hwndTarget = hWnd;
  1831. }
  1832. if (!RegisterRawInputDevices(rid, SDL_arraysize(rid), sizeof(RAWINPUTDEVICE))) {
  1833. return SDL_SetError("Couldn't register for raw input events");
  1834. }
  1835. return 0;
  1836. }
  1837. int RAWINPUT_UnregisterNotifications(void)
  1838. {
  1839. int i;
  1840. RAWINPUTDEVICE rid[SDL_arraysize(subscribed_devices)];
  1841. if (!SDL_RAWINPUT_inited) {
  1842. return 0;
  1843. }
  1844. for (i = 0; i < SDL_arraysize(subscribed_devices); i++) {
  1845. rid[i].usUsagePage = USB_USAGEPAGE_GENERIC_DESKTOP;
  1846. rid[i].usUsage = subscribed_devices[i];
  1847. rid[i].dwFlags = RIDEV_REMOVE;
  1848. rid[i].hwndTarget = NULL;
  1849. }
  1850. if (!RegisterRawInputDevices(rid, SDL_arraysize(rid), sizeof(RAWINPUTDEVICE))) {
  1851. return SDL_SetError("Couldn't unregister for raw input events");
  1852. }
  1853. return 0;
  1854. }
  1855. LRESULT CALLBACK
  1856. RAWINPUT_WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1857. {
  1858. LRESULT result = -1;
  1859. if (SDL_RAWINPUT_inited) {
  1860. SDL_LockJoysticks();
  1861. switch (msg) {
  1862. case WM_INPUT_DEVICE_CHANGE:
  1863. {
  1864. HANDLE hDevice = (HANDLE)lParam;
  1865. switch (wParam) {
  1866. case GIDC_ARRIVAL:
  1867. RAWINPUT_AddDevice(hDevice);
  1868. break;
  1869. case GIDC_REMOVAL:
  1870. {
  1871. SDL_RAWINPUT_Device *device;
  1872. device = RAWINPUT_DeviceFromHandle(hDevice);
  1873. if (device) {
  1874. RAWINPUT_DelDevice(device, SDL_TRUE);
  1875. }
  1876. break;
  1877. }
  1878. default:
  1879. break;
  1880. }
  1881. }
  1882. result = 0;
  1883. break;
  1884. case WM_INPUT:
  1885. {
  1886. Uint8 data[sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + USB_PACKET_LENGTH];
  1887. UINT buffer_size = SDL_arraysize(data);
  1888. if ((int)GetRawInputData((HRAWINPUT)lParam, RID_INPUT, data, &buffer_size, sizeof(RAWINPUTHEADER)) > 0) {
  1889. PRAWINPUT raw_input = (PRAWINPUT)data;
  1890. SDL_RAWINPUT_Device *device = RAWINPUT_DeviceFromHandle(raw_input->header.hDevice);
  1891. if (device) {
  1892. SDL_Joystick *joystick = device->joystick;
  1893. if (joystick) {
  1894. RAWINPUT_HandleStatePacket(joystick, raw_input->data.hid.bRawData, raw_input->data.hid.dwSizeHid);
  1895. }
  1896. }
  1897. }
  1898. }
  1899. result = 0;
  1900. break;
  1901. }
  1902. SDL_UnlockJoysticks();
  1903. }
  1904. if (result >= 0) {
  1905. return result;
  1906. }
  1907. return CallWindowProc(DefWindowProc, hWnd, msg, wParam, lParam);
  1908. }
  1909. static void RAWINPUT_JoystickQuit(void)
  1910. {
  1911. if (!SDL_RAWINPUT_inited) {
  1912. return;
  1913. }
  1914. RAWINPUT_RemoveDevices();
  1915. WIN_UnloadHIDDLL();
  1916. SDL_RAWINPUT_inited = SDL_FALSE;
  1917. }
  1918. static SDL_bool RAWINPUT_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out)
  1919. {
  1920. return SDL_FALSE;
  1921. }
  1922. SDL_JoystickDriver SDL_RAWINPUT_JoystickDriver = {
  1923. RAWINPUT_JoystickInit,
  1924. RAWINPUT_JoystickGetCount,
  1925. RAWINPUT_JoystickDetect,
  1926. RAWINPUT_JoystickGetDeviceName,
  1927. RAWINPUT_JoystickGetDevicePath,
  1928. RAWINPUT_JoystickGetDeviceSteamVirtualGamepadSlot,
  1929. RAWINPUT_JoystickGetDevicePlayerIndex,
  1930. RAWINPUT_JoystickSetDevicePlayerIndex,
  1931. RAWINPUT_JoystickGetDeviceGUID,
  1932. RAWINPUT_JoystickGetDeviceInstanceID,
  1933. RAWINPUT_JoystickOpen,
  1934. RAWINPUT_JoystickRumble,
  1935. RAWINPUT_JoystickRumbleTriggers,
  1936. RAWINPUT_JoystickGetCapabilities,
  1937. RAWINPUT_JoystickSetLED,
  1938. RAWINPUT_JoystickSendEffect,
  1939. RAWINPUT_JoystickSetSensorsEnabled,
  1940. RAWINPUT_JoystickUpdate,
  1941. RAWINPUT_JoystickClose,
  1942. RAWINPUT_JoystickQuit,
  1943. RAWINPUT_JoystickGetGamepadMapping
  1944. };
  1945. #endif /* SDL_JOYSTICK_RAWINPUT */
  1946. /* vi: set ts=4 sw=4 expandtab: */