InputControlExtensions.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Unity.Collections;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using UnityEngine.InputSystem.Controls;
  7. using UnityEngine.InputSystem.LowLevel;
  8. using UnityEngine.InputSystem.Utilities;
  9. ////REVIEW: some of the stuff here is really low-level; should we move it into a separate static class inside of .LowLevel?
  10. namespace UnityEngine.InputSystem
  11. {
  12. /// <summary>
  13. /// Various extension methods for <see cref="InputControl"/>. Mostly low-level routines.
  14. /// </summary>
  15. public static class InputControlExtensions
  16. {
  17. /// <summary>
  18. /// Find a control of the given type in control hierarchy of <paramref name="control"/>.
  19. /// </summary>
  20. /// <param name="control">Control whose parents to inspect.</param>
  21. /// <typeparam name="TControl">Type of control to look for. Actual control type can be
  22. /// subtype of this.</typeparam>
  23. /// <remarks>The found control of type <typeparamref name="TControl"/> which may be either
  24. /// <paramref name="control"/> itself or one of its parents. If no such control was found,
  25. /// returns <c>null</c>.</remarks>
  26. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  27. public static TControl FindInParentChain<TControl>(this InputControl control)
  28. where TControl : InputControl
  29. {
  30. if (control == null)
  31. throw new ArgumentNullException(nameof(control));
  32. for (var parent = control; parent != null; parent = parent.parent)
  33. if (parent is TControl parentOfType)
  34. return parentOfType;
  35. return null;
  36. }
  37. /// <summary>
  38. /// Check whether the given control is considered pressed according to the button press threshold.
  39. /// </summary>
  40. /// <param name="control">Control to check.</param>
  41. /// <param name="buttonPressPoint">Optional custom button press point. If not supplied, <see cref="InputSettings.defaultButtonPressPoint"/>
  42. /// is used.</param>
  43. /// <returns>True if the actuation of the given control is high enough for it to be considered pressed.</returns>
  44. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  45. /// <remarks>
  46. /// This method checks the actuation level of the control as <see cref="IsActuated"/> does. For <see cref="Controls.ButtonControl"/>s
  47. /// and other <c>float</c> value controls, this will effectively check whether the float value of the control exceeds the button
  48. /// point threshold. Note that if the control is an axis that can be both positive and negative, the press threshold works in
  49. /// both directions, i.e. it can be crossed both in the positive direction and in the negative direction.
  50. /// </remarks>
  51. /// <seealso cref="IsActuated"/>
  52. /// <seealso cref="InputSettings.defaultButtonPressPoint"/>
  53. /// <seealso cref="InputSystem.settings"/>
  54. public static bool IsPressed(this InputControl control, float buttonPressPoint = 0)
  55. {
  56. if (control == null)
  57. throw new ArgumentNullException(nameof(control));
  58. if (Mathf.Approximately(0, buttonPressPoint))
  59. {
  60. if (control is ButtonControl button)
  61. buttonPressPoint = button.pressPointOrDefault;
  62. else
  63. buttonPressPoint = ButtonControl.s_GlobalDefaultButtonPressPoint;
  64. }
  65. return control.IsActuated(buttonPressPoint);
  66. }
  67. /// <summary>
  68. /// Return true if the given control is actuated.
  69. /// </summary>
  70. /// <param name="control"></param>
  71. /// <param name="threshold">Magnitude threshold that the control must match or exceed to be considered actuated.
  72. /// An exception to this is the default value of zero. If threshold is zero, the control must have a magnitude
  73. /// greater than zero.</param>
  74. /// <returns></returns>
  75. /// <remarks>
  76. /// Actuation is defined as a control having a magnitude (<see cref="InputControl.EvaluateMagnitude()"/>
  77. /// greater than zero or, if the control does not support magnitudes, has been moved from its default
  78. /// state.
  79. ///
  80. /// In practice, this means that when actuated, a control will produce a value other than its default
  81. /// value.
  82. /// </remarks>
  83. public static bool IsActuated(this InputControl control, float threshold = 0)
  84. {
  85. // First perform cheap memory check. If we're in default state, we don't
  86. // need to invoke virtuals on the control.
  87. if (control.CheckStateIsAtDefault())
  88. return false;
  89. // Check magnitude of actuation.
  90. var magnitude = control.EvaluateMagnitude();
  91. if (magnitude < 0)
  92. {
  93. ////REVIEW: we probably want to do a value comparison on this path to compare it to the default value
  94. return true;
  95. }
  96. if (Mathf.Approximately(threshold, 0))
  97. return magnitude > 0;
  98. return magnitude >= threshold;
  99. }
  100. /// <summary>
  101. /// Read the current value of the control and return it as an object.
  102. /// </summary>
  103. /// <returns></returns>
  104. /// <remarks>
  105. /// This method allocates GC memory and thus may cause garbage collection when used during gameplay.
  106. ///
  107. /// Use <seealso cref="ReadValueIntoBuffer"/> to read values generically without having to know the
  108. /// specific value type of a control.
  109. /// </remarks>
  110. /// <seealso cref="ReadValueIntoBuffer"/>
  111. /// <seealso cref="InputControl{TValue}.ReadValue"/>
  112. public static unsafe object ReadValueAsObject(this InputControl control)
  113. {
  114. if (control == null)
  115. throw new ArgumentNullException(nameof(control));
  116. return control.ReadValueFromStateAsObject(control.currentStatePtr);
  117. }
  118. /// <summary>
  119. /// Read the current, processed value of the control and store it into the given memory buffer.
  120. /// </summary>
  121. /// <param name="buffer">Buffer to store value in. Note that the value is not stored with the offset
  122. /// found in <see cref="InputStateBlock.byteOffset"/> of the control's <see cref="InputControl.stateBlock"/>. It will
  123. /// be stored directly at the given address.</param>
  124. /// <param name="bufferSize">Size of the memory available at <paramref name="buffer"/> in bytes. Has to be
  125. /// at least <see cref="InputControl.valueSizeInBytes"/>. If the size is smaller, nothing will be written to the buffer.</param>
  126. /// <seealso cref="InputControl.valueSizeInBytes"/>
  127. /// <seealso cref="InputControl.valueType"/>
  128. /// <seealso cref="InputControl.ReadValueFromStateIntoBuffer"/>
  129. public static unsafe void ReadValueIntoBuffer(this InputControl control, void* buffer, int bufferSize)
  130. {
  131. if (control == null)
  132. throw new ArgumentNullException(nameof(control));
  133. if (buffer == null)
  134. throw new ArgumentNullException(nameof(buffer));
  135. control.ReadValueFromStateIntoBuffer(control.currentStatePtr, buffer, bufferSize);
  136. }
  137. /// <summary>
  138. /// Read the control's default value and return it as an object.
  139. /// </summary>
  140. /// <param name="control">Control to read default value from.</param>
  141. /// <returns></returns>
  142. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null.</exception>
  143. /// <remarks>
  144. /// This method allocates GC memory and should thus not be used during normal gameplay.
  145. /// </remarks>
  146. /// <seealso cref="InputControl.hasDefaultState"/>
  147. /// <seealso cref="InputControl.defaultStatePtr"/>
  148. public static unsafe object ReadDefaultValueAsObject(this InputControl control)
  149. {
  150. if (control == null)
  151. throw new ArgumentNullException(nameof(control));
  152. return control.ReadValueFromStateAsObject(control.defaultStatePtr);
  153. }
  154. /// <summary>
  155. /// Read the value for the given control from the given event.
  156. /// </summary>
  157. /// <param name="control">Control to read value for.</param>
  158. /// <param name="inputEvent">Event to read value from. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  159. /// <typeparam name="TValue">Type of value to read.</typeparam>
  160. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  161. /// <exception cref="ArgumentException"><paramref name="inputEvent"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  162. /// <returns>The value for the given control as read out from the given event or <c>default(TValue)</c> if the given
  163. /// event does not contain a value for the control (e.g. if it is a <see cref="DeltaStateEvent"/> not containing the relevant
  164. /// portion of the device's state memory).</returns>
  165. public static TValue ReadValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr inputEvent)
  166. where TValue : struct
  167. {
  168. if (control == null)
  169. throw new ArgumentNullException(nameof(control));
  170. if (!ReadValueFromEvent(control, inputEvent, out var value))
  171. return default;
  172. return value;
  173. }
  174. /// <summary>
  175. /// Check if the given event contains a value for the given control and if so, read the value.
  176. /// </summary>
  177. /// <param name="control">Control to read value for.</param>
  178. /// <param name="inputEvent">Input event. This must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.
  179. /// Note that in the case of a <see cref="DeltaStateEvent"/>, the control may not actually be part of the event. In this
  180. /// case, the method returns false and stores <c>default(TValue)</c> in <paramref name="value"/>.</param>
  181. /// <param name="value">Variable that receives the control value.</param>
  182. /// <typeparam name="TValue">Type of value to read.</typeparam>
  183. /// <returns>True if the value has been successfully read from the event, false otherwise.</returns>
  184. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  185. /// <exception cref="ArgumentException"><paramref name="inputEvent"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  186. /// <seealso cref="ReadUnprocessedValueFromEvent{TValue}(InputControl{TValue},InputEventPtr)"/>
  187. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")]
  188. public static unsafe bool ReadValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr inputEvent, out TValue value)
  189. where TValue : struct
  190. {
  191. if (control == null)
  192. throw new ArgumentNullException(nameof(control));
  193. var statePtr = control.GetStatePtrFromStateEvent(inputEvent);
  194. if (statePtr == null)
  195. {
  196. value = control.ReadDefaultValue();
  197. return false;
  198. }
  199. value = control.ReadValueFromState(statePtr);
  200. return true;
  201. }
  202. public static TValue ReadUnprocessedValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr eventPtr)
  203. where TValue : struct
  204. {
  205. if (control == null)
  206. throw new ArgumentNullException(nameof(control));
  207. var result = default(TValue);
  208. control.ReadUnprocessedValueFromEvent(eventPtr, out result);
  209. return result;
  210. }
  211. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")]
  212. public static unsafe bool ReadUnprocessedValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr inputEvent, out TValue value)
  213. where TValue : struct
  214. {
  215. if (control == null)
  216. throw new ArgumentNullException(nameof(control));
  217. var statePtr = control.GetStatePtrFromStateEvent(inputEvent);
  218. if (statePtr == null)
  219. {
  220. value = control.ReadDefaultValue();
  221. return false;
  222. }
  223. value = control.ReadUnprocessedValueFromState(statePtr);
  224. return true;
  225. }
  226. public static unsafe void WriteValueFromObjectIntoEvent(this InputControl control, InputEventPtr eventPtr, object value)
  227. {
  228. if (control == null)
  229. throw new ArgumentNullException(nameof(control));
  230. var statePtr = control.GetStatePtrFromStateEvent(eventPtr);
  231. if (statePtr == null)
  232. return;
  233. control.WriteValueFromObjectIntoState(value, statePtr);
  234. }
  235. /// <summary>
  236. /// Write the control's current value into <paramref name="statePtr"/>.
  237. /// </summary>
  238. /// <param name="control">Control to read the current value from and to store state for in <paramref name="statePtr"/>.</param>
  239. /// <param name="statePtr">State to receive the control's value in its respective <see cref="InputControl.stateBlock"/>.</param>
  240. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null or <paramref name="statePtr"/> is null.</exception>
  241. /// <remarks>
  242. /// This method is equivalent to <see cref="InputControl{TValue}.WriteValueIntoState"/> except that one does
  243. /// not have to know the value type of the given control.
  244. /// </remarks>
  245. /// <exception cref="NotSupportedException">The control does not support writing. This is the case, for
  246. /// example, that compute values (such as the magnitude of a vector).</exception>
  247. /// <seealso cref="InputControl{TValue}.WriteValueIntoState"/>
  248. public static unsafe void WriteValueIntoState(this InputControl control, void* statePtr)
  249. {
  250. if (control == null)
  251. throw new ArgumentNullException(nameof(control));
  252. if (statePtr == null)
  253. throw new ArgumentNullException(nameof(statePtr));
  254. var valueSize = control.valueSizeInBytes;
  255. var valuePtr = UnsafeUtility.Malloc(valueSize, 8, Allocator.Temp);
  256. try
  257. {
  258. control.ReadValueFromStateIntoBuffer(control.currentStatePtr, valuePtr, valueSize);
  259. control.WriteValueFromBufferIntoState(valuePtr, valueSize, statePtr);
  260. }
  261. finally
  262. {
  263. UnsafeUtility.Free(valuePtr, Allocator.Temp);
  264. }
  265. }
  266. public static unsafe void WriteValueIntoState<TValue>(this InputControl control, TValue value, void* statePtr)
  267. where TValue : struct
  268. {
  269. if (control == null)
  270. throw new ArgumentNullException(nameof(control));
  271. if (!(control is InputControl<TValue> controlOfType))
  272. throw new ArgumentException(
  273. $"Expecting control of type '{typeof(TValue).Name}' but got '{control.GetType().Name}'");
  274. controlOfType.WriteValueIntoState(value, statePtr);
  275. }
  276. public static unsafe void WriteValueIntoState<TValue>(this InputControl<TValue> control, TValue value, void* statePtr)
  277. where TValue : struct
  278. {
  279. if (control == null)
  280. throw new ArgumentNullException(nameof(control));
  281. if (statePtr == null)
  282. throw new ArgumentNullException(nameof(statePtr));
  283. var valuePtr = UnsafeUtility.AddressOf(ref value);
  284. var valueSize = UnsafeUtility.SizeOf<TValue>();
  285. control.WriteValueFromBufferIntoState(valuePtr, valueSize, statePtr);
  286. }
  287. public static unsafe void WriteValueIntoState<TValue>(this InputControl<TValue> control, void* statePtr)
  288. where TValue : struct
  289. {
  290. if (control == null)
  291. throw new ArgumentNullException(nameof(control));
  292. control.WriteValueIntoState(control.ReadValue(), statePtr);
  293. }
  294. /// <summary>
  295. ///
  296. /// </summary>
  297. /// <param name="state"></param>
  298. /// <param name="value">Value for <paramref name="control"/> to write into <paramref name="state"/>.</param>
  299. /// <typeparam name="TState"></typeparam>
  300. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null.</exception>
  301. /// <exception cref="ArgumentException">Control's value does not fit within the memory of <paramref name="state"/>.</exception>
  302. /// <exception cref="NotSupportedException"><paramref name="control"/> does not support writing.</exception>
  303. public static unsafe void WriteValueIntoState<TValue, TState>(this InputControl<TValue> control, TValue value, ref TState state)
  304. where TValue : struct
  305. where TState : struct, IInputStateTypeInfo
  306. {
  307. if (control == null)
  308. throw new ArgumentNullException(nameof(control));
  309. // Make sure the control's state actually fits within the given state.
  310. var sizeOfState = UnsafeUtility.SizeOf<TState>();
  311. if (control.stateOffsetRelativeToDeviceRoot + control.m_StateBlock.alignedSizeInBytes >= sizeOfState)
  312. throw new ArgumentException(
  313. $"Control {control.path} with offset {control.stateOffsetRelativeToDeviceRoot} and size of {control.m_StateBlock.sizeInBits} bits is out of bounds for state of type {typeof(TState).Name} with size {sizeOfState}",
  314. nameof(state));
  315. // Write value.
  316. var statePtr = (byte*)UnsafeUtility.AddressOf(ref state);
  317. control.WriteValueIntoState(value, statePtr);
  318. }
  319. public static void WriteValueIntoEvent<TValue>(this InputControl control, TValue value, InputEventPtr eventPtr)
  320. where TValue : struct
  321. {
  322. if (control == null)
  323. throw new ArgumentNullException(nameof(control));
  324. if (!eventPtr.valid)
  325. throw new ArgumentNullException(nameof(eventPtr));
  326. if (!(control is InputControl<TValue> controlOfType))
  327. throw new ArgumentException(
  328. $"Expecting control of type '{typeof(TValue).Name}' but got '{control.GetType().Name}'");
  329. controlOfType.WriteValueIntoEvent(value, eventPtr);
  330. }
  331. public static unsafe void WriteValueIntoEvent<TValue>(this InputControl<TValue> control, TValue value, InputEventPtr eventPtr)
  332. where TValue : struct
  333. {
  334. if (control == null)
  335. throw new ArgumentNullException(nameof(control));
  336. if (!eventPtr.valid)
  337. throw new ArgumentNullException(nameof(eventPtr));
  338. var statePtr = control.GetStatePtrFromStateEvent(eventPtr);
  339. if (statePtr == null)
  340. return;
  341. control.WriteValueIntoState(value, statePtr);
  342. }
  343. /// <summary>
  344. /// Copy the state of the device to the given memory buffer.
  345. /// </summary>
  346. /// <param name="device">An input device.</param>
  347. /// <param name="buffer">Buffer to copy the state of the device to.</param>
  348. /// <param name="bufferSizeInBytes">Size of <paramref name="buffer"/> in bytes.</param>
  349. /// <exception cref="ArgumentException"><paramref name="bufferSizeInBytes"/> is less than or equal to 0.</exception>
  350. /// <exception cref="ArgumentNullException"><paramref name="device"/> is <c>null</c>.</exception>
  351. /// <remarks>
  352. /// The method will copy however much fits into the given buffer. This means that if the state of the device
  353. /// is larger than what fits into the buffer, not all of the device's state is copied.
  354. /// </remarks>
  355. /// <seealso cref="InputControl.stateBlock"/>
  356. public static unsafe void CopyState(this InputDevice device, void* buffer, int bufferSizeInBytes)
  357. {
  358. if (device == null)
  359. throw new ArgumentNullException(nameof(device));
  360. if (bufferSizeInBytes <= 0)
  361. throw new ArgumentException("bufferSizeInBytes must be positive", nameof(bufferSizeInBytes));
  362. var stateBlock = device.m_StateBlock;
  363. var sizeToCopy = Math.Min(bufferSizeInBytes, stateBlock.alignedSizeInBytes);
  364. UnsafeUtility.MemCpy(buffer, (byte*)device.currentStatePtr + stateBlock.byteOffset, sizeToCopy);
  365. }
  366. /// <summary>
  367. /// Copy the state of the device to the given struct.
  368. /// </summary>
  369. /// <param name="device">An input device.</param>
  370. /// <param name="state">Struct to copy the state of the device into.</param>
  371. /// <typeparam name="TState">A state struct type such as <see cref="MouseState"/>.</typeparam>
  372. /// <exception cref="ArgumentException">The state format of <typeparamref name="TState"/> does not match
  373. /// the state form of <paramref name="device"/>.</exception>
  374. /// <exception cref="ArgumentNullException"><paramref name="device"/> is <c>null</c>.</exception>
  375. /// <remarks>
  376. /// This method will copy memory verbatim into the memory of the given struct. It will copy whatever
  377. /// memory of the device fits into the given struct.
  378. /// </remarks>
  379. /// <seealso cref="InputControl.stateBlock"/>
  380. public static unsafe void CopyState<TState>(this InputDevice device, out TState state)
  381. where TState : struct, IInputStateTypeInfo
  382. {
  383. if (device == null)
  384. throw new ArgumentNullException(nameof(device));
  385. state = default;
  386. if (device.stateBlock.format != state.format)
  387. throw new ArgumentException(
  388. $"Struct '{typeof(TState).Name}' has state format '{state.format}' which doesn't match device '{device}' with state format '{device.stateBlock.format}'",
  389. nameof(TState));
  390. var stateSize = UnsafeUtility.SizeOf<TState>();
  391. var statePtr = UnsafeUtility.AddressOf(ref state);
  392. device.CopyState(statePtr, stateSize);
  393. }
  394. /// <summary>
  395. /// Check whether the memory of the given control is in its default state.
  396. /// </summary>
  397. /// <param name="control">An input control on a device that's been added to the system (see <see cref="InputDevice.added"/>).</param>
  398. /// <returns>True if the state memory of the given control corresponds to the control's default.</returns>
  399. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  400. /// <remarks>
  401. /// This method is a cheaper check than actually reading out the value from the control and checking whether it
  402. /// is the same value as the default value. The method bypasses all value reading and simply performs a trivial
  403. /// memory comparison of the control's current state memory to the default state memory stored for the control.
  404. ///
  405. /// Note that the default state for the memory of a control does not necessary need to be all zeroes. For example,
  406. /// a stick axis may be stored as an unsigned 8-bit value with the memory state corresponding to a 0 value being 127.
  407. /// </remarks>
  408. /// <seealso cref="InputControl.stateBlock"/>
  409. public static unsafe bool CheckStateIsAtDefault(this InputControl control)
  410. {
  411. if (control == null)
  412. throw new ArgumentNullException(nameof(control));
  413. return CheckStateIsAtDefault(control, control.currentStatePtr);
  414. }
  415. /// <summary>
  416. /// Check if the given state corresponds to the default state of the control.
  417. /// </summary>
  418. /// <param name="control">Control to check the state for in <paramref name="statePtr"/>.</param>
  419. /// <param name="statePtr">Pointer to a state buffer containing the <see cref="InputControl.stateBlock"/> for <paramref name="control"/>.</param>
  420. /// <param name="maskPtr">If not null, only bits set to <c>false</c> (!) in the buffer will be taken into account. This can be used
  421. /// to mask out noise, i.e. every bit that is set in the mask is considered to represent noise.</param>
  422. /// <returns>True if the control/device is in its default state.</returns>
  423. /// <remarks>
  424. /// Note that default does not equate all zeroes. Stick axes, for example, that are stored as unsigned byte
  425. /// values will have their resting position at 127 and not at 0. This is why we explicitly store default
  426. /// state in a memory buffer instead of assuming zeroes.
  427. /// </remarks>
  428. /// <seealso cref="InputStateBuffers.defaultStateBuffer"/>
  429. public static unsafe bool CheckStateIsAtDefault(this InputControl control, void* statePtr, void* maskPtr = null)
  430. {
  431. if (control == null)
  432. throw new ArgumentNullException(nameof(control));
  433. if (statePtr == null)
  434. throw new ArgumentNullException(nameof(statePtr));
  435. return control.CompareState(statePtr, control.defaultStatePtr, maskPtr);
  436. }
  437. public static unsafe bool CheckStateIsAtDefaultIgnoringNoise(this InputControl control)
  438. {
  439. if (control == null)
  440. throw new ArgumentNullException(nameof(control));
  441. return control.CheckStateIsAtDefaultIgnoringNoise(control.currentStatePtr);
  442. }
  443. public static unsafe bool CheckStateIsAtDefaultIgnoringNoise(this InputControl control, void* statePtr)
  444. {
  445. if (control == null)
  446. throw new ArgumentNullException(nameof(control));
  447. if (statePtr == null)
  448. throw new ArgumentNullException(nameof(statePtr));
  449. return control.CheckStateIsAtDefault(statePtr, InputStateBuffers.s_NoiseMaskBuffer);
  450. }
  451. /// <summary>
  452. /// Compare the control's current state to the state stored in <paramref name="statePtr"/>.
  453. /// </summary>
  454. /// <param name="statePtr">State memory containing the control's <see cref="stateBlock"/>.</param>
  455. /// <returns>True if </returns>
  456. /// <seealso cref="currentStatePtr"/>
  457. /// <remarks>
  458. /// This method ignores noise
  459. ///
  460. /// This method will not actually read values but will instead compare state directly as it is stored
  461. /// in memory. <see cref="InputControl{TValue}.ReadValue"/> is not invoked and thus processors will
  462. /// not be run.
  463. /// </remarks>
  464. public static unsafe bool CompareStateIgnoringNoise(this InputControl control, void* statePtr)
  465. {
  466. if (control == null)
  467. throw new ArgumentNullException(nameof(control));
  468. if (statePtr == null)
  469. throw new ArgumentNullException(nameof(statePtr));
  470. return control.CompareState(control.currentStatePtr, statePtr, control.noiseMaskPtr);
  471. }
  472. /// <summary>
  473. /// Compare the control's stored state in <paramref name="firstStatePtr"/> to <paramref name="secondStatePtr"/>.
  474. /// </summary>
  475. /// <param name="firstStatePtr">Memory containing the control's <see cref="InputControl.stateBlock"/>.</param>
  476. /// <param name="secondStatePtr">Memory containing the control's <see cref="InputControl.stateBlock"/></param>
  477. /// <param name="maskPtr">Optional mask. If supplied, it will be used to mask the comparison between
  478. /// <paramref name="firstStatePtr"/> and <paramref name="secondStatePtr"/> such that any bit not set in the
  479. /// mask will be ignored even if different between the two states. This can be used, for example, to ignore
  480. /// noise in the state (<see cref="InputControl.noiseMaskPtr"/>).</param>
  481. /// <returns>True if the state is equivalent in both memory buffers.</returns>
  482. /// <remarks>
  483. /// Unlike <see cref="InputControl.CompareValue"/>, this method only compares raw memory state. If used on a stick, for example,
  484. /// it may mean that this method returns false for two stick values that would compare equal using <see cref="CompareValue"/>
  485. /// (e.g. if both stick values fall below the deadzone).
  486. /// </remarks>
  487. /// <seealso cref="InputControl.CompareValue"/>
  488. public static unsafe bool CompareState(this InputControl control, void* firstStatePtr, void* secondStatePtr, void* maskPtr = null)
  489. {
  490. ////REVIEW: for compound controls, do we want to go check leaves so as to not pick up on non-control noise in the state?
  491. //// e.g. from HID input reports; or should we just leave that to maskPtr?
  492. var firstPtr = (byte*)firstStatePtr + (int)control.m_StateBlock.byteOffset;
  493. var secondPtr = (byte*)secondStatePtr + (int)control.m_StateBlock.byteOffset;
  494. var mask = maskPtr != null ? (byte*)maskPtr + (int)control.m_StateBlock.byteOffset : null;
  495. if (control.m_StateBlock.sizeInBits == 1)
  496. {
  497. // If we have a mask and the bit is set in the mask, the control is to be ignored
  498. // and thus we consider it at default value.
  499. if (mask != null && MemoryHelpers.ReadSingleBit(mask, control.m_StateBlock.bitOffset))
  500. return true;
  501. return MemoryHelpers.ReadSingleBit(secondPtr, control.m_StateBlock.bitOffset) ==
  502. MemoryHelpers.ReadSingleBit(firstPtr, control.m_StateBlock.bitOffset);
  503. }
  504. return MemoryHelpers.MemCmpBitRegion(firstPtr, secondPtr,
  505. control.m_StateBlock.bitOffset, control.m_StateBlock.sizeInBits, mask);
  506. }
  507. public static unsafe bool CompareState(this InputControl control, void* statePtr, void* maskPtr = null)
  508. {
  509. if (control == null)
  510. throw new ArgumentNullException(nameof(control));
  511. if (statePtr == null)
  512. throw new ArgumentNullException(nameof(statePtr));
  513. return control.CompareState(control.currentStatePtr, statePtr, maskPtr);
  514. }
  515. /// <summary>
  516. /// Return true if the current value of <paramref name="control"/> is different to the one found
  517. /// in <paramref name="statePtr"/>.
  518. /// </summary>
  519. /// <param name="control">Control whose state to compare to what is stored in <paramref name="statePtr"/>.</param>
  520. /// <param name="statePtr">A block of input state memory containing the <see cref="InputControl.stateBlock"/>
  521. /// of <paramref name="control."/></param>
  522. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c> or <paramref name="statePtr"/>
  523. /// is <c>null</c>.</exception>
  524. /// <returns>True if the value of <paramref name="control"/> stored in <paramref name="statePtr"/> is different
  525. /// compared to what <see cref="InputControl{T}.ReadValue"/> of the control returns.</returns>
  526. public static unsafe bool HasValueChangeInState(this InputControl control, void* statePtr)
  527. {
  528. if (control == null)
  529. throw new ArgumentNullException(nameof(control));
  530. if (statePtr == null)
  531. throw new ArgumentNullException(nameof(statePtr));
  532. return control.CompareValue(control.currentStatePtr, statePtr);
  533. }
  534. public static unsafe bool HasValueChangeInEvent(this InputControl control, InputEventPtr eventPtr)
  535. {
  536. if (control == null)
  537. throw new ArgumentNullException(nameof(control));
  538. if (!eventPtr.valid)
  539. throw new ArgumentNullException(nameof(eventPtr));
  540. return control.CompareValue(control.currentStatePtr, control.GetStatePtrFromStateEvent(eventPtr));
  541. }
  542. /// <summary>
  543. /// Given a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>, return the raw memory pointer that can
  544. /// be used, for example, with <see cref="InputControl{T}.ReadValueFromState"/> to read out the value of <paramref name="control"/>
  545. /// contained in the event.
  546. /// </summary>
  547. /// <param name="control">Control to access state for in the given state event.</param>
  548. /// <param name="eventPtr">A <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/> containing input state.</param>
  549. /// <returns>A pointer that can be used with methods such as <see cref="InputControl{TValue}.ReadValueFromState"/> or <c>null</c>
  550. /// if <paramref name="eventPtr"/> does not contain state for the given <paramref name="control"/>.</returns>
  551. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c> -or- <paramref name="eventPtr"/> is invalid.</exception>
  552. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  553. /// <remarks>
  554. /// Note that the given state event must have the same state format (see <see cref="InputStateBlock.format"/>) as the device
  555. /// to which <paramref name="control"/> belongs. If this is not the case, the method will invariably return <c>null</c>.
  556. ///
  557. /// In practice, this means that the method cannot be used with touch events or, in general, with events sent to devices
  558. /// that implement <see cref="IInputStateCallbackReceiver"/> (which <see cref="Touchscreen"/> does) except if the event
  559. /// is in the same state format as the device. Touch events will generally be sent as state events containing only the
  560. /// state of a single <see cref="Controls.TouchControl"/>, not the state of the entire <see cref="Touchscreen"/>.
  561. /// </remarks>
  562. public static unsafe void* GetStatePtrFromStateEvent(this InputControl control, InputEventPtr eventPtr)
  563. {
  564. if (control == null)
  565. throw new ArgumentNullException(nameof(control));
  566. if (!eventPtr.valid)
  567. throw new ArgumentNullException(nameof(eventPtr));
  568. uint stateOffset;
  569. FourCC stateFormat;
  570. uint stateSizeInBytes;
  571. void* statePtr;
  572. if (eventPtr.IsA<DeltaStateEvent>())
  573. {
  574. var deltaEvent = DeltaStateEvent.From(eventPtr);
  575. // If it's a delta event, we need to subtract the delta state offset if it's not set to the root of the device
  576. stateOffset = deltaEvent->stateOffset;
  577. stateFormat = deltaEvent->stateFormat;
  578. stateSizeInBytes = deltaEvent->deltaStateSizeInBytes;
  579. statePtr = deltaEvent->deltaState;
  580. }
  581. else if (eventPtr.IsA<StateEvent>())
  582. {
  583. var stateEvent = StateEvent.From(eventPtr);
  584. stateOffset = 0;
  585. stateFormat = stateEvent->stateFormat;
  586. stateSizeInBytes = stateEvent->stateSizeInBytes;
  587. statePtr = stateEvent->state;
  588. }
  589. else
  590. {
  591. throw new ArgumentException("Event must be a state or delta state event", nameof(eventPtr));
  592. }
  593. // Make sure we have a state event compatible with our device. The event doesn't
  594. // have to be specifically for our device (we don't require device IDs to match) but
  595. // the formats have to match and the size must be within range of what we're trying
  596. // to read.
  597. var device = control.device;
  598. if (stateFormat != device.m_StateBlock.format)
  599. {
  600. // If the device is an IInputStateCallbackReceiver, there's a chance it actually recognizes
  601. // the state format in the event and can correlate it to the state as found on the device.
  602. if (!device.hasStateCallbacks ||
  603. !((IInputStateCallbackReceiver)device).GetStateOffsetForEvent(control, eventPtr, ref stateOffset))
  604. return null;
  605. }
  606. // Once a device has been added, global state buffer offsets are baked into control hierarchies.
  607. // We need to unsubtract those offsets here.
  608. // NOTE: If the given device has not actually been added to the system, the offset is simply 0
  609. // and this is a harmless NOP.
  610. stateOffset += device.m_StateBlock.byteOffset;
  611. // Return null if state is out of range.
  612. var controlOffset = (int)control.m_StateBlock.byteOffset - stateOffset;
  613. if (controlOffset < 0 || controlOffset + control.m_StateBlock.alignedSizeInBytes > stateSizeInBytes)
  614. return null;
  615. return (byte*)statePtr - (int)stateOffset;
  616. }
  617. /// <summary>
  618. /// Queue a value change on the given <paramref name="control"/> which will be processed and take effect
  619. /// in the next input update.
  620. /// </summary>
  621. /// <param name="control">Control to change the value of.</param>
  622. /// <param name="value">New value for the control.</param>
  623. /// <param name="time">Optional time at which the value change should take effect. If set, this will become
  624. /// the <see cref="InputEvent.time"/> of the queued event. If the time is in the future, the event will not
  625. /// be processed until it falls within the time of an input update slice (except if <see cref="InputSettings.timesliceEvents"/>
  626. /// is false, in which case the event will invariably be consumed in the next update).</param>
  627. /// <typeparam name="TValue">Type of value.</typeparam>
  628. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null.</exception>
  629. public static void QueueValueChange<TValue>(this InputControl<TValue> control, TValue value, double time = -1)
  630. where TValue : struct
  631. {
  632. if (control == null)
  633. throw new ArgumentNullException(nameof(control));
  634. ////TODO: if it's not a bit-addressing control, send a delta state change only
  635. using (StateEvent.From(control.device, out var eventPtr))
  636. {
  637. if (time >= 0)
  638. eventPtr.time = time;
  639. control.WriteValueIntoEvent(value, eventPtr);
  640. InputSystem.QueueEvent(eventPtr);
  641. }
  642. }
  643. /// <summary>
  644. /// Modify <paramref name="newState"/> to write an accumulated value of the control
  645. /// rather than the value currently found in the event.
  646. /// </summary>
  647. /// <param name="control">Control to perform the accumulation on.</param>
  648. /// <param name="currentStatePtr">Memory containing the control's current state. See <see
  649. /// cref="InputControl.currentStatePtr"/>.</param>
  650. /// <param name="newState">Event containing the new state about to be written to the device.</param>
  651. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  652. /// <remarks>
  653. /// This method reads the current, unprocessed value of the control from <see cref="currentStatePtr"/>
  654. /// and then adds it to the value of the control found in <paramref name="newState"/>.
  655. ///
  656. /// Note that the method does nothing if a value for the control is not contained in <paramref name="newState"/>.
  657. /// This can be the case, for example, for <see cref="DeltaStateEvent"/>s.
  658. /// </remarks>
  659. /// <seealso cref="Pointer.delta"/>
  660. public static unsafe void AccumulateValueInEvent(this InputControl<float> control, void* currentStatePtr, InputEventPtr newState)
  661. {
  662. if (control == null)
  663. throw new ArgumentNullException(nameof(control));
  664. if (!control.ReadUnprocessedValueFromEvent(newState, out var newDelta))
  665. return; // Value for the control not contained in the given event.
  666. var oldDelta = control.ReadUnprocessedValueFromState(currentStatePtr);
  667. control.WriteValueIntoEvent(oldDelta + newDelta, newState);
  668. }
  669. public static void FindControlsRecursive<TControl>(this InputControl parent, IList<TControl> controls, Func<TControl, bool> predicate)
  670. where TControl : InputControl
  671. {
  672. if (parent == null)
  673. throw new ArgumentNullException(nameof(parent));
  674. if (controls == null)
  675. throw new ArgumentNullException(nameof(controls));
  676. if (predicate == null)
  677. throw new ArgumentNullException(nameof(predicate));
  678. if (parent is TControl parentAsTControl && predicate(parentAsTControl))
  679. controls.Add(parentAsTControl);
  680. var children = parent.children;
  681. var childCount = children.Count;
  682. for (var i = 0; i < childCount; ++i)
  683. {
  684. var child = parent.children[i];
  685. FindControlsRecursive(child, controls, predicate);
  686. }
  687. }
  688. internal static string BuildPath(this InputControl control, string deviceLayout, StringBuilder builder = null)
  689. {
  690. if (control == null)
  691. throw new ArgumentNullException(nameof(control));
  692. if (string.IsNullOrEmpty(deviceLayout))
  693. throw new ArgumentNullException(nameof(deviceLayout));
  694. if (builder == null)
  695. builder = new StringBuilder();
  696. var device = control.device;
  697. builder.Append('<');
  698. builder.Append(deviceLayout);
  699. builder.Append('>');
  700. // Add usages of device, if any.
  701. var deviceUsages = device.usages;
  702. for (var i = 0; i < deviceUsages.Count; ++i)
  703. {
  704. builder.Append('{');
  705. builder.Append(deviceUsages[i]);
  706. builder.Append('}');
  707. }
  708. builder.Append('/');
  709. var devicePath = device.path;
  710. var controlPath = control.path;
  711. builder.Append(controlPath, devicePath.Length + 1, controlPath.Length - devicePath.Length - 1);
  712. return builder.ToString();
  713. }
  714. }
  715. }