InputSourceGameController.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * InputSourceGameController.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "InputSourceGameController.h"
  12. #include "InputHandler.h"
  13. #include "../CGameInfo.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../gui/CursorHandler.h"
  16. #include "../gui/EventDispatcher.h"
  17. #include "../gui/ShortcutHandler.h"
  18. #include "../../lib/CConfigHandler.h"
  19. void InputSourceGameController::gameControllerDeleter(SDL_GameController * gameController)
  20. {
  21. if(gameController)
  22. SDL_GameControllerClose(gameController);
  23. }
  24. InputSourceGameController::InputSourceGameController():
  25. configTriggerTreshold(settings["input"]["controllerTriggerTreshold"].Float()),
  26. configAxisDeadZone(settings["input"]["controllerAxisDeadZone"].Float()),
  27. configAxisFullZone(settings["input"]["controllerAxisFullZone"].Float()),
  28. configPointerSpeed(settings["input"]["controllerPointerSpeed"].Float()),
  29. configPointerScale(settings["input"]["controllerPointerScale"].Float()),
  30. configPanningSpeed(settings["input"]["controllerPanningSpeed"].Float()),
  31. configPanningScale(settings["input"]["controllerPanningScale"].Float()),
  32. cursorAxisValueX(0),
  33. cursorAxisValueY(0),
  34. cursorPlanDisX(0.0),
  35. cursorPlanDisY(0.0),
  36. scrollAxisMoved(false),
  37. scrollStart(Point(0,0)),
  38. scrollCurrent(Point(0,0)),
  39. scrollAxisValueX(0),
  40. scrollAxisValueY(0),
  41. scrollPlanDisX(0.0),
  42. scrollPlanDisY(0.0)
  43. {
  44. tryOpenAllGameControllers();
  45. }
  46. void InputSourceGameController::tryOpenAllGameControllers()
  47. {
  48. for(int i = 0; i < SDL_NumJoysticks(); ++i)
  49. if(SDL_IsGameController(i))
  50. openGameController(i);
  51. else
  52. logGlobal->warn("Joystick %d is an unsupported game controller!", i);
  53. }
  54. void InputSourceGameController::openGameController(int index)
  55. {
  56. SDL_GameController * controller = SDL_GameControllerOpen(index);
  57. if(!controller)
  58. {
  59. logGlobal->error("Fail to open game controller %d!", index);
  60. return;
  61. }
  62. GameControllerPtr controllerPtr(controller, &gameControllerDeleter);
  63. // Need to save joystick index for event. Joystick index may not be equal to index sometimes.
  64. int joystickIndex = getJoystickIndex(controllerPtr.get());
  65. if(joystickIndex < 0)
  66. {
  67. logGlobal->error("Fail to get joystick index of game controller %d!", index);
  68. return;
  69. }
  70. if(gameControllerMap.find(joystickIndex) != gameControllerMap.end())
  71. {
  72. logGlobal->warn("Game controller with joystick index %d is already opened.", joystickIndex);
  73. return;
  74. }
  75. gameControllerMap.try_emplace(joystickIndex, std::move(controllerPtr));
  76. }
  77. int InputSourceGameController::getJoystickIndex(SDL_GameController * controller)
  78. {
  79. SDL_Joystick * joystick = SDL_GameControllerGetJoystick(controller);
  80. if(!joystick)
  81. return -1;
  82. SDL_JoystickID instanceID = SDL_JoystickInstanceID(joystick);
  83. if(instanceID < 0)
  84. return -1;
  85. return instanceID;
  86. }
  87. void InputSourceGameController::handleEventDeviceAdded(const SDL_ControllerDeviceEvent & device)
  88. {
  89. if(gameControllerMap.find(device.which) != gameControllerMap.end())
  90. {
  91. logGlobal->warn("Game controller %d is already opened.", device.which);
  92. return;
  93. }
  94. openGameController(device.which);
  95. }
  96. void InputSourceGameController::handleEventDeviceRemoved(const SDL_ControllerDeviceEvent & device)
  97. {
  98. if(gameControllerMap.find(device.which) == gameControllerMap.end())
  99. {
  100. logGlobal->warn("Game controller %d is not opened before.", device.which);
  101. return;
  102. }
  103. gameControllerMap.erase(device.which);
  104. }
  105. void InputSourceGameController::handleEventDeviceRemapped(const SDL_ControllerDeviceEvent & device)
  106. {
  107. if(gameControllerMap.find(device.which) == gameControllerMap.end())
  108. {
  109. logGlobal->warn("Game controller %d is not opened.", device.which);
  110. return;
  111. }
  112. gameControllerMap.erase(device.which);
  113. openGameController(device.which);
  114. }
  115. double InputSourceGameController::getRealAxisValue(int value)
  116. {
  117. double ratio = static_cast<double>(value) / SDL_JOYSTICK_AXIS_MAX;
  118. double greenZone = configAxisFullZone - configAxisDeadZone;
  119. if (std::abs(ratio) < configAxisDeadZone)
  120. return 0;
  121. double scaledValue = (ratio - configAxisDeadZone) / greenZone;
  122. double clampedValue = std::clamp(scaledValue, -1.0, +1.0);
  123. return clampedValue;
  124. }
  125. void InputSourceGameController::dispatchAxisShortcuts(const std::vector<EShortcut> & shortcutsVector, SDL_GameControllerAxis axisID, int axisValue)
  126. {
  127. if(getRealAxisValue(axisValue) > configTriggerTreshold)
  128. {
  129. if(!pressedAxes.count(axisID))
  130. {
  131. GH.events().dispatchShortcutPressed(shortcutsVector);
  132. pressedAxes.insert(axisID);
  133. }
  134. }
  135. else
  136. {
  137. if(pressedAxes.count(axisID))
  138. {
  139. GH.events().dispatchShortcutReleased(shortcutsVector);
  140. pressedAxes.erase(axisID);
  141. }
  142. }
  143. }
  144. void InputSourceGameController::handleEventAxisMotion(const SDL_ControllerAxisEvent & axis)
  145. {
  146. tryToConvertCursor();
  147. SDL_GameControllerAxis axisID = static_cast<SDL_GameControllerAxis>(axis.axis);
  148. std::string axisName = SDL_GameControllerGetStringForAxis(axisID);
  149. auto axisActions = GH.shortcuts().translateJoystickAxis(axisName);
  150. auto buttonActions = GH.shortcuts().translateJoystickButton(axisName);
  151. for(const auto & action : axisActions)
  152. {
  153. switch(action)
  154. {
  155. case EShortcut::MOUSE_CURSOR_X:
  156. cursorAxisValueX = getRealAxisValue(axis.value);
  157. break;
  158. case EShortcut::MOUSE_CURSOR_Y:
  159. cursorAxisValueY = getRealAxisValue(axis.value);
  160. break;
  161. case EShortcut::MOUSE_SWIPE_X:
  162. scrollAxisValueX = getRealAxisValue(axis.value);
  163. break;
  164. case EShortcut::MOUSE_SWIPE_Y:
  165. scrollAxisValueY = getRealAxisValue(axis.value);
  166. break;
  167. }
  168. }
  169. dispatchAxisShortcuts(buttonActions, axisID, axis.value);
  170. }
  171. void InputSourceGameController::tryToConvertCursor()
  172. {
  173. assert(CCS);
  174. assert(CCS->curh);
  175. if(CCS->curh->getShowType() == Cursor::ShowType::HARDWARE)
  176. {
  177. const Point & cursorPosition = GH.getCursorPosition();
  178. CCS->curh->changeCursor(Cursor::ShowType::SOFTWARE);
  179. CCS->curh->cursorMove(cursorPosition.x, cursorPosition.y);
  180. GH.input().setCursorPosition(cursorPosition);
  181. }
  182. }
  183. void InputSourceGameController::handleEventButtonDown(const SDL_ControllerButtonEvent & button)
  184. {
  185. std::string buttonName = SDL_GameControllerGetStringForButton(static_cast<SDL_GameControllerButton>(button.button));
  186. const auto & shortcutsVector = GH.shortcuts().translateJoystickButton(buttonName);
  187. GH.events().dispatchShortcutPressed(shortcutsVector);
  188. }
  189. void InputSourceGameController::handleEventButtonUp(const SDL_ControllerButtonEvent & button)
  190. {
  191. std::string buttonName = SDL_GameControllerGetStringForButton(static_cast<SDL_GameControllerButton>(button.button));
  192. const auto & shortcutsVector = GH.shortcuts().translateJoystickButton(buttonName);
  193. GH.events().dispatchShortcutReleased(shortcutsVector);
  194. }
  195. void InputSourceGameController::doCursorMove(int deltaX, int deltaY)
  196. {
  197. if(deltaX == 0 && deltaY == 0)
  198. return;
  199. const Point & screenSize = GH.screenDimensions();
  200. const Point & cursorPosition = GH.getCursorPosition();
  201. int newX = std::min(std::max(cursorPosition.x + deltaX, 0), screenSize.x);
  202. int newY = std::min(std::max(cursorPosition.y + deltaY, 0), screenSize.y);
  203. Point targetPosition{newX, newY};
  204. GH.input().setCursorPosition(targetPosition);
  205. if(CCS && CCS->curh)
  206. CCS->curh->cursorMove(GH.getCursorPosition().x, GH.getCursorPosition().y);
  207. }
  208. int InputSourceGameController::getMoveDis(float planDis)
  209. {
  210. if(planDis >= 0)
  211. return std::floor(planDis);
  212. else
  213. return std::ceil(planDis);
  214. }
  215. void InputSourceGameController::handleUpdate()
  216. {
  217. std::chrono::steady_clock::time_point nowMs = std::chrono::steady_clock::now();
  218. if(lastCheckTime == std::chrono::steady_clock::time_point())
  219. {
  220. lastCheckTime = nowMs;
  221. return;
  222. }
  223. int32_t deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(nowMs - lastCheckTime).count();
  224. handleCursorUpdate(deltaTime);
  225. handleScrollUpdate(deltaTime);
  226. lastCheckTime = nowMs;
  227. }
  228. static double scaleAxis(double value, double power)
  229. {
  230. if (value > 0)
  231. return std::pow(value, power);
  232. else
  233. return -std::pow(-value, power);
  234. }
  235. void InputSourceGameController::handleCursorUpdate(int32_t deltaTimeMs)
  236. {
  237. float deltaTimeSeconds = static_cast<float>(deltaTimeMs) / 1000;
  238. if(vstd::isAlmostZero(cursorAxisValueX))
  239. cursorPlanDisX = 0;
  240. else
  241. cursorPlanDisX += deltaTimeSeconds * configPointerSpeed * scaleAxis(cursorAxisValueX, configPointerScale);
  242. if (vstd::isAlmostZero(cursorAxisValueY))
  243. cursorPlanDisY = 0;
  244. else
  245. cursorPlanDisY += deltaTimeSeconds * configPointerSpeed * scaleAxis(cursorAxisValueY, configPointerScale);
  246. int moveDisX = getMoveDis(cursorPlanDisX);
  247. int moveDisY = getMoveDis(cursorPlanDisY);
  248. cursorPlanDisX -= moveDisX;
  249. cursorPlanDisY -= moveDisY;
  250. doCursorMove(moveDisX, moveDisY);
  251. }
  252. void InputSourceGameController::handleScrollUpdate(int32_t deltaTimeMs)
  253. {
  254. if(!scrollAxisMoved && isScrollAxisReleased())
  255. {
  256. return;
  257. }
  258. else if(!scrollAxisMoved && !isScrollAxisReleased())
  259. {
  260. scrollAxisMoved = true;
  261. scrollCurrent = scrollStart = GH.input().getCursorPosition();
  262. GH.events().dispatchGesturePanningStarted(scrollStart);
  263. }
  264. else if(scrollAxisMoved && isScrollAxisReleased())
  265. {
  266. GH.events().dispatchGesturePanningEnded(scrollStart, scrollCurrent);
  267. scrollAxisMoved = false;
  268. scrollPlanDisX = scrollPlanDisY = 0;
  269. return;
  270. }
  271. float deltaTimeSeconds = static_cast<float>(deltaTimeMs) / 1000;
  272. scrollPlanDisX += deltaTimeSeconds * configPanningSpeed * scaleAxis(scrollAxisValueX, configPanningScale);
  273. scrollPlanDisY += deltaTimeSeconds * configPanningSpeed * scaleAxis(scrollAxisValueY, configPanningScale);
  274. int moveDisX = getMoveDis(scrollPlanDisX);
  275. int moveDisY = getMoveDis(scrollPlanDisY);
  276. if(moveDisX != 0 || moveDisY != 0)
  277. {
  278. scrollPlanDisX -= moveDisX;
  279. scrollPlanDisY -= moveDisY;
  280. scrollCurrent.x += moveDisX;
  281. scrollCurrent.y += moveDisY;
  282. Point distance(moveDisX, moveDisY);
  283. GH.events().dispatchGesturePanning(scrollStart, scrollCurrent, distance);
  284. }
  285. }
  286. bool InputSourceGameController::isScrollAxisReleased()
  287. {
  288. return scrollAxisValueX == 0 && scrollAxisValueY == 0;
  289. }