sdl_driver.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/logging/log.h"
  5. #include "common/math_util.h"
  6. #include "common/param_package.h"
  7. #include "common/settings.h"
  8. #include "common/thread.h"
  9. #include "common/vector_math.h"
  10. #include "input_common/drivers/sdl_driver.h"
  11. namespace InputCommon {
  12. namespace {
  13. std::string GetGUID(SDL_Joystick* joystick) {
  14. const SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
  15. char guid_str[33];
  16. SDL_JoystickGetGUIDString(guid, guid_str, sizeof(guid_str));
  17. return guid_str;
  18. }
  19. } // Anonymous namespace
  20. static int SDLEventWatcher(void* user_data, SDL_Event* event) {
  21. auto* const sdl_state = static_cast<SDLDriver*>(user_data);
  22. sdl_state->HandleGameControllerEvent(*event);
  23. return 0;
  24. }
  25. class SDLJoystick {
  26. public:
  27. SDLJoystick(std::string guid_, int port_, SDL_Joystick* joystick,
  28. SDL_GameController* game_controller)
  29. : guid{std::move(guid_)}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose},
  30. sdl_controller{game_controller, &SDL_GameControllerClose} {
  31. EnableMotion();
  32. }
  33. void EnableMotion() {
  34. if (sdl_controller) {
  35. SDL_GameController* controller = sdl_controller.get();
  36. if (SDL_GameControllerHasSensor(controller, SDL_SENSOR_ACCEL) && !has_accel) {
  37. SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_ACCEL, SDL_TRUE);
  38. has_accel = true;
  39. }
  40. if (SDL_GameControllerHasSensor(controller, SDL_SENSOR_GYRO) && !has_gyro) {
  41. SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_GYRO, SDL_TRUE);
  42. has_gyro = true;
  43. }
  44. }
  45. }
  46. bool HasGyro() const {
  47. return has_gyro;
  48. }
  49. bool HasAccel() const {
  50. return has_accel;
  51. }
  52. bool UpdateMotion(SDL_ControllerSensorEvent event) {
  53. constexpr float gravity_constant = 9.80665f;
  54. std::lock_guard lock{mutex};
  55. const u64 time_difference = event.timestamp - last_motion_update;
  56. last_motion_update = event.timestamp;
  57. switch (event.sensor) {
  58. case SDL_SENSOR_ACCEL: {
  59. motion.accel_x = -event.data[0] / gravity_constant;
  60. motion.accel_y = event.data[2] / gravity_constant;
  61. motion.accel_z = -event.data[1] / gravity_constant;
  62. break;
  63. }
  64. case SDL_SENSOR_GYRO: {
  65. motion.gyro_x = event.data[0] / (Common::PI * 2);
  66. motion.gyro_y = -event.data[2] / (Common::PI * 2);
  67. motion.gyro_z = event.data[1] / (Common::PI * 2);
  68. break;
  69. }
  70. }
  71. // Ignore duplicated timestamps
  72. if (time_difference == 0) {
  73. return false;
  74. }
  75. motion.delta_timestamp = time_difference * 1000;
  76. return true;
  77. }
  78. const BasicMotion& GetMotion() const {
  79. return motion;
  80. }
  81. bool RumblePlay(const Common::Input::VibrationStatus vibration) {
  82. constexpr u32 rumble_max_duration_ms = 1000;
  83. if (sdl_controller) {
  84. return SDL_GameControllerRumble(
  85. sdl_controller.get(), static_cast<u16>(vibration.low_amplitude),
  86. static_cast<u16>(vibration.high_amplitude), rumble_max_duration_ms) != -1;
  87. } else if (sdl_joystick) {
  88. return SDL_JoystickRumble(sdl_joystick.get(), static_cast<u16>(vibration.low_amplitude),
  89. static_cast<u16>(vibration.high_amplitude),
  90. rumble_max_duration_ms) != -1;
  91. }
  92. return false;
  93. }
  94. bool HasHDRumble() const {
  95. if (sdl_controller) {
  96. const auto type = SDL_GameControllerGetType(sdl_controller.get());
  97. return (type == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO) ||
  98. (type == SDL_CONTROLLER_TYPE_PS5);
  99. }
  100. return false;
  101. }
  102. /**
  103. * The Pad identifier of the joystick
  104. */
  105. const PadIdentifier GetPadIdentifier() const {
  106. return {
  107. .guid = Common::UUID{guid},
  108. .port = static_cast<std::size_t>(port),
  109. .pad = 0,
  110. };
  111. }
  112. /**
  113. * The guid of the joystick
  114. */
  115. const std::string& GetGUID() const {
  116. return guid;
  117. }
  118. /**
  119. * The number of joystick from the same type that were connected before this joystick
  120. */
  121. int GetPort() const {
  122. return port;
  123. }
  124. SDL_Joystick* GetSDLJoystick() const {
  125. return sdl_joystick.get();
  126. }
  127. SDL_GameController* GetSDLGameController() const {
  128. return sdl_controller.get();
  129. }
  130. void SetSDLJoystick(SDL_Joystick* joystick, SDL_GameController* controller) {
  131. sdl_joystick.reset(joystick);
  132. sdl_controller.reset(controller);
  133. }
  134. bool IsJoyconLeft() const {
  135. const std::string controller_name = GetControllerName();
  136. if (std::strstr(controller_name.c_str(), "Joy-Con Left") != nullptr) {
  137. return true;
  138. }
  139. if (std::strstr(controller_name.c_str(), "Joy-Con (L)") != nullptr) {
  140. return true;
  141. }
  142. return false;
  143. }
  144. bool IsJoyconRight() const {
  145. const std::string controller_name = GetControllerName();
  146. if (std::strstr(controller_name.c_str(), "Joy-Con Right") != nullptr) {
  147. return true;
  148. }
  149. if (std::strstr(controller_name.c_str(), "Joy-Con (R)") != nullptr) {
  150. return true;
  151. }
  152. return false;
  153. }
  154. Common::Input::BatteryLevel GetBatteryLevel() {
  155. const auto level = SDL_JoystickCurrentPowerLevel(sdl_joystick.get());
  156. switch (level) {
  157. case SDL_JOYSTICK_POWER_EMPTY:
  158. return Common::Input::BatteryLevel::Empty;
  159. case SDL_JOYSTICK_POWER_LOW:
  160. return Common::Input::BatteryLevel::Low;
  161. case SDL_JOYSTICK_POWER_MEDIUM:
  162. return Common::Input::BatteryLevel::Medium;
  163. case SDL_JOYSTICK_POWER_FULL:
  164. case SDL_JOYSTICK_POWER_MAX:
  165. return Common::Input::BatteryLevel::Full;
  166. case SDL_JOYSTICK_POWER_WIRED:
  167. return Common::Input::BatteryLevel::Charging;
  168. case SDL_JOYSTICK_POWER_UNKNOWN:
  169. default:
  170. return Common::Input::BatteryLevel::None;
  171. }
  172. }
  173. std::string GetControllerName() const {
  174. if (sdl_controller) {
  175. switch (SDL_GameControllerGetType(sdl_controller.get())) {
  176. case SDL_CONTROLLER_TYPE_XBOX360:
  177. return "Xbox 360 Controller";
  178. case SDL_CONTROLLER_TYPE_XBOXONE:
  179. return "Xbox One Controller";
  180. case SDL_CONTROLLER_TYPE_PS3:
  181. return "DualShock 3 Controller";
  182. case SDL_CONTROLLER_TYPE_PS4:
  183. return "DualShock 4 Controller";
  184. case SDL_CONTROLLER_TYPE_PS5:
  185. return "DualSense Controller";
  186. default:
  187. break;
  188. }
  189. const auto name = SDL_GameControllerName(sdl_controller.get());
  190. if (name) {
  191. return name;
  192. }
  193. }
  194. if (sdl_joystick) {
  195. const auto name = SDL_JoystickName(sdl_joystick.get());
  196. if (name) {
  197. return name;
  198. }
  199. }
  200. return "Unknown";
  201. }
  202. private:
  203. std::string guid;
  204. int port;
  205. std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
  206. std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller;
  207. mutable std::mutex mutex;
  208. u64 last_motion_update{};
  209. bool has_gyro{false};
  210. bool has_accel{false};
  211. BasicMotion motion;
  212. };
  213. std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickByGUID(const std::string& guid, int port) {
  214. std::lock_guard lock{joystick_map_mutex};
  215. const auto it = joystick_map.find(guid);
  216. if (it != joystick_map.end()) {
  217. while (it->second.size() <= static_cast<std::size_t>(port)) {
  218. auto joystick = std::make_shared<SDLJoystick>(guid, static_cast<int>(it->second.size()),
  219. nullptr, nullptr);
  220. it->second.emplace_back(std::move(joystick));
  221. }
  222. return it->second[static_cast<std::size_t>(port)];
  223. }
  224. auto joystick = std::make_shared<SDLJoystick>(guid, 0, nullptr, nullptr);
  225. return joystick_map[guid].emplace_back(std::move(joystick));
  226. }
  227. std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickBySDLID(SDL_JoystickID sdl_id) {
  228. auto sdl_joystick = SDL_JoystickFromInstanceID(sdl_id);
  229. const std::string guid = GetGUID(sdl_joystick);
  230. std::lock_guard lock{joystick_map_mutex};
  231. const auto map_it = joystick_map.find(guid);
  232. if (map_it == joystick_map.end()) {
  233. return nullptr;
  234. }
  235. const auto vec_it = std::find_if(map_it->second.begin(), map_it->second.end(),
  236. [&sdl_joystick](const auto& joystick) {
  237. return joystick->GetSDLJoystick() == sdl_joystick;
  238. });
  239. if (vec_it == map_it->second.end()) {
  240. return nullptr;
  241. }
  242. return *vec_it;
  243. }
  244. void SDLDriver::InitJoystick(int joystick_index) {
  245. SDL_Joystick* sdl_joystick = SDL_JoystickOpen(joystick_index);
  246. SDL_GameController* sdl_gamecontroller = nullptr;
  247. if (SDL_IsGameController(joystick_index)) {
  248. sdl_gamecontroller = SDL_GameControllerOpen(joystick_index);
  249. }
  250. if (!sdl_joystick) {
  251. LOG_ERROR(Input, "Failed to open joystick {}", joystick_index);
  252. return;
  253. }
  254. const std::string guid = GetGUID(sdl_joystick);
  255. std::lock_guard lock{joystick_map_mutex};
  256. if (joystick_map.find(guid) == joystick_map.end()) {
  257. auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_gamecontroller);
  258. PreSetController(joystick->GetPadIdentifier());
  259. SetBattery(joystick->GetPadIdentifier(), joystick->GetBatteryLevel());
  260. joystick_map[guid].emplace_back(std::move(joystick));
  261. return;
  262. }
  263. auto& joystick_guid_list = joystick_map[guid];
  264. const auto joystick_it =
  265. std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
  266. [](const auto& joystick) { return !joystick->GetSDLJoystick(); });
  267. if (joystick_it != joystick_guid_list.end()) {
  268. (*joystick_it)->SetSDLJoystick(sdl_joystick, sdl_gamecontroller);
  269. return;
  270. }
  271. const int port = static_cast<int>(joystick_guid_list.size());
  272. auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_gamecontroller);
  273. PreSetController(joystick->GetPadIdentifier());
  274. SetBattery(joystick->GetPadIdentifier(), joystick->GetBatteryLevel());
  275. joystick_guid_list.emplace_back(std::move(joystick));
  276. }
  277. void SDLDriver::CloseJoystick(SDL_Joystick* sdl_joystick) {
  278. const std::string guid = GetGUID(sdl_joystick);
  279. std::lock_guard lock{joystick_map_mutex};
  280. // This call to guid is safe since the joystick is guaranteed to be in the map
  281. const auto& joystick_guid_list = joystick_map[guid];
  282. const auto joystick_it = std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
  283. [&sdl_joystick](const auto& joystick) {
  284. return joystick->GetSDLJoystick() == sdl_joystick;
  285. });
  286. if (joystick_it != joystick_guid_list.end()) {
  287. (*joystick_it)->SetSDLJoystick(nullptr, nullptr);
  288. }
  289. }
  290. void SDLDriver::HandleGameControllerEvent(const SDL_Event& event) {
  291. switch (event.type) {
  292. case SDL_JOYBUTTONUP: {
  293. if (const auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  294. const PadIdentifier identifier = joystick->GetPadIdentifier();
  295. SetButton(identifier, event.jbutton.button, false);
  296. }
  297. break;
  298. }
  299. case SDL_JOYBUTTONDOWN: {
  300. if (const auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
  301. const PadIdentifier identifier = joystick->GetPadIdentifier();
  302. SetButton(identifier, event.jbutton.button, true);
  303. // Battery doesn't trigger an event so just update every button press
  304. SetBattery(identifier, joystick->GetBatteryLevel());
  305. }
  306. break;
  307. }
  308. case SDL_JOYHATMOTION: {
  309. if (const auto joystick = GetSDLJoystickBySDLID(event.jhat.which)) {
  310. const PadIdentifier identifier = joystick->GetPadIdentifier();
  311. SetHatButton(identifier, event.jhat.hat, event.jhat.value);
  312. }
  313. break;
  314. }
  315. case SDL_JOYAXISMOTION: {
  316. if (const auto joystick = GetSDLJoystickBySDLID(event.jaxis.which)) {
  317. const PadIdentifier identifier = joystick->GetPadIdentifier();
  318. SetAxis(identifier, event.jaxis.axis, event.jaxis.value / 32767.0f);
  319. }
  320. break;
  321. }
  322. case SDL_CONTROLLERSENSORUPDATE: {
  323. if (auto joystick = GetSDLJoystickBySDLID(event.csensor.which)) {
  324. if (joystick->UpdateMotion(event.csensor)) {
  325. const PadIdentifier identifier = joystick->GetPadIdentifier();
  326. SetMotion(identifier, 0, joystick->GetMotion());
  327. }
  328. }
  329. break;
  330. }
  331. case SDL_JOYDEVICEREMOVED:
  332. LOG_DEBUG(Input, "Controller removed with Instance_ID {}", event.jdevice.which);
  333. CloseJoystick(SDL_JoystickFromInstanceID(event.jdevice.which));
  334. break;
  335. case SDL_JOYDEVICEADDED:
  336. LOG_DEBUG(Input, "Controller connected with device index {}", event.jdevice.which);
  337. InitJoystick(event.jdevice.which);
  338. break;
  339. }
  340. }
  341. void SDLDriver::CloseJoysticks() {
  342. std::lock_guard lock{joystick_map_mutex};
  343. joystick_map.clear();
  344. }
  345. SDLDriver::SDLDriver(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
  346. if (!Settings::values.enable_raw_input) {
  347. // Disable raw input. When enabled this setting causes SDL to die when a web applet opens
  348. SDL_SetHint(SDL_HINT_JOYSTICK_RAWINPUT, "0");
  349. }
  350. // Prevent SDL from adding undesired axis
  351. SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
  352. // Enable HIDAPI rumble. This prevents SDL from disabling motion on PS4 and PS5 controllers
  353. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, "1");
  354. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE, "1");
  355. SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
  356. // Use hidapi driver for joycons. This will allow joycons to be detected as a GameController and
  357. // not a generic one
  358. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, "1");
  359. // Disable hidapi driver for xbox. Already default on Windows, this causes conflict with native
  360. // driver on Linux.
  361. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_XBOX, "0");
  362. // If the frontend is going to manage the event loop, then we don't start one here
  363. start_thread = SDL_WasInit(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) == 0;
  364. if (start_thread && SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
  365. LOG_CRITICAL(Input, "SDL_Init failed with: {}", SDL_GetError());
  366. return;
  367. }
  368. SDL_AddEventWatch(&SDLEventWatcher, this);
  369. initialized = true;
  370. if (start_thread) {
  371. poll_thread = std::thread([this] {
  372. Common::SetCurrentThreadName("yuzu:input:SDL");
  373. using namespace std::chrono_literals;
  374. while (initialized) {
  375. SDL_PumpEvents();
  376. std::this_thread::sleep_for(1ms);
  377. }
  378. });
  379. }
  380. // Because the events for joystick connection happens before we have our event watcher added, we
  381. // can just open all the joysticks right here
  382. for (int i = 0; i < SDL_NumJoysticks(); ++i) {
  383. InitJoystick(i);
  384. }
  385. }
  386. SDLDriver::~SDLDriver() {
  387. CloseJoysticks();
  388. SDL_DelEventWatch(&SDLEventWatcher, this);
  389. initialized = false;
  390. if (start_thread) {
  391. poll_thread.join();
  392. SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
  393. }
  394. }
  395. std::vector<Common::ParamPackage> SDLDriver::GetInputDevices() const {
  396. std::vector<Common::ParamPackage> devices;
  397. std::unordered_map<int, std::shared_ptr<SDLJoystick>> joycon_pairs;
  398. for (const auto& [key, value] : joystick_map) {
  399. for (const auto& joystick : value) {
  400. if (!joystick->GetSDLJoystick()) {
  401. continue;
  402. }
  403. const std::string name =
  404. fmt::format("{} {}", joystick->GetControllerName(), joystick->GetPort());
  405. devices.emplace_back(Common::ParamPackage{
  406. {"engine", GetEngineName()},
  407. {"display", std::move(name)},
  408. {"guid", joystick->GetGUID()},
  409. {"port", std::to_string(joystick->GetPort())},
  410. });
  411. if (joystick->IsJoyconLeft()) {
  412. joycon_pairs.insert_or_assign(joystick->GetPort(), joystick);
  413. }
  414. }
  415. }
  416. // Add dual controllers
  417. for (const auto& [key, value] : joystick_map) {
  418. for (const auto& joystick : value) {
  419. if (joystick->IsJoyconRight()) {
  420. if (!joycon_pairs.contains(joystick->GetPort())) {
  421. continue;
  422. }
  423. const auto joystick2 = joycon_pairs.at(joystick->GetPort());
  424. const std::string name =
  425. fmt::format("{} {}", "Nintendo Dual Joy-Con", joystick->GetPort());
  426. devices.emplace_back(Common::ParamPackage{
  427. {"engine", GetEngineName()},
  428. {"display", std::move(name)},
  429. {"guid", joystick->GetGUID()},
  430. {"guid2", joystick2->GetGUID()},
  431. {"port", std::to_string(joystick->GetPort())},
  432. });
  433. }
  434. }
  435. }
  436. return devices;
  437. }
  438. Common::Input::VibrationError SDLDriver::SetRumble(
  439. const PadIdentifier& identifier, const Common::Input::VibrationStatus& vibration) {
  440. const auto joystick =
  441. GetSDLJoystickByGUID(identifier.guid.RawString(), static_cast<int>(identifier.port));
  442. const auto process_amplitude_exp = [](f32 amplitude, f32 factor) {
  443. return (amplitude + std::pow(amplitude, factor)) * 0.5f * 0xFFFF;
  444. };
  445. // Default exponential curve for rumble
  446. f32 factor = 0.35f;
  447. // If vibration is set as a linear output use a flatter value
  448. if (vibration.type == Common::Input::VibrationAmplificationType::Linear) {
  449. factor = 0.5f;
  450. }
  451. // Amplitude for HD rumble needs no modification
  452. if (joystick->HasHDRumble()) {
  453. factor = 1.0f;
  454. }
  455. const Common::Input::VibrationStatus new_vibration{
  456. .low_amplitude = process_amplitude_exp(vibration.low_amplitude, factor),
  457. .low_frequency = vibration.low_frequency,
  458. .high_amplitude = process_amplitude_exp(vibration.high_amplitude, factor),
  459. .high_frequency = vibration.high_frequency,
  460. .type = Common::Input::VibrationAmplificationType::Exponential,
  461. };
  462. if (!joystick->RumblePlay(new_vibration)) {
  463. return Common::Input::VibrationError::Unknown;
  464. }
  465. return Common::Input::VibrationError::None;
  466. }
  467. Common::ParamPackage SDLDriver::BuildAnalogParamPackageForButton(int port, std::string guid,
  468. s32 axis, float value) const {
  469. Common::ParamPackage params{};
  470. params.Set("engine", GetEngineName());
  471. params.Set("port", port);
  472. params.Set("guid", std::move(guid));
  473. params.Set("axis", axis);
  474. params.Set("threshold", "0.5");
  475. params.Set("invert", value < 0 ? "-" : "+");
  476. return params;
  477. }
  478. Common::ParamPackage SDLDriver::BuildButtonParamPackageForButton(int port, std::string guid,
  479. s32 button) const {
  480. Common::ParamPackage params{};
  481. params.Set("engine", GetEngineName());
  482. params.Set("port", port);
  483. params.Set("guid", std::move(guid));
  484. params.Set("button", button);
  485. return params;
  486. }
  487. Common::ParamPackage SDLDriver::BuildHatParamPackageForButton(int port, std::string guid, s32 hat,
  488. u8 value) const {
  489. Common::ParamPackage params{};
  490. params.Set("engine", GetEngineName());
  491. params.Set("port", port);
  492. params.Set("guid", std::move(guid));
  493. params.Set("hat", hat);
  494. params.Set("direction", GetHatButtonName(value));
  495. return params;
  496. }
  497. Common::ParamPackage SDLDriver::BuildMotionParam(int port, std::string guid) const {
  498. Common::ParamPackage params{};
  499. params.Set("engine", GetEngineName());
  500. params.Set("motion", 0);
  501. params.Set("port", port);
  502. params.Set("guid", std::move(guid));
  503. return params;
  504. }
  505. Common::ParamPackage SDLDriver::BuildParamPackageForBinding(
  506. int port, const std::string& guid, const SDL_GameControllerButtonBind& binding) const {
  507. switch (binding.bindType) {
  508. case SDL_CONTROLLER_BINDTYPE_NONE:
  509. break;
  510. case SDL_CONTROLLER_BINDTYPE_AXIS:
  511. return BuildAnalogParamPackageForButton(port, guid, binding.value.axis);
  512. case SDL_CONTROLLER_BINDTYPE_BUTTON:
  513. return BuildButtonParamPackageForButton(port, guid, binding.value.button);
  514. case SDL_CONTROLLER_BINDTYPE_HAT:
  515. return BuildHatParamPackageForButton(port, guid, binding.value.hat.hat,
  516. static_cast<u8>(binding.value.hat.hat_mask));
  517. }
  518. return {};
  519. }
  520. Common::ParamPackage SDLDriver::BuildParamPackageForAnalog(PadIdentifier identifier, int axis_x,
  521. int axis_y, float offset_x,
  522. float offset_y) const {
  523. Common::ParamPackage params;
  524. params.Set("engine", GetEngineName());
  525. params.Set("port", static_cast<int>(identifier.port));
  526. params.Set("guid", identifier.guid.RawString());
  527. params.Set("axis_x", axis_x);
  528. params.Set("axis_y", axis_y);
  529. params.Set("offset_x", offset_x);
  530. params.Set("offset_y", offset_y);
  531. params.Set("invert_x", "+");
  532. params.Set("invert_y", "+");
  533. return params;
  534. }
  535. ButtonMapping SDLDriver::GetButtonMappingForDevice(const Common::ParamPackage& params) {
  536. if (!params.Has("guid") || !params.Has("port")) {
  537. return {};
  538. }
  539. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  540. auto* controller = joystick->GetSDLGameController();
  541. if (controller == nullptr) {
  542. return {};
  543. }
  544. // This list is missing ZL/ZR since those are not considered buttons in SDL GameController.
  545. // We will add those afterwards
  546. // This list also excludes Screenshot since theres not really a mapping for that
  547. ButtonBindings switch_to_sdl_button;
  548. if (SDL_GameControllerGetType(controller) == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO) {
  549. switch_to_sdl_button = GetNintendoButtonBinding(joystick);
  550. } else {
  551. switch_to_sdl_button = GetDefaultButtonBinding();
  552. }
  553. // Add the missing bindings for ZL/ZR
  554. static constexpr ZButtonBindings switch_to_sdl_axis{{
  555. {Settings::NativeButton::ZL, SDL_CONTROLLER_AXIS_TRIGGERLEFT},
  556. {Settings::NativeButton::ZR, SDL_CONTROLLER_AXIS_TRIGGERRIGHT},
  557. }};
  558. // Parameters contain two joysticks return dual
  559. if (params.Has("guid2")) {
  560. const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
  561. if (joystick2->GetSDLGameController() != nullptr) {
  562. return GetDualControllerMapping(joystick, joystick2, switch_to_sdl_button,
  563. switch_to_sdl_axis);
  564. }
  565. }
  566. return GetSingleControllerMapping(joystick, switch_to_sdl_button, switch_to_sdl_axis);
  567. }
  568. ButtonBindings SDLDriver::GetDefaultButtonBinding() const {
  569. return {
  570. std::pair{Settings::NativeButton::A, SDL_CONTROLLER_BUTTON_B},
  571. {Settings::NativeButton::B, SDL_CONTROLLER_BUTTON_A},
  572. {Settings::NativeButton::X, SDL_CONTROLLER_BUTTON_Y},
  573. {Settings::NativeButton::Y, SDL_CONTROLLER_BUTTON_X},
  574. {Settings::NativeButton::LStick, SDL_CONTROLLER_BUTTON_LEFTSTICK},
  575. {Settings::NativeButton::RStick, SDL_CONTROLLER_BUTTON_RIGHTSTICK},
  576. {Settings::NativeButton::L, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  577. {Settings::NativeButton::R, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  578. {Settings::NativeButton::Plus, SDL_CONTROLLER_BUTTON_START},
  579. {Settings::NativeButton::Minus, SDL_CONTROLLER_BUTTON_BACK},
  580. {Settings::NativeButton::DLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT},
  581. {Settings::NativeButton::DUp, SDL_CONTROLLER_BUTTON_DPAD_UP},
  582. {Settings::NativeButton::DRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT},
  583. {Settings::NativeButton::DDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN},
  584. {Settings::NativeButton::SL, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
  585. {Settings::NativeButton::SR, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
  586. {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
  587. {Settings::NativeButton::Screenshot, SDL_CONTROLLER_BUTTON_MISC1},
  588. };
  589. }
  590. ButtonBindings SDLDriver::GetNintendoButtonBinding(
  591. const std::shared_ptr<SDLJoystick>& joystick) const {
  592. // Default SL/SR mapping for pro controllers
  593. auto sl_button = SDL_CONTROLLER_BUTTON_LEFTSHOULDER;
  594. auto sr_button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;
  595. if (joystick->IsJoyconLeft()) {
  596. sl_button = SDL_CONTROLLER_BUTTON_PADDLE2;
  597. sr_button = SDL_CONTROLLER_BUTTON_PADDLE4;
  598. }
  599. if (joystick->IsJoyconRight()) {
  600. sl_button = SDL_CONTROLLER_BUTTON_PADDLE3;
  601. sr_button = SDL_CONTROLLER_BUTTON_PADDLE1;
  602. }
  603. return {
  604. std::pair{Settings::NativeButton::A, SDL_CONTROLLER_BUTTON_A},
  605. {Settings::NativeButton::B, SDL_CONTROLLER_BUTTON_B},
  606. {Settings::NativeButton::X, SDL_CONTROLLER_BUTTON_X},
  607. {Settings::NativeButton::Y, SDL_CONTROLLER_BUTTON_Y},
  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, sl_button},
  619. {Settings::NativeButton::SR, sr_button},
  620. {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
  621. {Settings::NativeButton::Screenshot, SDL_CONTROLLER_BUTTON_MISC1},
  622. };
  623. }
  624. ButtonMapping SDLDriver::GetSingleControllerMapping(
  625. const std::shared_ptr<SDLJoystick>& joystick, const ButtonBindings& switch_to_sdl_button,
  626. const ZButtonBindings& switch_to_sdl_axis) const {
  627. ButtonMapping mapping;
  628. mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());
  629. auto* controller = joystick->GetSDLGameController();
  630. for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
  631. const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
  632. mapping.insert_or_assign(
  633. switch_button,
  634. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  635. }
  636. for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
  637. const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
  638. mapping.insert_or_assign(
  639. switch_button,
  640. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  641. }
  642. return mapping;
  643. }
  644. ButtonMapping SDLDriver::GetDualControllerMapping(const std::shared_ptr<SDLJoystick>& joystick,
  645. const std::shared_ptr<SDLJoystick>& joystick2,
  646. const ButtonBindings& switch_to_sdl_button,
  647. const ZButtonBindings& switch_to_sdl_axis) const {
  648. ButtonMapping mapping;
  649. mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());
  650. auto* controller = joystick->GetSDLGameController();
  651. auto* controller2 = joystick2->GetSDLGameController();
  652. for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
  653. if (IsButtonOnLeftSide(switch_button)) {
  654. const auto& binding = SDL_GameControllerGetBindForButton(controller2, sdl_button);
  655. mapping.insert_or_assign(
  656. switch_button,
  657. BuildParamPackageForBinding(joystick2->GetPort(), joystick2->GetGUID(), binding));
  658. continue;
  659. }
  660. const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
  661. mapping.insert_or_assign(
  662. switch_button,
  663. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  664. }
  665. for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
  666. if (IsButtonOnLeftSide(switch_button)) {
  667. const auto& binding = SDL_GameControllerGetBindForAxis(controller2, sdl_axis);
  668. mapping.insert_or_assign(
  669. switch_button,
  670. BuildParamPackageForBinding(joystick2->GetPort(), joystick2->GetGUID(), binding));
  671. continue;
  672. }
  673. const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
  674. mapping.insert_or_assign(
  675. switch_button,
  676. BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
  677. }
  678. return mapping;
  679. }
  680. bool SDLDriver::IsButtonOnLeftSide(Settings::NativeButton::Values button) const {
  681. switch (button) {
  682. case Settings::NativeButton::DDown:
  683. case Settings::NativeButton::DLeft:
  684. case Settings::NativeButton::DRight:
  685. case Settings::NativeButton::DUp:
  686. case Settings::NativeButton::L:
  687. case Settings::NativeButton::LStick:
  688. case Settings::NativeButton::Minus:
  689. case Settings::NativeButton::Screenshot:
  690. case Settings::NativeButton::ZL:
  691. return true;
  692. default:
  693. return false;
  694. }
  695. }
  696. AnalogMapping SDLDriver::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
  697. if (!params.Has("guid") || !params.Has("port")) {
  698. return {};
  699. }
  700. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  701. const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
  702. auto* controller = joystick->GetSDLGameController();
  703. if (controller == nullptr) {
  704. return {};
  705. }
  706. AnalogMapping mapping = {};
  707. const auto& binding_left_x =
  708. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
  709. const auto& binding_left_y =
  710. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
  711. if (params.Has("guid2")) {
  712. const auto identifier = joystick2->GetPadIdentifier();
  713. PreSetController(identifier);
  714. PreSetAxis(identifier, binding_left_x.value.axis);
  715. PreSetAxis(identifier, binding_left_y.value.axis);
  716. const auto left_offset_x = -GetAxis(identifier, binding_left_x.value.axis);
  717. const auto left_offset_y = GetAxis(identifier, binding_left_y.value.axis);
  718. mapping.insert_or_assign(Settings::NativeAnalog::LStick,
  719. BuildParamPackageForAnalog(identifier, binding_left_x.value.axis,
  720. binding_left_y.value.axis,
  721. left_offset_x, left_offset_y));
  722. } else {
  723. const auto identifier = joystick->GetPadIdentifier();
  724. PreSetController(identifier);
  725. PreSetAxis(identifier, binding_left_x.value.axis);
  726. PreSetAxis(identifier, binding_left_y.value.axis);
  727. const auto left_offset_x = -GetAxis(identifier, binding_left_x.value.axis);
  728. const auto left_offset_y = GetAxis(identifier, binding_left_y.value.axis);
  729. mapping.insert_or_assign(Settings::NativeAnalog::LStick,
  730. BuildParamPackageForAnalog(identifier, binding_left_x.value.axis,
  731. binding_left_y.value.axis,
  732. left_offset_x, left_offset_y));
  733. }
  734. const auto& binding_right_x =
  735. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
  736. const auto& binding_right_y =
  737. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
  738. const auto identifier = joystick->GetPadIdentifier();
  739. PreSetController(identifier);
  740. PreSetAxis(identifier, binding_right_x.value.axis);
  741. PreSetAxis(identifier, binding_right_y.value.axis);
  742. const auto right_offset_x = -GetAxis(identifier, binding_right_x.value.axis);
  743. const auto right_offset_y = GetAxis(identifier, binding_right_y.value.axis);
  744. mapping.insert_or_assign(Settings::NativeAnalog::RStick,
  745. BuildParamPackageForAnalog(identifier, binding_right_x.value.axis,
  746. binding_right_y.value.axis, right_offset_x,
  747. right_offset_y));
  748. return mapping;
  749. }
  750. MotionMapping SDLDriver::GetMotionMappingForDevice(const Common::ParamPackage& params) {
  751. if (!params.Has("guid") || !params.Has("port")) {
  752. return {};
  753. }
  754. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  755. const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
  756. auto* controller = joystick->GetSDLGameController();
  757. if (controller == nullptr) {
  758. return {};
  759. }
  760. MotionMapping mapping = {};
  761. joystick->EnableMotion();
  762. if (joystick->HasGyro() || joystick->HasAccel()) {
  763. mapping.insert_or_assign(Settings::NativeMotion::MotionRight,
  764. BuildMotionParam(joystick->GetPort(), joystick->GetGUID()));
  765. }
  766. if (params.Has("guid2")) {
  767. joystick2->EnableMotion();
  768. if (joystick2->HasGyro() || joystick2->HasAccel()) {
  769. mapping.insert_or_assign(Settings::NativeMotion::MotionLeft,
  770. BuildMotionParam(joystick2->GetPort(), joystick2->GetGUID()));
  771. }
  772. } else {
  773. if (joystick->HasGyro() || joystick->HasAccel()) {
  774. mapping.insert_or_assign(Settings::NativeMotion::MotionLeft,
  775. BuildMotionParam(joystick->GetPort(), joystick->GetGUID()));
  776. }
  777. }
  778. return mapping;
  779. }
  780. Common::Input::ButtonNames SDLDriver::GetUIName(const Common::ParamPackage& params) const {
  781. if (params.Has("button")) {
  782. // TODO(German77): Find how to substitue the values for real button names
  783. return Common::Input::ButtonNames::Value;
  784. }
  785. if (params.Has("hat")) {
  786. return Common::Input::ButtonNames::Value;
  787. }
  788. if (params.Has("axis")) {
  789. return Common::Input::ButtonNames::Value;
  790. }
  791. if (params.Has("axis_x") && params.Has("axis_y") && params.Has("axis_z")) {
  792. return Common::Input::ButtonNames::Value;
  793. }
  794. if (params.Has("motion")) {
  795. return Common::Input::ButtonNames::Engine;
  796. }
  797. return Common::Input::ButtonNames::Invalid;
  798. }
  799. std::string SDLDriver::GetHatButtonName(u8 direction_value) const {
  800. switch (direction_value) {
  801. case SDL_HAT_UP:
  802. return "up";
  803. case SDL_HAT_DOWN:
  804. return "down";
  805. case SDL_HAT_LEFT:
  806. return "left";
  807. case SDL_HAT_RIGHT:
  808. return "right";
  809. default:
  810. return {};
  811. }
  812. }
  813. u8 SDLDriver::GetHatButtonId(const std::string& direction_name) const {
  814. Uint8 direction;
  815. if (direction_name == "up") {
  816. direction = SDL_HAT_UP;
  817. } else if (direction_name == "down") {
  818. direction = SDL_HAT_DOWN;
  819. } else if (direction_name == "left") {
  820. direction = SDL_HAT_LEFT;
  821. } else if (direction_name == "right") {
  822. direction = SDL_HAT_RIGHT;
  823. } else {
  824. direction = 0;
  825. }
  826. return direction;
  827. }
  828. bool SDLDriver::IsStickInverted(const Common::ParamPackage& params) {
  829. if (!params.Has("guid") || !params.Has("port")) {
  830. return false;
  831. }
  832. const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
  833. if (joystick == nullptr) {
  834. return false;
  835. }
  836. auto* controller = joystick->GetSDLGameController();
  837. if (controller == nullptr) {
  838. return false;
  839. }
  840. const auto& axis_x = params.Get("axis_x", 0);
  841. const auto& axis_y = params.Get("axis_y", 0);
  842. const auto& binding_left_x =
  843. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
  844. const auto& binding_right_x =
  845. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
  846. const auto& binding_left_y =
  847. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
  848. const auto& binding_right_y =
  849. SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
  850. if (axis_x != binding_left_y.value.axis && axis_x != binding_right_y.value.axis) {
  851. return false;
  852. }
  853. if (axis_y != binding_left_x.value.axis && axis_y != binding_right_x.value.axis) {
  854. return false;
  855. }
  856. return true;
  857. }
  858. } // namespace InputCommon