sdlInputManager.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "console/console.h"
  23. #include "console/consoleTypes.h"
  24. #include "console/engineAPI.h"
  25. #include "sim/actionMap.h"
  26. #include "sdlInputManager.h"
  27. typedef SDL_JoystickType SDLJoystickType;
  28. DefineEnumType(SDLJoystickType);
  29. ImplementEnumType(SDLJoystickType,
  30. "The type of device connected.\n\n"
  31. "@ingroup Input")
  32. { SDL_JOYSTICK_TYPE_UNKNOWN, "Unknown"},
  33. { SDL_JOYSTICK_TYPE_GAMECONTROLLER, "Game Controller" },
  34. { SDL_JOYSTICK_TYPE_WHEEL, "Wheel" },
  35. { SDL_JOYSTICK_TYPE_ARCADE_STICK, "Arcade Stick" },
  36. { SDL_JOYSTICK_TYPE_FLIGHT_STICK, "Flight Stick" },
  37. { SDL_JOYSTICK_TYPE_DANCE_PAD, "Dance Pad" },
  38. { SDL_JOYSTICK_TYPE_GUITAR, "Guitar" },
  39. { SDL_JOYSTICK_TYPE_DRUM_KIT, "Drum Kit" },
  40. { SDL_JOYSTICK_TYPE_ARCADE_PAD, "Arcade Pad" },
  41. { SDL_JOYSTICK_TYPE_THROTTLE, "Throttle" },
  42. EndImplementEnumType;
  43. typedef SDL_JoystickPowerLevel SDLPowerEnum;
  44. DefineEnumType(SDLPowerEnum);
  45. ImplementEnumType(SDLPowerEnum,
  46. "An enumeration of battery levels of a joystick.\n\n"
  47. "@ingroup Input")
  48. { SDL_JOYSTICK_POWER_UNKNOWN, "Unknown" },
  49. { SDL_JOYSTICK_POWER_EMPTY, "Empty" },
  50. { SDL_JOYSTICK_POWER_LOW, "Low" },
  51. { SDL_JOYSTICK_POWER_MEDIUM, "Medium" },
  52. { SDL_JOYSTICK_POWER_FULL, "Full" },
  53. { SDL_JOYSTICK_POWER_WIRED, "Wired" },
  54. { SDL_JOYSTICK_POWER_MAX, "Max" },
  55. EndImplementEnumType;
  56. IMPLEMENT_STATIC_CLASS(SDLInputManager, ,
  57. "@brief Static class exposing the SDL_Joystick and SDL_GameController APIs to Torque Script.\n"
  58. "SDLInputManager provides access to the functions of these APIs through static class "
  59. "functions.These functions are not required to bind or process events.By setting "
  60. "pref::Input::JoystickEnabled or pref::Input::sdlControllerEnabled to true, all connected "
  61. "devices will automatically be opened.All of the joystick and controller events defined "
  62. "in event.h can then be bound. For complete API documentation see the Joystick and Game "
  63. "Controller section of https ://wiki.libsdl.org/APIByCategory#Input_Events.\n\n"
  64. "@tsexample\n"
  65. "// Get the name and device type for all connected devices\n"
  66. "%sdlDevices = SDLInputManager::numJoysticks();\n"
  67. "for (%i = 0; %i < %sdlDevices; %i++)\n"
  68. "{\n"
  69. " %deviceName = SDLInputManager::JoystickNameForIndex(%i);\n"
  70. " %deviceType = SDLInputManager::GetDeviceType(%i);\n"
  71. "}\n"
  72. "\n"
  73. "// List all installed controller mappings\n"
  74. "%numMappings = SDLInputManager::GameControllerNumMappings();\n"
  75. "for (%i = 0; %i < %numMappings; %i++)\n"
  76. " echo(SDLInputManager::GameControllerMappingForIndex(%i));\n"
  77. "@endtsexample\n\n");
  78. IMPLEMENT_GLOBAL_CALLBACK(onSDLDeviceConnected, void, (S32 sdlIndex, const char* deviceName, const char* deviceType),
  79. (sdlIndex, deviceName, deviceType),
  80. "Callback that occurs when an input device is connected to the system.\n\n"
  81. "@param sdlIndex The index that will be used by sdl to refer to the device.\n"
  82. "@param deviceName The name that the device reports. This will be the return "
  83. "value of SDL_JoystickNameForIndex or SDL_GameControllerNameForIndex depending on the device type.\n"
  84. "@param deviceType The type of device connected. See SDLInputManager::getDeviceType() "
  85. "for possible string values.\n\n");
  86. IMPLEMENT_GLOBAL_CALLBACK(onSDLDeviceDisconnected, void, (S32 sdlIndex), (sdlIndex),
  87. "Callback that occurs when an input device is disconnected from the system.\n\n"
  88. "@param sdlIndex The index of the device that was removed.\n");
  89. //------------------------------------------------------------------------------
  90. // Static class variables:
  91. bool SDLInputManager::smJoystickEnabled = true;
  92. bool SDLInputManager::smJoystickSplitAxesLR = true;
  93. bool SDLInputManager::smControllerEnabled = true;
  94. bool SDLInputManager::smPOVButtonEvents = true;
  95. bool SDLInputManager::smPOVMaskEvents = false;
  96. // Map SDL controller Axis to torque input event
  97. // Commented text from map_StringForControllerAxis[] in SDL_gamecontroller.c
  98. S32 SDLInputManager::map_EventForControllerAxis[] = {
  99. SI_XAXIS, //"leftx",
  100. SI_YAXIS, //"lefty",
  101. SI_RXAXIS, //"rightx",
  102. SI_RYAXIS, //"righty",
  103. SI_ZAXIS, //"lefttrigger",
  104. SI_RZAXIS, //"righttrigger",
  105. -1 // NULL
  106. };
  107. // Map SDL controller button ID to torque input event
  108. // Commented text from map_StringForControllerButton[] in SDL_gamecontroller.c
  109. S32 SDLInputManager::map_EventForControllerButton[] = {
  110. XI_A, //"a",
  111. XI_B, //"b",
  112. XI_X, //"x",
  113. XI_Y, //"y",
  114. XI_BACK, //"back",
  115. XI_GUIDE, //"guide",
  116. XI_START, //"start",
  117. XI_LEFT_THUMB, //"leftstick",
  118. XI_RIGHT_THUMB, //"rightstick",
  119. XI_LEFT_SHOULDER, //"leftshoulder",
  120. XI_RIGHT_SHOULDER, //"rightshoulder",
  121. SI_UPOV, //"dpup",
  122. SI_DPOV, //"dpdown",
  123. SI_LPOV, //"dpleft",
  124. SI_RPOV, //"dpright",
  125. -1 // NULL
  126. };
  127. //------------------------------------------------------------------------------
  128. void SDLInputManager::joystickState::reset()
  129. {
  130. sdlInstID = -1;
  131. inputDevice = NULL;
  132. numAxes = 0;
  133. lastHatState[0] = 0;
  134. lastHatState[1] = 0;
  135. }
  136. //------------------------------------------------------------------------------
  137. SDLInputManager::SDLInputManager()
  138. {
  139. mEnabled = true;
  140. mJoystickActive = true;
  141. for (S32 i = 0; i < MaxJoysticks; ++i)
  142. {
  143. mJoysticks[i].reset();
  144. mJoysticks[i].torqueInstID = i;
  145. }
  146. for (S32 i = 0; i < MaxControllers; ++i)
  147. {
  148. mControllers[i].sdlInstID = -1;
  149. mControllers[i].torqueInstID = i;
  150. mControllers[i].inputDevice = NULL;
  151. }
  152. }
  153. //------------------------------------------------------------------------------
  154. void SDLInputManager::init()
  155. {
  156. Con::addVariable( "pref::Input::JoystickEnabled", TypeBool, &smJoystickEnabled,
  157. "If true, Joystick devices will be automatically opened.\n\n"
  158. "@ingroup Input");
  159. Con::addVariable("pref::Input::JoystickSplitAxesLR", TypeBool, &smJoystickSplitAxesLR,
  160. "Split axis inputs on 4 axis joysticks. This has no effect on any other device.\n\n"
  161. "4 Axis joysticks use IDs 0-3 which get mapped to xaxis, yaxis, zaxis and rxaxis. "
  162. "When true, this will increment IDs 2 and 3 so the inputs map to xaxis, yaxis, rxaxis and ryaxis.\n"
  163. "@ingroup Input");
  164. Con::addVariable("pref::Input::sdlControllerEnabled", TypeBool, &smControllerEnabled,
  165. "If true, any Joystick device that SDL recognizes as a Game Controller will be automatically opened as a game controller.\n\n"
  166. "@ingroup Input");
  167. Con::addVariable("pref::Input::JoystickPOVButtons", TypeBool, &smPOVButtonEvents,
  168. "If true, the pov hat will be treated as 4 buttons and make/break events will be generated for "
  169. "upov, dpov, lpov and rpov.\n"
  170. "@ingroup Input");
  171. Con::addVariable("pref::Input::JoystickPOVMask", TypeBool, &smPOVMaskEvents,
  172. "If true, the pov hat will be treated as a single input with a 4 bit mask value. The povmask "
  173. "event will be generated with the current mask every time the mask value changes.\n"
  174. "@ingroup Input");
  175. // POV Hat mask bits
  176. Con::setIntVariable("$SDLMask::HatUp", SDL_HAT_UP);
  177. Con::setIntVariable("$SDLMask::HatRight", SDL_HAT_RIGHT);
  178. Con::setIntVariable("$SDLMask::HatDown", SDL_HAT_DOWN);
  179. Con::setIntVariable("$SDLMask::HatLeft", SDL_HAT_LEFT);
  180. }
  181. //------------------------------------------------------------------------------
  182. bool SDLInputManager::enable()
  183. {
  184. disable();
  185. if (smControllerEnabled || smJoystickEnabled)
  186. {
  187. for (S32 i = 0; i < SDL_NumJoysticks(); ++i)
  188. {
  189. if (smControllerEnabled && SDL_IsGameController(i))
  190. openController(i, 0);
  191. else if (smJoystickEnabled)
  192. openJoystick(i, 0);
  193. }
  194. }
  195. mEnabled = true;
  196. return true;
  197. }
  198. //------------------------------------------------------------------------------
  199. void SDLInputManager::disable()
  200. {
  201. // Close any open devices
  202. for (S32 i = 0; i < MaxControllers; ++i)
  203. closeControllerByIndex(i);
  204. for (S32 i = 0; i < MaxJoysticks; ++i)
  205. closeJoystickByIndex(i);
  206. mEnabled = false;
  207. }
  208. //------------------------------------------------------------------------------
  209. void SDLInputManager::process()
  210. {
  211. }
  212. //------------------------------------------------------------------------------
  213. void SDLInputManager::processEvent(SDL_Event &evt)
  214. {
  215. switch (evt.type)
  216. {
  217. case SDL_JOYAXISMOTION:
  218. {
  219. joystickState* torqueMapping;
  220. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jaxis.which, torqueMapping))
  221. break;
  222. // SDL axis value inputs are in (range: -32768 to 32767)
  223. // Torque axis values are -1.0 to 1.0
  224. F32 value = ((F32)evt.jaxis.value) / (F32) (evt.jaxis.value > 0 ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  225. S32 mapAxis = SI_XAXIS + evt.jaxis.axis;
  226. if (evt.jaxis.axis > 1 && torqueMapping->numAxes == 4 && smJoystickSplitAxesLR)
  227. mapAxis += 1; // On a 4 axis, we'll shift the second two so we use LX LY RX RY instead of LX LY LZ RX
  228. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_AXIS, mapAxis, SI_MOVE, value);
  229. break;
  230. }
  231. case SDL_JOYBALLMOTION:
  232. {
  233. joystickState* torqueMapping;
  234. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jball.which, torqueMapping) || evt.jball.ball >= MaxBalls)
  235. break;
  236. if (evt.jball.xrel != 0)
  237. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_INT, evt.jball.ball ? SI_XBALL2 : SI_XBALL, SI_MOVE, (S32) evt.jball.xrel);
  238. if (evt.jball.yrel != 0)
  239. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_INT, evt.jball.ball ? SI_YBALL2 : SI_YBALL, SI_MOVE, (S32) evt.jball.yrel);
  240. break;
  241. }
  242. case SDL_JOYHATMOTION:
  243. {
  244. joystickState* torqueMapping;
  245. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jball.which, torqueMapping) || evt.jhat.hat >= MaxHats)
  246. break;
  247. if (torqueMapping->lastHatState[evt.jhat.hat] != evt.jhat.value)
  248. {
  249. buildHatEvents(JoystickDeviceType, torqueMapping->torqueInstID, torqueMapping->lastHatState[evt.jhat.hat], evt.jhat.value, evt.jhat.hat);
  250. torqueMapping->lastHatState[evt.jhat.hat] = evt.jhat.value;
  251. }
  252. break;
  253. }
  254. case SDL_JOYBUTTONDOWN:
  255. case SDL_JOYBUTTONUP:
  256. {
  257. joystickState* torqueMapping;
  258. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jbutton.which, torqueMapping))
  259. break;
  260. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_BUTTON, KEY_BUTTON0 + evt.jbutton.button,
  261. evt.cbutton.state == SDL_PRESSED ? SI_MAKE : SI_BREAK, evt.cbutton.state == SDL_PRESSED ? 1.0f : 0.0f);
  262. break;
  263. }
  264. case SDL_JOYDEVICEADDED:
  265. {
  266. deviceConnectedCallback(evt.jdevice.which);
  267. if (smControllerEnabled && SDL_IsGameController(evt.jdevice.which))
  268. break; // This device will be added as a controller
  269. if (smJoystickEnabled)
  270. openJoystick(evt.jdevice.which, 0);
  271. break;
  272. }
  273. case SDL_JOYDEVICEREMOVED:
  274. {
  275. onSDLDeviceDisconnected_callback(evt.jdevice.which);
  276. closeJoystick(evt.jdevice.which);
  277. }
  278. case SDL_CONTROLLERAXISMOTION:
  279. {
  280. controllerState* torqueMapping;
  281. if (mControllerMap.isEmpty() || !mControllerMap.find(evt.caxis.which, torqueMapping))
  282. break;
  283. // SDL axis value inputs are in (range: -32768 to 32767)
  284. // Torque axis values are -1.0 to 1.0
  285. F32 value = ((F32)evt.caxis.value) / (F32) (evt.caxis.value > 0 ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  286. buildInputEvent(GamepadDeviceType, torqueMapping->torqueInstID, SI_AXIS, map_EventForControllerAxis[evt.caxis.axis], SI_MOVE, value);
  287. break;
  288. }
  289. case SDL_CONTROLLERBUTTONDOWN:
  290. case SDL_CONTROLLERBUTTONUP:
  291. {
  292. controllerState* torqueMapping;
  293. if (mControllerMap.isEmpty() || !mControllerMap.find(evt.cbutton.which, torqueMapping))
  294. break;
  295. buildInputEvent(GamepadDeviceType, torqueMapping->torqueInstID, SI_BUTTON, map_EventForControllerButton[evt.cbutton.button],
  296. evt.cbutton.state == SDL_PRESSED ? SI_MAKE : SI_BREAK, evt.cbutton.state == SDL_PRESSED ? 1.0f : 0.0f);
  297. break;
  298. }
  299. case SDL_CONTROLLERDEVICEADDED:
  300. {
  301. if (smControllerEnabled)
  302. openController(evt.cdevice.which, 0);
  303. break;
  304. }
  305. case SDL_CONTROLLERDEVICEREMOVED:
  306. {
  307. closeController(evt.cdevice.which);
  308. break;
  309. }
  310. case SDL_CONTROLLERDEVICEREMAPPED:
  311. break;
  312. default:
  313. #ifdef TORQUE_DEBUG
  314. Con::warnf("Unhandled SDL input event: 0x%04x", evt.type);
  315. #endif
  316. break;
  317. }
  318. }
  319. //------------------------------------------------------------------------------
  320. void SDLInputManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, S32 iValue)
  321. {
  322. InputEventInfo newEvent;
  323. newEvent.deviceType = deviceType;
  324. newEvent.deviceInst = deviceInst;
  325. newEvent.objType = objType;
  326. newEvent.objInst = objInst;
  327. newEvent.action = action;
  328. newEvent.iValue = iValue;
  329. newEvent.postToSignal(Input::smInputEvent);
  330. }
  331. //------------------------------------------------------------------------------
  332. void SDLInputManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, F32 fValue)
  333. {
  334. InputEventInfo newEvent;
  335. newEvent.deviceType = deviceType;
  336. newEvent.deviceInst = deviceInst;
  337. newEvent.objType = objType;
  338. newEvent.objInst = objInst;
  339. newEvent.action = action;
  340. newEvent.fValue = fValue;
  341. newEvent.postToSignal(Input::smInputEvent);
  342. }
  343. //------------------------------------------------------------------------------
  344. void SDLInputManager::buildHatEvents(U32 deviceType, U32 deviceInst, U8 lastState, U8 currentState, S32 hatIndex)
  345. {
  346. if (smPOVButtonEvents)
  347. {
  348. if ((lastState & SDL_HAT_UP) != (currentState & SDL_HAT_UP))
  349. {
  350. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_UPOV2 : SI_UPOV,
  351. (currentState & SDL_HAT_UP) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_UP) ? 1.0f : 0.0f);
  352. }
  353. if ((lastState & SDL_HAT_DOWN) != (currentState & SDL_HAT_DOWN))
  354. {
  355. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_DPOV2 : SI_DPOV,
  356. (currentState & SDL_HAT_DOWN) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_DOWN) ? 1.0f : 0.0f);
  357. }
  358. if ((lastState & SDL_HAT_LEFT) != (currentState & SDL_HAT_LEFT))
  359. {
  360. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_LPOV2 : SI_LPOV,
  361. (currentState & SDL_HAT_LEFT) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_LEFT) ? 1.0f : 0.0f);
  362. }
  363. if ((lastState & SDL_HAT_RIGHT) != (currentState & SDL_HAT_RIGHT))
  364. {
  365. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_RPOV2 : SI_RPOV,
  366. (currentState & SDL_HAT_RIGHT) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_RIGHT) ? 1.0f : 0.0f);
  367. }
  368. }
  369. if (smPOVMaskEvents)
  370. {
  371. buildInputEvent(deviceType, deviceInst, SI_INT, hatIndex ? SI_POVMASK2 : SI_POVMASK, SI_VALUE, (S32) currentState);
  372. }
  373. }
  374. //------------------------------------------------------------------------------
  375. S32 SDLInputManager::openController(S32 sdlIndex, S32 requestedTID)
  376. {
  377. if ((sdlIndex < 0) || (sdlIndex >= SDL_NumJoysticks()) || (requestedTID < 0) || (requestedTID >= MaxControllers))
  378. return -1;
  379. if (SDL_IsGameController(sdlIndex))
  380. {
  381. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  382. if (inputDevice)
  383. {
  384. SDL_JoystickID sdlId = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(inputDevice));
  385. // See if the device is already open as a joystick
  386. for (S32 i = 0; i < MaxJoysticks; ++i)
  387. {
  388. if (mJoysticks[i].sdlInstID == sdlId)
  389. {
  390. if (!closeJoystickByIndex(i))
  391. {
  392. SDL_GameControllerClose(inputDevice);
  393. return -1;
  394. }
  395. }
  396. }
  397. controllerState* torqueMapping = NULL;
  398. if (mControllerMap.find(sdlId, torqueMapping))
  399. {
  400. if (torqueMapping->torqueInstID == (U32) requestedTID)
  401. {
  402. SDL_GameControllerClose(inputDevice);
  403. return requestedTID; // Already open at the requested ID
  404. }
  405. closeControllerByIndex(torqueMapping->torqueInstID);
  406. }
  407. S32 gamepadSlot = -1;
  408. if (!mControllers[requestedTID].inputDevice)
  409. gamepadSlot = requestedTID;
  410. else
  411. {
  412. // Find the first available gamepad device slot
  413. for (S32 i = 0; i < MaxControllers; ++i)
  414. {
  415. if (!mControllers[i].inputDevice)
  416. {
  417. gamepadSlot = i;
  418. break;
  419. }
  420. }
  421. }
  422. if (gamepadSlot == -1)
  423. {
  424. Con::errorf("Unable to open Game Controller %s. Too many devices present.", SDL_GameControllerName(inputDevice));
  425. SDL_GameControllerClose(inputDevice);
  426. return -1;
  427. }
  428. mControllers[gamepadSlot].inputDevice = inputDevice;
  429. mControllers[gamepadSlot].sdlInstID = sdlId;
  430. mControllerMap.insertUnique(sdlId, &mControllers[gamepadSlot]);
  431. return gamepadSlot;
  432. }
  433. }
  434. return -1;
  435. }
  436. //------------------------------------------------------------------------------
  437. void SDLInputManager::closeController(SDL_JoystickID sdlId)
  438. {
  439. controllerState* torqueMapping = NULL;
  440. if (mControllerMap.find(sdlId, torqueMapping))
  441. closeControllerByIndex(torqueMapping->torqueInstID);
  442. }
  443. //------------------------------------------------------------------------------
  444. bool SDLInputManager::closeControllerByIndex(S32 index)
  445. {
  446. if (index < 0 || index >= MaxControllers)
  447. return false;
  448. if (mControllers[index].inputDevice && mControllers[index].sdlInstID != -1)
  449. {
  450. SDL_GameControllerClose(mControllers[index].inputDevice);
  451. mControllerMap.erase(mControllers[index].sdlInstID);
  452. mControllers[index].sdlInstID = -1;
  453. mControllers[index].inputDevice = NULL;
  454. return true;
  455. }
  456. return false;
  457. }
  458. //------------------------------------------------------------------------------
  459. S32 SDLInputManager::openJoystick(S32 sdlIndex, S32 requestedTID)
  460. {
  461. if ((sdlIndex < 0) || (sdlIndex >= SDL_NumJoysticks()) || (requestedTID < 0) || (requestedTID >= MaxJoysticks))
  462. return -1;
  463. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  464. if (inputDevice)
  465. {
  466. SDL_JoystickID sdlId = SDL_JoystickInstanceID(inputDevice);
  467. // See if the device is already open as a controller
  468. for (S32 i = 0; i < MaxControllers; ++i)
  469. {
  470. if (mControllers[i].sdlInstID == sdlId)
  471. {
  472. if (!closeControllerByIndex(i))
  473. {
  474. SDL_JoystickClose(inputDevice);
  475. return -1;
  476. }
  477. }
  478. }
  479. joystickState* torqueMapping = NULL;
  480. if (mJoystickMap.find(sdlId, torqueMapping))
  481. {
  482. if (torqueMapping->torqueInstID == (U32) requestedTID)
  483. {
  484. SDL_JoystickClose(inputDevice);
  485. return requestedTID; // Already open at the requested ID
  486. }
  487. closeJoystickByIndex(torqueMapping->torqueInstID);
  488. }
  489. S32 joystickSlot = -1;
  490. if (!mJoysticks[requestedTID].inputDevice)
  491. joystickSlot = requestedTID;
  492. else
  493. {
  494. // Find the first available joystick device slot
  495. for (S32 i = 0; i < MaxJoysticks; ++i)
  496. {
  497. if (!mJoysticks[i].inputDevice)
  498. {
  499. joystickSlot = i;
  500. break;
  501. }
  502. }
  503. }
  504. if (joystickSlot == -1)
  505. {
  506. Con::errorf("Unable to open Joystick %s. Too many devices present.", SDL_JoystickName(inputDevice));
  507. SDL_JoystickClose(inputDevice);
  508. return -1;
  509. }
  510. mJoysticks[joystickSlot].inputDevice = inputDevice;
  511. mJoysticks[joystickSlot].sdlInstID = sdlId;
  512. mJoysticks[joystickSlot].numAxes = SDL_JoystickNumAxes(inputDevice);
  513. mJoystickMap.insertUnique(sdlId, &mJoysticks[joystickSlot]);
  514. return joystickSlot;
  515. }
  516. return -1;
  517. }
  518. //------------------------------------------------------------------------------
  519. void SDLInputManager::closeJoystick(SDL_JoystickID sdlId)
  520. {
  521. joystickState* torqueMapping = NULL;
  522. if (mJoystickMap.find(sdlId, torqueMapping))
  523. closeJoystickByIndex(torqueMapping->torqueInstID);
  524. }
  525. //------------------------------------------------------------------------------
  526. bool SDLInputManager::closeJoystickByIndex(S32 index)
  527. {
  528. if (index < 0 || index >= MaxJoysticks)
  529. return false;
  530. if (mJoysticks[index].inputDevice && mJoysticks[index].sdlInstID != -1)
  531. {
  532. SDL_JoystickClose(mJoysticks[index].inputDevice);
  533. mJoystickMap.erase(mJoysticks[index].sdlInstID);
  534. mJoysticks[index].reset();
  535. return true;
  536. }
  537. return false;
  538. }
  539. //------------------------------------------------------------------------------
  540. void SDLInputManager::closeDevice(S32 sdlIndex)
  541. {
  542. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  543. return;
  544. SDL_JoystickID sdlId = -1;
  545. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  546. if (inputDevice)
  547. {
  548. sdlId = SDL_JoystickInstanceID(inputDevice);
  549. SDL_JoystickClose(inputDevice);
  550. }
  551. if (sdlId < 0)
  552. return;
  553. for (S32 i = 0; i < MaxControllers; ++i)
  554. {
  555. if (mControllers[i].sdlInstID == sdlId)
  556. {
  557. closeControllerByIndex(i);
  558. return;
  559. }
  560. }
  561. for (S32 i = 0; i < MaxJoysticks; ++i)
  562. {
  563. if (mJoysticks[i].sdlInstID == sdlId)
  564. {
  565. closeJoystickByIndex(i);
  566. return;
  567. }
  568. }
  569. }
  570. //------------------------------------------------------------------------------
  571. void SDLInputManager::deviceConnectedCallback(S32 index)
  572. {
  573. // This will generate the script callback:
  574. // onSDLDeviceConnected(%sdlIndex, %isController, %deviceName)
  575. bool isController = SDL_IsGameController(index);
  576. const char *deviceName = isController ? SDL_GameControllerNameForIndex(index) : SDL_JoystickNameForIndex(index);
  577. SDL_JoystickType deviceType = SDL_JoystickGetDeviceType(index);
  578. onSDLDeviceConnected_callback(index, deviceName, castConsoleTypeToString(deviceType));
  579. }
  580. //------------------------------------------------------------------------------
  581. // Console interface
  582. //------------------------------------------------------------------------------
  583. // Get the N'th SDL device state -1=doesn't exist, 0=closed, 1=open joystick, 2=open controller
  584. S32 SDLInputManager::getJoystickOpenState(S32 sdlIndex)
  585. {
  586. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  587. return -1;
  588. S32 currentState = 0;
  589. // We need to open the joystick to get the sdl instanceID
  590. // This will increase the refcount on the joystick if it was already open.
  591. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  592. if (inputDevice)
  593. {
  594. SDL_JoystickID sdlId = SDL_JoystickInstanceID(inputDevice);
  595. controllerState* controllerMapping = NULL;
  596. joystickState* joystickMapping = NULL;
  597. if (!mControllerMap.isEmpty() && mControllerMap.find(sdlId, controllerMapping))
  598. currentState = 2;
  599. else if (!mJoystickMap.isEmpty() && mJoystickMap.find(sdlId, joystickMapping))
  600. currentState = 1;
  601. // Close the joystick to return the refcount to the previouse state
  602. SDL_JoystickClose(inputDevice);
  603. }
  604. return currentState;
  605. }
  606. //------------------------------------------------------------------------------
  607. // Fills in the torque device instance string from an sdl joystick index number
  608. void SDLInputManager::getJoystickTorqueInst(S32 sdlIndex, char* instBuffer)
  609. {
  610. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  611. return;
  612. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  613. if (inputDevice)
  614. {
  615. SDL_JoystickID sdlId = SDL_JoystickInstanceID(inputDevice);
  616. controllerState* controllerMapping = NULL;
  617. joystickState* joystickMapping = NULL;
  618. if (!mControllerMap.isEmpty() && mControllerMap.find(sdlId, controllerMapping))
  619. ActionMap::getDeviceName(GamepadDeviceType, controllerMapping->torqueInstID, instBuffer);
  620. else if (!mJoystickMap.isEmpty() && mJoystickMap.find(sdlId, joystickMapping))
  621. ActionMap::getDeviceName(JoystickDeviceType, joystickMapping->torqueInstID, instBuffer);
  622. SDL_JoystickClose(inputDevice);
  623. }
  624. }
  625. //------------------------------------------------------------------------------
  626. DefineEngineStaticMethod(SDLInputManager, numJoysticks, S32, (), ,
  627. "@brief Returns the number of currently connected joystick devices.\n\n"
  628. "Game Controllers are a sub-set of joysticks and are included in the joystick count. "
  629. "See https://wiki.libsdl.org/SDL_NumJoysticks for more details.\n"
  630. "@ingroup Input")
  631. {
  632. return SDL_NumJoysticks();
  633. }
  634. //------------------------------------------------------------------------------
  635. DefineEngineStaticMethod(SDLInputManager, getDeviceOpenState, S32, ( S32 sdlIndex ), ( 0 ),
  636. "@brief Used to determine the current state of the N'th item in the SDL device list.\n\n"
  637. "@param sdlIndex The SDL index for this device.\n"
  638. "@return values:\n"
  639. "-1 if the device does not exist (invalid sdlIndex passed)\n"
  640. "0 The device is closed\n"
  641. "1 The device is open as a Joystick\n"
  642. "2 The device is open as a Game Controller\n"
  643. "@ingroup Input")
  644. {
  645. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  646. if (mgr && mgr->isEnabled())
  647. return mgr->getJoystickOpenState(sdlIndex);
  648. return -1;
  649. }
  650. //------------------------------------------------------------------------------
  651. DefineEngineStaticMethod(SDLInputManager, openAsJoystick, S32, ( S32 sdlIndex, S32 torqueInstId ), ( 0, 0 ),
  652. "@brief Used to open the device as a Joystick.\n\n"
  653. "If the device is currently open as a Game Controller, it will be closed and opened as "
  654. "a Joystick. If it is currently opened as a Joystick with a different T3D instance ID, "
  655. "it will be changed to the requested ID if that ID is available.\n"
  656. "@param sdlIndex The SDL index for this device.\n"
  657. "@param torqueInstId Is the requested T3D device instance ID. If there is already an open Joystick with "
  658. "the requested ID, The first available ID will be assigned.\n"
  659. "@return The T3D device instance ID assigned, or -1 if the device could not be opened.")
  660. {
  661. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  662. if (mgr && mgr->isEnabled())
  663. return mgr->openJoystick(sdlIndex, torqueInstId);
  664. return -1;
  665. }
  666. //------------------------------------------------------------------------------
  667. DefineEngineStaticMethod(SDLInputManager, openAsController, S32, (S32 sdlIndex, S32 torqueInstId), (0, 0),
  668. "@brief Used to open the device as a Game Controller.\n\n"
  669. "If the device is currently open as a Joystick, it will be closed and opened as "
  670. "a Game Controller. If it is currently opened as a Game Controller with a different "
  671. "T3D instance ID, it will be changed to the requested ID if that ID is available.\n"
  672. "@param sdlIndex The SDL index for this device.\n"
  673. "@param torqueInstId Is the requested T3D device instance ID. If there is already an "
  674. "open Game Controller with the requested ID, The first available ID will be assigned.\n"
  675. "@return The T3D device instance ID assigned, or -1 if the device could not be opened.")
  676. {
  677. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  678. if (mgr && mgr->isEnabled())
  679. return mgr->openController(sdlIndex, torqueInstId);
  680. return -1;
  681. }
  682. //------------------------------------------------------------------------------
  683. DefineEngineStaticMethod(SDLInputManager, closeDevice, void, (S32 sdlIndex), (0),
  684. "@brief Used to close the N'th item in the SDL device list.\n\n"
  685. "This will close a Joystick or Game Controller.\n"
  686. "@param sdlIndex The SDL index for this device.\n")
  687. {
  688. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  689. if (mgr && mgr->isEnabled())
  690. mgr->closeDevice(sdlIndex);
  691. return;
  692. }
  693. //------------------------------------------------------------------------------
  694. DefineEngineStaticMethod(SDLInputManager, getTorqueInstFromDevice, const char *, (S32 sdlIndex), (0),
  695. "@brief Gets the T3D instance identifier for an open SDL joystick.\n\n"
  696. "@param sdlIndex The SDL index for this device.\n"
  697. "@return Returns the T3D instance ID used for mapping this device or Null if it does not exist.\n"
  698. "@ingroup Input")
  699. {
  700. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  701. if (mgr && mgr->isEnabled())
  702. {
  703. char* deviceInst = Con::getReturnBuffer(32);
  704. deviceInst[0] = '\0';
  705. mgr->getJoystickTorqueInst(sdlIndex, deviceInst);
  706. return deviceInst;
  707. }
  708. return NULL;
  709. }
  710. //------------------------------------------------------------------------------
  711. DefineEngineStaticMethod(SDLInputManager, JoystickNameForIndex, const char *, (S32 sdlIndex), (0),
  712. "@brief Exposes SDL_JoystickNameForIndex() to script.\n\n"
  713. "@param sdlIndex The SDL index for this device.\n"
  714. "@return Returns the name of the selected joystick or Null if it does not exist.\n"
  715. "@see https://wiki.libsdl.org/SDL_JoystickNameForIndex \n"
  716. "@ingroup Input")
  717. {
  718. if (sdlIndex >= 0 && sdlIndex < SDL_NumJoysticks())
  719. return SDL_JoystickNameForIndex(sdlIndex);
  720. return NULL;
  721. }
  722. //------------------------------------------------------------------------------
  723. DefineEngineStaticMethod(SDLInputManager, ControllerNameForIndex, const char *, (S32 sdlIndex), (0),
  724. "@brief Exposes SDL_GameControllerNameForIndex() to script.\n\n"
  725. "@param sdlIndex The SDL index for this device.\n"
  726. "@return Returns the implementation dependent name for the game controller, "
  727. "or NULL if there is no name or the index is invalid.\n"
  728. "@see https://wiki.libsdl.org/SDL_GameControllerNameForIndex \n"
  729. "@ingroup Input")
  730. {
  731. if (sdlIndex >= 0 && sdlIndex < SDL_NumJoysticks() || !SDL_IsGameController(sdlIndex))
  732. return SDL_GameControllerNameForIndex(sdlIndex);
  733. return NULL;
  734. }
  735. //------------------------------------------------------------------------------
  736. DefineEngineStaticMethod(SDLInputManager, JoystickGetGUID, const char *, (S32 sdlIndex), (0),
  737. "@brief Exposes SDL_JoystickGetDeviceGUID() to script.\n\n"
  738. "@param sdlIndex The SDL index for this device.\n"
  739. "@return GUID for the indexed device or Null if it does not exist.\n"
  740. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceGUID \n"
  741. "@ingroup Input")
  742. {
  743. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  744. return NULL;
  745. SDL_JoystickGUID guidVal = SDL_JoystickGetDeviceGUID(sdlIndex);
  746. char *guidStr = Con::getReturnBuffer(64);
  747. SDL_JoystickGetGUIDString(guidVal, guidStr, 64);
  748. return guidStr;
  749. }
  750. //------------------------------------------------------------------------------
  751. DefineEngineStaticMethod(SDLInputManager, GetVendor, S32, (S32 sdlIndex), (0),
  752. "Gets the USB vendor ID of a joystick device, if available.\n\n"
  753. "@param sdlIndex The SDL index for this device.\n"
  754. "@return The USB vendor ID. If the vendor ID isn't available this function returns 0.\n"
  755. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceVendor \n"
  756. "@see https://wiki.libsdl.org/SDL_JoystickGetVendor \n"
  757. "@see https://wiki.libsdl.org/SDL_GameControllerGetVendor \n"
  758. "@ingroup Input")
  759. {
  760. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  761. return 0;
  762. return (S32) SDL_JoystickGetDeviceVendor(sdlIndex);
  763. }
  764. //------------------------------------------------------------------------------
  765. DefineEngineStaticMethod(SDLInputManager, GetProduct, S32, (S32 sdlIndex), (0),
  766. "Gets the USB product ID of a joystick device, if available.\n\n"
  767. "@param sdlIndex The SDL index for this device.\n"
  768. "@return The USB product ID. If the product ID isn't available this function returns 0.\n"
  769. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceProduct \n"
  770. "@see https://wiki.libsdl.org/SDL_JoystickGetProduct \n"
  771. "@see https://wiki.libsdl.org/SDL_GameControllerGetProduct \n"
  772. "@ingroup Input")
  773. {
  774. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  775. return 0;
  776. return (S32)SDL_JoystickGetDeviceProduct(sdlIndex);
  777. }
  778. //------------------------------------------------------------------------------
  779. DefineEngineStaticMethod(SDLInputManager, GetProductVersion, S32, (S32 sdlIndex), (0),
  780. "Gets the product version of a joystick device, if available.\n\n"
  781. "@param sdlIndex The SDL index for this device.\n"
  782. "@return The product version. If the product version isn't available this function returns 0.\n"
  783. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceProductVersion \n"
  784. "@see https://wiki.libsdl.org/SDL_JoystickGetProductVersion \n"
  785. "@see https://wiki.libsdl.org/SDL_GameControllerGetProductVersion \n"
  786. "@ingroup Input")
  787. {
  788. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  789. return 0;
  790. return (S32)SDL_JoystickGetDeviceProductVersion(sdlIndex);
  791. }
  792. //------------------------------------------------------------------------------
  793. DefineEngineStaticMethod(SDLInputManager, GetDeviceType, SDLJoystickType, (S32 sdlIndex), (0),
  794. "@brief Exposes SDL_JoystickGetDeviceType() to script.\n\n"
  795. "@param sdlIndex The SDL index for this device.\n"
  796. "@return The type of device connected. Possible return strings are: \"Unknown\", "
  797. "\"Game Controller\", \"Wheel\", \"Arcade Stick\", \"Flight Stick\", \"Dance Pad\", "
  798. "\"Guitar\", \"Drum Kit\", \"Arcade Pad\" and \"Throttle\"\n"
  799. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceType \n"
  800. "@ingroup Input")
  801. {
  802. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  803. return SDL_JOYSTICK_TYPE_UNKNOWN;
  804. return SDL_JoystickGetDeviceType(sdlIndex);
  805. }
  806. //------------------------------------------------------------------------------
  807. DefineEngineStaticMethod(SDLInputManager, JoystickNumAxes, S32, (S32 sdlIndex), (0),
  808. "@brief Exposes SDL_JoystickNumAxes() to script.\n\n"
  809. "@param sdlIndex The SDL index for this device.\n"
  810. "@return Returns the number of axis controls/number of axes on success or zero on failure.\n"
  811. "@see https://wiki.libsdl.org/SDL_JoystickNumAxes \n"
  812. "@ingroup Input")
  813. {
  814. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  815. return 0;
  816. S32 numAxes = 0;
  817. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  818. if (inputDevice)
  819. {
  820. numAxes = SDL_JoystickNumAxes(inputDevice);
  821. if (numAxes < 0)
  822. {
  823. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  824. numAxes = 0;
  825. }
  826. SDL_JoystickClose(inputDevice);
  827. }
  828. return numAxes;
  829. }
  830. //------------------------------------------------------------------------------
  831. DefineEngineStaticMethod(SDLInputManager, JoystickNumBalls, S32, (S32 sdlIndex), (0),
  832. "@brief Exposes SDL_JoystickNumBalls() to script.\n\n"
  833. "@param sdlIndex The SDL index for this device.\n"
  834. "@return Returns the number of trackballs on success or zero on failure.\n"
  835. "@see https://wiki.libsdl.org/SDL_JoystickNumBalls \n"
  836. "@ingroup Input")
  837. {
  838. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  839. return 0;
  840. S32 numBalls = 0;
  841. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  842. if (inputDevice)
  843. {
  844. numBalls = SDL_JoystickNumBalls(inputDevice);
  845. if (numBalls < 0)
  846. {
  847. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  848. numBalls = 0;
  849. }
  850. SDL_JoystickClose(inputDevice);
  851. }
  852. return numBalls;
  853. }
  854. //------------------------------------------------------------------------------
  855. DefineEngineStaticMethod(SDLInputManager, JoystickNumButtons, S32, (S32 sdlIndex), (0),
  856. "@brief Exposes SDL_JoystickNumButtons() to script.\n\n"
  857. "@param sdlIndex The SDL index for this device.\n"
  858. "@return Returns the number of buttons on success or zero on failure.\n"
  859. "@see https://wiki.libsdl.org/SDL_JoystickNumButtons \n"
  860. "@ingroup Input")
  861. {
  862. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  863. return 0;
  864. S32 numButtons = 0;
  865. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  866. if (inputDevice)
  867. {
  868. numButtons = SDL_JoystickNumButtons(inputDevice);
  869. if (numButtons < 0)
  870. {
  871. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  872. numButtons = 0;
  873. }
  874. SDL_JoystickClose(inputDevice);
  875. }
  876. return numButtons;
  877. }
  878. //------------------------------------------------------------------------------
  879. DefineEngineStaticMethod(SDLInputManager, JoystickNumHats, S32, (S32 sdlIndex), (0),
  880. "@brief Exposes SDL_JoystickNumHats() to script.\n\n"
  881. "@param sdlIndex The SDL index for this device.\n"
  882. "@return Returns the number of POV hats on success or zero on failure.\n"
  883. "@see https://wiki.libsdl.org/SDL_JoystickNumHats \n"
  884. "@ingroup Input")
  885. {
  886. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  887. return 0;
  888. S32 numHats = 0;
  889. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  890. if (inputDevice)
  891. {
  892. numHats = SDL_JoystickNumHats(inputDevice);
  893. if (numHats < 0)
  894. {
  895. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  896. numHats = 0;
  897. }
  898. SDL_JoystickClose(inputDevice);
  899. }
  900. return numHats;
  901. }
  902. //------------------------------------------------------------------------------
  903. DefineEngineStaticMethod(SDLInputManager, IsGameController, bool, (S32 sdlIndex), (0),
  904. "@brief Exposes SDL_IsGameController() to script.\n\n"
  905. "@param sdlIndex The SDL index for this device.\n"
  906. "@return Returns true if the given joystick is supported by the game controller "
  907. "interface, false if it isn't or it's an invalid index.\n"
  908. "@see https://wiki.libsdl.org/SDL_IsGameController \n"
  909. "@ingroup Input")
  910. {
  911. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks() || !SDL_IsGameController(sdlIndex))
  912. return false;
  913. return true;
  914. }
  915. //------------------------------------------------------------------------------
  916. DefineEngineStaticMethod(SDLInputManager, JoystickIsHaptic, bool, (S32 sdlIndex), (0),
  917. "@brief Exposes SDL_JoystickIsHaptic() to script.\n\n"
  918. "@param sdlIndex The SDL index for this device.\n"
  919. "@return Returns true if the joystick is haptic.\n"
  920. "@see https://wiki.libsdl.org/SDL_JoystickIsHaptic \n"
  921. "@ingroup Input")
  922. {
  923. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  924. return false;
  925. bool isHaptic = false;
  926. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  927. if (inputDevice)
  928. {
  929. isHaptic = (SDL_JoystickIsHaptic(inputDevice) == SDL_TRUE);
  930. SDL_JoystickClose(inputDevice);
  931. }
  932. return isHaptic;
  933. }
  934. //------------------------------------------------------------------------------
  935. DefineEngineStaticMethod(SDLInputManager, JoystickPowerLevel, SDLPowerEnum, (S32 sdlIndex), (0),
  936. "@brief Exposes SDL_JoystickCurrentPowerLevel() to script.\n\n"
  937. "@param sdlIndex The SDL index for this device.\n"
  938. "@return Returns the current battery level or \"Wired\" if it's a connected device.\n"
  939. "@see https://wiki.libsdl.org/SDL_JoystickCurrentPowerLevel \n"
  940. "@ingroup Input")
  941. {
  942. SDL_JoystickPowerLevel powerLevel = SDL_JOYSTICK_POWER_UNKNOWN;
  943. if (sdlIndex >= 0 && sdlIndex < SDL_NumJoysticks())
  944. {
  945. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  946. if (inputDevice)
  947. {
  948. powerLevel = SDL_JoystickCurrentPowerLevel(inputDevice);
  949. SDL_JoystickClose(inputDevice);
  950. }
  951. }
  952. return powerLevel;
  953. }
  954. //------------------------------------------------------------------------------
  955. DefineEngineStaticMethod(SDLInputManager, JoystickGetSpecs, String, (S32 sdlIndex), (0),
  956. "@brief A convenience function to reurn all of the data for a Joystick/Game Controller "
  957. " packed as fields in a tab separated string.\n\n"
  958. "There is overhead involved in querying joystick data, especially if the device is not open. "
  959. "If more than one field is required, it is more efficient to call JoystickGetSpecs() and "
  960. "parse the data out of the return string than to call the console method for each.\n"
  961. "@param sdlIndex The SDL index for this device.\n"
  962. "@return A tab separated string that can be parsed from script with getField()/getFields().\n\n"
  963. "Field 0: Number of Axes\n"
  964. " 1: Number of Buttons\n"
  965. " 2: Number of POV Hats\n"
  966. " 3: Number of Trackballs\n"
  967. " 4: SDL_IsGameController() (Boolean)\n"
  968. " 5: SDL_JoystickIsHaptic() (Boolean)\n"
  969. " 6: Power Level (String)\n"
  970. " 7: Device Type (String)\n"
  971. "@ingroup Input")
  972. {
  973. String specStr;
  974. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  975. return specStr;
  976. bool isController = SDL_IsGameController(sdlIndex);
  977. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  978. if (inputDevice)
  979. {
  980. SDL_JoystickPowerLevel powerLevel = SDL_JoystickCurrentPowerLevel(inputDevice);
  981. SDL_JoystickType deviceType = SDL_JoystickGetDeviceType(sdlIndex);
  982. specStr = String::ToString("%d\t%d\t%d\t%d\t%d\t%d\t%s\t%s\t",
  983. SDL_JoystickNumAxes(inputDevice), SDL_JoystickNumButtons(inputDevice),
  984. SDL_JoystickNumHats(inputDevice), SDL_JoystickNumBalls(inputDevice),
  985. isController ? 1 : 0, (SDL_JoystickIsHaptic(inputDevice) == SDL_TRUE) ? 1 : 0,
  986. castConsoleTypeToString(powerLevel), castConsoleTypeToString(deviceType));
  987. SDL_JoystickClose(inputDevice);
  988. }
  989. return specStr;
  990. }
  991. //------------------------------------------------------------------------------
  992. DefineEngineStaticMethod(SDLInputManager, JoystickGetAxes, String, (S32 sdlIndex), (0),
  993. "@brief Gets the current value for all joystick axes.\n\n"
  994. "@param sdlIndex The SDL index for this device.\n"
  995. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  996. "Each axis is one field, so a 4 axis device will have 4 fields.\n\n"
  997. "@ingroup Input")
  998. {
  999. String axesStr;
  1000. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1001. return axesStr;
  1002. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  1003. if (inputDevice)
  1004. {
  1005. S32 numAxes = SDL_JoystickNumAxes(inputDevice);
  1006. for (S32 i = 0; i < numAxes; i++)
  1007. {
  1008. F32 axisVal = (F32) SDL_JoystickGetAxis(inputDevice, i);
  1009. F32 value = axisVal / (F32)(axisVal > 0.0f ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  1010. axesStr += String::ToString("%0.3f\t", value);
  1011. }
  1012. SDL_JoystickClose(inputDevice);
  1013. }
  1014. return axesStr;
  1015. }
  1016. //------------------------------------------------------------------------------
  1017. DefineEngineStaticMethod(SDLInputManager, JoystickGetButtons, String, (S32 sdlIndex), (0),
  1018. "@brief Gets the current value for all joystick buttons.\n\n"
  1019. "@param sdlIndex The SDL index for this device.\n"
  1020. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1021. "Each button is one field. 0 - SDL_JoystickNumButtons() fields.\n\n"
  1022. "@ingroup Input")
  1023. {
  1024. String buttonStr;
  1025. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1026. return buttonStr;
  1027. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  1028. if (inputDevice)
  1029. {
  1030. S32 numbuttons = SDL_JoystickNumButtons(inputDevice);
  1031. for (S32 i = 0; i < numbuttons; i++)
  1032. {
  1033. buttonStr += String::ToString("%d\t", (S32) SDL_JoystickGetButton(inputDevice, i));
  1034. }
  1035. SDL_JoystickClose(inputDevice);
  1036. }
  1037. return buttonStr;
  1038. }
  1039. //------------------------------------------------------------------------------
  1040. DefineEngineStaticMethod(SDLInputManager, JoystickGetHats, String, (S32 sdlIndex), (0),
  1041. "@brief Gets the current value for all POV hats.\n\n"
  1042. "@param sdlIndex The SDL index for this device.\n"
  1043. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1044. "Each hat is one field. 0 - SDL_JoystickNumHats() fields. The value is a 4 bit bitmask. "
  1045. "If no bits are set, the hat is centered. Bit 0 is up, 1 is right, 2 is down and 3 is left.\n\n"
  1046. "@ingroup Input")
  1047. {
  1048. String hatStr;
  1049. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1050. return hatStr;
  1051. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  1052. if (inputDevice)
  1053. {
  1054. S32 numHats = SDL_JoystickNumHats(inputDevice);
  1055. for (S32 i = 0; i < numHats; i++)
  1056. {
  1057. hatStr += String::ToString("%d\t", (S32)SDL_JoystickGetHat(inputDevice, i));
  1058. }
  1059. SDL_JoystickClose(inputDevice);
  1060. }
  1061. return hatStr;
  1062. }
  1063. //------------------------------------------------------------------------------
  1064. DefineEngineStaticMethod(SDLInputManager, ControllerGetAxes, String, (S32 sdlIndex), (0),
  1065. "@brief Gets the current value for all controller axes.\n\n"
  1066. "@param sdlIndex The SDL index for this device.\n"
  1067. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1068. "Game controllers always have 6 axes in the following order: 0-LX, 1-LY, 2-RX, 3-RY, 4-LT, 5-RT.\n\n"
  1069. "@ingroup Input")
  1070. {
  1071. String axesStr;
  1072. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1073. return axesStr;
  1074. bool isController = SDL_IsGameController(sdlIndex);
  1075. if (!isController)
  1076. return axesStr;
  1077. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  1078. if (inputDevice)
  1079. {
  1080. for (S32 i = SDL_CONTROLLER_AXIS_LEFTX; i < SDL_CONTROLLER_AXIS_MAX; i++)
  1081. {
  1082. F32 axisVal = (F32)SDL_GameControllerGetAxis(inputDevice, (SDL_GameControllerAxis) i);
  1083. F32 value = axisVal / (F32)(axisVal > 0.0f ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  1084. axesStr += String::ToString("%0.3f\t", value);
  1085. }
  1086. SDL_GameControllerClose(inputDevice);
  1087. }
  1088. return axesStr;
  1089. }
  1090. //------------------------------------------------------------------------------
  1091. DefineEngineStaticMethod(SDLInputManager, ControllerGetButtons, String, (S32 sdlIndex), (0),
  1092. "@brief Gets the current value for all controller buttons.\n\n"
  1093. "@param sdlIndex The SDL index for this device.\n"
  1094. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1095. "Game controllers always have 15 buttons in the following order: 0-A, 1-B, 2-X, 3-Y, 4-Back, "
  1096. "5-Guide, 6-Start, 7-Left Stick, 8-Right Stick, 9-Left Shoulder, 10-Right Shoulder, "
  1097. "11-DPad Up, 12-DPad Down, 13-DPad Left, 14-DPad Right.\n\n"
  1098. "@ingroup Input")
  1099. {
  1100. String buttonStr;
  1101. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1102. return buttonStr;
  1103. bool isController = SDL_IsGameController(sdlIndex);
  1104. if (!isController)
  1105. return buttonStr;
  1106. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  1107. if (inputDevice)
  1108. {
  1109. for (S32 i = SDL_CONTROLLER_BUTTON_A; i < SDL_CONTROLLER_BUTTON_MAX; i++)
  1110. {
  1111. buttonStr += String::ToString("%d\t", (S32)SDL_GameControllerGetButton(inputDevice, (SDL_GameControllerButton) i));
  1112. }
  1113. SDL_GameControllerClose(inputDevice);
  1114. }
  1115. return buttonStr;
  1116. }
  1117. //------------------------------------------------------------------------------
  1118. DefineEngineStaticMethod(SDLInputManager, GameControllerMapping, String, (S32 sdlIndex), (0),
  1119. "@brief Exposes SDL_GameControllerMapping() to script.\n\n"
  1120. "@param sdlIndex The SDL index for this device.\n"
  1121. "@return Returns a string that has the controller's mapping or NULL if no mapping "
  1122. "is available or it does not exist.\n"
  1123. "@see https://wiki.libsdl.org/SDL_JoystickNameForIndex \n"
  1124. "@ingroup Input")
  1125. {
  1126. String mapping;
  1127. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1128. return mapping;
  1129. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  1130. if (inputDevice)
  1131. {
  1132. char* sdlStr = SDL_GameControllerMapping(inputDevice);
  1133. if (sdlStr)
  1134. {
  1135. mapping = sdlStr;
  1136. SDL_free(sdlStr);
  1137. }
  1138. else
  1139. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  1140. SDL_GameControllerClose(inputDevice);
  1141. }
  1142. return mapping;
  1143. }
  1144. //------------------------------------------------------------------------------
  1145. DefineEngineStaticMethod(SDLInputManager, GameControllerMappingForGUID, String, (const char* guidStr), ,
  1146. "@brief Exposes SDL_GameControllerMappingForGUID() to script.\n\n"
  1147. "@param guidStr The GUID for which a mapping is desired.\n"
  1148. "@return Returns a mapping string or NULL on error.\n"
  1149. "@see https://wiki.libsdl.org/SDL_GameControllerMappingForGUID \n"
  1150. "@ingroup Input")
  1151. {
  1152. String mapping;
  1153. SDL_JoystickGUID guid = SDL_JoystickGetGUIDFromString(guidStr);
  1154. char* sdlStr = SDL_GameControllerMappingForGUID(guid);
  1155. if (sdlStr)
  1156. {
  1157. mapping = sdlStr;
  1158. SDL_free(sdlStr);
  1159. }
  1160. return mapping;
  1161. }
  1162. //------------------------------------------------------------------------------
  1163. DefineEngineStaticMethod(SDLInputManager, GameControllerAddMapping, S32, (const char* mappingString), ,
  1164. "@brief Exposes SDL_GameControllerAddMapping() to script.\n\n"
  1165. "Use this function to add support for controllers that SDL is unaware of or "
  1166. "to cause an existing controller to have a different binding.\n"
  1167. "@param mappingString The new mapping string to apply. Full details on the format of this "
  1168. "string are available at the linked SDL wiki page.\n"
  1169. "@return Returns 1 if a new mapping is added, 0 if an existing mapping is updated, -1 on error.\n"
  1170. "@see https://wiki.libsdl.org/SDL_GameControllerAddMapping \n"
  1171. "@ingroup Input")
  1172. {
  1173. S32 retVal = SDL_GameControllerAddMapping(mappingString);
  1174. if (retVal == -1)
  1175. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  1176. return retVal;
  1177. }
  1178. //------------------------------------------------------------------------------
  1179. DefineEngineStaticMethod(SDLInputManager, GameControllerAddMappingsFromFile, S32, (const char* fileName), ,
  1180. "@brief Exposes SDL_GameControllerAddMappingsFromFile() to script.\n\n"
  1181. "Use this function to load a set of Game Controller mappings from a file, filtered by the "
  1182. "current SDL_GetPlatform(). A community sourced database of controllers is available at "
  1183. "https://raw.githubusercontent.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt \n"
  1184. "@param fileName The file to load mappings from.\n"
  1185. "@return Returns the number of mappings added or -1 on error.\n"
  1186. "@see https://wiki.libsdl.org/SDL_GameControllerAddMappingsFromFile \n"
  1187. "@ingroup Input")
  1188. {
  1189. char torquePath[1024];
  1190. Con::expandScriptFilename(torquePath, sizeof(torquePath), fileName);
  1191. S32 retVal = SDL_GameControllerAddMappingsFromFile(torquePath);
  1192. if (retVal == -1)
  1193. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  1194. return retVal;
  1195. }
  1196. //------------------------------------------------------------------------------
  1197. DefineEngineStaticMethod(SDLInputManager, GameControllerNumMappings, S32, (), ,
  1198. "Get the number of mappings installed. Used with GameControllerMappingForIndex "
  1199. "to iterate through all installed mappings.\n\n"
  1200. "@ingroup Input")
  1201. {
  1202. return SDL_GameControllerNumMappings();
  1203. }
  1204. //------------------------------------------------------------------------------
  1205. DefineEngineStaticMethod(SDLInputManager, GameControllerMappingForIndex, String, (S32 mappingIndex), ,
  1206. "Get the mapping at a particular index.\n\n"
  1207. "@param mappingIndex The index for which a mapping is desired.\n"
  1208. "@return Returns a mapping string or NULL if the index is out of range.\n"
  1209. "@ingroup Input")
  1210. {
  1211. String mapping;
  1212. char* sdlStr = SDL_GameControllerMappingForIndex(mappingIndex);
  1213. if (sdlStr)
  1214. {
  1215. mapping = sdlStr;
  1216. SDL_free(sdlStr);
  1217. }
  1218. return mapping;
  1219. }