SDL2Gamepad.cs 17 KB

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