emulated_controller.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <common/scope_exit.h>
  5. #include "common/polyfill_ranges.h"
  6. #include "common/thread.h"
  7. #include "hid_core/frontend/emulated_controller.h"
  8. #include "hid_core/frontend/input_converter.h"
  9. #include "hid_core/hid_util.h"
  10. namespace Core::HID {
  11. constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
  12. constexpr s32 HID_TRIGGER_MAX = 0x7fff;
  13. constexpr u32 TURBO_BUTTON_DELAY = 4;
  14. // Use a common UUID for TAS and Virtual Gamepad
  15. constexpr Common::UUID TAS_UUID =
  16. Common::UUID{{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xA5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
  17. constexpr Common::UUID VIRTUAL_UUID =
  18. Common::UUID{{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
  19. EmulatedController::EmulatedController(NpadIdType npad_id_type_) : npad_id_type(npad_id_type_) {}
  20. EmulatedController::~EmulatedController() = default;
  21. NpadStyleIndex EmulatedController::MapSettingsTypeToNPad(Settings::ControllerType type) {
  22. switch (type) {
  23. case Settings::ControllerType::ProController:
  24. return NpadStyleIndex::ProController;
  25. case Settings::ControllerType::DualJoyconDetached:
  26. return NpadStyleIndex::JoyconDual;
  27. case Settings::ControllerType::LeftJoycon:
  28. return NpadStyleIndex::JoyconLeft;
  29. case Settings::ControllerType::RightJoycon:
  30. return NpadStyleIndex::JoyconRight;
  31. case Settings::ControllerType::Handheld:
  32. return NpadStyleIndex::Handheld;
  33. case Settings::ControllerType::GameCube:
  34. return NpadStyleIndex::GameCube;
  35. case Settings::ControllerType::Pokeball:
  36. return NpadStyleIndex::Pokeball;
  37. case Settings::ControllerType::NES:
  38. return NpadStyleIndex::NES;
  39. case Settings::ControllerType::SNES:
  40. return NpadStyleIndex::SNES;
  41. case Settings::ControllerType::N64:
  42. return NpadStyleIndex::N64;
  43. case Settings::ControllerType::SegaGenesis:
  44. return NpadStyleIndex::SegaGenesis;
  45. default:
  46. return NpadStyleIndex::ProController;
  47. }
  48. }
  49. Settings::ControllerType EmulatedController::MapNPadToSettingsType(NpadStyleIndex type) {
  50. switch (type) {
  51. case NpadStyleIndex::ProController:
  52. return Settings::ControllerType::ProController;
  53. case NpadStyleIndex::JoyconDual:
  54. return Settings::ControllerType::DualJoyconDetached;
  55. case NpadStyleIndex::JoyconLeft:
  56. return Settings::ControllerType::LeftJoycon;
  57. case NpadStyleIndex::JoyconRight:
  58. return Settings::ControllerType::RightJoycon;
  59. case NpadStyleIndex::Handheld:
  60. return Settings::ControllerType::Handheld;
  61. case NpadStyleIndex::GameCube:
  62. return Settings::ControllerType::GameCube;
  63. case NpadStyleIndex::Pokeball:
  64. return Settings::ControllerType::Pokeball;
  65. case NpadStyleIndex::NES:
  66. return Settings::ControllerType::NES;
  67. case NpadStyleIndex::SNES:
  68. return Settings::ControllerType::SNES;
  69. case NpadStyleIndex::N64:
  70. return Settings::ControllerType::N64;
  71. case NpadStyleIndex::SegaGenesis:
  72. return Settings::ControllerType::SegaGenesis;
  73. default:
  74. return Settings::ControllerType::ProController;
  75. }
  76. }
  77. void EmulatedController::ReloadFromSettings() {
  78. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  79. const auto& player = Settings::values.players.GetValue()[player_index];
  80. for (std::size_t index = 0; index < player.buttons.size(); ++index) {
  81. button_params[index] = Common::ParamPackage(player.buttons[index]);
  82. }
  83. for (std::size_t index = 0; index < player.analogs.size(); ++index) {
  84. stick_params[index] = Common::ParamPackage(player.analogs[index]);
  85. }
  86. for (std::size_t index = 0; index < player.motions.size(); ++index) {
  87. motion_params[index] = Common::ParamPackage(player.motions[index]);
  88. }
  89. controller.color_values = {};
  90. ReloadColorsFromSettings();
  91. ring_params[0] = Common::ParamPackage(Settings::values.ringcon_analogs);
  92. // Other or debug controller should always be a pro controller
  93. if (npad_id_type != NpadIdType::Other) {
  94. SetNpadStyleIndex(MapSettingsTypeToNPad(player.controller_type));
  95. original_npad_type = npad_type;
  96. } else {
  97. SetNpadStyleIndex(NpadStyleIndex::ProController);
  98. original_npad_type = npad_type;
  99. }
  100. Disconnect();
  101. if (player.connected) {
  102. Connect();
  103. }
  104. ReloadInput();
  105. }
  106. void EmulatedController::ReloadColorsFromSettings() {
  107. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  108. const auto& player = Settings::values.players.GetValue()[player_index];
  109. // Avoid updating colors if overridden by physical controller
  110. if (controller.color_values[LeftIndex].body != 0 &&
  111. controller.color_values[RightIndex].body != 0) {
  112. return;
  113. }
  114. controller.colors_state.fullkey = {
  115. .body = GetNpadColor(player.body_color_left),
  116. .button = GetNpadColor(player.button_color_left),
  117. };
  118. controller.colors_state.left = {
  119. .body = GetNpadColor(player.body_color_left),
  120. .button = GetNpadColor(player.button_color_left),
  121. };
  122. controller.colors_state.right = {
  123. .body = GetNpadColor(player.body_color_right),
  124. .button = GetNpadColor(player.button_color_right),
  125. };
  126. }
  127. void EmulatedController::LoadDevices() {
  128. // TODO(german77): Use more buttons to detect the correct device
  129. const auto left_joycon = button_params[Settings::NativeButton::DRight];
  130. const auto right_joycon = button_params[Settings::NativeButton::A];
  131. // Triggers for GC controllers
  132. trigger_params[LeftIndex] = button_params[Settings::NativeButton::ZL];
  133. trigger_params[RightIndex] = button_params[Settings::NativeButton::ZR];
  134. color_params[LeftIndex] = left_joycon;
  135. color_params[RightIndex] = right_joycon;
  136. color_params[LeftIndex].Set("color", true);
  137. color_params[RightIndex].Set("color", true);
  138. battery_params[LeftIndex] = left_joycon;
  139. battery_params[RightIndex] = right_joycon;
  140. battery_params[LeftIndex].Set("battery", true);
  141. battery_params[RightIndex].Set("battery", true);
  142. camera_params[0] = right_joycon;
  143. camera_params[0].Set("camera", true);
  144. nfc_params[1] = right_joycon;
  145. nfc_params[1].Set("nfc", true);
  146. // Only map virtual devices to the first controller
  147. if (npad_id_type == NpadIdType::Player1 || npad_id_type == NpadIdType::Handheld) {
  148. camera_params[1] = Common::ParamPackage{"engine:camera,camera:1"};
  149. ring_params[1] = Common::ParamPackage{"engine:joycon,axis_x:100,axis_y:101"};
  150. nfc_params[0] = Common::ParamPackage{"engine:virtual_amiibo,nfc:1"};
  151. }
  152. output_params[LeftIndex] = left_joycon;
  153. output_params[RightIndex] = right_joycon;
  154. output_params[2] = camera_params[1];
  155. output_params[3] = nfc_params[0];
  156. output_params[LeftIndex].Set("output", true);
  157. output_params[RightIndex].Set("output", true);
  158. output_params[2].Set("output", true);
  159. output_params[3].Set("output", true);
  160. LoadTASParams();
  161. LoadVirtualGamepadParams();
  162. std::ranges::transform(button_params, button_devices.begin(), Common::Input::CreateInputDevice);
  163. std::ranges::transform(stick_params, stick_devices.begin(), Common::Input::CreateInputDevice);
  164. std::ranges::transform(motion_params, motion_devices.begin(), Common::Input::CreateInputDevice);
  165. std::ranges::transform(trigger_params, trigger_devices.begin(),
  166. Common::Input::CreateInputDevice);
  167. std::ranges::transform(battery_params, battery_devices.begin(),
  168. Common::Input::CreateInputDevice);
  169. std::ranges::transform(color_params, color_devices.begin(), Common::Input::CreateInputDevice);
  170. std::ranges::transform(camera_params, camera_devices.begin(), Common::Input::CreateInputDevice);
  171. std::ranges::transform(ring_params, ring_analog_devices.begin(),
  172. Common::Input::CreateInputDevice);
  173. std::ranges::transform(nfc_params, nfc_devices.begin(), Common::Input::CreateInputDevice);
  174. std::ranges::transform(output_params, output_devices.begin(),
  175. Common::Input::CreateOutputDevice);
  176. // Initialize TAS devices
  177. std::ranges::transform(tas_button_params, tas_button_devices.begin(),
  178. Common::Input::CreateInputDevice);
  179. std::ranges::transform(tas_stick_params, tas_stick_devices.begin(),
  180. Common::Input::CreateInputDevice);
  181. // Initialize virtual gamepad devices
  182. std::ranges::transform(virtual_button_params, virtual_button_devices.begin(),
  183. Common::Input::CreateInputDevice);
  184. std::ranges::transform(virtual_stick_params, virtual_stick_devices.begin(),
  185. Common::Input::CreateInputDevice);
  186. std::ranges::transform(virtual_motion_params, virtual_motion_devices.begin(),
  187. Common::Input::CreateInputDevice);
  188. }
  189. void EmulatedController::LoadTASParams() {
  190. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  191. Common::ParamPackage common_params{};
  192. common_params.Set("engine", "tas");
  193. common_params.Set("port", static_cast<int>(player_index));
  194. for (auto& param : tas_button_params) {
  195. param = common_params;
  196. }
  197. for (auto& param : tas_stick_params) {
  198. param = common_params;
  199. }
  200. // TODO(german77): Replace this with an input profile or something better
  201. tas_button_params[Settings::NativeButton::A].Set("button", 0);
  202. tas_button_params[Settings::NativeButton::B].Set("button", 1);
  203. tas_button_params[Settings::NativeButton::X].Set("button", 2);
  204. tas_button_params[Settings::NativeButton::Y].Set("button", 3);
  205. tas_button_params[Settings::NativeButton::LStick].Set("button", 4);
  206. tas_button_params[Settings::NativeButton::RStick].Set("button", 5);
  207. tas_button_params[Settings::NativeButton::L].Set("button", 6);
  208. tas_button_params[Settings::NativeButton::R].Set("button", 7);
  209. tas_button_params[Settings::NativeButton::ZL].Set("button", 8);
  210. tas_button_params[Settings::NativeButton::ZR].Set("button", 9);
  211. tas_button_params[Settings::NativeButton::Plus].Set("button", 10);
  212. tas_button_params[Settings::NativeButton::Minus].Set("button", 11);
  213. tas_button_params[Settings::NativeButton::DLeft].Set("button", 12);
  214. tas_button_params[Settings::NativeButton::DUp].Set("button", 13);
  215. tas_button_params[Settings::NativeButton::DRight].Set("button", 14);
  216. tas_button_params[Settings::NativeButton::DDown].Set("button", 15);
  217. tas_button_params[Settings::NativeButton::SLLeft].Set("button", 16);
  218. tas_button_params[Settings::NativeButton::SRLeft].Set("button", 17);
  219. tas_button_params[Settings::NativeButton::Home].Set("button", 18);
  220. tas_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
  221. tas_button_params[Settings::NativeButton::SLRight].Set("button", 20);
  222. tas_button_params[Settings::NativeButton::SRRight].Set("button", 21);
  223. tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
  224. tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
  225. tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
  226. tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
  227. // set to optimal stick to avoid sanitizing the stick and tweaking the coordinates
  228. // making sure they play back in the game as originally written down in the script file
  229. tas_stick_params[Settings::NativeAnalog::LStick].Set("deadzone", 0.0f);
  230. tas_stick_params[Settings::NativeAnalog::LStick].Set("range", 1.0f);
  231. tas_stick_params[Settings::NativeAnalog::RStick].Set("deadzone", 0.0f);
  232. tas_stick_params[Settings::NativeAnalog::RStick].Set("range", 1.0f);
  233. }
  234. void EmulatedController::LoadVirtualGamepadParams() {
  235. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  236. Common::ParamPackage common_params{};
  237. common_params.Set("engine", "virtual_gamepad");
  238. common_params.Set("port", static_cast<int>(player_index));
  239. for (auto& param : virtual_button_params) {
  240. param = common_params;
  241. }
  242. for (auto& param : virtual_stick_params) {
  243. param = common_params;
  244. }
  245. for (auto& param : virtual_stick_params) {
  246. param = common_params;
  247. }
  248. for (auto& param : virtual_motion_params) {
  249. param = common_params;
  250. }
  251. // TODO(german77): Replace this with an input profile or something better
  252. virtual_button_params[Settings::NativeButton::A].Set("button", 0);
  253. virtual_button_params[Settings::NativeButton::B].Set("button", 1);
  254. virtual_button_params[Settings::NativeButton::X].Set("button", 2);
  255. virtual_button_params[Settings::NativeButton::Y].Set("button", 3);
  256. virtual_button_params[Settings::NativeButton::LStick].Set("button", 4);
  257. virtual_button_params[Settings::NativeButton::RStick].Set("button", 5);
  258. virtual_button_params[Settings::NativeButton::L].Set("button", 6);
  259. virtual_button_params[Settings::NativeButton::R].Set("button", 7);
  260. virtual_button_params[Settings::NativeButton::ZL].Set("button", 8);
  261. virtual_button_params[Settings::NativeButton::ZR].Set("button", 9);
  262. virtual_button_params[Settings::NativeButton::Plus].Set("button", 10);
  263. virtual_button_params[Settings::NativeButton::Minus].Set("button", 11);
  264. virtual_button_params[Settings::NativeButton::DLeft].Set("button", 12);
  265. virtual_button_params[Settings::NativeButton::DUp].Set("button", 13);
  266. virtual_button_params[Settings::NativeButton::DRight].Set("button", 14);
  267. virtual_button_params[Settings::NativeButton::DDown].Set("button", 15);
  268. virtual_button_params[Settings::NativeButton::SLLeft].Set("button", 16);
  269. virtual_button_params[Settings::NativeButton::SRLeft].Set("button", 17);
  270. virtual_button_params[Settings::NativeButton::Home].Set("button", 18);
  271. virtual_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
  272. virtual_button_params[Settings::NativeButton::SLRight].Set("button", 20);
  273. virtual_button_params[Settings::NativeButton::SRRight].Set("button", 21);
  274. virtual_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
  275. virtual_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
  276. virtual_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
  277. virtual_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
  278. virtual_stick_params[Settings::NativeAnalog::LStick].Set("deadzone", 0.0f);
  279. virtual_stick_params[Settings::NativeAnalog::LStick].Set("range", 1.0f);
  280. virtual_stick_params[Settings::NativeAnalog::RStick].Set("deadzone", 0.0f);
  281. virtual_stick_params[Settings::NativeAnalog::RStick].Set("range", 1.0f);
  282. virtual_motion_params[Settings::NativeMotion::MotionLeft].Set("motion", 0);
  283. virtual_motion_params[Settings::NativeMotion::MotionRight].Set("motion", 0);
  284. }
  285. void EmulatedController::ReloadInput() {
  286. // If you load any device here add the equivalent to the UnloadInput() function
  287. LoadDevices();
  288. for (std::size_t index = 0; index < button_devices.size(); ++index) {
  289. if (!button_devices[index]) {
  290. continue;
  291. }
  292. const auto uuid = Common::UUID{button_params[index].Get("guid", "")};
  293. button_devices[index]->SetCallback({
  294. .on_change =
  295. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  296. SetButton(callback, index, uuid);
  297. },
  298. });
  299. button_devices[index]->ForceUpdate();
  300. }
  301. for (std::size_t index = 0; index < stick_devices.size(); ++index) {
  302. if (!stick_devices[index]) {
  303. continue;
  304. }
  305. const auto uuid = Common::UUID{stick_params[index].Get("guid", "")};
  306. stick_devices[index]->SetCallback({
  307. .on_change =
  308. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  309. SetStick(callback, index, uuid);
  310. },
  311. });
  312. stick_devices[index]->ForceUpdate();
  313. }
  314. for (std::size_t index = 0; index < trigger_devices.size(); ++index) {
  315. if (!trigger_devices[index]) {
  316. continue;
  317. }
  318. const auto uuid = Common::UUID{trigger_params[index].Get("guid", "")};
  319. trigger_devices[index]->SetCallback({
  320. .on_change =
  321. [this, index, uuid](const Common::Input::CallbackStatus& callback) {
  322. SetTrigger(callback, index, uuid);
  323. },
  324. });
  325. trigger_devices[index]->ForceUpdate();
  326. }
  327. for (std::size_t index = 0; index < battery_devices.size(); ++index) {
  328. if (!battery_devices[index]) {
  329. continue;
  330. }
  331. battery_devices[index]->SetCallback({
  332. .on_change =
  333. [this, index](const Common::Input::CallbackStatus& callback) {
  334. SetBattery(callback, index);
  335. },
  336. });
  337. battery_devices[index]->ForceUpdate();
  338. }
  339. for (std::size_t index = 0; index < color_devices.size(); ++index) {
  340. if (!color_devices[index]) {
  341. continue;
  342. }
  343. color_devices[index]->SetCallback({
  344. .on_change =
  345. [this, index](const Common::Input::CallbackStatus& callback) {
  346. SetColors(callback, index);
  347. },
  348. });
  349. color_devices[index]->ForceUpdate();
  350. }
  351. for (std::size_t index = 0; index < motion_devices.size(); ++index) {
  352. if (!motion_devices[index]) {
  353. continue;
  354. }
  355. motion_devices[index]->SetCallback({
  356. .on_change =
  357. [this, index](const Common::Input::CallbackStatus& callback) {
  358. SetMotion(callback, index);
  359. },
  360. });
  361. // Restore motion state
  362. auto& emulated_motion = controller.motion_values[index].emulated;
  363. auto& motion = controller.motion_state[index];
  364. emulated_motion.ResetRotations();
  365. emulated_motion.ResetQuaternion();
  366. motion.accel = emulated_motion.GetAcceleration();
  367. motion.gyro = emulated_motion.GetGyroscope();
  368. motion.rotation = emulated_motion.GetRotations();
  369. motion.euler = emulated_motion.GetEulerAngles();
  370. motion.orientation = emulated_motion.GetOrientation();
  371. motion.is_at_rest = !emulated_motion.IsMoving(motion_sensitivity);
  372. }
  373. for (std::size_t index = 0; index < camera_devices.size(); ++index) {
  374. if (!camera_devices[index]) {
  375. continue;
  376. }
  377. camera_devices[index]->SetCallback({
  378. .on_change =
  379. [this](const Common::Input::CallbackStatus& callback) { SetCamera(callback); },
  380. });
  381. camera_devices[index]->ForceUpdate();
  382. }
  383. for (std::size_t index = 0; index < ring_analog_devices.size(); ++index) {
  384. if (!ring_analog_devices[index]) {
  385. continue;
  386. }
  387. ring_analog_devices[index]->SetCallback({
  388. .on_change =
  389. [this](const Common::Input::CallbackStatus& callback) { SetRingAnalog(callback); },
  390. });
  391. ring_analog_devices[index]->ForceUpdate();
  392. }
  393. for (std::size_t index = 0; index < nfc_devices.size(); ++index) {
  394. if (!nfc_devices[index]) {
  395. continue;
  396. }
  397. nfc_devices[index]->SetCallback({
  398. .on_change =
  399. [this](const Common::Input::CallbackStatus& callback) { SetNfc(callback); },
  400. });
  401. nfc_devices[index]->ForceUpdate();
  402. }
  403. // Register TAS devices. No need to force update
  404. for (std::size_t index = 0; index < tas_button_devices.size(); ++index) {
  405. if (!tas_button_devices[index]) {
  406. continue;
  407. }
  408. tas_button_devices[index]->SetCallback({
  409. .on_change =
  410. [this, index](const Common::Input::CallbackStatus& callback) {
  411. SetButton(callback, index, TAS_UUID);
  412. },
  413. });
  414. }
  415. for (std::size_t index = 0; index < tas_stick_devices.size(); ++index) {
  416. if (!tas_stick_devices[index]) {
  417. continue;
  418. }
  419. tas_stick_devices[index]->SetCallback({
  420. .on_change =
  421. [this, index](const Common::Input::CallbackStatus& callback) {
  422. SetStick(callback, index, TAS_UUID);
  423. },
  424. });
  425. }
  426. // Register virtual devices. No need to force update
  427. for (std::size_t index = 0; index < virtual_button_devices.size(); ++index) {
  428. if (!virtual_button_devices[index]) {
  429. continue;
  430. }
  431. virtual_button_devices[index]->SetCallback({
  432. .on_change =
  433. [this, index](const Common::Input::CallbackStatus& callback) {
  434. SetButton(callback, index, VIRTUAL_UUID);
  435. },
  436. });
  437. }
  438. for (std::size_t index = 0; index < virtual_stick_devices.size(); ++index) {
  439. if (!virtual_stick_devices[index]) {
  440. continue;
  441. }
  442. virtual_stick_devices[index]->SetCallback({
  443. .on_change =
  444. [this, index](const Common::Input::CallbackStatus& callback) {
  445. SetStick(callback, index, VIRTUAL_UUID);
  446. },
  447. });
  448. }
  449. for (std::size_t index = 0; index < virtual_motion_devices.size(); ++index) {
  450. if (!virtual_motion_devices[index]) {
  451. continue;
  452. }
  453. virtual_motion_devices[index]->SetCallback({
  454. .on_change =
  455. [this, index](const Common::Input::CallbackStatus& callback) {
  456. SetMotion(callback, index);
  457. },
  458. });
  459. }
  460. turbo_button_state = 0;
  461. is_initalized = true;
  462. }
  463. void EmulatedController::UnloadInput() {
  464. is_initalized = false;
  465. for (auto& button : button_devices) {
  466. button.reset();
  467. }
  468. for (auto& stick : stick_devices) {
  469. stick.reset();
  470. }
  471. for (auto& motion : motion_devices) {
  472. motion.reset();
  473. }
  474. for (auto& trigger : trigger_devices) {
  475. trigger.reset();
  476. }
  477. for (auto& battery : battery_devices) {
  478. battery.reset();
  479. }
  480. for (auto& color : color_devices) {
  481. color.reset();
  482. }
  483. for (auto& output : output_devices) {
  484. output.reset();
  485. }
  486. for (auto& button : tas_button_devices) {
  487. button.reset();
  488. }
  489. for (auto& stick : tas_stick_devices) {
  490. stick.reset();
  491. }
  492. for (auto& button : virtual_button_devices) {
  493. button.reset();
  494. }
  495. for (auto& stick : virtual_stick_devices) {
  496. stick.reset();
  497. }
  498. for (auto& motion : virtual_motion_devices) {
  499. motion.reset();
  500. }
  501. for (auto& camera : camera_devices) {
  502. camera.reset();
  503. }
  504. for (auto& ring : ring_analog_devices) {
  505. ring.reset();
  506. }
  507. for (auto& nfc : nfc_devices) {
  508. nfc.reset();
  509. }
  510. }
  511. void EmulatedController::EnableConfiguration() {
  512. std::scoped_lock lock{connect_mutex, npad_mutex};
  513. is_configuring = true;
  514. tmp_is_connected = is_connected;
  515. tmp_npad_type = npad_type;
  516. }
  517. void EmulatedController::DisableConfiguration() {
  518. is_configuring = false;
  519. // Get Joycon colors before turning on the controller
  520. for (const auto& color_device : color_devices) {
  521. color_device->ForceUpdate();
  522. }
  523. // Apply temporary npad type to the real controller
  524. if (tmp_npad_type != npad_type) {
  525. if (is_connected) {
  526. Disconnect();
  527. }
  528. SetNpadStyleIndex(tmp_npad_type);
  529. original_npad_type = tmp_npad_type;
  530. }
  531. // Apply temporary connected status to the real controller
  532. if (tmp_is_connected != is_connected) {
  533. if (tmp_is_connected) {
  534. Connect();
  535. return;
  536. }
  537. Disconnect();
  538. }
  539. }
  540. void EmulatedController::EnableSystemButtons() {
  541. std::scoped_lock lock{mutex};
  542. system_buttons_enabled = true;
  543. }
  544. void EmulatedController::DisableSystemButtons() {
  545. std::scoped_lock lock{mutex};
  546. system_buttons_enabled = false;
  547. controller.home_button_state.raw = 0;
  548. controller.capture_button_state.raw = 0;
  549. }
  550. void EmulatedController::ResetSystemButtons() {
  551. std::scoped_lock lock{mutex};
  552. controller.home_button_state.home.Assign(false);
  553. controller.capture_button_state.capture.Assign(false);
  554. }
  555. bool EmulatedController::IsConfiguring() const {
  556. return is_configuring;
  557. }
  558. void EmulatedController::SaveCurrentConfig() {
  559. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  560. auto& player = Settings::values.players.GetValue()[player_index];
  561. player.connected = is_connected;
  562. player.controller_type = MapNPadToSettingsType(npad_type);
  563. for (std::size_t index = 0; index < player.buttons.size(); ++index) {
  564. player.buttons[index] = button_params[index].Serialize();
  565. }
  566. for (std::size_t index = 0; index < player.analogs.size(); ++index) {
  567. player.analogs[index] = stick_params[index].Serialize();
  568. }
  569. for (std::size_t index = 0; index < player.motions.size(); ++index) {
  570. player.motions[index] = motion_params[index].Serialize();
  571. }
  572. if (npad_id_type == NpadIdType::Player1) {
  573. Settings::values.ringcon_analogs = ring_params[0].Serialize();
  574. }
  575. }
  576. void EmulatedController::RestoreConfig() {
  577. if (!is_configuring) {
  578. return;
  579. }
  580. ReloadFromSettings();
  581. }
  582. std::vector<Common::ParamPackage> EmulatedController::GetMappedDevices() const {
  583. std::vector<Common::ParamPackage> devices;
  584. for (const auto& param : button_params) {
  585. if (!param.Has("engine")) {
  586. continue;
  587. }
  588. const auto devices_it = std::find_if(
  589. devices.begin(), devices.end(), [&param](const Common::ParamPackage& param_) {
  590. return param.Get("engine", "") == param_.Get("engine", "") &&
  591. param.Get("guid", "") == param_.Get("guid", "") &&
  592. param.Get("port", 0) == param_.Get("port", 0) &&
  593. param.Get("pad", 0) == param_.Get("pad", 0);
  594. });
  595. if (devices_it != devices.end()) {
  596. continue;
  597. }
  598. auto& device = devices.emplace_back();
  599. device.Set("engine", param.Get("engine", ""));
  600. device.Set("guid", param.Get("guid", ""));
  601. device.Set("port", param.Get("port", 0));
  602. device.Set("pad", param.Get("pad", 0));
  603. }
  604. for (const auto& param : stick_params) {
  605. if (!param.Has("engine")) {
  606. continue;
  607. }
  608. if (param.Get("engine", "") == "analog_from_button") {
  609. continue;
  610. }
  611. const auto devices_it = std::find_if(
  612. devices.begin(), devices.end(), [&param](const Common::ParamPackage& param_) {
  613. return param.Get("engine", "") == param_.Get("engine", "") &&
  614. param.Get("guid", "") == param_.Get("guid", "") &&
  615. param.Get("port", 0) == param_.Get("port", 0) &&
  616. param.Get("pad", 0) == param_.Get("pad", 0);
  617. });
  618. if (devices_it != devices.end()) {
  619. continue;
  620. }
  621. auto& device = devices.emplace_back();
  622. device.Set("engine", param.Get("engine", ""));
  623. device.Set("guid", param.Get("guid", ""));
  624. device.Set("port", param.Get("port", 0));
  625. device.Set("pad", param.Get("pad", 0));
  626. }
  627. return devices;
  628. }
  629. Common::ParamPackage EmulatedController::GetButtonParam(std::size_t index) const {
  630. if (index >= button_params.size()) {
  631. return {};
  632. }
  633. return button_params[index];
  634. }
  635. Common::ParamPackage EmulatedController::GetStickParam(std::size_t index) const {
  636. if (index >= stick_params.size()) {
  637. return {};
  638. }
  639. return stick_params[index];
  640. }
  641. Common::ParamPackage EmulatedController::GetMotionParam(std::size_t index) const {
  642. if (index >= motion_params.size()) {
  643. return {};
  644. }
  645. return motion_params[index];
  646. }
  647. void EmulatedController::SetButtonParam(std::size_t index, Common::ParamPackage param) {
  648. if (index >= button_params.size()) {
  649. return;
  650. }
  651. button_params[index] = std::move(param);
  652. ReloadInput();
  653. }
  654. void EmulatedController::SetStickParam(std::size_t index, Common::ParamPackage param) {
  655. if (index >= stick_params.size()) {
  656. return;
  657. }
  658. stick_params[index] = std::move(param);
  659. ReloadInput();
  660. }
  661. void EmulatedController::SetMotionParam(std::size_t index, Common::ParamPackage param) {
  662. if (index >= motion_params.size()) {
  663. return;
  664. }
  665. motion_params[index] = std::move(param);
  666. ReloadInput();
  667. }
  668. void EmulatedController::StartMotionCalibration() {
  669. for (ControllerMotionInfo& motion : controller.motion_values) {
  670. motion.emulated.Calibrate();
  671. }
  672. }
  673. void EmulatedController::SetButton(const Common::Input::CallbackStatus& callback, std::size_t index,
  674. Common::UUID uuid) {
  675. if (index >= controller.button_values.size()) {
  676. return;
  677. }
  678. std::unique_lock lock{mutex};
  679. bool value_changed = false;
  680. const auto new_status = TransformToButton(callback);
  681. auto& current_status = controller.button_values[index];
  682. // Only read button values that have the same uuid or are pressed once
  683. if (current_status.uuid != uuid) {
  684. if (!new_status.value) {
  685. return;
  686. }
  687. }
  688. current_status.toggle = new_status.toggle;
  689. current_status.turbo = new_status.turbo;
  690. current_status.uuid = uuid;
  691. // Update button status with current
  692. if (!current_status.toggle) {
  693. current_status.locked = false;
  694. if (current_status.value != new_status.value) {
  695. current_status.value = new_status.value;
  696. value_changed = true;
  697. }
  698. } else {
  699. // Toggle button and lock status
  700. if (new_status.value && !current_status.locked) {
  701. current_status.locked = true;
  702. current_status.value = !current_status.value;
  703. value_changed = true;
  704. }
  705. // Unlock button ready for next press
  706. if (!new_status.value && current_status.locked) {
  707. current_status.locked = false;
  708. }
  709. }
  710. if (!value_changed) {
  711. return;
  712. }
  713. if (is_configuring) {
  714. controller.npad_button_state.raw = NpadButton::None;
  715. controller.debug_pad_button_state.raw = 0;
  716. controller.home_button_state.raw = 0;
  717. controller.capture_button_state.raw = 0;
  718. lock.unlock();
  719. TriggerOnChange(ControllerTriggerType::Button, false);
  720. return;
  721. }
  722. // GC controllers have triggers not buttons
  723. if (npad_type == NpadStyleIndex::GameCube) {
  724. if (index == Settings::NativeButton::ZR) {
  725. return;
  726. }
  727. if (index == Settings::NativeButton::ZL) {
  728. return;
  729. }
  730. }
  731. switch (index) {
  732. case Settings::NativeButton::A:
  733. controller.npad_button_state.a.Assign(current_status.value);
  734. controller.debug_pad_button_state.a.Assign(current_status.value);
  735. break;
  736. case Settings::NativeButton::B:
  737. controller.npad_button_state.b.Assign(current_status.value);
  738. controller.debug_pad_button_state.b.Assign(current_status.value);
  739. break;
  740. case Settings::NativeButton::X:
  741. controller.npad_button_state.x.Assign(current_status.value);
  742. controller.debug_pad_button_state.x.Assign(current_status.value);
  743. break;
  744. case Settings::NativeButton::Y:
  745. controller.npad_button_state.y.Assign(current_status.value);
  746. controller.debug_pad_button_state.y.Assign(current_status.value);
  747. break;
  748. case Settings::NativeButton::LStick:
  749. controller.npad_button_state.stick_l.Assign(current_status.value);
  750. break;
  751. case Settings::NativeButton::RStick:
  752. controller.npad_button_state.stick_r.Assign(current_status.value);
  753. break;
  754. case Settings::NativeButton::L:
  755. controller.npad_button_state.l.Assign(current_status.value);
  756. controller.debug_pad_button_state.l.Assign(current_status.value);
  757. break;
  758. case Settings::NativeButton::R:
  759. controller.npad_button_state.r.Assign(current_status.value);
  760. controller.debug_pad_button_state.r.Assign(current_status.value);
  761. break;
  762. case Settings::NativeButton::ZL:
  763. controller.npad_button_state.zl.Assign(current_status.value);
  764. controller.debug_pad_button_state.zl.Assign(current_status.value);
  765. break;
  766. case Settings::NativeButton::ZR:
  767. controller.npad_button_state.zr.Assign(current_status.value);
  768. controller.debug_pad_button_state.zr.Assign(current_status.value);
  769. break;
  770. case Settings::NativeButton::Plus:
  771. controller.npad_button_state.plus.Assign(current_status.value);
  772. controller.debug_pad_button_state.plus.Assign(current_status.value);
  773. break;
  774. case Settings::NativeButton::Minus:
  775. controller.npad_button_state.minus.Assign(current_status.value);
  776. controller.debug_pad_button_state.minus.Assign(current_status.value);
  777. break;
  778. case Settings::NativeButton::DLeft:
  779. controller.npad_button_state.left.Assign(current_status.value);
  780. controller.debug_pad_button_state.d_left.Assign(current_status.value);
  781. break;
  782. case Settings::NativeButton::DUp:
  783. controller.npad_button_state.up.Assign(current_status.value);
  784. controller.debug_pad_button_state.d_up.Assign(current_status.value);
  785. break;
  786. case Settings::NativeButton::DRight:
  787. controller.npad_button_state.right.Assign(current_status.value);
  788. controller.debug_pad_button_state.d_right.Assign(current_status.value);
  789. break;
  790. case Settings::NativeButton::DDown:
  791. controller.npad_button_state.down.Assign(current_status.value);
  792. controller.debug_pad_button_state.d_down.Assign(current_status.value);
  793. break;
  794. case Settings::NativeButton::SLLeft:
  795. controller.npad_button_state.left_sl.Assign(current_status.value);
  796. break;
  797. case Settings::NativeButton::SLRight:
  798. controller.npad_button_state.right_sl.Assign(current_status.value);
  799. break;
  800. case Settings::NativeButton::SRLeft:
  801. controller.npad_button_state.left_sr.Assign(current_status.value);
  802. break;
  803. case Settings::NativeButton::SRRight:
  804. controller.npad_button_state.right_sr.Assign(current_status.value);
  805. break;
  806. case Settings::NativeButton::Home:
  807. if (!system_buttons_enabled) {
  808. break;
  809. }
  810. controller.home_button_state.home.Assign(current_status.value);
  811. break;
  812. case Settings::NativeButton::Screenshot:
  813. if (!system_buttons_enabled) {
  814. break;
  815. }
  816. controller.capture_button_state.capture.Assign(current_status.value);
  817. break;
  818. }
  819. lock.unlock();
  820. if (!is_connected) {
  821. if (npad_id_type == NpadIdType::Player1 && npad_type != NpadStyleIndex::Handheld) {
  822. Connect();
  823. }
  824. if (npad_id_type == NpadIdType::Handheld && npad_type == NpadStyleIndex::Handheld) {
  825. Connect();
  826. }
  827. }
  828. TriggerOnChange(ControllerTriggerType::Button, true);
  829. }
  830. void EmulatedController::SetStick(const Common::Input::CallbackStatus& callback, std::size_t index,
  831. Common::UUID uuid) {
  832. if (index >= controller.stick_values.size()) {
  833. return;
  834. }
  835. auto trigger_guard =
  836. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Stick, !is_configuring); });
  837. std::scoped_lock lock{mutex};
  838. const auto stick_value = TransformToStick(callback);
  839. // Only read stick values that have the same uuid or are over the threshold to avoid flapping
  840. if (controller.stick_values[index].uuid != uuid) {
  841. const bool is_tas = uuid == TAS_UUID;
  842. if (is_tas && stick_value.x.value == 0 && stick_value.y.value == 0) {
  843. trigger_guard.Cancel();
  844. return;
  845. }
  846. if (!is_tas && !stick_value.down && !stick_value.up && !stick_value.left &&
  847. !stick_value.right) {
  848. trigger_guard.Cancel();
  849. return;
  850. }
  851. }
  852. controller.stick_values[index] = stick_value;
  853. controller.stick_values[index].uuid = uuid;
  854. if (is_configuring) {
  855. controller.analog_stick_state.left = {};
  856. controller.analog_stick_state.right = {};
  857. return;
  858. }
  859. const AnalogStickState stick{
  860. .x = static_cast<s32>(controller.stick_values[index].x.value * HID_JOYSTICK_MAX),
  861. .y = static_cast<s32>(controller.stick_values[index].y.value * HID_JOYSTICK_MAX),
  862. };
  863. switch (index) {
  864. case Settings::NativeAnalog::LStick:
  865. controller.analog_stick_state.left = stick;
  866. controller.npad_button_state.stick_l_left.Assign(controller.stick_values[index].left);
  867. controller.npad_button_state.stick_l_up.Assign(controller.stick_values[index].up);
  868. controller.npad_button_state.stick_l_right.Assign(controller.stick_values[index].right);
  869. controller.npad_button_state.stick_l_down.Assign(controller.stick_values[index].down);
  870. break;
  871. case Settings::NativeAnalog::RStick:
  872. controller.analog_stick_state.right = stick;
  873. controller.npad_button_state.stick_r_left.Assign(controller.stick_values[index].left);
  874. controller.npad_button_state.stick_r_up.Assign(controller.stick_values[index].up);
  875. controller.npad_button_state.stick_r_right.Assign(controller.stick_values[index].right);
  876. controller.npad_button_state.stick_r_down.Assign(controller.stick_values[index].down);
  877. break;
  878. }
  879. }
  880. void EmulatedController::SetTrigger(const Common::Input::CallbackStatus& callback,
  881. std::size_t index, Common::UUID uuid) {
  882. if (index >= controller.trigger_values.size()) {
  883. return;
  884. }
  885. auto trigger_guard =
  886. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Trigger, !is_configuring); });
  887. std::scoped_lock lock{mutex};
  888. const auto trigger_value = TransformToTrigger(callback);
  889. // Only read trigger values that have the same uuid or are pressed once
  890. if (controller.trigger_values[index].uuid != uuid) {
  891. if (!trigger_value.pressed.value) {
  892. return;
  893. }
  894. }
  895. controller.trigger_values[index] = trigger_value;
  896. controller.trigger_values[index].uuid = uuid;
  897. if (is_configuring) {
  898. controller.gc_trigger_state.left = 0;
  899. controller.gc_trigger_state.right = 0;
  900. return;
  901. }
  902. // Only GC controllers have analog triggers
  903. if (npad_type != NpadStyleIndex::GameCube) {
  904. trigger_guard.Cancel();
  905. return;
  906. }
  907. const auto& trigger = controller.trigger_values[index];
  908. switch (index) {
  909. case Settings::NativeTrigger::LTrigger:
  910. controller.gc_trigger_state.left = static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
  911. controller.npad_button_state.zl.Assign(trigger.pressed.value);
  912. break;
  913. case Settings::NativeTrigger::RTrigger:
  914. controller.gc_trigger_state.right =
  915. static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
  916. controller.npad_button_state.zr.Assign(trigger.pressed.value);
  917. break;
  918. }
  919. }
  920. void EmulatedController::SetMotion(const Common::Input::CallbackStatus& callback,
  921. std::size_t index) {
  922. if (index >= controller.motion_values.size()) {
  923. return;
  924. }
  925. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::Motion, !is_configuring); });
  926. std::scoped_lock lock{mutex};
  927. auto& raw_status = controller.motion_values[index].raw_status;
  928. auto& emulated = controller.motion_values[index].emulated;
  929. raw_status = TransformToMotion(callback);
  930. emulated.SetAcceleration(Common::Vec3f{
  931. raw_status.accel.x.value,
  932. raw_status.accel.y.value,
  933. raw_status.accel.z.value,
  934. });
  935. emulated.SetGyroscope(Common::Vec3f{
  936. raw_status.gyro.x.value,
  937. raw_status.gyro.y.value,
  938. raw_status.gyro.z.value,
  939. });
  940. emulated.SetUserGyroThreshold(raw_status.gyro.x.properties.threshold);
  941. emulated.UpdateRotation(raw_status.delta_timestamp);
  942. emulated.UpdateOrientation(raw_status.delta_timestamp);
  943. auto& motion = controller.motion_state[index];
  944. motion.accel = emulated.GetAcceleration();
  945. motion.gyro = emulated.GetGyroscope();
  946. motion.rotation = emulated.GetRotations();
  947. motion.euler = emulated.GetEulerAngles();
  948. motion.orientation = emulated.GetOrientation();
  949. motion.is_at_rest = !emulated.IsMoving(motion_sensitivity);
  950. }
  951. void EmulatedController::SetColors(const Common::Input::CallbackStatus& callback,
  952. std::size_t index) {
  953. if (index >= controller.color_values.size()) {
  954. return;
  955. }
  956. auto trigger_guard =
  957. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Color, !is_configuring); });
  958. std::scoped_lock lock{mutex};
  959. controller.color_values[index] = TransformToColor(callback);
  960. if (is_configuring) {
  961. return;
  962. }
  963. if (controller.color_values[index].body == 0) {
  964. trigger_guard.Cancel();
  965. return;
  966. }
  967. controller.colors_state.fullkey = {
  968. .body = GetNpadColor(controller.color_values[index].body),
  969. .button = GetNpadColor(controller.color_values[index].buttons),
  970. };
  971. if (npad_type == NpadStyleIndex::ProController) {
  972. controller.colors_state.left = {
  973. .body = GetNpadColor(controller.color_values[index].left_grip),
  974. .button = GetNpadColor(controller.color_values[index].buttons),
  975. };
  976. controller.colors_state.right = {
  977. .body = GetNpadColor(controller.color_values[index].right_grip),
  978. .button = GetNpadColor(controller.color_values[index].buttons),
  979. };
  980. } else {
  981. switch (index) {
  982. case LeftIndex:
  983. controller.colors_state.left = {
  984. .body = GetNpadColor(controller.color_values[index].body),
  985. .button = GetNpadColor(controller.color_values[index].buttons),
  986. };
  987. break;
  988. case RightIndex:
  989. controller.colors_state.right = {
  990. .body = GetNpadColor(controller.color_values[index].body),
  991. .button = GetNpadColor(controller.color_values[index].buttons),
  992. };
  993. break;
  994. }
  995. }
  996. }
  997. void EmulatedController::SetBattery(const Common::Input::CallbackStatus& callback,
  998. std::size_t index) {
  999. if (index >= controller.battery_values.size()) {
  1000. return;
  1001. }
  1002. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::Battery, !is_configuring); });
  1003. std::scoped_lock lock{mutex};
  1004. controller.battery_values[index] = TransformToBattery(callback);
  1005. if (is_configuring) {
  1006. return;
  1007. }
  1008. bool is_charging = false;
  1009. bool is_powered = false;
  1010. NpadBatteryLevel battery_level = NpadBatteryLevel::Empty;
  1011. switch (controller.battery_values[index]) {
  1012. case Common::Input::BatteryLevel::Charging:
  1013. is_charging = true;
  1014. is_powered = true;
  1015. battery_level = NpadBatteryLevel::Full;
  1016. break;
  1017. case Common::Input::BatteryLevel::Medium:
  1018. battery_level = NpadBatteryLevel::High;
  1019. break;
  1020. case Common::Input::BatteryLevel::Low:
  1021. battery_level = NpadBatteryLevel::Low;
  1022. break;
  1023. case Common::Input::BatteryLevel::Critical:
  1024. battery_level = NpadBatteryLevel::Critical;
  1025. break;
  1026. case Common::Input::BatteryLevel::Empty:
  1027. battery_level = NpadBatteryLevel::Empty;
  1028. break;
  1029. case Common::Input::BatteryLevel::None:
  1030. case Common::Input::BatteryLevel::Full:
  1031. default:
  1032. is_powered = true;
  1033. battery_level = NpadBatteryLevel::Full;
  1034. break;
  1035. }
  1036. switch (index) {
  1037. case LeftIndex:
  1038. controller.battery_state.left = {
  1039. .is_powered = is_powered,
  1040. .is_charging = is_charging,
  1041. .battery_level = battery_level,
  1042. };
  1043. break;
  1044. case RightIndex:
  1045. controller.battery_state.right = {
  1046. .is_powered = is_powered,
  1047. .is_charging = is_charging,
  1048. .battery_level = battery_level,
  1049. };
  1050. break;
  1051. case DualIndex:
  1052. controller.battery_state.dual = {
  1053. .is_powered = is_powered,
  1054. .is_charging = is_charging,
  1055. .battery_level = battery_level,
  1056. };
  1057. break;
  1058. }
  1059. }
  1060. void EmulatedController::SetCamera(const Common::Input::CallbackStatus& callback) {
  1061. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::IrSensor, !is_configuring); });
  1062. std::scoped_lock lock{mutex};
  1063. controller.camera_values = TransformToCamera(callback);
  1064. if (is_configuring) {
  1065. return;
  1066. }
  1067. controller.camera_state.sample++;
  1068. controller.camera_state.format =
  1069. static_cast<Core::IrSensor::ImageTransferProcessorFormat>(controller.camera_values.format);
  1070. controller.camera_state.data = controller.camera_values.data;
  1071. }
  1072. void EmulatedController::SetRingAnalog(const Common::Input::CallbackStatus& callback) {
  1073. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::RingController, !is_configuring); });
  1074. std::scoped_lock lock{mutex};
  1075. const auto force_value = TransformToStick(callback);
  1076. controller.ring_analog_value = force_value.x;
  1077. if (is_configuring) {
  1078. return;
  1079. }
  1080. controller.ring_analog_state.force = force_value.x.value;
  1081. }
  1082. void EmulatedController::SetNfc(const Common::Input::CallbackStatus& callback) {
  1083. SCOPE_EXIT({ TriggerOnChange(ControllerTriggerType::Nfc, !is_configuring); });
  1084. std::scoped_lock lock{mutex};
  1085. controller.nfc_values = TransformToNfc(callback);
  1086. if (is_configuring) {
  1087. return;
  1088. }
  1089. controller.nfc_state = controller.nfc_values;
  1090. }
  1091. bool EmulatedController::SetVibration(std::size_t device_index, VibrationValue vibration) {
  1092. if (!is_initalized) {
  1093. return false;
  1094. }
  1095. if (device_index >= output_devices.size()) {
  1096. return false;
  1097. }
  1098. if (!output_devices[device_index]) {
  1099. return false;
  1100. }
  1101. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  1102. const auto& player = Settings::values.players.GetValue()[player_index];
  1103. const f32 strength = static_cast<f32>(player.vibration_strength) / 100.0f;
  1104. if (!player.vibration_enabled) {
  1105. return false;
  1106. }
  1107. // Exponential amplification is too strong at low amplitudes. Switch to a linear
  1108. // amplification if strength is set below 0.7f
  1109. const Common::Input::VibrationAmplificationType type =
  1110. strength > 0.7f ? Common::Input::VibrationAmplificationType::Exponential
  1111. : Common::Input::VibrationAmplificationType::Linear;
  1112. const Common::Input::VibrationStatus status = {
  1113. .low_amplitude = std::min(vibration.low_amplitude * strength, 1.0f),
  1114. .low_frequency = vibration.low_frequency,
  1115. .high_amplitude = std::min(vibration.high_amplitude * strength, 1.0f),
  1116. .high_frequency = vibration.high_frequency,
  1117. .type = type,
  1118. };
  1119. return output_devices[device_index]->SetVibration(status) ==
  1120. Common::Input::DriverResult::Success;
  1121. }
  1122. bool EmulatedController::IsVibrationEnabled(std::size_t device_index) {
  1123. const auto player_index = Service::HID::NpadIdTypeToIndex(npad_id_type);
  1124. const auto& player = Settings::values.players.GetValue()[player_index];
  1125. if (!is_initalized) {
  1126. return false;
  1127. }
  1128. if (!player.vibration_enabled) {
  1129. return false;
  1130. }
  1131. if (device_index >= output_devices.size()) {
  1132. return false;
  1133. }
  1134. if (!output_devices[device_index]) {
  1135. return false;
  1136. }
  1137. return output_devices[device_index]->IsVibrationEnabled();
  1138. }
  1139. Common::Input::DriverResult EmulatedController::SetPollingMode(
  1140. EmulatedDeviceIndex device_index, Common::Input::PollingMode polling_mode) {
  1141. LOG_INFO(Service_HID, "Set polling mode {}, device_index={}", polling_mode, device_index);
  1142. if (!is_initalized) {
  1143. return Common::Input::DriverResult::InvalidHandle;
  1144. }
  1145. auto& left_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Left)];
  1146. auto& right_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1147. auto& nfc_output_device = output_devices[3];
  1148. if (device_index == EmulatedDeviceIndex::LeftIndex) {
  1149. controller.left_polling_mode = polling_mode;
  1150. return left_output_device->SetPollingMode(polling_mode);
  1151. }
  1152. if (device_index == EmulatedDeviceIndex::RightIndex) {
  1153. controller.right_polling_mode = polling_mode;
  1154. const auto virtual_nfc_result = nfc_output_device->SetPollingMode(polling_mode);
  1155. const auto mapped_nfc_result = right_output_device->SetPollingMode(polling_mode);
  1156. // Restore previous state
  1157. if (mapped_nfc_result != Common::Input::DriverResult::Success) {
  1158. right_output_device->SetPollingMode(Common::Input::PollingMode::Active);
  1159. }
  1160. if (virtual_nfc_result == Common::Input::DriverResult::Success) {
  1161. return virtual_nfc_result;
  1162. }
  1163. return mapped_nfc_result;
  1164. }
  1165. controller.left_polling_mode = polling_mode;
  1166. controller.right_polling_mode = polling_mode;
  1167. left_output_device->SetPollingMode(polling_mode);
  1168. right_output_device->SetPollingMode(polling_mode);
  1169. nfc_output_device->SetPollingMode(polling_mode);
  1170. return Common::Input::DriverResult::Success;
  1171. }
  1172. Common::Input::PollingMode EmulatedController::GetPollingMode(
  1173. EmulatedDeviceIndex device_index) const {
  1174. if (device_index == EmulatedDeviceIndex::LeftIndex) {
  1175. return controller.left_polling_mode;
  1176. }
  1177. return controller.right_polling_mode;
  1178. }
  1179. bool EmulatedController::SetCameraFormat(
  1180. Core::IrSensor::ImageTransferProcessorFormat camera_format) {
  1181. LOG_INFO(Service_HID, "Set camera format {}", camera_format);
  1182. if (!is_initalized) {
  1183. return false;
  1184. }
  1185. auto& right_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1186. auto& camera_output_device = output_devices[2];
  1187. if (right_output_device->SetCameraFormat(static_cast<Common::Input::CameraFormat>(
  1188. camera_format)) == Common::Input::DriverResult::Success) {
  1189. return true;
  1190. }
  1191. // Fallback to Qt camera if native device doesn't have support
  1192. return camera_output_device->SetCameraFormat(static_cast<Common::Input::CameraFormat>(
  1193. camera_format)) == Common::Input::DriverResult::Success;
  1194. }
  1195. Common::ParamPackage EmulatedController::GetRingParam() const {
  1196. return ring_params[0];
  1197. }
  1198. void EmulatedController::SetRingParam(Common::ParamPackage param) {
  1199. ring_params[0] = std::move(param);
  1200. ReloadInput();
  1201. }
  1202. bool EmulatedController::HasNfc() const {
  1203. if (!is_initalized) {
  1204. return false;
  1205. }
  1206. const auto& nfc_output_device = output_devices[3];
  1207. switch (npad_type) {
  1208. case NpadStyleIndex::JoyconRight:
  1209. case NpadStyleIndex::JoyconDual:
  1210. case NpadStyleIndex::ProController:
  1211. case NpadStyleIndex::Handheld:
  1212. break;
  1213. default:
  1214. return false;
  1215. }
  1216. const bool has_virtual_nfc =
  1217. npad_id_type == NpadIdType::Player1 || npad_id_type == NpadIdType::Handheld;
  1218. const bool is_virtual_nfc_supported =
  1219. nfc_output_device->SupportsNfc() != Common::Input::NfcState::NotSupported;
  1220. return is_connected && (has_virtual_nfc && is_virtual_nfc_supported);
  1221. }
  1222. bool EmulatedController::AddNfcHandle() {
  1223. nfc_handles++;
  1224. return SetPollingMode(EmulatedDeviceIndex::RightIndex, Common::Input::PollingMode::NFC) ==
  1225. Common::Input::DriverResult::Success;
  1226. }
  1227. bool EmulatedController::RemoveNfcHandle() {
  1228. nfc_handles--;
  1229. if (nfc_handles <= 0) {
  1230. return SetPollingMode(EmulatedDeviceIndex::RightIndex,
  1231. Common::Input::PollingMode::Active) ==
  1232. Common::Input::DriverResult::Success;
  1233. }
  1234. return true;
  1235. }
  1236. bool EmulatedController::StartNfcPolling() {
  1237. if (!is_initalized) {
  1238. return false;
  1239. }
  1240. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1241. auto& nfc_virtual_output_device = output_devices[3];
  1242. const auto device_result = nfc_output_device->StartNfcPolling();
  1243. const auto virtual_device_result = nfc_virtual_output_device->StartNfcPolling();
  1244. return device_result == Common::Input::NfcState::Success ||
  1245. virtual_device_result == Common::Input::NfcState::Success;
  1246. }
  1247. bool EmulatedController::StopNfcPolling() {
  1248. if (!is_initalized) {
  1249. return false;
  1250. }
  1251. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1252. auto& nfc_virtual_output_device = output_devices[3];
  1253. const auto device_result = nfc_output_device->StopNfcPolling();
  1254. const auto virtual_device_result = nfc_virtual_output_device->StopNfcPolling();
  1255. return device_result == Common::Input::NfcState::Success ||
  1256. virtual_device_result == Common::Input::NfcState::Success;
  1257. }
  1258. bool EmulatedController::ReadAmiiboData(std::vector<u8>& data) {
  1259. if (!is_initalized) {
  1260. return false;
  1261. }
  1262. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1263. auto& nfc_virtual_output_device = output_devices[3];
  1264. if (nfc_output_device->ReadAmiiboData(data) == Common::Input::NfcState::Success) {
  1265. return true;
  1266. }
  1267. return nfc_virtual_output_device->ReadAmiiboData(data) == Common::Input::NfcState::Success;
  1268. }
  1269. bool EmulatedController::ReadMifareData(const Common::Input::MifareRequest& request,
  1270. Common::Input::MifareRequest& out_data) {
  1271. if (!is_initalized) {
  1272. return false;
  1273. }
  1274. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1275. auto& nfc_virtual_output_device = output_devices[3];
  1276. if (nfc_output_device->ReadMifareData(request, out_data) == Common::Input::NfcState::Success) {
  1277. return true;
  1278. }
  1279. return nfc_virtual_output_device->ReadMifareData(request, out_data) ==
  1280. Common::Input::NfcState::Success;
  1281. }
  1282. bool EmulatedController::WriteMifareData(const Common::Input::MifareRequest& request) {
  1283. if (!is_initalized) {
  1284. return false;
  1285. }
  1286. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1287. auto& nfc_virtual_output_device = output_devices[3];
  1288. if (nfc_output_device->WriteMifareData(request) == Common::Input::NfcState::Success) {
  1289. return true;
  1290. }
  1291. return nfc_virtual_output_device->WriteMifareData(request) == Common::Input::NfcState::Success;
  1292. }
  1293. bool EmulatedController::WriteNfc(const std::vector<u8>& data) {
  1294. if (!is_initalized) {
  1295. return false;
  1296. }
  1297. auto& nfc_output_device = output_devices[static_cast<std::size_t>(DeviceIndex::Right)];
  1298. auto& nfc_virtual_output_device = output_devices[3];
  1299. if (nfc_output_device->SupportsNfc() != Common::Input::NfcState::NotSupported) {
  1300. return nfc_output_device->WriteNfcData(data) == Common::Input::NfcState::Success;
  1301. }
  1302. return nfc_virtual_output_device->WriteNfcData(data) == Common::Input::NfcState::Success;
  1303. }
  1304. void EmulatedController::SetLedPattern() {
  1305. if (!is_initalized) {
  1306. return;
  1307. }
  1308. for (auto& device : output_devices) {
  1309. if (!device) {
  1310. continue;
  1311. }
  1312. const LedPattern pattern = GetLedPattern();
  1313. const Common::Input::LedStatus status = {
  1314. .led_1 = pattern.position1 != 0,
  1315. .led_2 = pattern.position2 != 0,
  1316. .led_3 = pattern.position3 != 0,
  1317. .led_4 = pattern.position4 != 0,
  1318. };
  1319. device->SetLED(status);
  1320. }
  1321. }
  1322. void EmulatedController::SetGyroscopeZeroDriftMode(GyroscopeZeroDriftMode mode) {
  1323. for (auto& motion : controller.motion_values) {
  1324. switch (mode) {
  1325. case GyroscopeZeroDriftMode::Loose:
  1326. motion_sensitivity = motion.emulated.IsAtRestLoose;
  1327. motion.emulated.SetGyroThreshold(motion.emulated.ThresholdLoose);
  1328. break;
  1329. case GyroscopeZeroDriftMode::Tight:
  1330. motion_sensitivity = motion.emulated.IsAtRestThight;
  1331. motion.emulated.SetGyroThreshold(motion.emulated.ThresholdThight);
  1332. break;
  1333. case GyroscopeZeroDriftMode::Standard:
  1334. default:
  1335. motion_sensitivity = motion.emulated.IsAtRestStandard;
  1336. motion.emulated.SetGyroThreshold(motion.emulated.ThresholdStandard);
  1337. break;
  1338. }
  1339. }
  1340. }
  1341. void EmulatedController::SetSupportedNpadStyleTag(NpadStyleTag supported_styles) {
  1342. supported_style_tag = supported_styles;
  1343. if (!is_connected) {
  1344. return;
  1345. }
  1346. // Attempt to reconnect with the original type
  1347. if (npad_type != original_npad_type) {
  1348. Disconnect();
  1349. const auto current_npad_type = npad_type;
  1350. SetNpadStyleIndex(original_npad_type);
  1351. if (IsControllerSupported()) {
  1352. Connect();
  1353. return;
  1354. }
  1355. SetNpadStyleIndex(current_npad_type);
  1356. Connect();
  1357. }
  1358. if (IsControllerSupported()) {
  1359. return;
  1360. }
  1361. Disconnect();
  1362. // Fallback Fullkey controllers to Pro controllers
  1363. if (IsControllerFullkey() && supported_style_tag.fullkey) {
  1364. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
  1365. SetNpadStyleIndex(NpadStyleIndex::ProController);
  1366. Connect();
  1367. return;
  1368. }
  1369. // Fallback Dual joycon controllers to Pro controllers
  1370. if (npad_type == NpadStyleIndex::JoyconDual && supported_style_tag.fullkey) {
  1371. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Pro controller", npad_type);
  1372. SetNpadStyleIndex(NpadStyleIndex::ProController);
  1373. Connect();
  1374. return;
  1375. }
  1376. // Fallback Pro controllers to Dual joycon
  1377. if (npad_type == NpadStyleIndex::ProController && supported_style_tag.joycon_dual) {
  1378. LOG_WARNING(Service_HID, "Reconnecting controller type {} as Dual Joycons", npad_type);
  1379. SetNpadStyleIndex(NpadStyleIndex::JoyconDual);
  1380. Connect();
  1381. return;
  1382. }
  1383. LOG_ERROR(Service_HID, "Controller type {} is not supported. Disconnecting controller",
  1384. npad_type);
  1385. }
  1386. bool EmulatedController::IsControllerFullkey(bool use_temporary_value) const {
  1387. std::scoped_lock lock{mutex};
  1388. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1389. switch (type) {
  1390. case NpadStyleIndex::ProController:
  1391. case NpadStyleIndex::GameCube:
  1392. case NpadStyleIndex::NES:
  1393. case NpadStyleIndex::SNES:
  1394. case NpadStyleIndex::N64:
  1395. case NpadStyleIndex::SegaGenesis:
  1396. return true;
  1397. default:
  1398. return false;
  1399. }
  1400. }
  1401. bool EmulatedController::IsControllerSupported(bool use_temporary_value) const {
  1402. std::scoped_lock lock{mutex};
  1403. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1404. switch (type) {
  1405. case NpadStyleIndex::ProController:
  1406. return supported_style_tag.fullkey.As<bool>();
  1407. case NpadStyleIndex::Handheld:
  1408. return supported_style_tag.handheld.As<bool>();
  1409. case NpadStyleIndex::JoyconDual:
  1410. return supported_style_tag.joycon_dual.As<bool>();
  1411. case NpadStyleIndex::JoyconLeft:
  1412. return supported_style_tag.joycon_left.As<bool>();
  1413. case NpadStyleIndex::JoyconRight:
  1414. return supported_style_tag.joycon_right.As<bool>();
  1415. case NpadStyleIndex::GameCube:
  1416. return supported_style_tag.gamecube.As<bool>();
  1417. case NpadStyleIndex::Pokeball:
  1418. return supported_style_tag.palma.As<bool>();
  1419. case NpadStyleIndex::NES:
  1420. return supported_style_tag.lark.As<bool>();
  1421. case NpadStyleIndex::SNES:
  1422. return supported_style_tag.lucia.As<bool>();
  1423. case NpadStyleIndex::N64:
  1424. return supported_style_tag.lagoon.As<bool>();
  1425. case NpadStyleIndex::SegaGenesis:
  1426. return supported_style_tag.lager.As<bool>();
  1427. default:
  1428. return false;
  1429. }
  1430. }
  1431. void EmulatedController::Connect(bool use_temporary_value) {
  1432. if (!IsControllerSupported(use_temporary_value)) {
  1433. const auto type = is_configuring && use_temporary_value ? tmp_npad_type : npad_type;
  1434. LOG_ERROR(Service_HID, "Controller type {} is not supported", type);
  1435. return;
  1436. }
  1437. auto trigger_guard =
  1438. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Connected, !is_configuring); });
  1439. std::scoped_lock lock{connect_mutex, mutex};
  1440. if (is_configuring) {
  1441. tmp_is_connected = true;
  1442. return;
  1443. }
  1444. if (is_connected) {
  1445. trigger_guard.Cancel();
  1446. return;
  1447. }
  1448. is_connected = true;
  1449. }
  1450. void EmulatedController::Disconnect() {
  1451. auto trigger_guard =
  1452. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Disconnected, !is_configuring); });
  1453. std::scoped_lock lock{connect_mutex, mutex};
  1454. if (is_configuring) {
  1455. tmp_is_connected = false;
  1456. return;
  1457. }
  1458. if (!is_connected) {
  1459. trigger_guard.Cancel();
  1460. return;
  1461. }
  1462. is_connected = false;
  1463. }
  1464. bool EmulatedController::IsConnected(bool get_temporary_value) const {
  1465. std::scoped_lock lock{connect_mutex};
  1466. if (get_temporary_value && is_configuring) {
  1467. return tmp_is_connected;
  1468. }
  1469. return is_connected;
  1470. }
  1471. NpadIdType EmulatedController::GetNpadIdType() const {
  1472. std::scoped_lock lock{mutex};
  1473. return npad_id_type;
  1474. }
  1475. NpadStyleIndex EmulatedController::GetNpadStyleIndex(bool get_temporary_value) const {
  1476. std::scoped_lock lock{npad_mutex};
  1477. if (get_temporary_value && is_configuring) {
  1478. return tmp_npad_type;
  1479. }
  1480. return npad_type;
  1481. }
  1482. void EmulatedController::SetNpadStyleIndex(NpadStyleIndex npad_type_) {
  1483. auto trigger_guard =
  1484. SCOPE_GUARD({ TriggerOnChange(ControllerTriggerType::Type, !is_configuring); });
  1485. std::scoped_lock lock{mutex, npad_mutex};
  1486. if (is_configuring) {
  1487. if (tmp_npad_type == npad_type_) {
  1488. trigger_guard.Cancel();
  1489. return;
  1490. }
  1491. tmp_npad_type = npad_type_;
  1492. return;
  1493. }
  1494. if (npad_type == npad_type_) {
  1495. trigger_guard.Cancel();
  1496. return;
  1497. }
  1498. if (is_connected) {
  1499. LOG_WARNING(Service_HID, "Controller {} type changed while it's connected",
  1500. Service::HID::NpadIdTypeToIndex(npad_id_type));
  1501. }
  1502. npad_type = npad_type_;
  1503. }
  1504. LedPattern EmulatedController::GetLedPattern() const {
  1505. switch (npad_id_type) {
  1506. case NpadIdType::Player1:
  1507. return LedPattern{1, 0, 0, 0};
  1508. case NpadIdType::Player2:
  1509. return LedPattern{1, 1, 0, 0};
  1510. case NpadIdType::Player3:
  1511. return LedPattern{1, 1, 1, 0};
  1512. case NpadIdType::Player4:
  1513. return LedPattern{1, 1, 1, 1};
  1514. case NpadIdType::Player5:
  1515. return LedPattern{1, 0, 0, 1};
  1516. case NpadIdType::Player6:
  1517. return LedPattern{1, 0, 1, 0};
  1518. case NpadIdType::Player7:
  1519. return LedPattern{1, 0, 1, 1};
  1520. case NpadIdType::Player8:
  1521. return LedPattern{0, 1, 1, 0};
  1522. default:
  1523. return LedPattern{0, 0, 0, 0};
  1524. }
  1525. }
  1526. ButtonValues EmulatedController::GetButtonsValues() const {
  1527. std::scoped_lock lock{mutex};
  1528. return controller.button_values;
  1529. }
  1530. SticksValues EmulatedController::GetSticksValues() const {
  1531. std::scoped_lock lock{mutex};
  1532. return controller.stick_values;
  1533. }
  1534. TriggerValues EmulatedController::GetTriggersValues() const {
  1535. std::scoped_lock lock{mutex};
  1536. return controller.trigger_values;
  1537. }
  1538. ControllerMotionValues EmulatedController::GetMotionValues() const {
  1539. std::scoped_lock lock{mutex};
  1540. return controller.motion_values;
  1541. }
  1542. ColorValues EmulatedController::GetColorsValues() const {
  1543. std::scoped_lock lock{mutex};
  1544. return controller.color_values;
  1545. }
  1546. BatteryValues EmulatedController::GetBatteryValues() const {
  1547. std::scoped_lock lock{mutex};
  1548. return controller.battery_values;
  1549. }
  1550. CameraValues EmulatedController::GetCameraValues() const {
  1551. std::scoped_lock lock{mutex};
  1552. return controller.camera_values;
  1553. }
  1554. RingAnalogValue EmulatedController::GetRingSensorValues() const {
  1555. return controller.ring_analog_value;
  1556. }
  1557. HomeButtonState EmulatedController::GetHomeButtons() const {
  1558. std::scoped_lock lock{mutex};
  1559. if (is_configuring) {
  1560. return {};
  1561. }
  1562. return controller.home_button_state;
  1563. }
  1564. CaptureButtonState EmulatedController::GetCaptureButtons() const {
  1565. std::scoped_lock lock{mutex};
  1566. if (is_configuring) {
  1567. return {};
  1568. }
  1569. return controller.capture_button_state;
  1570. }
  1571. NpadButtonState EmulatedController::GetNpadButtons() const {
  1572. std::scoped_lock lock{mutex};
  1573. if (is_configuring) {
  1574. return {};
  1575. }
  1576. return {controller.npad_button_state.raw & GetTurboButtonMask()};
  1577. }
  1578. DebugPadButton EmulatedController::GetDebugPadButtons() const {
  1579. std::scoped_lock lock{mutex};
  1580. if (is_configuring) {
  1581. return {};
  1582. }
  1583. return controller.debug_pad_button_state;
  1584. }
  1585. AnalogSticks EmulatedController::GetSticks() const {
  1586. std::scoped_lock lock{mutex};
  1587. if (is_configuring) {
  1588. return {};
  1589. }
  1590. return controller.analog_stick_state;
  1591. }
  1592. NpadGcTriggerState EmulatedController::GetTriggers() const {
  1593. std::scoped_lock lock{mutex};
  1594. if (is_configuring) {
  1595. return {};
  1596. }
  1597. return controller.gc_trigger_state;
  1598. }
  1599. MotionState EmulatedController::GetMotions() const {
  1600. std::unique_lock lock{mutex};
  1601. return controller.motion_state;
  1602. }
  1603. ControllerColors EmulatedController::GetColors() const {
  1604. std::scoped_lock lock{mutex};
  1605. return controller.colors_state;
  1606. }
  1607. BatteryLevelState EmulatedController::GetBattery() const {
  1608. std::scoped_lock lock{mutex};
  1609. return controller.battery_state;
  1610. }
  1611. const CameraState& EmulatedController::GetCamera() const {
  1612. std::scoped_lock lock{mutex};
  1613. return controller.camera_state;
  1614. }
  1615. RingSensorForce EmulatedController::GetRingSensorForce() const {
  1616. return controller.ring_analog_state;
  1617. }
  1618. const NfcState& EmulatedController::GetNfc() const {
  1619. std::scoped_lock lock{mutex};
  1620. return controller.nfc_state;
  1621. }
  1622. NpadColor EmulatedController::GetNpadColor(u32 color) {
  1623. return {
  1624. .r = static_cast<u8>((color >> 16) & 0xFF),
  1625. .g = static_cast<u8>((color >> 8) & 0xFF),
  1626. .b = static_cast<u8>(color & 0xFF),
  1627. .a = 0xff,
  1628. };
  1629. }
  1630. void EmulatedController::TriggerOnChange(ControllerTriggerType type, bool is_npad_service_update) {
  1631. std::scoped_lock lock{callback_mutex};
  1632. for (const auto& poller_pair : callback_list) {
  1633. const ControllerUpdateCallback& poller = poller_pair.second;
  1634. if (!is_npad_service_update && poller.is_npad_service) {
  1635. continue;
  1636. }
  1637. if (poller.on_change) {
  1638. poller.on_change(type);
  1639. }
  1640. }
  1641. }
  1642. int EmulatedController::SetCallback(ControllerUpdateCallback update_callback) {
  1643. std::scoped_lock lock{callback_mutex};
  1644. callback_list.insert_or_assign(last_callback_key, std::move(update_callback));
  1645. return last_callback_key++;
  1646. }
  1647. void EmulatedController::DeleteCallback(int key) {
  1648. std::scoped_lock lock{callback_mutex};
  1649. const auto& iterator = callback_list.find(key);
  1650. if (iterator == callback_list.end()) {
  1651. LOG_ERROR(Input, "Tried to delete non-existent callback {}", key);
  1652. return;
  1653. }
  1654. callback_list.erase(iterator);
  1655. }
  1656. void EmulatedController::StatusUpdate() {
  1657. turbo_button_state = (turbo_button_state + 1) % (TURBO_BUTTON_DELAY * 2);
  1658. // Some drivers like key motion need constant refreshing
  1659. for (std::size_t index = 0; index < motion_devices.size(); ++index) {
  1660. const auto& raw_status = controller.motion_values[index].raw_status;
  1661. auto& device = motion_devices[index];
  1662. if (!raw_status.force_update) {
  1663. continue;
  1664. }
  1665. if (!device) {
  1666. continue;
  1667. }
  1668. device->ForceUpdate();
  1669. }
  1670. }
  1671. NpadButton EmulatedController::GetTurboButtonMask() const {
  1672. // Apply no mask when disabled
  1673. if (turbo_button_state < TURBO_BUTTON_DELAY) {
  1674. return {NpadButton::All};
  1675. }
  1676. NpadButtonState button_mask{};
  1677. for (std::size_t index = 0; index < controller.button_values.size(); ++index) {
  1678. if (!controller.button_values[index].turbo) {
  1679. continue;
  1680. }
  1681. switch (index) {
  1682. case Settings::NativeButton::A:
  1683. button_mask.a.Assign(1);
  1684. break;
  1685. case Settings::NativeButton::B:
  1686. button_mask.b.Assign(1);
  1687. break;
  1688. case Settings::NativeButton::X:
  1689. button_mask.x.Assign(1);
  1690. break;
  1691. case Settings::NativeButton::Y:
  1692. button_mask.y.Assign(1);
  1693. break;
  1694. case Settings::NativeButton::L:
  1695. button_mask.l.Assign(1);
  1696. break;
  1697. case Settings::NativeButton::R:
  1698. button_mask.r.Assign(1);
  1699. break;
  1700. case Settings::NativeButton::ZL:
  1701. button_mask.zl.Assign(1);
  1702. break;
  1703. case Settings::NativeButton::ZR:
  1704. button_mask.zr.Assign(1);
  1705. break;
  1706. case Settings::NativeButton::DLeft:
  1707. button_mask.left.Assign(1);
  1708. break;
  1709. case Settings::NativeButton::DUp:
  1710. button_mask.up.Assign(1);
  1711. break;
  1712. case Settings::NativeButton::DRight:
  1713. button_mask.right.Assign(1);
  1714. break;
  1715. case Settings::NativeButton::DDown:
  1716. button_mask.down.Assign(1);
  1717. break;
  1718. case Settings::NativeButton::SLLeft:
  1719. button_mask.left_sl.Assign(1);
  1720. break;
  1721. case Settings::NativeButton::SLRight:
  1722. button_mask.right_sl.Assign(1);
  1723. break;
  1724. case Settings::NativeButton::SRLeft:
  1725. button_mask.left_sr.Assign(1);
  1726. break;
  1727. case Settings::NativeButton::SRRight:
  1728. button_mask.right_sr.Assign(1);
  1729. break;
  1730. default:
  1731. break;
  1732. }
  1733. }
  1734. return static_cast<NpadButton>(~button_mask.raw);
  1735. }
  1736. } // namespace Core::HID