SDL2Gamepad.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using Ryujinx.Common.Configuration.Hid;
  2. using Ryujinx.Common.Configuration.Hid.Controller;
  3. using Ryujinx.Common.Logging;
  4. using Ryujinx.Common.Utilities;
  5. using Ryujinx.HLE.HOS.Services.Hid;
  6. using SDL2;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Numerics;
  10. using System.Threading;
  11. using static SDL2.SDL;
  12. namespace Ryujinx.Input.SDL2
  13. {
  14. class SDL2Gamepad : IGamepad
  15. {
  16. private bool HasConfiguration => _configuration != null;
  17. private readonly record struct ButtonMappingEntry(GamepadButtonInputId To, GamepadButtonInputId From)
  18. {
  19. public bool IsValid => To is not GamepadButtonInputId.Unbound && From is not GamepadButtonInputId.Unbound;
  20. }
  21. private StandardControllerInputConfig _configuration;
  22. private static readonly SDL_GameControllerButton[] _buttonsDriverMapping = new SDL_GameControllerButton[(int)GamepadButtonInputId.Count]
  23. {
  24. // Unbound, ignored.
  25. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  26. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_A,
  27. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_B,
  28. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_X,
  29. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_Y,
  30. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSTICK,
  31. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSTICK,
  32. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
  33. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
  34. // NOTE: The left and right trigger are axis, we handle those differently
  35. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  36. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  37. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_UP,
  38. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_DOWN,
  39. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_LEFT,
  40. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
  41. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_BACK,
  42. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_START,
  43. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_GUIDE,
  44. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_MISC1,
  45. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE1,
  46. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE2,
  47. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE3,
  48. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_PADDLE4,
  49. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_TOUCHPAD,
  50. // Virtual buttons are invalid, ignored.
  51. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  52. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  53. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  54. SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID,
  55. };
  56. private readonly Lock _userMappingLock = new();
  57. private readonly List<ButtonMappingEntry> _buttonsUserMapping;
  58. private readonly StickInputId[] _stickUserMapping = new StickInputId[(int)StickInputId.Count]
  59. {
  60. StickInputId.Unbound,
  61. StickInputId.Left,
  62. StickInputId.Right,
  63. };
  64. public GamepadFeaturesFlag Features { get; }
  65. private nint _gamepadHandle;
  66. private float _triggerThreshold;
  67. public SDL2Gamepad(nint gamepadHandle, string driverId)
  68. {
  69. _gamepadHandle = gamepadHandle;
  70. _buttonsUserMapping = new List<ButtonMappingEntry>(20);
  71. Name = SDL_GameControllerName(_gamepadHandle);
  72. Id = driverId;
  73. Features = GetFeaturesFlag();
  74. _triggerThreshold = 0.0f;
  75. // Enable motion tracking
  76. if (Features.HasFlag(GamepadFeaturesFlag.Motion))
  77. {
  78. if (SDL_GameControllerSetSensorEnabled(_gamepadHandle, SDL_SensorType.SDL_SENSOR_ACCEL, SDL_bool.SDL_TRUE) != 0)
  79. {
  80. Logger.Error?.Print(LogClass.Hid, $"Could not enable data reporting for SensorType {SDL_SensorType.SDL_SENSOR_ACCEL}.");
  81. }
  82. if (SDL_GameControllerSetSensorEnabled(_gamepadHandle, SDL_SensorType.SDL_SENSOR_GYRO, SDL_bool.SDL_TRUE) != 0)
  83. {
  84. Logger.Error?.Print(LogClass.Hid, $"Could not enable data reporting for SensorType {SDL_SensorType.SDL_SENSOR_GYRO}.");
  85. }
  86. }
  87. }
  88. public void SetLed(uint packedRgb)
  89. {
  90. if (!Features.HasFlag(GamepadFeaturesFlag.Led)) return;
  91. byte red = packedRgb > 0 ? (byte)(packedRgb >> 16) : (byte)0;
  92. byte green = packedRgb > 0 ? (byte)(packedRgb >> 8) : (byte)0;
  93. byte blue = packedRgb > 0 ? (byte)(packedRgb % 256) : (byte)0;
  94. if (SDL_GameControllerSetLED(_gamepadHandle, red, green, blue) != 0)
  95. Logger.Error?.Print(LogClass.Hid, "LED is not supported on this game controller.");
  96. }
  97. private GamepadFeaturesFlag GetFeaturesFlag()
  98. {
  99. GamepadFeaturesFlag result = GamepadFeaturesFlag.None;
  100. if (SDL_GameControllerHasSensor(_gamepadHandle, SDL_SensorType.SDL_SENSOR_ACCEL) == SDL_bool.SDL_TRUE &&
  101. SDL_GameControllerHasSensor(_gamepadHandle, SDL_SensorType.SDL_SENSOR_GYRO) == SDL_bool.SDL_TRUE)
  102. {
  103. result |= GamepadFeaturesFlag.Motion;
  104. }
  105. if (SDL_GameControllerHasRumble(_gamepadHandle) == SDL_bool.SDL_TRUE)
  106. {
  107. result |= GamepadFeaturesFlag.Rumble;
  108. }
  109. if (SDL_GameControllerHasLED(_gamepadHandle) == SDL_bool.SDL_TRUE)
  110. {
  111. result |= GamepadFeaturesFlag.Led;
  112. }
  113. return result;
  114. }
  115. public string Id { get; }
  116. public string Name { get; }
  117. public bool IsConnected => SDL_GameControllerGetAttached(_gamepadHandle) == SDL_bool.SDL_TRUE;
  118. protected virtual void Dispose(bool disposing)
  119. {
  120. if (disposing && _gamepadHandle != nint.Zero)
  121. {
  122. Rainbow.Updated -= RainbowColorChanged;
  123. SDL_GameControllerClose(_gamepadHandle);
  124. _gamepadHandle = nint.Zero;
  125. }
  126. }
  127. public void Dispose()
  128. {
  129. Dispose(true);
  130. }
  131. public void SetTriggerThreshold(float triggerThreshold)
  132. {
  133. _triggerThreshold = triggerThreshold;
  134. }
  135. public void Rumble(float lowFrequency, float highFrequency, uint durationMs)
  136. {
  137. if (!Features.HasFlag(GamepadFeaturesFlag.Rumble))
  138. return;
  139. ushort lowFrequencyRaw = (ushort)(lowFrequency * ushort.MaxValue);
  140. ushort highFrequencyRaw = (ushort)(highFrequency * ushort.MaxValue);
  141. if (durationMs == uint.MaxValue)
  142. {
  143. if (SDL_GameControllerRumble(_gamepadHandle, lowFrequencyRaw, highFrequencyRaw, SDL_HAPTIC_INFINITY) != 0)
  144. Logger.Error?.Print(LogClass.Hid, "Rumble is not supported on this game controller.");
  145. }
  146. else if (durationMs > SDL_HAPTIC_INFINITY)
  147. {
  148. Logger.Error?.Print(LogClass.Hid, $"Unsupported rumble duration {durationMs}");
  149. }
  150. else
  151. {
  152. if (SDL_GameControllerRumble(_gamepadHandle, lowFrequencyRaw, highFrequencyRaw, durationMs) != 0)
  153. Logger.Error?.Print(LogClass.Hid, "Rumble is not supported on this game controller.");
  154. }
  155. }
  156. public Vector3 GetMotionData(MotionInputId inputId)
  157. {
  158. SDL_SensorType sensorType = inputId switch
  159. {
  160. MotionInputId.Accelerometer => SDL_SensorType.SDL_SENSOR_ACCEL,
  161. MotionInputId.Gyroscope => SDL_SensorType.SDL_SENSOR_GYRO,
  162. _ => SDL_SensorType.SDL_SENSOR_INVALID
  163. };
  164. if (!Features.HasFlag(GamepadFeaturesFlag.Motion) || sensorType is SDL_SensorType.SDL_SENSOR_INVALID)
  165. return Vector3.Zero;
  166. const int ElementCount = 3;
  167. unsafe
  168. {
  169. float* values = stackalloc float[ElementCount];
  170. int result = SDL_GameControllerGetSensorData(_gamepadHandle, sensorType, (nint)values, ElementCount);
  171. if (result != 0)
  172. return Vector3.Zero;
  173. Vector3 value = new(values[0], values[1], values[2]);
  174. return inputId switch
  175. {
  176. MotionInputId.Gyroscope => RadToDegree(value),
  177. MotionInputId.Accelerometer => GsToMs2(value),
  178. _ => value
  179. };
  180. }
  181. }
  182. private static Vector3 RadToDegree(Vector3 rad) => rad * (180 / MathF.PI);
  183. private static Vector3 GsToMs2(Vector3 gs) => gs / SDL_STANDARD_GRAVITY;
  184. private void RainbowColorChanged(int packedRgb)
  185. {
  186. if (!_configuration.Led.UseRainbow) return;
  187. SetLed((uint)packedRgb);
  188. }
  189. private bool _rainbowColorEnabled;
  190. public void SetConfiguration(InputConfig configuration)
  191. {
  192. lock (_userMappingLock)
  193. {
  194. _configuration = (StandardControllerInputConfig)configuration;
  195. if (Features.HasFlag(GamepadFeaturesFlag.Led) && _configuration.Led.EnableLed)
  196. {
  197. if (_configuration.Led.TurnOffLed)
  198. (this as IGamepad).ClearLed();
  199. else switch (_configuration.Led.UseRainbow)
  200. {
  201. case true when !_rainbowColorEnabled:
  202. Rainbow.Updated += RainbowColorChanged;
  203. _rainbowColorEnabled = true;
  204. break;
  205. case false when _rainbowColorEnabled:
  206. Rainbow.Updated -= RainbowColorChanged;
  207. _rainbowColorEnabled = false;
  208. break;
  209. }
  210. if (!_configuration.Led.TurnOffLed && !_rainbowColorEnabled)
  211. SetLed(_configuration.Led.LedColor);
  212. }
  213. _buttonsUserMapping.Clear();
  214. // First update sticks
  215. _stickUserMapping[(int)StickInputId.Left] = (StickInputId)_configuration.LeftJoyconStick.Joystick;
  216. _stickUserMapping[(int)StickInputId.Right] = (StickInputId)_configuration.RightJoyconStick.Joystick;
  217. // Then left joycon
  218. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftStick, (GamepadButtonInputId)_configuration.LeftJoyconStick.StickButton));
  219. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadUp, (GamepadButtonInputId)_configuration.LeftJoycon.DpadUp));
  220. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadDown, (GamepadButtonInputId)_configuration.LeftJoycon.DpadDown));
  221. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadLeft, (GamepadButtonInputId)_configuration.LeftJoycon.DpadLeft));
  222. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadRight, (GamepadButtonInputId)_configuration.LeftJoycon.DpadRight));
  223. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.Minus, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonMinus));
  224. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftShoulder, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonL));
  225. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftTrigger, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonZl));
  226. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleRightTrigger0, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonSr));
  227. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleLeftTrigger0, (GamepadButtonInputId)_configuration.LeftJoycon.ButtonSl));
  228. // Finally right joycon
  229. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightStick, (GamepadButtonInputId)_configuration.RightJoyconStick.StickButton));
  230. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.A, (GamepadButtonInputId)_configuration.RightJoycon.ButtonA));
  231. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.B, (GamepadButtonInputId)_configuration.RightJoycon.ButtonB));
  232. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.X, (GamepadButtonInputId)_configuration.RightJoycon.ButtonX));
  233. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.Y, (GamepadButtonInputId)_configuration.RightJoycon.ButtonY));
  234. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.Plus, (GamepadButtonInputId)_configuration.RightJoycon.ButtonPlus));
  235. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightShoulder, (GamepadButtonInputId)_configuration.RightJoycon.ButtonR));
  236. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightTrigger, (GamepadButtonInputId)_configuration.RightJoycon.ButtonZr));
  237. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleRightTrigger1, (GamepadButtonInputId)_configuration.RightJoycon.ButtonSr));
  238. _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleLeftTrigger1, (GamepadButtonInputId)_configuration.RightJoycon.ButtonSl));
  239. SetTriggerThreshold(_configuration.TriggerThreshold);
  240. }
  241. }
  242. public GamepadStateSnapshot GetStateSnapshot()
  243. {
  244. return IGamepad.GetStateSnapshot(this);
  245. }
  246. public GamepadStateSnapshot GetMappedStateSnapshot()
  247. {
  248. GamepadStateSnapshot rawState = GetStateSnapshot();
  249. GamepadStateSnapshot result = default;
  250. lock (_userMappingLock)
  251. {
  252. if (_buttonsUserMapping.Count == 0)
  253. return rawState;
  254. // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
  255. foreach (ButtonMappingEntry entry in _buttonsUserMapping)
  256. {
  257. if (!entry.IsValid)
  258. continue;
  259. // Do not touch state of button already pressed
  260. if (!result.IsPressed(entry.To))
  261. {
  262. result.SetPressed(entry.To, rawState.IsPressed(entry.From));
  263. }
  264. }
  265. (float leftStickX, float leftStickY) = rawState.GetStick(_stickUserMapping[(int)StickInputId.Left]);
  266. (float rightStickX, float rightStickY) = rawState.GetStick(_stickUserMapping[(int)StickInputId.Right]);
  267. result.SetStick(StickInputId.Left, leftStickX, leftStickY);
  268. result.SetStick(StickInputId.Right, rightStickX, rightStickY);
  269. }
  270. return result;
  271. }
  272. private static float ConvertRawStickValue(short value)
  273. {
  274. const float ConvertRate = 1.0f / (short.MaxValue + 0.5f);
  275. return value * ConvertRate;
  276. }
  277. private JoyconConfigControllerStick<GamepadInputId, Common.Configuration.Hid.Controller.StickInputId> GetLogicalJoyStickConfig(StickInputId inputId)
  278. {
  279. switch (inputId)
  280. {
  281. case StickInputId.Left:
  282. if (_configuration.RightJoyconStick.Joystick == Common.Configuration.Hid.Controller.StickInputId.Left)
  283. return _configuration.RightJoyconStick;
  284. else
  285. return _configuration.LeftJoyconStick;
  286. case StickInputId.Right:
  287. if (_configuration.LeftJoyconStick.Joystick == Common.Configuration.Hid.Controller.StickInputId.Right)
  288. return _configuration.LeftJoyconStick;
  289. else
  290. return _configuration.RightJoyconStick;
  291. }
  292. return null;
  293. }
  294. public (float, float) GetStick(StickInputId inputId)
  295. {
  296. if (inputId == StickInputId.Unbound)
  297. return (0.0f, 0.0f);
  298. (short stickX, short stickY) = GetStickXY(inputId);
  299. float resultX = ConvertRawStickValue(stickX);
  300. float resultY = -ConvertRawStickValue(stickY);
  301. if (HasConfiguration)
  302. {
  303. var joyconStickConfig = GetLogicalJoyStickConfig(inputId);
  304. if (joyconStickConfig != null)
  305. {
  306. if (joyconStickConfig.InvertStickX)
  307. resultX = -resultX;
  308. if (joyconStickConfig.InvertStickY)
  309. resultY = -resultY;
  310. if (joyconStickConfig.Rotate90CW)
  311. {
  312. float temp = resultX;
  313. resultX = resultY;
  314. resultY = -temp;
  315. }
  316. }
  317. }
  318. return (resultX, resultY);
  319. }
  320. // ReSharper disable once InconsistentNaming
  321. private (short, short) GetStickXY(StickInputId inputId) =>
  322. inputId switch
  323. {
  324. StickInputId.Left => (
  325. SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTX),
  326. SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTY)),
  327. StickInputId.Right => (
  328. SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTX),
  329. SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTY)),
  330. _ => throw new NotSupportedException($"Unsupported stick {inputId}")
  331. };
  332. public bool IsPressed(GamepadButtonInputId inputId)
  333. {
  334. switch (inputId)
  335. {
  336. case GamepadButtonInputId.LeftTrigger:
  337. return ConvertRawStickValue(SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERLEFT)) > _triggerThreshold;
  338. case GamepadButtonInputId.RightTrigger:
  339. return ConvertRawStickValue(SDL_GameControllerGetAxis(_gamepadHandle, SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) > _triggerThreshold;
  340. }
  341. if (_buttonsDriverMapping[(int)inputId] == SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID)
  342. {
  343. return false;
  344. }
  345. return SDL_GameControllerGetButton(_gamepadHandle, _buttonsDriverMapping[(int)inputId]) == 1;
  346. }
  347. }
  348. }