emulated_controller.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include "common/polyfill_ranges.h"
  5. #include "common/thread.h"
  6. #include "core/hid/emulated_controller.h"
  7. #include "core/hid/input_converter.h"
  8. namespace Core::HID {
  9. constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
  10. constexpr s32 HID_TRIGGER_MAX = 0x7fff;
  11. EmulatedController::EmulatedController(NpadIdType npad_id_type_) : npad_id_type(npad_id_type_) {}
  12. EmulatedController::~EmulatedController() = default;
  13. NpadStyleIndex EmulatedController::MapSettingsTypeToNPad(Settings::ControllerType type) {
  14. switch (type) {
  15. case Settings::ControllerType::ProController:
  16. return NpadStyleIndex::ProController;
  17. case Settings::ControllerType::DualJoyconDetached:
  18. return NpadStyleIndex::JoyconDual;
  19. case Settings::ControllerType::LeftJoycon:
  20. return NpadStyleIndex::JoyconLeft;
  21. case Settings::ControllerType::RightJoycon:
  22. return NpadStyleIndex::JoyconRight;
  23. case Settings::ControllerType::Handheld:
  24. return NpadStyleIndex::Handheld;
  25. case Settings::ControllerType::GameCube:
  26. return NpadStyleIndex::GameCube;
  27. case Settings::ControllerType::Pokeball:
  28. return NpadStyleIndex::Pokeball;
  29. case Settings::ControllerType::NES:
  30. return NpadStyleIndex::NES;
  31. case Settings::ControllerType::SNES:
  32. return NpadStyleIndex::SNES;
  33. case Settings::ControllerType::N64:
  34. return NpadStyleIndex::N64;
  35. case Settings::ControllerType::SegaGenesis:
  36. return NpadStyleIndex::SegaGenesis;
  37. default:
  38. return NpadStyleIndex::ProController;
  39. }
  40. }
  41. Settings::ControllerType EmulatedController::MapNPadToSettingsType(NpadStyleIndex type) {
  42. switch (type) {
  43. case NpadStyleIndex::ProController:
  44. return Settings::ControllerType::ProController;
  45. case NpadStyleIndex::JoyconDual:
  46. return Settings::ControllerType::DualJoyconDetached;
  47. case NpadStyleIndex::JoyconLeft:
  48. return Settings::ControllerType::LeftJoycon;
  49. case NpadStyleIndex::JoyconRight:
  50. return Settings::ControllerType::RightJoycon;
  51. case NpadStyleIndex::Handheld:
  52. return Settings::ControllerType::Handheld;
  53. case NpadStyleIndex::GameCube:
  54. return Settings::ControllerType::GameCube;
  55. case NpadStyleIndex::Pokeball:
  56. return Settings::ControllerType::Pokeball;
  57. case NpadStyleIndex::NES:
  58. return Settings::ControllerType::NES;
  59. case NpadStyleIndex::SNES:
  60. return Settings::ControllerType::SNES;
  61. case NpadStyleIndex::N64:
  62. return Settings::ControllerType::N64;
  63. case NpadStyleIndex::SegaGenesis:
  64. return Settings::ControllerType::SegaGenesis;
  65. default:
  66. return Settings::ControllerType::ProController;
  67. }
  68. }
  69. void EmulatedController::ReloadFromSettings() {
  70. const auto player_index = NpadIdTypeToIndex(npad_id_type);
  71. const auto& player = Settings::values.players.GetValue()[player_index];
  72. for (std::size_t index = 0; index < player.buttons.size(); ++index) {
  73. button_params[index] = Common::ParamPackage(player.buttons[index]);
  74. }
  75. for (std::size_t index = 0; index < player.analogs.size(); ++index) {
  76. stick_params[index] = Common::ParamPackage(player.analogs[index]);
  77. }
  78. for (std::size_t index = 0; index < player.motions.size(); ++index) {
  79. motion_params[index] = Common::ParamPackage(player.motions[index]);
  80. }
  81. controller.colors_state.fullkey = {
  82. .body = GetNpadColor(player.body_color_left),
  83. .button = GetNpadColor(player.button_color_left),
  84. };
  85. controller.colors_state.left = {
  86. .body = GetNpadColor(player.body_color_left),
  87. .button = GetNpadColor(player.button_color_left),
  88. };
  89. controller.colors_state.right = {
  90. .body = GetNpadColor(player.body_color_right),
  91. .button = GetNpadColor(player.button_color_right),
  92. };
  93. // Other or debug controller should always be a pro controller
  94. if (npad_id_type != NpadIdType::Other) {
  95. SetNpadStyleIndex(MapSettingsTypeToNPad(player.controller_type));
  96. original_npad_type = npad_type;
  97. } else {
  98. SetNpadStyleIndex(NpadStyleIndex::ProController);
  99. original_npad_type = npad_type;
  100. }
  101. Disconnect();
  102. if (player.connected) {
  103. Connect();
  104. }
  105. ReloadInput();
  106. }
  107. void EmulatedController::LoadDevices() {
  108. // TODO(german77): Use more buttons to detect the correct device
  109. const auto left_joycon = button_params[Settings::NativeButton::DRight];
  110. const auto right_joycon = button_params[Settings::NativeButton::A];
  111. // Triggers for GC controllers
  112. trigger_params[LeftIndex] = button_params[Settings::NativeButton::ZL];
  113. trigger_params[RightIndex] = button_params[Settings::NativeButton::ZR];
  114. battery_params[LeftIndex] = left_joycon;
  115. battery_params[RightIndex] = right_joycon;
  116. battery_params[LeftIndex].Set("battery", true);
  117. battery_params[RightIndex].Set("battery", true);
  118. camera_params = Common::ParamPackage{"engine:camera,camera:1"};
  119. nfc_params = Common::ParamPackage{"engine:virtual_amiibo,nfc:1"};
  120. output_params[LeftIndex] = left_joycon;
  121. output_params[RightIndex] = right_joycon;
  122. output_params[2] = camera_params;
  123. output_params[3] = nfc_params;
  124. output_params[LeftIndex].Set("output", true);
  125. output_params[RightIndex].Set("output", true);
  126. output_params[2].Set("output", true);
  127. output_params[3].Set("output", true);
  128. LoadTASParams();
  129. LoadVirtualGamepadParams();
  130. std::ranges::transform(button_params, button_devices.begin(), Common::Input::CreateInputDevice);
  131. std::ranges::transform(stick_params, stick_devices.begin(), Common::Input::CreateInputDevice);
  132. std::ranges::transform(motion_params, motion_devices.begin(), Common::Input::CreateInputDevice);
  133. std::ranges::transform(trigger_params, trigger_devices.begin(),
  134. Common::Input::CreateInputDevice);
  135. std::ranges::transform(battery_params, battery_devices.begin(),
  136. Common::Input::CreateInputDevice);
  137. camera_devices = Common::Input::CreateInputDevice(camera_params);
  138. nfc_devices = Common::Input::CreateInputDevice(nfc_params);
  139. std::ranges::transform(output_params, output_devices.begin(),
  140. Common::Input::CreateOutputDevice);
  141. // Initialize TAS devices
  142. std::ranges::transform(tas_button_params, tas_button_devices.begin(),
  143. Common::Input::CreateInputDevice);
  144. std::ranges::transform(tas_stick_params, tas_stick_devices.begin(),
  145. Common::Input::CreateInputDevice);
  146. // Initialize virtual gamepad devices
  147. std::ranges::transform(virtual_button_params, virtual_button_devices.begin(),
  148. Common::Input::CreateInputDevice);
  149. std::ranges::transform(virtual_stick_params, virtual_stick_devices.begin(),
  150. Common::Input::CreateInputDevice);
  151. }
  152. void EmulatedController::LoadTASParams() {
  153. const auto player_index = NpadIdTypeToIndex(npad_id_type);
  154. Common::ParamPackage common_params{};
  155. common_params.Set("engine", "tas");
  156. common_params.Set("port", static_cast<int>(player_index));
  157. for (auto& param : tas_button_params) {
  158. param = common_params;
  159. }
  160. for (auto& param : tas_stick_params) {
  161. param = common_params;
  162. }
  163. // TODO(german77): Replace this with an input profile or something better
  164. tas_button_params[Settings::NativeButton::A].Set("button", 0);
  165. tas_button_params[Settings::NativeButton::B].Set("button", 1);
  166. tas_button_params[Settings::NativeButton::X].Set("button", 2);
  167. tas_button_params[Settings::NativeButton::Y].Set("button", 3);
  168. tas_button_params[Settings::NativeButton::LStick].Set("button", 4);
  169. tas_button_params[Settings::NativeButton::RStick].Set("button", 5);
  170. tas_button_params[Settings::NativeButton::L].Set("button", 6);
  171. tas_button_params[Settings::NativeButton::R].Set("button", 7);
  172. tas_button_params[Settings::NativeButton::ZL].Set("button", 8);
  173. tas_button_params[Settings::NativeButton::ZR].Set("button", 9);
  174. tas_button_params[Settings::NativeButton::Plus].Set("button", 10);
  175. tas_button_params[Settings::NativeButton::Minus].Set("button", 11);
  176. tas_button_params[Settings::NativeButton::DLeft].Set("button", 12);
  177. tas_button_params[Settings::NativeButton::DUp].Set("button", 13);
  178. tas_button_params[Settings::NativeButton::DRight].Set("button", 14);
  179. tas_button_params[Settings::NativeButton::DDown].Set("button", 15);
  180. tas_button_params[Settings::NativeButton::SL].Set("button", 16);
  181. tas_button_params[Settings::NativeButton::SR].Set("button", 17);
  182. tas_button_params[Settings::NativeButton::Home].Set("button", 18);
  183. tas_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
  184. tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
  185. tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
  186. tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
  187. tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
  188. // set to optimal stick to avoid sanitizing the stick and tweaking the coordinates
  189. // making sure they play back in the game as originally written down in the script file
  190. tas_stick_params[Settings::NativeAnalog::LStick].Set("deadzone", 0.0f);
  191. tas_stick_params[Settings::NativeAnalog::LStick].Set("range", 1.0f);
  192. tas_stick_params[Settings::NativeAnalog::RStick].Set("deadzone", 0.0f);
  193. tas_stick_params[Settings::NativeAnalog::RStick].Set("range", 1.0f);
  194. }
  195. void EmulatedController::LoadVirtualGamepadParams() {
  196. const auto player_index = NpadIdTypeToIndex(npad_id_type);
  197. Common::ParamPackage common_params{};
  198. common_params.Set("engine", "virtual_gamepad");
  199. common_params.Set("port", static_cast<int>(player_index));
  200. for (auto& param : virtual_button_params) {
  201. param = common_params;
  202. }
  203. for (auto& param : virtual_stick_params) {
  204. param = common_params;
  205. }
  206. // TODO(german77): Replace this with an input profile or something better
  207. virtual_button_params[Settings::NativeButton::A].Set("button", 0);
  208. virtual_button_params[Settings::NativeButton::B].Set("button", 1);
  209. virtual_button_params[Settings::NativeButton::X].Set("button", 2);
  210. virtual_button_params[Settings::NativeButton::Y].Set("button", 3);
  211. virtual_button_params[Settings::NativeButton::LStick].Set("button", 4);
  212. virtual_button_params[Settings::NativeButton::RStick].Set("button", 5);
  213. virtual_button_params[Settings::NativeButton::L].Set("button", 6);
  214. virtual_button_params[Settings::NativeButton::R].Set("button", 7);
  215. virtual_button_params[Settings::NativeButton::ZL].Set("button", 8);
  216. virtual_button_params[Settings::NativeButton::ZR].Set("button", 9);
  217. virtual_button_params[Settings::NativeButton::Plus].Set("button", 10);
  218. virtual_button_params[Settings::NativeButton::Minus].Set("button", 11);
  219. virtual_button_params[Settings::NativeButton::DLeft].Set("button", 12);
  220. virtual_button_params[Settings::NativeButton::DUp].Set("button", 13);
  221. virtual_button_params[Settings::NativeButton::DRight].Set("button", 14);
  222. virtual_button_params[Settings::NativeButton::DDown].Set("button", 15);
  223. virtual_button_params[Settings::NativeButton::SL].Set("button", 16);
  224. virtual_button_params[Settings::NativeButton::SR].Set("button", 17);
  225. virtual_button_params[Settings::NativeButton::Home].Set("button", 18);
  226. virtual_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
  227. virtual_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
  228. virtual_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
  229. virtual_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
  230. virtual_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
  231. }
  232. void EmulatedController::ReloadInput() {
  233. // If you load any device here add the equivalent to the UnloadInput() function
  234. LoadDevices();
  235. for (std::size_t index = 0; index < button_devices.size(); ++index) {
  236. if (!button_devices[index]) {
  237. continue;
  238. }
  239. const auto uuid = Common::UUID{button_params[index].Get("guid", "")};
  240. button_devices[index]->SetCallback({
  241. .on_change =
  242. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  243. SetButton(callback, index, uuid);
  244. },
  245. });
  246. button_devices[index]->ForceUpdate();
  247. }
  248. for (std::size_t index = 0; index < stick_devices.size(); ++index) {
  249. if (!stick_devices[index]) {
  250. continue;
  251. }
  252. const auto uuid = Common::UUID{stick_params[index].Get("guid", "")};
  253. stick_devices[index]->SetCallback({
  254. .on_change =
  255. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  256. SetStick(callback, index, uuid);
  257. },
  258. });
  259. stick_devices[index]->ForceUpdate();
  260. }
  261. for (std::size_t index = 0; index < trigger_devices.size(); ++index) {
  262. if (!trigger_devices[index]) {
  263. continue;
  264. }
  265. const auto uuid = Common::UUID{trigger_params[index].Get("guid", "")};
  266. trigger_devices[index]->SetCallback({
  267. .on_change =
  268. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  269. SetTrigger(callback, index, uuid);
  270. },
  271. });
  272. trigger_devices[index]->ForceUpdate();
  273. }
  274. for (std::size_t index = 0; index < battery_devices.size(); ++index) {
  275. if (!battery_devices[index]) {
  276. continue;
  277. }
  278. battery_devices[index]->SetCallback({
  279. .on_change =
  280. [this, index](const Common::Input::CallbackStatus& callback) {
  281. SetBattery(callback, index);
  282. },
  283. });
  284. battery_devices[index]->ForceUpdate();
  285. }
  286. for (std::size_t index = 0; index < motion_devices.size(); ++index) {
  287. if (!motion_devices[index]) {
  288. continue;
  289. }
  290. motion_devices[index]->SetCallback({
  291. .on_change =
  292. [this, index](const Common::Input::CallbackStatus& callback) {
  293. SetMotion(callback, index);
  294. },
  295. });
  296. motion_devices[index]->ForceUpdate();
  297. }
  298. if (camera_devices) {
  299. camera_devices->SetCallback({
  300. .on_change =
  301. [this](const Common::Input::CallbackStatus& callback) { SetCamera(callback); },
  302. });
  303. camera_devices->ForceUpdate();
  304. }
  305. if (nfc_devices) {
  306. if (npad_id_type == NpadIdType::Handheld || npad_id_type == NpadIdType::Player1) {
  307. nfc_devices->SetCallback({
  308. .on_change =
  309. [this](const Common::Input::CallbackStatus& callback) { SetNfc(callback); },
  310. });
  311. nfc_devices->ForceUpdate();
  312. }
  313. }
  314. // Use a common UUID for TAS
  315. static constexpr Common::UUID TAS_UUID = Common::UUID{
  316. {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xA5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
  317. // Register TAS devices. No need to force update
  318. for (std::size_t index = 0; index < tas_button_devices.size(); ++index) {
  319. if (!tas_button_devices[index]) {
  320. continue;
  321. }
  322. tas_button_devices[index]->SetCallback({
  323. .on_change =
  324. [this, index](const Common::Input::CallbackStatus& callback) {
  325. SetButton(callback, index, TAS_UUID);
  326. },
  327. });
  328. }
  329. for (std::size_t index = 0; index < tas_stick_devices.size(); ++index) {
  330. if (!tas_stick_devices[index]) {
  331. continue;
  332. }
  333. tas_stick_devices[index]->SetCallback({
  334. .on_change =
  335. [this, index](const Common::Input::CallbackStatus& callback) {
  336. SetStick(callback, index, TAS_UUID);
  337. },
  338. });
  339. }
  340. // Use a common UUID for Virtual Gamepad
  341. static constexpr Common::UUID VIRTUAL_UUID = Common::UUID{
  342. {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
  343. // Register virtual devices. No need to force update
  344. for (std::size_t index = 0; index < virtual_button_devices.size(); ++index) {
  345. if (!virtual_button_devices[index]) {
  346. continue;
  347. }
  348. virtual_button_devices[index]->SetCallback({
  349. .on_change =
  350. [this, index](const Common::Input::CallbackStatus& callback) {
  351. SetButton(callback, index, VIRTUAL_UUID);
  352. },
  353. });
  354. }
  355. for (std::size_t index = 0; index < virtual_stick_devices.size(); ++index) {
  356. if (!virtual_stick_devices[index]) {
  357. continue;
  358. }
  359. virtual_stick_devices[index]->SetCallback({
  360. .on_change =
  361. [this, index](const Common::Input::CallbackStatus& callback) {
  362. SetStick(callback, index, VIRTUAL_UUID);
  363. },
  364. });
  365. }
  366. }
  367. void EmulatedController::UnloadInput() {
  368. for (auto& button : button_devices) {
  369. button.reset();
  370. }
  371. for (auto& stick : stick_devices) {
  372. stick.reset();
  373. }
  374. for (auto& motion : motion_devices) {
  375. motion.reset();
  376. }
  377. for (auto& trigger : trigger_devices) {
  378. trigger.reset();
  379. }
  380. for (auto& battery : battery_devices) {
  381. battery.reset();
  382. }
  383. for (auto& output : output_devices) {
  384. output.reset();
  385. }
  386. for (auto& button : tas_button_devices) {
  387. button.reset();
  388. }
  389. for (auto& stick : tas_stick_devices) {
  390. stick.reset();
  391. }
  392. for (auto& button : virtual_button_devices) {
  393. button.reset();
  394. }
  395. for (auto& stick : virtual_stick_devices) {
  396. stick.reset();
  397. }
  398. camera_devices.reset();
  399. nfc_devices.reset();
  400. }
  401. void EmulatedController::EnableConfiguration() {
  402. is_configuring = true;
  403. tmp_is_connected = is_connected;
  404. tmp_npad_type = npad_type;
  405. }
  406. void EmulatedController::DisableConfiguration() {
  407. is_configuring = false;
  408. // Apply temporary npad type to the real controller
  409. if (tmp_npad_type != npad_type) {
  410. if (is_connected) {
  411. Disconnect();
  412. }
  413. SetNpadStyleIndex(tmp_npad_type);
  414. original_npad_type = tmp_npad_type;
  415. }
  416. // Apply temporary connected status to the real controller
  417. if (tmp_is_connected != is_connected) {
  418. if (tmp_is_connected) {
  419. Connect();
  420. return;
  421. }
  422. Disconnect();
  423. }
  424. }
  425. void EmulatedController::EnableSystemButtons() {
  426. std::scoped_lock lock{mutex};
  427. system_buttons_enabled = true;
  428. }
  429. void EmulatedController::DisableSystemButtons() {
  430. std::scoped_lock lock{mutex};
  431. system_buttons_enabled = false;
  432. }
  433. void EmulatedController::ResetSystemButtons() {
  434. std::scoped_lock lock{mutex};
  435. controller.home_button_state.home.Assign(false);
  436. controller.capture_button_state.capture.Assign(false);
  437. }
  438. bool EmulatedController::IsConfiguring() const {
  439. return is_configuring;
  440. }
  441. void EmulatedController::SaveCurrentConfig() {
  442. const auto player_index = NpadIdTypeToIndex(npad_id_type);
  443. auto& player = Settings::values.players.GetValue()[player_index];
  444. player.connected = is_connected;
  445. player.controller_type = MapNPadToSettingsType(npad_type);
  446. for (std::size_t index = 0; index < player.buttons.size(); ++index) {
  447. player.buttons[index] = button_params[index].Serialize();
  448. }
  449. for (std::size_t index = 0; index < player.analogs.size(); ++index) {
  450. player.analogs[index] = stick_params[index].Serialize();
  451. }
  452. for (std::size_t index = 0; index < player.motions.size(); ++index) {
  453. player.motions[index] = motion_params[index].Serialize();
  454. }
  455. }
  456. void EmulatedController::RestoreConfig() {
  457. if (!is_configuring) {
  458. return;
  459. }
  460. ReloadFromSettings();
  461. }
  462. std::vector<Common::ParamPackage> EmulatedController::GetMappedDevices() const {
  463. std::vector<Common::ParamPackage> devices;
  464. for (const auto& param : button_params) {
  465. if (!param.Has("engine")) {
  466. continue;
  467. }
  468. const auto devices_it = std::find_if(
  469. devices.begin(), devices.end(), [&param](const Common::ParamPackage& param_) {
  470. return param.Get("engine", "") == param_.Get("engine", "") &&
  471. param.Get("guid", "") == param_.Get("guid", "") &&
  472. param.Get("port", 0) == param_.Get("port", 0) &&
  473. param.Get("pad", 0) == param_.Get("pad", 0);
  474. });
  475. if (devices_it != devices.end()) {
  476. continue;
  477. }
  478. auto& device = devices.emplace_back();
  479. device.Set("engine", param.Get("engine", ""));
  480. device.Set("guid", param.Get("guid", ""));
  481. device.Set("port", param.Get("port", 0));
  482. device.Set("pad", param.Get("pad", 0));
  483. }
  484. for (const auto& param : stick_params) {
  485. if (!param.Has("engine")) {
  486. continue;
  487. }
  488. if (param.Get("engine", "") == "analog_from_button") {
  489. continue;
  490. }
  491. const auto devices_it = std::find_if(
  492. devices.begin(), devices.end(), [&param](const Common::ParamPackage& param_) {
  493. return param.Get("engine", "") == param_.Get("engine", "") &&
  494. param.Get("guid", "") == param_.Get("guid", "") &&
  495. param.Get("port", 0) == param_.Get("port", 0) &&
  496. param.Get("pad", 0) == param_.Get("pad", 0);
  497. });
  498. if (devices_it != devices.end()) {
  499. continue;
  500. }
  501. auto& device = devices.emplace_back();
  502. device.Set("engine", param.Get("engine", ""));
  503. device.Set("guid", param.Get("guid", ""));
  504. device.Set("port", param.Get("port", 0));
  505. device.Set("pad", param.Get("pad", 0));
  506. }
  507. return devices;
  508. }
  509. Common::ParamPackage EmulatedController::GetButtonParam(std::size_t index) const {
  510. if (index >= button_params.size()) {
  511. return {};
  512. }
  513. return button_params[index];
  514. }
  515. Common::ParamPackage EmulatedController::GetStickParam(std::size_t index) const {
  516. if (index >= stick_params.size()) {
  517. return {};
  518. }
  519. return stick_params[index];
  520. }
  521. Common::ParamPackage EmulatedController::GetMotionParam(std::size_t index) const {
  522. if (index >= motion_params.size()) {
  523. return {};
  524. }
  525. return motion_params[index];
  526. }
  527. void EmulatedController::SetButtonParam(std::size_t index, Common::ParamPackage param) {
  528. if (index >= button_params.size()) {
  529. return;
  530. }
  531. button_params[index] = std::move(param);
  532. ReloadInput();
  533. }
  534. void EmulatedController::SetStickParam(std::size_t index, Common::ParamPackage param) {
  535. if (index >= stick_params.size()) {
  536. return;
  537. }
  538. stick_params[index] = std::move(param);
  539. ReloadInput();
  540. }
  541. void EmulatedController::SetMotionParam(std::size_t index, Common::ParamPackage param) {
  542. if (index >= motion_params.size()) {
  543. return;
  544. }
  545. motion_params[index] = std::move(param);
  546. ReloadInput();
  547. }
  548. void EmulatedController::SetButton(const Common::Input::CallbackStatus& callback, std::size_t index,
  549. Common::UUID uuid) {
  550. if (index >= controller.button_values.size()) {
  551. return;
  552. }
  553. std::unique_lock lock{mutex};
  554. bool value_changed = false;
  555. const auto new_status = TransformToButton(callback);
  556. auto& current_status = controller.button_values[index];
  557. // Only read button values that have the same uuid or are pressed once
  558. if (current_status.uuid != uuid) {
  559. if (!new_status.value) {
  560. return;
  561. }
  562. }
  563. current_status.toggle = new_status.toggle;
  564. current_status.uuid = uuid;
  565. // Update button status with current
  566. if (!current_status.toggle) {
  567. current_status.locked = false;
  568. if (current_status.value != new_status.value) {
  569. current_status.value = new_status.value;
  570. value_changed = true;
  571. }
  572. } else {
  573. // Toggle button and lock status
  574. if (new_status.value && !current_status.locked) {
  575. current_status.locked = true;
  576. current_status.value = !current_status.value;
  577. value_changed = true;
  578. }
  579. // Unlock button ready for next press
  580. if (!new_status.value && current_status.locked) {
  581. current_status.locked = false;
  582. }
  583. }
  584. if (!value_changed) {
  585. return;
  586. }
  587. if (is_configuring) {
  588. controller.npad_button_state.raw = NpadButton::None;
  589. controller.debug_pad_button_state.raw = 0;
  590. lock.unlock();
  591. TriggerOnChange(ControllerTriggerType::Button, false);
  592. return;
  593. }
  594. // GC controllers have triggers not buttons
  595. if (npad_type == NpadStyleIndex::GameCube) {
  596. if (index == Settings::NativeButton::ZR) {
  597. return;
  598. }
  599. if (index == Settings::NativeButton::ZL) {
  600. return;
  601. }
  602. }
  603. switch (index) {
  604. case Settings::NativeButton::A:
  605. controller.npad_button_state.a.Assign(current_status.value);
  606. controller.debug_pad_button_state.a.Assign(current_status.value);
  607. break;
  608. case Settings::NativeButton::B:
  609. controller.npad_button_state.b.Assign(current_status.value);
  610. controller.debug_pad_button_state.b.Assign(current_status.value);
  611. break;
  612. case Settings::NativeButton::X:
  613. controller.npad_button_state.x.Assign(current_status.value);
  614. controller.debug_pad_button_state.x.Assign(current_status.value);
  615. break;
  616. case Settings::NativeButton::Y:
  617. controller.npad_button_state.y.Assign(current_status.value);
  618. controller.debug_pad_button_state.y.Assign(current_status.value);
  619. break;
  620. case Settings::NativeButton::LStick:
  621. controller.npad_button_state.stick_l.Assign(current_status.value);
  622. break;
  623. case Settings::NativeButton::RStick:
  624. controller.npad_button_state.stick_r.Assign(current_status.value);
  625. break;
  626. case Settings::NativeButton::L:
  627. controller.npad_button_state.l.Assign(current_status.value);
  628. controller.debug_pad_button_state.l.Assign(current_status.value);
  629. break;
  630. case Settings::NativeButton::R:
  631. controller.npad_button_state.r.Assign(current_status.value);
  632. controller.debug_pad_button_state.r.Assign(current_status.value);
  633. break;
  634. case Settings::NativeButton::ZL:
  635. controller.npad_button_state.zl.Assign(current_status.value);
  636. controller.debug_pad_button_state.zl.Assign(current_status.value);
  637. break;
  638. case Settings::NativeButton::ZR:
  639. controller.npad_button_state.zr.Assign(current_status.value);
  640. controller.debug_pad_button_state.zr.Assign(current_status.value);
  641. break;
  642. case Settings::NativeButton::Plus:
  643. controller.npad_button_state.plus.Assign(current_status.value);
  644. controller.debug_pad_button_state.plus.Assign(current_status.value);
  645. break;
  646. case Settings::NativeButton::Minus:
  647. controller.npad_button_state.minus.Assign(current_status.value);
  648. controller.debug_pad_button_state.minus.Assign(current_status.value);
  649. break;
  650. case Settings::NativeButton::DLeft:
  651. controller.npad_button_state.left.Assign(current_status.value);
  652. controller.debug_pad_button_state.d_left.Assign(current_status.value);
  653. break;
  654. case Settings::NativeButton::DUp:
  655. controller.npad_button_state.up.Assign(current_status.value);
  656. controller.debug_pad_button_state.d_up.Assign(current_status.value);
  657. break;
  658. case Settings::NativeButton::DRight:
  659. controller.npad_button_state.right.Assign(current_status.value);
  660. controller.debug_pad_button_state.d_right.Assign(current_status.value);
  661. break;
  662. case Settings::NativeButton::DDown:
  663. controller.npad_button_state.down.Assign(current_status.value);
  664. controller.debug_pad_button_state.d_down.Assign(current_status.value);
  665. break;
  666. case Settings::NativeButton::SL:
  667. controller.npad_button_state.left_sl.Assign(current_status.value);
  668. controller.npad_button_state.right_sl.Assign(current_status.value);
  669. break;
  670. case Settings::NativeButton::SR:
  671. controller.npad_button_state.left_sr.Assign(current_status.value);
  672. controller.npad_button_state.right_sr.Assign(current_status.value);
  673. break;
  674. case Settings::NativeButton::Home:
  675. if (!system_buttons_enabled) {
  676. break;
  677. }
  678. controller.home_button_state.home.Assign(current_status.value);
  679. break;
  680. case Settings::NativeButton::Screenshot:
  681. if (!system_buttons_enabled) {
  682. break;
  683. }
  684. controller.capture_button_state.capture.Assign(current_status.value);
  685. break;
  686. }
  687. lock.unlock();
  688. if (!is_connected) {
  689. if (npad_id_type == NpadIdType::Player1 && npad_type != NpadStyleIndex::Handheld) {
  690. Connect();
  691. }
  692. if (npad_id_type == NpadIdType::Handheld && npad_type == NpadStyleIndex::Handheld) {
  693. Connect();
  694. }
  695. }
  696. TriggerOnChange(ControllerTriggerType::Button, true);
  697. }
  698. void EmulatedController::SetStick(const Common::Input::CallbackStatus& callback, std::size_t index,
  699. Common::UUID uuid) {
  700. if (index >= controller.stick_values.size()) {
  701. return;
  702. }
  703. std::unique_lock lock{mutex};
  704. const auto stick_value = TransformToStick(callback);
  705. // Only read stick values that have the same uuid or are over the threshold to avoid flapping
  706. if (controller.stick_values[index].uuid != uuid) {
  707. if (!stick_value.down && !stick_value.up && !stick_value.left && !stick_value.right) {
  708. return;
  709. }
  710. }
  711. controller.stick_values[index] = stick_value;
  712. controller.stick_values[index].uuid = uuid;
  713. if (is_configuring) {
  714. controller.analog_stick_state.left = {};
  715. controller.analog_stick_state.right = {};
  716. lock.unlock();
  717. TriggerOnChange(ControllerTriggerType::Stick, false);
  718. return;
  719. }
  720. const AnalogStickState stick{
  721. .x = static_cast<s32>(controller.stick_values[index].x.value * HID_JOYSTICK_MAX),
  722. .y = static_cast<s32>(controller.stick_values[index].y.value * HID_JOYSTICK_MAX),
  723. };
  724. switch (index) {
  725. case Settings::NativeAnalog::LStick:
  726. controller.analog_stick_state.left = stick;
  727. controller.npad_button_state.stick_l_left.Assign(controller.stick_values[index].left);
  728. controller.npad_button_state.stick_l_up.Assign(controller.stick_values[index].up);
  729. controller.npad_button_state.stick_l_right.Assign(controller.stick_values[index].right);
  730. controller.npad_button_state.stick_l_down.Assign(controller.stick_values[index].down);
  731. break;
  732. case Settings::NativeAnalog::RStick:
  733. controller.analog_stick_state.right = stick;
  734. controller.npad_button_state.stick_r_left.Assign(controller.stick_values[index].left);
  735. controller.npad_button_state.stick_r_up.Assign(controller.stick_values[index].up);
  736. controller.npad_button_state.stick_r_right.Assign(controller.stick_values[index].right);
  737. controller.npad_button_state.stick_r_down.Assign(controller.stick_values[index].down);
  738. break;
  739. }
  740. lock.unlock();
  741. TriggerOnChange(ControllerTriggerType::Stick, true);
  742. }
  743. void EmulatedController::SetTrigger(const Common::Input::CallbackStatus& callback,
  744. std::size_t index, Common::UUID uuid) {
  745. if (index >= controller.trigger_values.size()) {
  746. return;
  747. }
  748. std::unique_lock lock{mutex};
  749. const auto trigger_value = TransformToTrigger(callback);
  750. // Only read trigger values that have the same uuid or are pressed once
  751. if (controller.trigger_values[index].uuid != uuid) {
  752. if (!trigger_value.pressed.value) {
  753. return;
  754. }
  755. }
  756. controller.trigger_values[index] = trigger_value;
  757. controller.trigger_values[index].uuid = uuid;
  758. if (is_configuring) {
  759. controller.gc_trigger_state.left = 0;
  760. controller.gc_trigger_state.right = 0;
  761. lock.unlock();
  762. TriggerOnChange(ControllerTriggerType::Trigger, false);
  763. return;
  764. }
  765. // Only GC controllers have analog triggers
  766. if (npad_type != NpadStyleIndex::GameCube) {
  767. return;
  768. }
  769. const auto& trigger = controller.trigger_values[index];
  770. switch (index) {
  771. case Settings::NativeTrigger::LTrigger:
  772. controller.gc_trigger_state.left = static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
  773. controller.npad_button_state.zl.Assign(trigger.pressed.value);
  774. break;
  775. case Settings::NativeTrigger::RTrigger:
  776. controller.gc_trigger_state.right =
  777. static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
  778. controller.npad_button_state.zr.Assign(trigger.pressed.value);
  779. break;
  780. }
  781. lock.unlock();
  782. TriggerOnChange(ControllerTriggerType::Trigger, true);
  783. }
  784. void EmulatedController::SetMotion(const Common::Input::CallbackStatus& callback,
  785. std::size_t index) {
  786. if (index >= controller.motion_values.size()) {
  787. return;
  788. }
  789. std::unique_lock lock{mutex};
  790. auto& raw_status = controller.motion_values[index].raw_status;
  791. auto& emulated = controller.motion_values[index].emulated;
  792. raw_status = TransformToMotion(callback);
  793. emulated.SetAcceleration(Common::Vec3f{
  794. raw_status.accel.x.value,
  795. raw_status.accel.y.value,
  796. raw_status.accel.z.value,
  797. });
  798. emulated.SetGyroscope(Common::Vec3f{
  799. raw_status.gyro.x.value,
  800. raw_status.gyro.y.value,
  801. raw_status.gyro.z.value,
  802. });
  803. emulated.SetGyroThreshold(raw_status.gyro.x.properties.threshold);
  804. emulated.UpdateRotation(raw_status.delta_timestamp);
  805. emulated.UpdateOrientation(raw_status.delta_timestamp);
  806. force_update_motion = raw_status.force_update;
  807. if (is_configuring) {
  808. lock.unlock();
  809. TriggerOnChange(ControllerTriggerType::Motion, false);
  810. return;
  811. }
  812. auto& motion = controller.motion_state[index];
  813. motion.accel = emulated.GetAcceleration();
  814. motion.gyro = emulated.GetGyroscope();
  815. motion.rotation = emulated.GetRotations();
  816. motion.orientation = emulated.GetOrientation();
  817. motion.is_at_rest = !emulated.IsMoving(motion_sensitivity);
  818. lock.unlock();
  819. TriggerOnChange(ControllerTriggerType::Motion, true);
  820. }
  821. void EmulatedController::SetBattery(const Common::Input::CallbackStatus& callback,
  822. std::size_t index) {
  823. if (index >= controller.battery_values.size()) {
  824. return;
  825. }
  826. std::unique_lock lock{mutex};
  827. controller.battery_values[index] = TransformToBattery(callback);
  828. if (is_configuring) {
  829. lock.unlock();
  830. TriggerOnChange(ControllerTriggerType::Battery, false);
  831. return;
  832. }
  833. bool is_charging = false;
  834. bool is_powered = false;
  835. NpadBatteryLevel battery_level = 0;
  836. switch (controller.battery_values[index]) {
  837. case Common::Input::BatteryLevel::Charging:
  838. is_charging = true;
  839. is_powered = true;
  840. battery_level = 6;
  841. break;
  842. case Common::Input::BatteryLevel::Medium:
  843. battery_level = 6;
  844. break;
  845. case Common::Input::BatteryLevel::Low:
  846. battery_level = 4;
  847. break;
  848. case Common::Input::BatteryLevel::Critical:
  849. battery_level = 2;
  850. break;
  851. case Common::Input::BatteryLevel::Empty:
  852. battery_level = 0;
  853. break;
  854. case Common::Input::BatteryLevel::None:
  855. case Common::Input::BatteryLevel::Full:
  856. default:
  857. is_powered = true;
  858. battery_level = 8;
  859. break;
  860. }
  861. switch (index) {
  862. case LeftIndex:
  863. controller.battery_state.left = {
  864. .is_powered = is_powered,
  865. .is_charging = is_charging,
  866. .battery_level = battery_level,
  867. };
  868. break;
  869. case RightIndex:
  870. controller.battery_state.right = {
  871. .is_powered = is_powered,
  872. .is_charging = is_charging,
  873. .battery_level = battery_level,
  874. };
  875. break;
  876. case DualIndex:
  877. controller.battery_state.dual = {
  878. .is_powered = is_powered,
  879. .is_charging = is_charging,
  880. .battery_level = battery_level,
  881. };
  882. break;
  883. }
  884. lock.unlock();
  885. TriggerOnChange(ControllerTriggerType::Battery, true);
  886. }
  887. void EmulatedController::SetCamera(const Common::Input::CallbackStatus& callback) {
  888. std::unique_lock lock{mutex};
  889. controller.camera_values = TransformToCamera(callback);
  890. if (is_configuring) {
  891. lock.unlock();
  892. TriggerOnChange(ControllerTriggerType::IrSensor, false);
  893. return;
  894. }
  895. controller.camera_state.sample++;
  896. controller.camera_state.format =
  897. static_cast<Core::IrSensor::ImageTransferProcessorFormat>(controller.camera_values.format);
  898. controller.camera_state.data = controller.camera_values.data;
  899. lock.unlock();
  900. TriggerOnChange(ControllerTriggerType::IrSensor, true);
  901. }
  902. void EmulatedController::SetNfc(const Common::Input::CallbackStatus& callback) {
  903. std::unique_lock lock{mutex};
  904. controller.nfc_values = TransformToNfc(callback);
  905. if (is_configuring) {
  906. lock.unlock();
  907. TriggerOnChange(ControllerTriggerType::Nfc, false);
  908. return;
  909. }
  910. controller.nfc_state = {
  911. controller.nfc_values.state,
  912. controller.nfc_values.data,
  913. };
  914. lock.unlock();
  915. TriggerOnChange(ControllerTriggerType::Nfc, true);
  916. }
  917. bool EmulatedController::SetVibration(std::size_t device_index, VibrationValue vibration) {
  918. if (device_index >= output_devices.size()) {
  919. return false;
  920. }
  921. if (!output_devices[device_index]) {
  922. return false;
  923. }
  924. const auto player_index = NpadIdTypeToIndex(npad_id_type);
  925. const auto& player = Settings::values.players.GetValue()[player_index];
  926. const f32 strength = static_cast<f32>(player.vibration_strength) / 100.0f;
  927. if (!player.vibration_enabled) {
  928. return false;
  929. }
  930. // Exponential amplification is too strong at low amplitudes. Switch to a linear
  931. // amplification if strength is set below 0.7f
  932. const Common::Input::VibrationAmplificationType type =
  933. strength > 0.7f ? Common::Input::VibrationAmplificationType::Exponential
  934. : Common::Input::VibrationAmplificationType::Linear;
  935. const Common::Input::VibrationStatus status = {
  936. .low_amplitude = std::min(vibration.low_amplitude * strength, 1.0f),
  937. .low_frequency = vibration.low_frequency,
  938. .high_amplitude = std::min(vibration.high_amplitude * strength, 1.0f),
  939. .high_frequency = vibration.high_frequency,
  940. .type = type,
  941. };
  942. return output_devices[device_index]->SetVibration(status) ==
  943. Common::Input::VibrationError::None;
  944. }
  945. bool EmulatedController::IsVibrationEnabled(std::size_t device_index) {
  946. const auto player_index = NpadIdTypeToIndex(npad_id_type);
  947. const auto& player = Settings::values.players.GetValue()[player_index];
  948. if (!player.vibration_enabled) {
  949. return false;
  950. }
  951. if (device_index >= output_devices.size()) {
  952. return false;
  953. }
  954. if (!output_devices[device_index]) {
  955. return false;
  956. }
  957. return output_devices[device_index]->IsVibrationEnabled();
  958. }
  959. bool EmulatedController::SetPollingMode(Common::Input::PollingMode polling_mode) {
  960. LOG_INFO(Service_HID, "Set polling mode {}", polling_mode);
  961. auto& output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  962. auto& nfc_output_device = output_devices[3];
  963. const auto virtual_nfc_result = nfc_output_device->SetPollingMode(polling_mode);
  964. const auto mapped_nfc_result = output_device->SetPollingMode(polling_mode);
  965. return virtual_nfc_result == Common::Input::PollingError::None ||
  966. mapped_nfc_result == Common::Input::PollingError::None;
  967. }
  968. bool EmulatedController::SetCameraFormat(
  969. Core::IrSensor::ImageTransferProcessorFormat camera_format) {
  970. LOG_INFO(Service_HID, "Set camera format {}", camera_format);
  971. auto& right_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  972. auto& camera_output_device = output_devices[2];
  973. if (right_output_device->SetCameraFormat(static_cast<Common::Input::CameraFormat>(
  974. camera_format)) == Common::Input::CameraError::None) {
  975. return true;
  976. }
  977. // Fallback to Qt camera if native device doesn't have support
  978. return camera_output_device->SetCameraFormat(static_cast<Common::Input::CameraFormat>(
  979. camera_format)) == Common::Input::CameraError::None;
  980. }
  981. bool EmulatedController::HasNfc() const {
  982. const auto& nfc_output_device = output_devices[3];
  983. switch (npad_type) {
  984. case NpadStyleIndex::JoyconRight:
  985. case NpadStyleIndex::JoyconDual:
  986. case NpadStyleIndex::ProController:
  987. case NpadStyleIndex::Handheld:
  988. break;
  989. default:
  990. return false;
  991. }
  992. const bool has_virtual_nfc =
  993. npad_id_type == NpadIdType::Player1 || npad_id_type == NpadIdType::Handheld;
  994. const bool is_virtual_nfc_supported =
  995. nfc_output_device->SupportsNfc() != Common::Input::NfcState::NotSupported;
  996. return is_connected && (has_virtual_nfc && is_virtual_nfc_supported);
  997. }
  998. bool EmulatedController::WriteNfc(const std::vector<u8>& data) {
  999. auto& nfc_output_device = output_devices[3];
  1000. return nfc_output_device->WriteNfcData(data) == Common::Input::NfcState::Success;
  1001. }
  1002. void EmulatedController::SetLedPattern() {
  1003. for (auto& device : output_devices) {
  1004. if (!device) {
  1005. continue;
  1006. }
  1007. const LedPattern pattern = GetLedPattern();
  1008. const Common::Input::LedStatus status = {
  1009. .led_1 = pattern.position1 != 0,
  1010. .led_2 = pattern.position2 != 0,
  1011. .led_3 = pattern.position3 != 0,
  1012. .led_4 = pattern.position4 != 0,
  1013. };
  1014. device->SetLED(status);
  1015. }
  1016. }
  1017. void EmulatedController::SetSupportedNpadStyleTag(NpadStyleTag supported_styles) {
  1018. supported_style_tag = supported_styles;
  1019. if (!is_connected) {
  1020. return;
  1021. }
  1022. // Attempt to reconnect with the original type
  1023. if (npad_type != original_npad_type) {
  1024. Disconnect();
  1025. const auto current_npad_type = npad_type;
  1026. SetNpadStyleIndex(original_npad_type);
  1027. if (IsControllerSupported()) {
  1028. Connect();
  1029. return;
  1030. }
  1031. SetNpadStyleIndex(current_npad_type);
  1032. Connect();
  1033. }
  1034. if (IsControllerSupported()) {
  1035. return;
  1036. }
  1037. Disconnect();
  1038. // Fallback Fullkey controllers to Pro controllers
  1039. if (IsControllerFullkey() && supported_style_tag.fullkey) {
  1040. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
  1041. SetNpadStyleIndex(NpadStyleIndex::ProController);
  1042. Connect();
  1043. return;
  1044. }
  1045. // Fallback Dual joycon controllers to Pro controllers
  1046. if (npad_type == NpadStyleIndex::JoyconDual && supported_style_tag.fullkey) {
  1047. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
  1048. SetNpadStyleIndex(NpadStyleIndex::ProController);
  1049. Connect();
  1050. return;
  1051. }
  1052. // Fallback Pro controllers to Dual joycon
  1053. if (npad_type == NpadStyleIndex::ProController && supported_style_tag.joycon_dual) {
  1054. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Dual Joycons", npad_type);
  1055. SetNpadStyleIndex(NpadStyleIndex::JoyconDual);
  1056. Connect();
  1057. return;
  1058. }
  1059. LOG_ERROR(Service_HID, "Controller type {} is not supported. Disconnecting controller",
  1060. npad_type);
  1061. }
  1062. bool EmulatedController::IsControllerFullkey(bool use_temporary_value) const {
  1063. std::scoped_lock lock{mutex};
  1064. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1065. switch (type) {
  1066. case NpadStyleIndex::ProController:
  1067. case NpadStyleIndex::GameCube:
  1068. case NpadStyleIndex::NES:
  1069. case NpadStyleIndex::SNES:
  1070. case NpadStyleIndex::N64:
  1071. case NpadStyleIndex::SegaGenesis:
  1072. return true;
  1073. default:
  1074. return false;
  1075. }
  1076. }
  1077. bool EmulatedController::IsControllerSupported(bool use_temporary_value) const {
  1078. std::scoped_lock lock{mutex};
  1079. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1080. switch (type) {
  1081. case NpadStyleIndex::ProController:
  1082. return supported_style_tag.fullkey.As<bool>();
  1083. case NpadStyleIndex::Handheld:
  1084. return supported_style_tag.handheld.As<bool>();
  1085. case NpadStyleIndex::JoyconDual:
  1086. return supported_style_tag.joycon_dual.As<bool>();
  1087. case NpadStyleIndex::JoyconLeft:
  1088. return supported_style_tag.joycon_left.As<bool>();
  1089. case NpadStyleIndex::JoyconRight:
  1090. return supported_style_tag.joycon_right.As<bool>();
  1091. case NpadStyleIndex::GameCube:
  1092. return supported_style_tag.gamecube.As<bool>();
  1093. case NpadStyleIndex::Pokeball:
  1094. return supported_style_tag.palma.As<bool>();
  1095. case NpadStyleIndex::NES:
  1096. return supported_style_tag.lark.As<bool>();
  1097. case NpadStyleIndex::SNES:
  1098. return supported_style_tag.lucia.As<bool>();
  1099. case NpadStyleIndex::N64:
  1100. return supported_style_tag.lagoon.As<bool>();
  1101. case NpadStyleIndex::SegaGenesis:
  1102. return supported_style_tag.lager.As<bool>();
  1103. default:
  1104. return false;
  1105. }
  1106. }
  1107. void EmulatedController::Connect(bool use_temporary_value) {
  1108. if (!IsControllerSupported(use_temporary_value)) {
  1109. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1110. LOG_ERROR(Service_HID, "Controller type {} is not supported", type);
  1111. return;
  1112. }
  1113. std::unique_lock lock{mutex};
  1114. if (is_configuring) {
  1115. tmp_is_connected = true;
  1116. lock.unlock();
  1117. TriggerOnChange(ControllerTriggerType::Connected, false);
  1118. return;
  1119. }
  1120. if (is_connected) {
  1121. return;
  1122. }
  1123. is_connected = true;
  1124. lock.unlock();
  1125. TriggerOnChange(ControllerTriggerType::Connected, true);
  1126. }
  1127. void EmulatedController::Disconnect() {
  1128. std::unique_lock lock{mutex};
  1129. if (is_configuring) {
  1130. tmp_is_connected = false;
  1131. lock.unlock();
  1132. TriggerOnChange(ControllerTriggerType::Disconnected, false);
  1133. return;
  1134. }
  1135. if (!is_connected) {
  1136. return;
  1137. }
  1138. is_connected = false;
  1139. lock.unlock();
  1140. TriggerOnChange(ControllerTriggerType::Disconnected, true);
  1141. }
  1142. bool EmulatedController::IsConnected(bool get_temporary_value) const {
  1143. std::scoped_lock lock{mutex};
  1144. if (get_temporary_value && is_configuring) {
  1145. return tmp_is_connected;
  1146. }
  1147. return is_connected;
  1148. }
  1149. NpadIdType EmulatedController::GetNpadIdType() const {
  1150. std::scoped_lock lock{mutex};
  1151. return npad_id_type;
  1152. }
  1153. NpadStyleIndex EmulatedController::GetNpadStyleIndex(bool get_temporary_value) const {
  1154. std::scoped_lock lock{mutex};
  1155. if (get_temporary_value && is_configuring) {
  1156. return tmp_npad_type;
  1157. }
  1158. return npad_type;
  1159. }
  1160. void EmulatedController::SetNpadStyleIndex(NpadStyleIndex npad_type_) {
  1161. std::unique_lock lock{mutex};
  1162. if (is_configuring) {
  1163. if (tmp_npad_type == npad_type_) {
  1164. return;
  1165. }
  1166. tmp_npad_type = npad_type_;
  1167. lock.unlock();
  1168. TriggerOnChange(ControllerTriggerType::Type, false);
  1169. return;
  1170. }
  1171. if (npad_type == npad_type_) {
  1172. return;
  1173. }
  1174. if (is_connected) {
  1175. LOG_WARNING(Service_HID, "Controller {} type changed while it's connected",
  1176. NpadIdTypeToIndex(npad_id_type));
  1177. }
  1178. npad_type = npad_type_;
  1179. lock.unlock();
  1180. TriggerOnChange(ControllerTriggerType::Type, true);
  1181. }
  1182. LedPattern EmulatedController::GetLedPattern() const {
  1183. switch (npad_id_type) {
  1184. case NpadIdType::Player1:
  1185. return LedPattern{1, 0, 0, 0};
  1186. case NpadIdType::Player2:
  1187. return LedPattern{1, 1, 0, 0};
  1188. case NpadIdType::Player3:
  1189. return LedPattern{1, 1, 1, 0};
  1190. case NpadIdType::Player4:
  1191. return LedPattern{1, 1, 1, 1};
  1192. case NpadIdType::Player5:
  1193. return LedPattern{1, 0, 0, 1};
  1194. case NpadIdType::Player6:
  1195. return LedPattern{1, 0, 1, 0};
  1196. case NpadIdType::Player7:
  1197. return LedPattern{1, 0, 1, 1};
  1198. case NpadIdType::Player8:
  1199. return LedPattern{0, 1, 1, 0};
  1200. default:
  1201. return LedPattern{0, 0, 0, 0};
  1202. }
  1203. }
  1204. ButtonValues EmulatedController::GetButtonsValues() const {
  1205. std::scoped_lock lock{mutex};
  1206. return controller.button_values;
  1207. }
  1208. SticksValues EmulatedController::GetSticksValues() const {
  1209. std::scoped_lock lock{mutex};
  1210. return controller.stick_values;
  1211. }
  1212. TriggerValues EmulatedController::GetTriggersValues() const {
  1213. std::scoped_lock lock{mutex};
  1214. return controller.trigger_values;
  1215. }
  1216. ControllerMotionValues EmulatedController::GetMotionValues() const {
  1217. std::scoped_lock lock{mutex};
  1218. return controller.motion_values;
  1219. }
  1220. ColorValues EmulatedController::GetColorsValues() const {
  1221. std::scoped_lock lock{mutex};
  1222. return controller.color_values;
  1223. }
  1224. BatteryValues EmulatedController::GetBatteryValues() const {
  1225. std::scoped_lock lock{mutex};
  1226. return controller.battery_values;
  1227. }
  1228. CameraValues EmulatedController::GetCameraValues() const {
  1229. std::scoped_lock lock{mutex};
  1230. return controller.camera_values;
  1231. }
  1232. HomeButtonState EmulatedController::GetHomeButtons() const {
  1233. std::scoped_lock lock{mutex};
  1234. if (is_configuring) {
  1235. return {};
  1236. }
  1237. return controller.home_button_state;
  1238. }
  1239. CaptureButtonState EmulatedController::GetCaptureButtons() const {
  1240. std::scoped_lock lock{mutex};
  1241. if (is_configuring) {
  1242. return {};
  1243. }
  1244. return controller.capture_button_state;
  1245. }
  1246. NpadButtonState EmulatedController::GetNpadButtons() const {
  1247. std::scoped_lock lock{mutex};
  1248. if (is_configuring) {
  1249. return {};
  1250. }
  1251. return controller.npad_button_state;
  1252. }
  1253. DebugPadButton EmulatedController::GetDebugPadButtons() const {
  1254. std::scoped_lock lock{mutex};
  1255. if (is_configuring) {
  1256. return {};
  1257. }
  1258. return controller.debug_pad_button_state;
  1259. }
  1260. AnalogSticks EmulatedController::GetSticks() const {
  1261. std::unique_lock lock{mutex};
  1262. if (is_configuring) {
  1263. return {};
  1264. }
  1265. // Some drivers like stick from buttons need constant refreshing
  1266. for (auto& device : stick_devices) {
  1267. if (!device) {
  1268. continue;
  1269. }
  1270. lock.unlock();
  1271. device->SoftUpdate();
  1272. lock.lock();
  1273. }
  1274. return controller.analog_stick_state;
  1275. }
  1276. NpadGcTriggerState EmulatedController::GetTriggers() const {
  1277. std::scoped_lock lock{mutex};
  1278. if (is_configuring) {
  1279. return {};
  1280. }
  1281. return controller.gc_trigger_state;
  1282. }
  1283. MotionState EmulatedController::GetMotions() const {
  1284. std::unique_lock lock{mutex};
  1285. // Some drivers like mouse motion need constant refreshing
  1286. if (force_update_motion) {
  1287. for (auto& device : motion_devices) {
  1288. if (!device) {
  1289. continue;
  1290. }
  1291. lock.unlock();
  1292. device->ForceUpdate();
  1293. lock.lock();
  1294. }
  1295. }
  1296. return controller.motion_state;
  1297. }
  1298. ControllerColors EmulatedController::GetColors() const {
  1299. std::scoped_lock lock{mutex};
  1300. return controller.colors_state;
  1301. }
  1302. BatteryLevelState EmulatedController::GetBattery() const {
  1303. std::scoped_lock lock{mutex};
  1304. return controller.battery_state;
  1305. }
  1306. const CameraState& EmulatedController::GetCamera() const {
  1307. std::scoped_lock lock{mutex};
  1308. return controller.camera_state;
  1309. }
  1310. const NfcState& EmulatedController::GetNfc() const {
  1311. std::scoped_lock lock{mutex};
  1312. return controller.nfc_state;
  1313. }
  1314. NpadColor EmulatedController::GetNpadColor(u32 color) {
  1315. return {
  1316. .r = static_cast<u8>((color >> 16) & 0xFF),
  1317. .g = static_cast<u8>((color >> 8) & 0xFF),
  1318. .b = static_cast<u8>(color & 0xFF),
  1319. .a = 0xff,
  1320. };
  1321. }
  1322. void EmulatedController::TriggerOnChange(ControllerTriggerType type, bool is_npad_service_update) {
  1323. std::scoped_lock lock{callback_mutex};
  1324. for (const auto& poller_pair : callback_list) {
  1325. const ControllerUpdateCallback& poller = poller_pair.second;
  1326. if (!is_npad_service_update && poller.is_npad_service) {
  1327. continue;
  1328. }
  1329. if (poller.on_change) {
  1330. poller.on_change(type);
  1331. }
  1332. }
  1333. }
  1334. int EmulatedController::SetCallback(ControllerUpdateCallback update_callback) {
  1335. std::scoped_lock lock{callback_mutex};
  1336. callback_list.insert_or_assign(last_callback_key, std::move(update_callback));
  1337. return last_callback_key++;
  1338. }
  1339. void EmulatedController::DeleteCallback(int key) {
  1340. std::scoped_lock lock{callback_mutex};
  1341. const auto& iterator = callback_list.find(key);
  1342. if (iterator == callback_list.end()) {
  1343. LOG_ERROR(Input, "Tried to delete non-existent callback {}", key);
  1344. return;
  1345. }
  1346. callback_list.erase(iterator);
  1347. }
  1348. } // namespace Core::HID