sdl_impl.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <atomic>
  6. #include <cmath>
  7. #include <functional>
  8. #include <mutex>
  9. #include <optional>
  10. #include <sstream>
  11. #include <string>
  12. #include <thread>
  13. #include <tuple>
  14. #include <unordered_map>
  15. #include <utility>
  16. #include <vector>
  17. #include <SDL.h>
  18. #include "common/logging/log.h"
  19. #include "common/param_package.h"
  20. #include "common/threadsafe_queue.h"
  21. #include "core/frontend/input.h"
  22. #include "input_common/sdl/sdl_impl.h"
  23. #include "input_common/settings.h"
  24. namespace InputCommon::SDL {
  25. namespace {
  26. std::string GetGUID(SDL_Joystick* joystick) {
  27. const SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
  28. char guid_str[33];
  29. SDL_JoystickGetGUIDString(guid, guid_str, sizeof(guid_str));
  30. return guid_str;
  31. }
  32. /// Creates a ParamPackage from an SDL_Event that can directly be used to create a ButtonDevice
  33. Common::ParamPackage SDLEventToButtonParamPackage(SDLState& state, const SDL_Event& event);
  34. } // Anonymous namespace
  35. static int SDLEventWatcher(void* user_data, SDL_Event* event) {
  36. auto* const sdl_state = static_cast<SDLState*>(user_data);
  37. // Don't handle the event if we are configuring
  38. if (sdl_state->polling) {
  39. sdl_state->event_queue.Push(*event);
  40. } else {
  41. sdl_state->HandleGameControllerEvent(*event);
  42. }
  43. return 0;
  44. }
  45. class SDLJoystick {
  46. public:
  47. SDLJoystick(std::string guid_, int port_, SDL_Joystick* joystick,
  48. SDL_GameController* gamecontroller)
  49. : guid{std::move(guid_)}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose},
  50. sdl_controller{gamecontroller, &SDL_GameControllerClose} {}
  51. void SetButton(int button, bool value) {
  52. std::lock_guard lock{mutex};
  53. state.buttons.insert_or_assign(button, value);
  54. }
  55. bool GetButton(int button) const {
  56. std::lock_guard lock{mutex};
  57. return state.buttons.at(button);
  58. }
  59. void SetAxis(int axis, Sint16 value) {
  60. std::lock_guard lock{mutex};
  61. state.axes.insert_or_assign(axis, value);
  62. }
  63. float GetAxis(int axis, float range) const {
  64. std::lock_guard lock{mutex};
  65. return state.axes.at(axis) / (32767.0f * range);
  66. }
  67. std::tuple<float, float> GetAnalog(int axis_x, int axis_y, float range) const {
  68. float x = GetAxis(axis_x, range);
  69. float y = GetAxis(axis_y, range);
  70. y = -y; // 3DS uses an y-axis inverse from SDL
  71. // Make sure the coordinates are in the unit circle,
  72. // otherwise normalize it.
  73. float r = x * x + y * y;
  74. if (r > 1.0f) {
  75. r = std::sqrt(r);
  76. x /= r;
  77. y /= r;
  78. }
  79. return std::make_tuple(x, y);
  80. }
  81. void SetHat(int hat, Uint8 direction) {
  82. std::lock_guard lock{mutex};
  83. state.hats.insert_or_assign(hat, direction);
  84. }
  85. bool GetHatDirection(int hat, Uint8 direction) const {
  86. std::lock_guard lock{mutex};
  87. return (state.hats.at(hat) & direction) != 0;
  88. }
  89. /**
  90. * The guid of the joystick
  91. */
  92. const std::string& GetGUID() const {
  93. return guid;
  94. }
  95. /**
  96. * The number of joystick from the same type that were connected before this joystick
  97. */
  98. int GetPort() const {
  99. return port;
  100. }
  101. SDL_Joystick* GetSDLJoystick() const {
  102. return sdl_joystick.get();
  103. }
  104. void SetSDLJoystick(SDL_Joystick* joystick, SDL_GameController* controller) {
  105. sdl_controller.reset(controller);
  106. sdl_joystick.reset(joystick);
  107. }
  108. SDL_GameController* GetSDLGameController() const {
  109. return sdl_controller.get();
  110. }
  111. private:
  112. struct State {
  113. std::unordered_map<int, bool> buttons;
  114. std::unordered_map<int, Sint16> axes;
  115. std::unordered_map<int, Uint8> hats;
  116. } state;
  117. std::string guid;
  118. int port;
  119. std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
  120. std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller;
  121. mutable std::mutex mutex;
  122. };
  123. std::shared_ptr<SDLJoystick> SDLState::GetSDLJoystickByGUID(const std::string& guid, int port) {
  124. std::lock_guard lock{joystick_map_mutex};
  125. const auto it = joystick_map.find(guid);
  126. if (it != joystick_map.end()) {
  127. while (it->second.size() <= static_cast<std::size_t>(port)) {
  128. auto joystick = std::make_shared<SDLJoystick>(guid, static_cast<int>(it->second.size()),
  129. nullptr, nullptr);
  130. it->second.emplace_back(std::move(joystick));
  131. }
  132. return it->second[port];
  133. }
  134. auto joystick = std::make_shared<SDLJoystick>(guid, 0, nullptr, nullptr);
  135. return joystick_map[guid].emplace_back(std::move(joystick));
  136. }
  137. std::shared_ptr<SDLJoystick> SDLState::GetSDLJoystickBySDLID(SDL_JoystickID sdl_id) {
  138. auto sdl_joystick = SDL_JoystickFromInstanceID(sdl_id);
  139. auto sdl_controller = SDL_GameControllerFromInstanceID(sdl_id);
  140. const std::string guid = GetGUID(sdl_joystick);
  141. std::lock_guard lock{joystick_map_mutex};
  142. const auto map_it = joystick_map.find(guid);
  143. if (map_it != joystick_map.end()) {
  144. const auto vec_it =
  145. std::find_if(map_it->second.begin(), map_it->second.end(),
  146. [&sdl_joystick](const std::shared_ptr<SDLJoystick>& joystick) {
  147. return sdl_joystick == joystick->GetSDLJoystick();
  148. });
  149. if (vec_it != map_it->second.end()) {
  150. // This is the common case: There is already an existing SDL_Joystick maped to a
  151. // SDLJoystick. return the SDLJoystick
  152. return *vec_it;
  153. }
  154. // Search for a SDLJoystick without a mapped SDL_Joystick...
  155. const auto nullptr_it = std::find_if(map_it->second.begin(), map_it->second.end(),
  156. [](const std::shared_ptr<SDLJoystick>& joystick) {
  157. return !joystick->GetSDLJoystick();
  158. });
  159. if (nullptr_it != map_it->second.end()) {
  160. // ... and map it
  161. (*nullptr_it)->SetSDLJoystick(sdl_joystick, sdl_controller);
  162. return *nullptr_it;
  163. }
  164. // There is no SDLJoystick without a mapped SDL_Joystick
  165. // Create a new SDLJoystick
  166. const int port = static_cast<int>(map_it->second.size());
  167. auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_controller);
  168. return map_it->second.emplace_back(std::move(joystick));
  169. }
  170. auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_controller);
  171. return joystick_map[guid].emplace_back(std::move(joystick));
  172. }
  173. void SDLState::InitJoystick(int joystick_index) {
  174. SDL_Joystick* sdl_joystick = SDL_JoystickOpen(joystick_index);
  175. SDL_GameController* sdl_gamecontroller = nullptr;
  176. if (SDL_IsGameController(joystick_index)) {
  177. sdl_gamecontroller = SDL_GameControllerOpen(joystick_index);
  178. }
  179. if (!sdl_joystick) {
  180. LOG_ERROR(Input, "failed to open joystick {}", joystick_index);
  181. return;
  182. }
  183. const std::string guid = GetGUID(sdl_joystick);
  184. std::lock_guard lock{joystick_map_mutex};
  185. if (joystick_map.find(guid) == joystick_map.end()) {
  186. auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_gamecontroller);
  187. joystick_map[guid].emplace_back(std::move(joystick));
  188. return;
  189. }
  190. auto& joystick_guid_list = joystick_map[guid];
  191. const auto it = std::find_if(
  192. joystick_guid_list.begin(), joystick_guid_list.end(),
  193. [](const std::shared_ptr<SDLJoystick>& joystick) { return !joystick->GetSDLJoystick(); });
  194. if (it != joystick_guid_list.end()) {
  195. (*it)->SetSDLJoystick(sdl_joystick, sdl_gamecontroller);
  196. return;
  197. }
  198. const int port = static_cast<int>(joystick_guid_list.size());
  199. auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_gamecontroller);
  200. joystick_guid_list.emplace_back(std::move(joystick));
  201. }
  202. void SDLState::CloseJoystick(SDL_Joystick* sdl_joystick) {
  203. const std::string guid = GetGUID(sdl_joystick);
  204. std::shared_ptr<SDLJoystick> joystick;
  205. {
  206. std::lock_guard lock{joystick_map_mutex};
  207. // This call to guid is safe since the joystick is guaranteed to be in the map
  208. const auto& joystick_guid_list = joystick_map[guid];
  209. const auto joystick_it =
  210. std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
  211. [&sdl_joystick](const std::shared_ptr<SDLJoystick>& joystick) {
  212. return joystick->GetSDLJoystick() == sdl_joystick;
  213. });
  214. joystick = *joystick_it;
  215. }
  216. // Destruct SDL_Joystick outside the lock guard because SDL can internally call the
  217. // event callback which locks the mutex again.
  218. joystick->SetSDLJoystick(nullptr, nullptr);
  219. }
  220. void SDLState::HandleGameControllerEvent(const SDL_Event& event) {
  221. switch (event.type) {
  222. case SDL_JOYBUTTONUP: {
  223. if (auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  224. joystick->SetButton(event.jbutton.button, false);
  225. }
  226. break;
  227. }
  228. case SDL_JOYBUTTONDOWN: {
  229. if (auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  230. joystick->SetButton(event.jbutton.button, true);
  231. }
  232. break;
  233. }
  234. case SDL_JOYHATMOTION: {
  235. if (auto joystick = GetSDLJoystickBySDLID(event.jhat.which)) {
  236. joystick->SetHat(event.jhat.hat, event.jhat.value);
  237. }
  238. break;
  239. }
  240. case SDL_JOYAXISMOTION: {
  241. if (auto joystick = GetSDLJoystickBySDLID(event.jaxis.which)) {
  242. joystick->SetAxis(event.jaxis.axis, event.jaxis.value);
  243. }
  244. break;
  245. }
  246. case SDL_JOYDEVICEREMOVED:
  247. LOG_DEBUG(Input, "Controller removed with Instance_ID {}", event.jdevice.which);
  248. CloseJoystick(SDL_JoystickFromInstanceID(event.jdevice.which));
  249. break;
  250. case SDL_JOYDEVICEADDED:
  251. LOG_DEBUG(Input, "Controller connected with device index {}", event.jdevice.which);
  252. InitJoystick(event.jdevice.which);
  253. break;
  254. }
  255. }
  256. void SDLState::CloseJoysticks() {
  257. std::lock_guard lock{joystick_map_mutex};
  258. joystick_map.clear();
  259. }
  260. class SDLButton final : public Input::ButtonDevice {
  261. public:
  262. explicit SDLButton(std::shared_ptr<SDLJoystick> joystick_, int button_)
  263. : joystick(std::move(joystick_)), button(button_) {}
  264. bool GetStatus() const override {
  265. return joystick->GetButton(button);
  266. }
  267. private:
  268. std::shared_ptr<SDLJoystick> joystick;
  269. int button;
  270. };
  271. class SDLDirectionButton final : public Input::ButtonDevice {
  272. public:
  273. explicit SDLDirectionButton(std::shared_ptr<SDLJoystick> joystick_, int hat_, Uint8 direction_)
  274. : joystick(std::move(joystick_)), hat(hat_), direction(direction_) {}
  275. bool GetStatus() const override {
  276. return joystick->GetHatDirection(hat, direction);
  277. }
  278. private:
  279. std::shared_ptr<SDLJoystick> joystick;
  280. int hat;
  281. Uint8 direction;
  282. };
  283. class SDLAxisButton final : public Input::ButtonDevice {
  284. public:
  285. explicit SDLAxisButton(std::shared_ptr<SDLJoystick> joystick_, int axis_, float threshold_,
  286. bool trigger_if_greater_)
  287. : joystick(std::move(joystick_)), axis(axis_), threshold(threshold_),
  288. trigger_if_greater(trigger_if_greater_) {}
  289. bool GetStatus() const override {
  290. const float axis_value = joystick->GetAxis(axis, 1.0f);
  291. if (trigger_if_greater) {
  292. return axis_value > threshold;
  293. }
  294. return axis_value < threshold;
  295. }
  296. private:
  297. std::shared_ptr<SDLJoystick> joystick;
  298. int axis;
  299. float threshold;
  300. bool trigger_if_greater;
  301. };
  302. class SDLAnalog final : public Input::AnalogDevice {
  303. public:
  304. SDLAnalog(std::shared_ptr<SDLJoystick> joystick_, int axis_x_, int axis_y_, float deadzone_,
  305. float range_)
  306. : joystick(std::move(joystick_)), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_),
  307. range(range_) {}
  308. std::tuple<float, float> GetStatus() const override {
  309. const auto [x, y] = joystick->GetAnalog(axis_x, axis_y, range);
  310. const float r = std::sqrt((x * x) + (y * y));
  311. if (r > deadzone) {
  312. return std::make_tuple(x / r * (r - deadzone) / (1 - deadzone),
  313. y / r * (r - deadzone) / (1 - deadzone));
  314. }
  315. return {};
  316. }
  317. bool GetAnalogDirectionStatus(Input::AnalogDirection direction) const override {
  318. const auto [x, y] = GetStatus();
  319. const float directional_deadzone = 0.5f;
  320. switch (direction) {
  321. case Input::AnalogDirection::RIGHT:
  322. return x > directional_deadzone;
  323. case Input::AnalogDirection::LEFT:
  324. return x < -directional_deadzone;
  325. case Input::AnalogDirection::UP:
  326. return y > directional_deadzone;
  327. case Input::AnalogDirection::DOWN:
  328. return y < -directional_deadzone;
  329. }
  330. return false;
  331. }
  332. private:
  333. std::shared_ptr<SDLJoystick> joystick;
  334. const int axis_x;
  335. const int axis_y;
  336. const float deadzone;
  337. const float range;
  338. };
  339. /// A button device factory that creates button devices from SDL joystick
  340. class SDLButtonFactory final : public Input::Factory<Input::ButtonDevice> {
  341. public:
  342. explicit SDLButtonFactory(SDLState& state_) : state(state_) {}
  343. /**
  344. * Creates a button device from a joystick button
  345. * @param params contains parameters for creating the device:
  346. * - "guid": the guid of the joystick to bind
  347. * - "port": the nth joystick of the same type to bind
  348. * - "button"(optional): the index of the button to bind
  349. * - "hat"(optional): the index of the hat to bind as direction buttons
  350. * - "axis"(optional): the index of the axis to bind
  351. * - "direction"(only used for hat): the direction name of the hat to bind. Can be "up",
  352. * "down", "left" or "right"
  353. * - "threshold"(only used for axis): a float value in (-1.0, 1.0) which the button is
  354. * triggered if the axis value crosses
  355. * - "direction"(only used for axis): "+" means the button is triggered when the axis
  356. * value is greater than the threshold; "-" means the button is triggered when the axis
  357. * value is smaller than the threshold
  358. */
  359. std::unique_ptr<Input::ButtonDevice> Create(const Common::ParamPackage& params) override {
  360. const std::string guid = params.Get("guid", "0");
  361. const int port = params.Get("port", 0);
  362. auto joystick = state.GetSDLJoystickByGUID(guid, port);
  363. if (params.Has("hat")) {
  364. const int hat = params.Get("hat", 0);
  365. const std::string direction_name = params.Get("direction", "");
  366. Uint8 direction;
  367. if (direction_name == "up") {
  368. direction = SDL_HAT_UP;
  369. } else if (direction_name == "down") {
  370. direction = SDL_HAT_DOWN;
  371. } else if (direction_name == "left") {
  372. direction = SDL_HAT_LEFT;
  373. } else if (direction_name == "right") {
  374. direction = SDL_HAT_RIGHT;
  375. } else {
  376. direction = 0;
  377. }
  378. // This is necessary so accessing GetHat with hat won't crash
  379. joystick->SetHat(hat, SDL_HAT_CENTERED);
  380. return std::make_unique<SDLDirectionButton>(joystick, hat, direction);
  381. }
  382. if (params.Has("axis")) {
  383. const int axis = params.Get("axis", 0);
  384. const float threshold = params.Get("threshold", 0.5f);
  385. const std::string direction_name = params.Get("direction", "");
  386. bool trigger_if_greater;
  387. if (direction_name == "+") {
  388. trigger_if_greater = true;
  389. } else if (direction_name == "-") {
  390. trigger_if_greater = false;
  391. } else {
  392. trigger_if_greater = true;
  393. LOG_ERROR(Input, "Unknown direction {}", direction_name);
  394. }
  395. // This is necessary so accessing GetAxis with axis won't crash
  396. joystick->SetAxis(axis, 0);
  397. return std::make_unique<SDLAxisButton>(joystick, axis, threshold, trigger_if_greater);
  398. }
  399. const int button = params.Get("button", 0);
  400. // This is necessary so accessing GetButton with button won't crash
  401. joystick->SetButton(button, false);
  402. return std::make_unique<SDLButton>(joystick, button);
  403. }
  404. private:
  405. SDLState& state;
  406. };
  407. /// An analog device factory that creates analog devices from SDL joystick
  408. class SDLAnalogFactory final : public Input::Factory<Input::AnalogDevice> {
  409. public:
  410. explicit SDLAnalogFactory(SDLState& state_) : state(state_) {}
  411. /**
  412. * Creates analog device from joystick axes
  413. * @param params contains parameters for creating the device:
  414. * - "guid": the guid of the joystick to bind
  415. * - "port": the nth joystick of the same type
  416. * - "axis_x": the index of the axis to be bind as x-axis
  417. * - "axis_y": the index of the axis to be bind as y-axis
  418. */
  419. std::unique_ptr<Input::AnalogDevice> Create(const Common::ParamPackage& params) override {
  420. const std::string guid = params.Get("guid", "0");
  421. const int port = params.Get("port", 0);
  422. const int axis_x = params.Get("axis_x", 0);
  423. const int axis_y = params.Get("axis_y", 1);
  424. const float deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, 1.0f);
  425. const float range = std::clamp(params.Get("range", 1.0f), 0.50f, 1.50f);
  426. auto joystick = state.GetSDLJoystickByGUID(guid, port);
  427. // This is necessary so accessing GetAxis with axis_x and axis_y won't crash
  428. joystick->SetAxis(axis_x, 0);
  429. joystick->SetAxis(axis_y, 0);
  430. return std::make_unique<SDLAnalog>(joystick, axis_x, axis_y, deadzone, range);
  431. }
  432. private:
  433. SDLState& state;
  434. };
  435. SDLState::SDLState() {
  436. using namespace Input;
  437. analog_factory = std::make_shared<SDLAnalogFactory>(*this);
  438. button_factory = std::make_shared<SDLButtonFactory>(*this);
  439. RegisterFactory<AnalogDevice>("sdl", analog_factory);
  440. RegisterFactory<ButtonDevice>("sdl", button_factory);
  441. // If the frontend is going to manage the event loop, then we dont start one here
  442. start_thread = !SDL_WasInit(SDL_INIT_JOYSTICK);
  443. if (start_thread && SDL_Init(SDL_INIT_JOYSTICK) < 0) {
  444. LOG_CRITICAL(Input, "SDL_Init(SDL_INIT_JOYSTICK) failed with: {}", SDL_GetError());
  445. return;
  446. }
  447. has_gamecontroller = SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
  448. if (SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1") == SDL_FALSE) {
  449. LOG_ERROR(Input, "Failed to set hint for background events with: {}", SDL_GetError());
  450. }
  451. SDL_AddEventWatch(&SDLEventWatcher, this);
  452. initialized = true;
  453. if (start_thread) {
  454. poll_thread = std::thread([this] {
  455. using namespace std::chrono_literals;
  456. while (initialized) {
  457. SDL_PumpEvents();
  458. std::this_thread::sleep_for(5ms);
  459. }
  460. });
  461. }
  462. // Because the events for joystick connection happens before we have our event watcher added, we
  463. // can just open all the joysticks right here
  464. for (int i = 0; i < SDL_NumJoysticks(); ++i) {
  465. InitJoystick(i);
  466. }
  467. }
  468. SDLState::~SDLState() {
  469. using namespace Input;
  470. UnregisterFactory<ButtonDevice>("sdl");
  471. UnregisterFactory<AnalogDevice>("sdl");
  472. CloseJoysticks();
  473. SDL_DelEventWatch(&SDLEventWatcher, this);
  474. initialized = false;
  475. if (start_thread) {
  476. poll_thread.join();
  477. SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
  478. }
  479. }
  480. std::vector<Common::ParamPackage> SDLState::GetInputDevices() {
  481. std::scoped_lock lock(joystick_map_mutex);
  482. std::vector<Common::ParamPackage> devices;
  483. for (const auto& [key, value] : joystick_map) {
  484. for (const auto& joystick : value) {
  485. auto joy = joystick->GetSDLJoystick();
  486. if (auto controller = joystick->GetSDLGameController()) {
  487. std::string name =
  488. fmt::format("{} {}", SDL_GameControllerName(controller), joystick->GetPort());
  489. devices.emplace_back(Common::ParamPackage{
  490. {"class", "sdl"},
  491. {"display", std::move(name)},
  492. {"guid", joystick->GetGUID()},
  493. {"port", std::to_string(joystick->GetPort())},
  494. });
  495. } else if (joy) {
  496. std::string name = fmt::format("{} {}", SDL_JoystickName(joy), joystick->GetPort());
  497. devices.emplace_back(Common::ParamPackage{
  498. {"class", "sdl"},
  499. {"display", std::move(name)},
  500. {"guid", joystick->GetGUID()},
  501. {"port", std::to_string(joystick->GetPort())},
  502. });
  503. }
  504. }
  505. }
  506. return devices;
  507. }
  508. namespace {
  509. Common::ParamPackage BuildAnalogParamPackageForButton(int port, std::string guid, u8 axis,
  510. float value = 0.1f) {
  511. Common::ParamPackage params({{"engine", "sdl"}});
  512. params.Set("port", port);
  513. params.Set("guid", guid);
  514. params.Set("axis", axis);
  515. if (value > 0) {
  516. params.Set("direction", "+");
  517. params.Set("threshold", "0.5");
  518. } else {
  519. params.Set("direction", "-");
  520. params.Set("threshold", "-0.5");
  521. }
  522. return params;
  523. }
  524. Common::ParamPackage BuildButtonParamPackageForButton(int port, std::string guid, u8 button) {
  525. Common::ParamPackage params({{"engine", "sdl"}});
  526. params.Set("port", port);
  527. params.Set("guid", guid);
  528. params.Set("button", button);
  529. return params;
  530. }
  531. Common::ParamPackage BuildHatParamPackageForButton(int port, std::string guid, u8 hat, u8 value) {
  532. Common::ParamPackage params({{"engine", "sdl"}});
  533. params.Set("port", port);
  534. params.Set("guid", guid);
  535. params.Set("hat", hat);
  536. switch (value) {
  537. case SDL_HAT_UP:
  538. params.Set("direction", "up");
  539. break;
  540. case SDL_HAT_DOWN:
  541. params.Set("direction", "down");
  542. break;
  543. case SDL_HAT_LEFT:
  544. params.Set("direction", "left");
  545. break;
  546. case SDL_HAT_RIGHT:
  547. params.Set("direction", "right");
  548. break;
  549. default:
  550. return {};
  551. }
  552. return params;
  553. }
  554. Common::ParamPackage SDLEventToButtonParamPackage(SDLState& state, const SDL_Event& event) {
  555. switch (event.type) {
  556. case SDL_JOYAXISMOTION: {
  557. const auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
  558. return BuildAnalogParamPackageForButton(joystick->GetPort(), joystick->GetGUID(),
  559. event.jaxis.axis, event.jaxis.value);
  560. }
  561. case SDL_JOYBUTTONUP: {
  562. const auto joystick = state.GetSDLJoystickBySDLID(event.jbutton.which);
  563. return BuildButtonParamPackageForButton(joystick->GetPort(), joystick->GetGUID(),
  564. event.jbutton.button);
  565. }
  566. case SDL_JOYHATMOTION: {
  567. const auto joystick = state.GetSDLJoystickBySDLID(event.jhat.which);
  568. return BuildHatParamPackageForButton(joystick->GetPort(), joystick->GetGUID(),
  569. event.jhat.hat, event.jhat.value);
  570. }
  571. }
  572. return {};
  573. }
  574. Common::ParamPackage BuildParamPackageForBinding(int port, const std::string& guid,
  575. const SDL_GameControllerButtonBind& binding) {
  576. switch (binding.bindType) {
  577. case SDL_CONTROLLER_BINDTYPE_AXIS:
  578. return BuildAnalogParamPackageForButton(port, guid, binding.value.axis);
  579. case SDL_CONTROLLER_BINDTYPE_BUTTON:
  580. return BuildButtonParamPackageForButton(port, guid, binding.value.button);
  581. case SDL_CONTROLLER_BINDTYPE_HAT:
  582. return BuildHatParamPackageForButton(port, guid, binding.value.hat.hat,
  583. binding.value.hat.hat_mask);
  584. }
  585. return {};
  586. }
  587. Common::ParamPackage BuildParamPackageForAnalog(int port, const std::string& guid, int axis_x,
  588. int axis_y) {
  589. Common::ParamPackage params;
  590. params.Set("engine", "sdl");
  591. params.Set("port", port);
  592. params.Set("guid", guid);
  593. params.Set("axis_x", axis_x);
  594. params.Set("axis_y", axis_y);
  595. return params;
  596. }
  597. } // Anonymous namespace
  598. ButtonMapping SDLState::GetButtonMappingForDevice(const Common::ParamPackage& params) {
  599. // This list is missing ZL/ZR since those are not considered buttons in SDL GameController.
  600. // We will add those afterwards
  601. // This list also excludes Screenshot since theres not really a mapping for that
  602. std::unordered_map<Settings::NativeButton::Values, SDL_GameControllerButton>
  603. switch_to_sdl_button = {
  604. {Settings::NativeButton::A, SDL_CONTROLLER_BUTTON_B},
  605. {Settings::NativeButton::B, SDL_CONTROLLER_BUTTON_A},
  606. {Settings::NativeButton::X, SDL_CONTROLLER_BUTTON_Y},
  607. {Settings::NativeButton::Y, SDL_CONTROLLER_BUTTON_X},
  608. {Settings::NativeButton::LStick, SDL_CONTROLLER_BUTTON_LEFTSTICK},
  609. {Settings::NativeButton::RStick, SDL_CONTROLLER_BUTTON_RIGHTSTICK},
  610. {Settings::NativeButton::L, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  611. {Settings::NativeButton::R, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  612. {Settings::NativeButton::Plus, SDL_CONTROLLER_BUTTON_START},
  613. {Settings::NativeButton::Minus, SDL_CONTROLLER_BUTTON_BACK},
  614. {Settings::NativeButton::DLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT},
  615. {Settings::NativeButton::DUp, SDL_CONTROLLER_BUTTON_DPAD_UP},
  616. {Settings::NativeButton::DRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT},
  617. {Settings::NativeButton::DDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN},
  618. {Settings::NativeButton::SL, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  619. {Settings::NativeButton::SR, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  620. {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
  621. };
  622. if (!params.Has("guid") || !params.Has("port")) {
  623. return {};
  624. }
  625. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  626. auto controller = joystick->GetSDLGameController();
  627. if (!controller) {
  628. return {};
  629. }
  630. ButtonMapping mapping{};
  631. for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
  632. const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
  633. mapping[switch_button] =
  634. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding);
  635. }
  636. // Add the missing bindings for ZL/ZR
  637. std::unordered_map<Settings::NativeButton::Values, SDL_GameControllerAxis> switch_to_sdl_axis =
  638. {
  639. {Settings::NativeButton::ZL, SDL_CONTROLLER_AXIS_TRIGGERLEFT},
  640. {Settings::NativeButton::ZR, SDL_CONTROLLER_AXIS_TRIGGERRIGHT},
  641. };
  642. for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
  643. const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
  644. mapping[switch_button] =
  645. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding);
  646. }
  647. return mapping;
  648. }
  649. AnalogMapping SDLState::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
  650. if (!params.Has("guid") || !params.Has("port")) {
  651. return {};
  652. }
  653. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  654. auto controller = joystick->GetSDLGameController();
  655. if (!controller) {
  656. return {};
  657. }
  658. AnalogMapping mapping = {};
  659. const auto& binding_left_x =
  660. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
  661. const auto& binding_left_y =
  662. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
  663. mapping[Settings::NativeAnalog::LStick] =
  664. BuildParamPackageForAnalog(joystick->GetPort(), joystick->GetGUID(),
  665. binding_left_x.value.axis, binding_left_y.value.axis);
  666. const auto& binding_right_x =
  667. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
  668. const auto& binding_right_y =
  669. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
  670. mapping[Settings::NativeAnalog::RStick] =
  671. BuildParamPackageForAnalog(joystick->GetPort(), joystick->GetGUID(),
  672. binding_right_x.value.axis, binding_right_y.value.axis);
  673. return mapping;
  674. }
  675. namespace Polling {
  676. class SDLPoller : public InputCommon::Polling::DevicePoller {
  677. public:
  678. explicit SDLPoller(SDLState& state_) : state(state_) {}
  679. void Start(const std::string& device_id) override {
  680. state.event_queue.Clear();
  681. state.polling = true;
  682. }
  683. void Stop() override {
  684. state.polling = false;
  685. }
  686. protected:
  687. SDLState& state;
  688. };
  689. class SDLButtonPoller final : public SDLPoller {
  690. public:
  691. explicit SDLButtonPoller(SDLState& state_) : SDLPoller(state_) {}
  692. Common::ParamPackage GetNextInput() override {
  693. SDL_Event event;
  694. while (state.event_queue.Pop(event)) {
  695. const auto package = FromEvent(event);
  696. if (package) {
  697. return *package;
  698. }
  699. }
  700. return {};
  701. }
  702. [[nodiscard]] std::optional<Common::ParamPackage> FromEvent(const SDL_Event& event) const {
  703. switch (event.type) {
  704. case SDL_JOYAXISMOTION:
  705. if (std::abs(event.jaxis.value / 32767.0) < 0.5) {
  706. break;
  707. }
  708. [[fallthrough]];
  709. case SDL_JOYBUTTONUP:
  710. case SDL_JOYHATMOTION:
  711. return {SDLEventToButtonParamPackage(state, event)};
  712. }
  713. return std::nullopt;
  714. }
  715. };
  716. /**
  717. * Attempts to match the press to a controller joy axis (left/right stick) and if a match
  718. * isn't found, checks if the event matches anything from SDLButtonPoller and uses that
  719. * instead
  720. */
  721. class SDLAnalogPreferredPoller final : public SDLPoller {
  722. public:
  723. explicit SDLAnalogPreferredPoller(SDLState& state_)
  724. : SDLPoller(state_), button_poller(state_) {}
  725. void Start(const std::string& device_id) override {
  726. SDLPoller::Start(device_id);
  727. // Load the game controller
  728. // Reset stored axes
  729. analog_x_axis = -1;
  730. analog_y_axis = -1;
  731. }
  732. Common::ParamPackage GetNextInput() override {
  733. SDL_Event event;
  734. while (state.event_queue.Pop(event)) {
  735. // Filter out axis events that are below a threshold
  736. if (event.type == SDL_JOYAXISMOTION && std::abs(event.jaxis.value / 32767.0) < 0.5) {
  737. continue;
  738. }
  739. // Simplify controller config by testing if game controller support is enabled.
  740. if (event.type == SDL_JOYAXISMOTION) {
  741. const auto axis = event.jaxis.axis;
  742. const auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
  743. const auto controller = joystick->GetSDLGameController();
  744. if (controller) {
  745. const auto axis_left_x =
  746. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX)
  747. .value.axis;
  748. const auto axis_left_y =
  749. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY)
  750. .value.axis;
  751. const auto axis_right_x =
  752. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX)
  753. .value.axis;
  754. const auto axis_right_y =
  755. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY)
  756. .value.axis;
  757. if (axis == axis_left_x || axis == axis_left_y) {
  758. analog_x_axis = axis_left_x;
  759. analog_y_axis = axis_left_y;
  760. break;
  761. } else if (axis == axis_right_x || axis == axis_right_y) {
  762. analog_x_axis = axis_right_x;
  763. analog_y_axis = axis_right_y;
  764. break;
  765. }
  766. }
  767. }
  768. // If the press wasn't accepted as a joy axis, check for a button press
  769. auto button_press = button_poller.FromEvent(event);
  770. if (button_press) {
  771. return *button_press;
  772. }
  773. }
  774. if (analog_x_axis != -1 && analog_y_axis != -1) {
  775. const auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
  776. auto params = BuildParamPackageForAnalog(joystick->GetPort(), joystick->GetGUID(),
  777. analog_x_axis, analog_y_axis);
  778. analog_x_axis = -1;
  779. analog_y_axis = -1;
  780. return params;
  781. }
  782. return {};
  783. }
  784. private:
  785. int analog_x_axis = -1;
  786. int analog_y_axis = -1;
  787. SDLButtonPoller button_poller;
  788. };
  789. } // namespace Polling
  790. SDLState::Pollers SDLState::GetPollers(InputCommon::Polling::DeviceType type) {
  791. Pollers pollers;
  792. switch (type) {
  793. case InputCommon::Polling::DeviceType::AnalogPreferred:
  794. pollers.emplace_back(std::make_unique<Polling::SDLAnalogPreferredPoller>(*this));
  795. break;
  796. case InputCommon::Polling::DeviceType::Button:
  797. pollers.emplace_back(std::make_unique<Polling::SDLButtonPoller>(*this));
  798. break;
  799. }
  800. return pollers;
  801. }
  802. } // namespace InputCommon::SDL