input.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. // SPDX-FileCopyrightText: 2017 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <functional>
  5. #include <memory>
  6. #include <string>
  7. #include <unordered_map>
  8. #include <utility>
  9. #include <vector>
  10. #include "common/logging/log.h"
  11. #include "common/param_package.h"
  12. #include "common/uuid.h"
  13. namespace Common::Input {
  14. // Type of data that is expected to recieve or send
  15. enum class InputType {
  16. None,
  17. Battery,
  18. Button,
  19. Stick,
  20. Analog,
  21. Trigger,
  22. Motion,
  23. Touch,
  24. Color,
  25. Vibration,
  26. Nfc,
  27. IrSensor,
  28. };
  29. // Internal battery charge level
  30. enum class BatteryLevel : u32 {
  31. None,
  32. Empty,
  33. Critical,
  34. Low,
  35. Medium,
  36. Full,
  37. Charging,
  38. };
  39. enum class PollingMode {
  40. // Constant polling of buttons, analogs and motion data
  41. Active,
  42. // Only update on button change, digital analogs
  43. Pasive,
  44. // Enable near field communication polling
  45. NFC,
  46. // Enable infrared camera polling
  47. IR,
  48. // Enable ring controller polling
  49. Ring,
  50. };
  51. enum class CameraFormat {
  52. Size320x240,
  53. Size160x120,
  54. Size80x60,
  55. Size40x30,
  56. Size20x15,
  57. None,
  58. };
  59. // Different results that can happen from a device request
  60. enum class DriverResult {
  61. Success,
  62. WrongReply,
  63. Timeout,
  64. UnsupportedControllerType,
  65. HandleInUse,
  66. ErrorReadingData,
  67. ErrorWritingData,
  68. NoDeviceDetected,
  69. InvalidHandle,
  70. NotSupported,
  71. Disabled,
  72. Unknown,
  73. };
  74. // Nfc reply from the controller
  75. enum class NfcState {
  76. Success,
  77. NewAmiibo,
  78. WaitingForAmiibo,
  79. AmiiboRemoved,
  80. NotAnAmiibo,
  81. NotSupported,
  82. WrongDeviceState,
  83. WriteFailed,
  84. Unknown,
  85. };
  86. // Hint for amplification curve to be used
  87. enum class VibrationAmplificationType {
  88. Linear,
  89. Exponential,
  90. };
  91. // Analog properties for calibration
  92. struct AnalogProperties {
  93. // Anything below this value will be detected as zero
  94. float deadzone{};
  95. // Anyting above this values will be detected as one
  96. float range{1.0f};
  97. // Minimum value to be detected as active
  98. float threshold{0.5f};
  99. // Drift correction applied to the raw data
  100. float offset{};
  101. // Invert direction of the sensor data
  102. bool inverted{};
  103. // Press once to activate, press again to release
  104. bool toggle{};
  105. };
  106. // Single analog sensor data
  107. struct AnalogStatus {
  108. float value{};
  109. float raw_value{};
  110. AnalogProperties properties{};
  111. };
  112. // Button data
  113. struct ButtonStatus {
  114. Common::UUID uuid{};
  115. bool value{};
  116. // Invert value of the button
  117. bool inverted{};
  118. // Press once to activate, press again to release
  119. bool toggle{};
  120. // Internal lock for the toggle status
  121. bool locked{};
  122. };
  123. // Internal battery data
  124. using BatteryStatus = BatteryLevel;
  125. // Analog and digital joystick data
  126. struct StickStatus {
  127. Common::UUID uuid{};
  128. AnalogStatus x{};
  129. AnalogStatus y{};
  130. bool left{};
  131. bool right{};
  132. bool up{};
  133. bool down{};
  134. };
  135. // Analog and digital trigger data
  136. struct TriggerStatus {
  137. Common::UUID uuid{};
  138. AnalogStatus analog{};
  139. ButtonStatus pressed{};
  140. };
  141. // 3D vector representing motion input
  142. struct MotionSensor {
  143. AnalogStatus x{};
  144. AnalogStatus y{};
  145. AnalogStatus z{};
  146. };
  147. // Motion data used to calculate controller orientation
  148. struct MotionStatus {
  149. // Gyroscope vector measurement in radians/s.
  150. MotionSensor gyro{};
  151. // Acceleration vector measurement in G force
  152. MotionSensor accel{};
  153. // Time since last measurement in microseconds
  154. u64 delta_timestamp{};
  155. // Request to update after reading the value
  156. bool force_update{};
  157. };
  158. // Data of a single point on a touch screen
  159. struct TouchStatus {
  160. ButtonStatus pressed{};
  161. AnalogStatus x{};
  162. AnalogStatus y{};
  163. int id{};
  164. };
  165. // Physical controller color in RGB format
  166. struct BodyColorStatus {
  167. u32 body{};
  168. u32 buttons{};
  169. u32 left_grip{};
  170. u32 right_grip{};
  171. };
  172. // HD rumble data
  173. struct VibrationStatus {
  174. f32 low_amplitude{};
  175. f32 low_frequency{};
  176. f32 high_amplitude{};
  177. f32 high_frequency{};
  178. VibrationAmplificationType type;
  179. };
  180. // Physical controller LED pattern
  181. struct LedStatus {
  182. bool led_1{};
  183. bool led_2{};
  184. bool led_3{};
  185. bool led_4{};
  186. };
  187. // Raw data fom camera
  188. struct CameraStatus {
  189. CameraFormat format{CameraFormat::None};
  190. std::vector<u8> data{};
  191. };
  192. struct NfcStatus {
  193. NfcState state{};
  194. std::vector<u8> data{};
  195. };
  196. // List of buttons to be passed to Qt that can be translated
  197. enum class ButtonNames {
  198. Undefined,
  199. Invalid,
  200. // This will display the engine name instead of the button name
  201. Engine,
  202. // This will display the button by value instead of the button name
  203. Value,
  204. // Joycon button names
  205. ButtonLeft,
  206. ButtonRight,
  207. ButtonDown,
  208. ButtonUp,
  209. ButtonA,
  210. ButtonB,
  211. ButtonX,
  212. ButtonY,
  213. ButtonPlus,
  214. ButtonMinus,
  215. ButtonHome,
  216. ButtonCapture,
  217. ButtonStickL,
  218. ButtonStickR,
  219. TriggerL,
  220. TriggerZL,
  221. TriggerSL,
  222. TriggerR,
  223. TriggerZR,
  224. TriggerSR,
  225. // GC button names
  226. TriggerZ,
  227. ButtonStart,
  228. // DS4 button names
  229. L1,
  230. L2,
  231. L3,
  232. R1,
  233. R2,
  234. R3,
  235. Circle,
  236. Cross,
  237. Square,
  238. Triangle,
  239. Share,
  240. Options,
  241. Home,
  242. Touch,
  243. // Mouse buttons
  244. ButtonMouseWheel,
  245. ButtonBackward,
  246. ButtonForward,
  247. ButtonTask,
  248. ButtonExtra,
  249. };
  250. // Callback data consisting of an input type and the equivalent data status
  251. struct CallbackStatus {
  252. InputType type{InputType::None};
  253. ButtonStatus button_status{};
  254. StickStatus stick_status{};
  255. AnalogStatus analog_status{};
  256. TriggerStatus trigger_status{};
  257. MotionStatus motion_status{};
  258. TouchStatus touch_status{};
  259. BodyColorStatus color_status{};
  260. BatteryStatus battery_status{};
  261. VibrationStatus vibration_status{};
  262. CameraFormat camera_status{CameraFormat::None};
  263. NfcState nfc_status{NfcState::Unknown};
  264. std::vector<u8> raw_data{};
  265. };
  266. // Triggered once every input change
  267. struct InputCallback {
  268. std::function<void(const CallbackStatus&)> on_change;
  269. };
  270. /// An abstract class template for an input device (a button, an analog input, etc.).
  271. class InputDevice {
  272. public:
  273. virtual ~InputDevice() = default;
  274. // Force input device to update data regardless of the current state
  275. virtual void ForceUpdate() {}
  276. // Sets the function to be triggered when input changes
  277. void SetCallback(InputCallback callback_) {
  278. callback = std::move(callback_);
  279. }
  280. // Triggers the function set in the callback
  281. void TriggerOnChange(const CallbackStatus& status) {
  282. if (callback.on_change) {
  283. callback.on_change(status);
  284. }
  285. }
  286. private:
  287. InputCallback callback;
  288. };
  289. /// An abstract class template for an output device (rumble, LED pattern, polling mode).
  290. class OutputDevice {
  291. public:
  292. virtual ~OutputDevice() = default;
  293. virtual DriverResult SetLED([[maybe_unused]] const LedStatus& led_status) {
  294. return DriverResult::NotSupported;
  295. }
  296. virtual DriverResult SetVibration([[maybe_unused]] const VibrationStatus& vibration_status) {
  297. return DriverResult::NotSupported;
  298. }
  299. virtual bool IsVibrationEnabled() {
  300. return false;
  301. }
  302. virtual DriverResult SetPollingMode([[maybe_unused]] PollingMode polling_mode) {
  303. return DriverResult::NotSupported;
  304. }
  305. virtual DriverResult SetCameraFormat([[maybe_unused]] CameraFormat camera_format) {
  306. return DriverResult::NotSupported;
  307. }
  308. virtual NfcState SupportsNfc() const {
  309. return NfcState::NotSupported;
  310. }
  311. virtual NfcState WriteNfcData([[maybe_unused]] const std::vector<u8>& data) {
  312. return NfcState::NotSupported;
  313. }
  314. };
  315. /// An abstract class template for a factory that can create input devices.
  316. template <typename InputDeviceType>
  317. class Factory {
  318. public:
  319. virtual ~Factory() = default;
  320. virtual std::unique_ptr<InputDeviceType> Create(const Common::ParamPackage&) = 0;
  321. };
  322. namespace Impl {
  323. template <typename InputDeviceType>
  324. using FactoryListType = std::unordered_map<std::string, std::shared_ptr<Factory<InputDeviceType>>>;
  325. template <typename InputDeviceType>
  326. struct FactoryList {
  327. static FactoryListType<InputDeviceType> list;
  328. };
  329. template <typename InputDeviceType>
  330. FactoryListType<InputDeviceType> FactoryList<InputDeviceType>::list;
  331. } // namespace Impl
  332. /**
  333. * Registers an input device factory.
  334. * @tparam InputDeviceType the type of input devices the factory can create
  335. * @param name the name of the factory. Will be used to match the "engine" parameter when creating
  336. * a device
  337. * @param factory the factory object to register
  338. */
  339. template <typename InputDeviceType>
  340. void RegisterFactory(const std::string& name, std::shared_ptr<Factory<InputDeviceType>> factory) {
  341. auto pair = std::make_pair(name, std::move(factory));
  342. if (!Impl::FactoryList<InputDeviceType>::list.insert(std::move(pair)).second) {
  343. LOG_ERROR(Input, "Factory '{}' already registered", name);
  344. }
  345. }
  346. inline void RegisterInputFactory(const std::string& name,
  347. std::shared_ptr<Factory<InputDevice>> factory) {
  348. RegisterFactory<InputDevice>(name, std::move(factory));
  349. }
  350. inline void RegisterOutputFactory(const std::string& name,
  351. std::shared_ptr<Factory<OutputDevice>> factory) {
  352. RegisterFactory<OutputDevice>(name, std::move(factory));
  353. }
  354. /**
  355. * Unregisters an input device factory.
  356. * @tparam InputDeviceType the type of input devices the factory can create
  357. * @param name the name of the factory to unregister
  358. */
  359. template <typename InputDeviceType>
  360. void UnregisterFactory(const std::string& name) {
  361. if (Impl::FactoryList<InputDeviceType>::list.erase(name) == 0) {
  362. LOG_ERROR(Input, "Factory '{}' not registered", name);
  363. }
  364. }
  365. inline void UnregisterInputFactory(const std::string& name) {
  366. UnregisterFactory<InputDevice>(name);
  367. }
  368. inline void UnregisterOutputFactory(const std::string& name) {
  369. UnregisterFactory<OutputDevice>(name);
  370. }
  371. /**
  372. * Create an input device from given paramters.
  373. * @tparam InputDeviceType the type of input devices to create
  374. * @param params a serialized ParamPackage string that contains all parameters for creating the
  375. * device
  376. */
  377. template <typename InputDeviceType>
  378. std::unique_ptr<InputDeviceType> CreateDeviceFromString(const std::string& params) {
  379. const Common::ParamPackage package(params);
  380. const std::string engine = package.Get("engine", "null");
  381. const auto& factory_list = Impl::FactoryList<InputDeviceType>::list;
  382. const auto pair = factory_list.find(engine);
  383. if (pair == factory_list.end()) {
  384. if (engine != "null") {
  385. LOG_ERROR(Input, "Unknown engine name: {}", engine);
  386. }
  387. return std::make_unique<InputDeviceType>();
  388. }
  389. return pair->second->Create(package);
  390. }
  391. inline std::unique_ptr<InputDevice> CreateInputDeviceFromString(const std::string& params) {
  392. return CreateDeviceFromString<InputDevice>(params);
  393. }
  394. inline std::unique_ptr<OutputDevice> CreateOutputDeviceFromString(const std::string& params) {
  395. return CreateDeviceFromString<OutputDevice>(params);
  396. }
  397. /**
  398. * Create an input device from given parameters.
  399. * @tparam InputDeviceType the type of input devices to create
  400. * @param package A ParamPackage that contains all parameters for creating the device
  401. */
  402. template <typename InputDeviceType>
  403. std::unique_ptr<InputDeviceType> CreateDevice(const ParamPackage& package) {
  404. const std::string engine = package.Get("engine", "null");
  405. const auto& factory_list = Impl::FactoryList<InputDeviceType>::list;
  406. const auto pair = factory_list.find(engine);
  407. if (pair == factory_list.end()) {
  408. if (engine != "null") {
  409. LOG_ERROR(Input, "Unknown engine name: {}", engine);
  410. }
  411. return std::make_unique<InputDeviceType>();
  412. }
  413. return pair->second->Create(package);
  414. }
  415. inline std::unique_ptr<InputDevice> CreateInputDevice(const ParamPackage& package) {
  416. return CreateDevice<InputDevice>(package);
  417. }
  418. inline std::unique_ptr<OutputDevice> CreateOutputDevice(const ParamPackage& package) {
  419. return CreateDevice<OutputDevice>(package);
  420. }
  421. } // namespace Common::Input