설명 없음
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InputControlExtensions.cs 99KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using Unity.Collections;
  8. using Unity.Collections.LowLevel.Unsafe;
  9. using UnityEngine.InputSystem.Controls;
  10. using UnityEngine.InputSystem.LowLevel;
  11. using UnityEngine.InputSystem.Utilities;
  12. ////REVIEW: some of the stuff here is really low-level; should we move it into a separate static class inside of .LowLevel?
  13. namespace UnityEngine.InputSystem
  14. {
  15. /// <summary>
  16. /// Various extension methods for <see cref="InputControl"/>. Mostly low-level routines.
  17. /// </summary>
  18. public static class InputControlExtensions
  19. {
  20. /// <summary>
  21. /// Find a control of the given type in control hierarchy of <paramref name="control"/>.
  22. /// </summary>
  23. /// <param name="control">Control whose parents to inspect.</param>
  24. /// <typeparam name="TControl">Type of control to look for. Actual control type can be
  25. /// subtype of this.</typeparam>
  26. /// <remarks>The found control of type <typeparamref name="TControl"/> which may be either
  27. /// <paramref name="control"/> itself or one of its parents. If no such control was found,
  28. /// returns <c>null</c>.</remarks>
  29. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  30. public static TControl FindInParentChain<TControl>(this InputControl control)
  31. where TControl : InputControl
  32. {
  33. if (control == null)
  34. throw new ArgumentNullException(nameof(control));
  35. for (var parent = control; parent != null; parent = parent.parent)
  36. if (parent is TControl parentOfType)
  37. return parentOfType;
  38. return null;
  39. }
  40. ////REVIEW: This ist too high up in the class hierarchy; can be applied to any kind of control without it being readily apparent what exactly it means
  41. /// <summary>
  42. /// Check whether the given control is considered pressed according to the button press threshold.
  43. /// </summary>
  44. /// <param name="control">Control to check.</param>
  45. /// <param name="buttonPressPoint">Optional custom button press point. If not supplied, <see cref="InputSettings.defaultButtonPressPoint"/>
  46. /// is used.</param>
  47. /// <returns>True if the actuation of the given control is high enough for it to be considered pressed.</returns>
  48. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  49. /// <remarks>
  50. /// This method checks the actuation level of the control as <see cref="IsActuated"/> does. For <see cref="Controls.ButtonControl"/>s
  51. /// and other <c>float</c> value controls, this will effectively check whether the float value of the control exceeds the button
  52. /// point threshold. Note that if the control is an axis that can be both positive and negative, the press threshold works in
  53. /// both directions, i.e. it can be crossed both in the positive direction and in the negative direction.
  54. /// </remarks>
  55. /// <seealso cref="IsActuated"/>
  56. /// <seealso cref="InputSettings.defaultButtonPressPoint"/>
  57. /// <seealso cref="InputSystem.settings"/>
  58. public static bool IsPressed(this InputControl control, float buttonPressPoint = 0)
  59. {
  60. if (control == null)
  61. throw new ArgumentNullException(nameof(control));
  62. if (Mathf.Approximately(0, buttonPressPoint))
  63. {
  64. if (control is ButtonControl button)
  65. buttonPressPoint = button.pressPointOrDefault;
  66. else
  67. buttonPressPoint = ButtonControl.s_GlobalDefaultButtonPressPoint;
  68. }
  69. return control.IsActuated(buttonPressPoint);
  70. }
  71. /// <summary>
  72. /// Return true if the given control is actuated.
  73. /// </summary>
  74. /// <param name="control"></param>
  75. /// <param name="threshold">Magnitude threshold that the control must match or exceed to be considered actuated.
  76. /// An exception to this is the default value of zero. If threshold is zero, the control must have a magnitude
  77. /// greater than zero.</param>
  78. /// <returns></returns>
  79. /// <remarks>
  80. /// Actuation is defined as a control having a magnitude (<see cref="InputControl.EvaluateMagnitude()"/>
  81. /// greater than zero or, if the control does not support magnitudes, has been moved from its default
  82. /// state.
  83. ///
  84. /// In practice, this means that when actuated, a control will produce a value other than its default
  85. /// value.
  86. /// </remarks>
  87. public static bool IsActuated(this InputControl control, float threshold = 0)
  88. {
  89. // First perform cheap memory check. If we're in default state, we don't
  90. // need to invoke virtuals on the control.
  91. if (control.CheckStateIsAtDefault())
  92. return false;
  93. // Check magnitude of actuation.
  94. var magnitude = control.magnitude;
  95. if (magnitude < 0)
  96. {
  97. // We know the control is not in default state but we also know it doesn't support
  98. // magnitude. So, all we can say is that it is actuated. Not how much it is actuated.
  99. //
  100. // If we're looking for a specific threshold here, consider the control to always
  101. // be under. But if not, consider it actuated "by virtue of not being in default state".
  102. if (Mathf.Approximately(threshold, 0))
  103. return true;
  104. return false;
  105. }
  106. if (Mathf.Approximately(threshold, 0))
  107. return magnitude > 0;
  108. return magnitude >= threshold;
  109. }
  110. /// <summary>
  111. /// Read the current value of the control and return it as an object.
  112. /// </summary>
  113. /// <returns></returns>
  114. /// <remarks>
  115. /// This method allocates GC memory and thus may cause garbage collection when used during gameplay.
  116. ///
  117. /// Use <seealso cref="ReadValueIntoBuffer"/> to read values generically without having to know the
  118. /// specific value type of a control.
  119. /// </remarks>
  120. /// <seealso cref="ReadValueIntoBuffer"/>
  121. /// <seealso cref="InputControl{TValue}.ReadValue"/>
  122. public static unsafe object ReadValueAsObject(this InputControl control)
  123. {
  124. if (control == null)
  125. throw new ArgumentNullException(nameof(control));
  126. return control.ReadValueFromStateAsObject(control.currentStatePtr);
  127. }
  128. /// <summary>
  129. /// Read the current, processed value of the control and store it into the given memory buffer.
  130. /// </summary>
  131. /// <param name="buffer">Buffer to store value in. Note that the value is not stored with the offset
  132. /// found in <see cref="InputStateBlock.byteOffset"/> of the control's <see cref="InputControl.stateBlock"/>. It will
  133. /// be stored directly at the given address.</param>
  134. /// <param name="bufferSize">Size of the memory available at <paramref name="buffer"/> in bytes. Has to be
  135. /// at least <see cref="InputControl.valueSizeInBytes"/>. If the size is smaller, nothing will be written to the buffer.</param>
  136. /// <seealso cref="InputControl.valueSizeInBytes"/>
  137. /// <seealso cref="InputControl.valueType"/>
  138. /// <seealso cref="InputControl.ReadValueFromStateIntoBuffer"/>
  139. public static unsafe void ReadValueIntoBuffer(this InputControl control, void* buffer, int bufferSize)
  140. {
  141. if (control == null)
  142. throw new ArgumentNullException(nameof(control));
  143. if (buffer == null)
  144. throw new ArgumentNullException(nameof(buffer));
  145. control.ReadValueFromStateIntoBuffer(control.currentStatePtr, buffer, bufferSize);
  146. }
  147. /// <summary>
  148. /// Read the control's default value and return it as an object.
  149. /// </summary>
  150. /// <param name="control">Control to read default value from.</param>
  151. /// <returns></returns>
  152. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null.</exception>
  153. /// <remarks>
  154. /// This method allocates GC memory and should thus not be used during normal gameplay.
  155. /// </remarks>
  156. /// <seealso cref="InputControl.hasDefaultState"/>
  157. /// <seealso cref="InputControl.defaultStatePtr"/>
  158. public static unsafe object ReadDefaultValueAsObject(this InputControl control)
  159. {
  160. if (control == null)
  161. throw new ArgumentNullException(nameof(control));
  162. return control.ReadValueFromStateAsObject(control.defaultStatePtr);
  163. }
  164. /// <summary>
  165. /// Read the value for the given control from the given event.
  166. /// </summary>
  167. /// <param name="control">Control to read value for.</param>
  168. /// <param name="inputEvent">Event to read value from. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  169. /// <typeparam name="TValue">Type of value to read.</typeparam>
  170. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  171. /// <exception cref="ArgumentException"><paramref name="inputEvent"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  172. /// <returns>The value for the given control as read out from the given event or <c>default(TValue)</c> if the given
  173. /// event does not contain a value for the control (e.g. if it is a <see cref="DeltaStateEvent"/> not containing the relevant
  174. /// portion of the device's state memory).</returns>
  175. public static TValue ReadValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr inputEvent)
  176. where TValue : struct
  177. {
  178. if (control == null)
  179. throw new ArgumentNullException(nameof(control));
  180. if (!ReadValueFromEvent(control, inputEvent, out var value))
  181. return default;
  182. return value;
  183. }
  184. /// <summary>
  185. /// Check if the given event contains a value for the given control and if so, read the value.
  186. /// </summary>
  187. /// <param name="control">Control to read value for.</param>
  188. /// <param name="inputEvent">Input event. This must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.
  189. /// Note that in the case of a <see cref="DeltaStateEvent"/>, the control may not actually be part of the event. In this
  190. /// case, the method returns false and stores <c>default(TValue)</c> in <paramref name="value"/>.</param>
  191. /// <param name="value">Variable that receives the control value.</param>
  192. /// <typeparam name="TValue">Type of value to read.</typeparam>
  193. /// <returns>True if the value has been successfully read from the event, false otherwise.</returns>
  194. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  195. /// <exception cref="ArgumentException"><paramref name="inputEvent"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  196. /// <seealso cref="ReadUnprocessedValueFromEvent{TValue}(InputControl{TValue},InputEventPtr)"/>
  197. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")]
  198. public static unsafe bool ReadValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr inputEvent, out TValue value)
  199. where TValue : struct
  200. {
  201. if (control == null)
  202. throw new ArgumentNullException(nameof(control));
  203. var statePtr = control.GetStatePtrFromStateEvent(inputEvent);
  204. if (statePtr == null)
  205. {
  206. value = control.ReadDefaultValue();
  207. return false;
  208. }
  209. value = control.ReadValueFromState(statePtr);
  210. return true;
  211. }
  212. /// <summary>
  213. /// Read the value of <paramref name="control"/> from the given <paramref name="inputEvent"/> without having to
  214. /// know the specific value type of the control.
  215. /// </summary>
  216. /// <param name="control">Control to read the value for.</param>
  217. /// <param name="inputEvent">An <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/> to read the value from.</param>
  218. /// <returns>The current value for the control or <c>null</c> if the control's value is not included
  219. /// in the event.</returns>
  220. /// <seealso cref="InputControl.ReadValueFromStateAsObject"/>
  221. public static unsafe object ReadValueFromEventAsObject(this InputControl control, InputEventPtr inputEvent)
  222. {
  223. if (control == null)
  224. throw new ArgumentNullException(nameof(control));
  225. var statePtr = control.GetStatePtrFromStateEvent(inputEvent);
  226. if (statePtr == null)
  227. return control.ReadDefaultValueAsObject();
  228. return control.ReadValueFromStateAsObject(statePtr);
  229. }
  230. public static TValue ReadUnprocessedValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr eventPtr)
  231. where TValue : struct
  232. {
  233. if (control == null)
  234. throw new ArgumentNullException(nameof(control));
  235. var result = default(TValue);
  236. control.ReadUnprocessedValueFromEvent(eventPtr, out result);
  237. return result;
  238. }
  239. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")]
  240. public static unsafe bool ReadUnprocessedValueFromEvent<TValue>(this InputControl<TValue> control, InputEventPtr inputEvent, out TValue value)
  241. where TValue : struct
  242. {
  243. if (control == null)
  244. throw new ArgumentNullException(nameof(control));
  245. var statePtr = control.GetStatePtrFromStateEvent(inputEvent);
  246. if (statePtr == null)
  247. {
  248. value = control.ReadDefaultValue();
  249. return false;
  250. }
  251. value = control.ReadUnprocessedValueFromState(statePtr);
  252. return true;
  253. }
  254. ////REVIEW: this has the opposite argument order of WriteValueFromObjectIntoState; fix!
  255. public static unsafe void WriteValueFromObjectIntoEvent(this InputControl control, InputEventPtr eventPtr, object value)
  256. {
  257. if (control == null)
  258. throw new ArgumentNullException(nameof(control));
  259. var statePtr = control.GetStatePtrFromStateEvent(eventPtr);
  260. if (statePtr == null)
  261. return;
  262. control.WriteValueFromObjectIntoState(value, statePtr);
  263. }
  264. /// <summary>
  265. /// Write the control's current value into <paramref name="statePtr"/>.
  266. /// </summary>
  267. /// <param name="control">Control to read the current value from and to store state for in <paramref name="statePtr"/>.</param>
  268. /// <param name="statePtr">State to receive the control's value in its respective <see cref="InputControl.stateBlock"/>.</param>
  269. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null or <paramref name="statePtr"/> is null.</exception>
  270. /// <remarks>
  271. /// This method is equivalent to <see cref="InputControl{TValue}.WriteValueIntoState"/> except that one does
  272. /// not have to know the value type of the given control.
  273. /// </remarks>
  274. /// <exception cref="NotSupportedException">The control does not support writing. This is the case, for
  275. /// example, that compute values (such as the magnitude of a vector).</exception>
  276. /// <seealso cref="InputControl{TValue}.WriteValueIntoState"/>
  277. public static unsafe void WriteValueIntoState(this InputControl control, void* statePtr)
  278. {
  279. if (control == null)
  280. throw new ArgumentNullException(nameof(control));
  281. if (statePtr == null)
  282. throw new ArgumentNullException(nameof(statePtr));
  283. var valueSize = control.valueSizeInBytes;
  284. var valuePtr = UnsafeUtility.Malloc(valueSize, 8, Allocator.Temp);
  285. try
  286. {
  287. control.ReadValueFromStateIntoBuffer(control.currentStatePtr, valuePtr, valueSize);
  288. control.WriteValueFromBufferIntoState(valuePtr, valueSize, statePtr);
  289. }
  290. finally
  291. {
  292. UnsafeUtility.Free(valuePtr, Allocator.Temp);
  293. }
  294. }
  295. public static unsafe void WriteValueIntoState<TValue>(this InputControl control, TValue value, void* statePtr)
  296. where TValue : struct
  297. {
  298. if (control == null)
  299. throw new ArgumentNullException(nameof(control));
  300. if (!(control is InputControl<TValue> controlOfType))
  301. throw new ArgumentException(
  302. $"Expecting control of type '{typeof(TValue).Name}' but got '{control.GetType().Name}'");
  303. controlOfType.WriteValueIntoState(value, statePtr);
  304. }
  305. public static unsafe void WriteValueIntoState<TValue>(this InputControl<TValue> control, TValue value, void* statePtr)
  306. where TValue : struct
  307. {
  308. if (control == null)
  309. throw new ArgumentNullException(nameof(control));
  310. if (statePtr == null)
  311. throw new ArgumentNullException(nameof(statePtr));
  312. var valuePtr = UnsafeUtility.AddressOf(ref value);
  313. var valueSize = UnsafeUtility.SizeOf<TValue>();
  314. control.WriteValueFromBufferIntoState(valuePtr, valueSize, statePtr);
  315. }
  316. public static unsafe void WriteValueIntoState<TValue>(this InputControl<TValue> control, void* statePtr)
  317. where TValue : struct
  318. {
  319. if (control == null)
  320. throw new ArgumentNullException(nameof(control));
  321. control.WriteValueIntoState(control.ReadValue(), statePtr);
  322. }
  323. /// <summary>
  324. ///
  325. /// </summary>
  326. /// <param name="state"></param>
  327. /// <param name="value">Value for <paramref name="control"/> to write into <paramref name="state"/>.</param>
  328. /// <typeparam name="TState"></typeparam>
  329. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null.</exception>
  330. /// <exception cref="ArgumentException">Control's value does not fit within the memory of <paramref name="state"/>.</exception>
  331. /// <exception cref="NotSupportedException"><paramref name="control"/> does not support writing.</exception>
  332. public static unsafe void WriteValueIntoState<TValue, TState>(this InputControl<TValue> control, TValue value, ref TState state)
  333. where TValue : struct
  334. where TState : struct, IInputStateTypeInfo
  335. {
  336. if (control == null)
  337. throw new ArgumentNullException(nameof(control));
  338. // Make sure the control's state actually fits within the given state.
  339. var sizeOfState = UnsafeUtility.SizeOf<TState>();
  340. if (control.stateOffsetRelativeToDeviceRoot + control.m_StateBlock.alignedSizeInBytes >= sizeOfState)
  341. throw new ArgumentException(
  342. $"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}",
  343. nameof(state));
  344. // Write value.
  345. var statePtr = (byte*)UnsafeUtility.AddressOf(ref state);
  346. control.WriteValueIntoState(value, statePtr);
  347. }
  348. public static void WriteValueIntoEvent<TValue>(this InputControl control, TValue value, InputEventPtr eventPtr)
  349. where TValue : struct
  350. {
  351. if (control == null)
  352. throw new ArgumentNullException(nameof(control));
  353. if (!eventPtr.valid)
  354. throw new ArgumentNullException(nameof(eventPtr));
  355. if (!(control is InputControl<TValue> controlOfType))
  356. throw new ArgumentException(
  357. $"Expecting control of type '{typeof(TValue).Name}' but got '{control.GetType().Name}'");
  358. controlOfType.WriteValueIntoEvent(value, eventPtr);
  359. }
  360. public static unsafe void WriteValueIntoEvent<TValue>(this InputControl<TValue> control, TValue value, InputEventPtr eventPtr)
  361. where TValue : struct
  362. {
  363. if (control == null)
  364. throw new ArgumentNullException(nameof(control));
  365. if (!eventPtr.valid)
  366. throw new ArgumentNullException(nameof(eventPtr));
  367. var statePtr = control.GetStatePtrFromStateEvent(eventPtr);
  368. if (statePtr == null)
  369. return;
  370. control.WriteValueIntoState(value, statePtr);
  371. }
  372. /// <summary>
  373. /// Copy the state of the device to the given memory buffer.
  374. /// </summary>
  375. /// <param name="device">An input device.</param>
  376. /// <param name="buffer">Buffer to copy the state of the device to.</param>
  377. /// <param name="bufferSizeInBytes">Size of <paramref name="buffer"/> in bytes.</param>
  378. /// <exception cref="ArgumentException"><paramref name="bufferSizeInBytes"/> is less than or equal to 0.</exception>
  379. /// <exception cref="ArgumentNullException"><paramref name="device"/> is <c>null</c>.</exception>
  380. /// <remarks>
  381. /// The method will copy however much fits into the given buffer. This means that if the state of the device
  382. /// is larger than what fits into the buffer, not all of the device's state is copied.
  383. /// </remarks>
  384. /// <seealso cref="InputControl.stateBlock"/>
  385. public static unsafe void CopyState(this InputDevice device, void* buffer, int bufferSizeInBytes)
  386. {
  387. if (device == null)
  388. throw new ArgumentNullException(nameof(device));
  389. if (bufferSizeInBytes <= 0)
  390. throw new ArgumentException("bufferSizeInBytes must be positive", nameof(bufferSizeInBytes));
  391. var stateBlock = device.m_StateBlock;
  392. var sizeToCopy = Math.Min(bufferSizeInBytes, stateBlock.alignedSizeInBytes);
  393. UnsafeUtility.MemCpy(buffer, (byte*)device.currentStatePtr + stateBlock.byteOffset, sizeToCopy);
  394. }
  395. /// <summary>
  396. /// Copy the state of the device to the given struct.
  397. /// </summary>
  398. /// <param name="device">An input device.</param>
  399. /// <param name="state">Struct to copy the state of the device into.</param>
  400. /// <typeparam name="TState">A state struct type such as <see cref="MouseState"/>.</typeparam>
  401. /// <exception cref="ArgumentException">The state format of <typeparamref name="TState"/> does not match
  402. /// the state form of <paramref name="device"/>.</exception>
  403. /// <exception cref="ArgumentNullException"><paramref name="device"/> is <c>null</c>.</exception>
  404. /// <remarks>
  405. /// This method will copy memory verbatim into the memory of the given struct. It will copy whatever
  406. /// memory of the device fits into the given struct.
  407. /// </remarks>
  408. /// <seealso cref="InputControl.stateBlock"/>
  409. public static unsafe void CopyState<TState>(this InputDevice device, out TState state)
  410. where TState : struct, IInputStateTypeInfo
  411. {
  412. if (device == null)
  413. throw new ArgumentNullException(nameof(device));
  414. state = default;
  415. if (device.stateBlock.format != state.format)
  416. throw new ArgumentException(
  417. $"Struct '{typeof(TState).Name}' has state format '{state.format}' which doesn't match device '{device}' with state format '{device.stateBlock.format}'",
  418. nameof(TState));
  419. var stateSize = UnsafeUtility.SizeOf<TState>();
  420. var statePtr = UnsafeUtility.AddressOf(ref state);
  421. device.CopyState(statePtr, stateSize);
  422. }
  423. /// <summary>
  424. /// Check whether the memory of the given control is in its default state.
  425. /// </summary>
  426. /// <param name="control">An input control on a device that's been added to the system (see <see cref="InputDevice.added"/>).</param>
  427. /// <returns>True if the state memory of the given control corresponds to the control's default.</returns>
  428. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  429. /// <remarks>
  430. /// This method is a cheaper check than actually reading out the value from the control and checking whether it
  431. /// is the same value as the default value. The method bypasses all value reading and simply performs a trivial
  432. /// memory comparison of the control's current state memory to the default state memory stored for the control.
  433. ///
  434. /// Note that the default state for the memory of a control does not necessary need to be all zeroes. For example,
  435. /// a stick axis may be stored as an unsigned 8-bit value with the memory state corresponding to a 0 value being 127.
  436. /// </remarks>
  437. /// <seealso cref="InputControl.stateBlock"/>
  438. public static unsafe bool CheckStateIsAtDefault(this InputControl control)
  439. {
  440. if (control == null)
  441. throw new ArgumentNullException(nameof(control));
  442. return CheckStateIsAtDefault(control, control.currentStatePtr);
  443. }
  444. /// <summary>
  445. /// Check if the given state corresponds to the default state of the control.
  446. /// </summary>
  447. /// <param name="control">Control to check the state for in <paramref name="statePtr"/>.</param>
  448. /// <param name="statePtr">Pointer to a state buffer containing the <see cref="InputControl.stateBlock"/> for <paramref name="control"/>.</param>
  449. /// <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
  450. /// to mask out noise, i.e. every bit that is set in the mask is considered to represent noise.</param>
  451. /// <returns>True if the control/device is in its default state.</returns>
  452. /// <remarks>
  453. /// Note that default does not equate all zeroes. Stick axes, for example, that are stored as unsigned byte
  454. /// values will have their resting position at 127 and not at 0. This is why we explicitly store default
  455. /// state in a memory buffer instead of assuming zeroes.
  456. /// </remarks>
  457. /// <seealso cref="InputControl{TValue}.ReadDefaultValue"/>
  458. public static unsafe bool CheckStateIsAtDefault(this InputControl control, void* statePtr, void* maskPtr = null)
  459. {
  460. if (control == null)
  461. throw new ArgumentNullException(nameof(control));
  462. if (statePtr == null)
  463. throw new ArgumentNullException(nameof(statePtr));
  464. return control.CompareState(statePtr, control.defaultStatePtr, maskPtr);
  465. }
  466. public static unsafe bool CheckStateIsAtDefaultIgnoringNoise(this InputControl control)
  467. {
  468. if (control == null)
  469. throw new ArgumentNullException(nameof(control));
  470. return control.CheckStateIsAtDefaultIgnoringNoise(control.currentStatePtr);
  471. }
  472. /// <summary>
  473. /// Check if the given state corresponds to the default state of the control or has different state only
  474. /// for parts marked as noise.
  475. /// </summary>
  476. /// <param name="control">Control to check the state for in <paramref name="statePtr"/>.</param>
  477. /// <param name="statePtr">Pointer to a state buffer containing the <see cref="InputControl.stateBlock"/> for <paramref name="control"/>.</param>
  478. /// <returns>True if the control/device is in its default state (ignoring any bits marked as noise).</returns>
  479. /// <remarks>
  480. /// Note that default does not equate all zeroes. Stick axes, for example, that are stored as unsigned byte
  481. /// values will have their resting position at 127 and not at 0. This is why we explicitly store default
  482. /// state in a memory buffer instead of assuming zeroes.
  483. /// </remarks>
  484. /// <seealso cref="InputControl{TValue}.ReadDefaultValue"/>
  485. /// <seealso cref="InputControl.noisy"/>
  486. /// <seealso cref="InputControl.noiseMaskPtr"/>
  487. public static unsafe bool CheckStateIsAtDefaultIgnoringNoise(this InputControl control, void* statePtr)
  488. {
  489. if (control == null)
  490. throw new ArgumentNullException(nameof(control));
  491. if (statePtr == null)
  492. throw new ArgumentNullException(nameof(statePtr));
  493. return control.CheckStateIsAtDefault(statePtr, InputStateBuffers.s_NoiseMaskBuffer);
  494. }
  495. /// <summary>
  496. /// Compare the control's current state to the state stored in <paramref name="statePtr"/>.
  497. /// </summary>
  498. /// <param name="statePtr">State memory containing the control's <see cref="InputControl.stateBlock"/>.</param>
  499. /// <returns>True if </returns>
  500. /// <seealso cref="InputControl.currentStatePtr"/>
  501. /// <remarks>
  502. /// This method ignores noise
  503. ///
  504. /// This method will not actually read values but will instead compare state directly as it is stored
  505. /// in memory. <see cref="InputControl{TValue}.ReadValue"/> is not invoked and thus processors will
  506. /// not be run.
  507. /// </remarks>
  508. public static unsafe bool CompareStateIgnoringNoise(this InputControl control, void* statePtr)
  509. {
  510. if (control == null)
  511. throw new ArgumentNullException(nameof(control));
  512. if (statePtr == null)
  513. throw new ArgumentNullException(nameof(statePtr));
  514. return control.CompareState(control.currentStatePtr, statePtr, control.noiseMaskPtr);
  515. }
  516. /// <summary>
  517. /// Compare the control's stored state in <paramref name="firstStatePtr"/> to <paramref name="secondStatePtr"/>.
  518. /// </summary>
  519. /// <param name="firstStatePtr">Memory containing the control's <see cref="InputControl.stateBlock"/>.</param>
  520. /// <param name="secondStatePtr">Memory containing the control's <see cref="InputControl.stateBlock"/></param>
  521. /// <param name="maskPtr">Optional mask. If supplied, it will be used to mask the comparison between
  522. /// <paramref name="firstStatePtr"/> and <paramref name="secondStatePtr"/> such that any bit not set in the
  523. /// mask will be ignored even if different between the two states. This can be used, for example, to ignore
  524. /// noise in the state (<see cref="InputControl.noiseMaskPtr"/>).</param>
  525. /// <returns>True if the state is equivalent in both memory buffers.</returns>
  526. /// <remarks>
  527. /// Unlike <see cref="InputControl.CompareValue"/>, this method only compares raw memory state. If used on a stick, for example,
  528. /// it may mean that this method returns false for two stick values that would compare equal using <see cref="InputControl.CompareValue"/>
  529. /// (e.g. if both stick values fall below the deadzone).
  530. /// </remarks>
  531. /// <seealso cref="InputControl.CompareValue"/>
  532. public static unsafe bool CompareState(this InputControl control, void* firstStatePtr, void* secondStatePtr, void* maskPtr = null)
  533. {
  534. ////REVIEW: for compound controls, do we want to go check leaves so as to not pick up on non-control noise in the state?
  535. //// e.g. from HID input reports; or should we just leave that to maskPtr?
  536. var firstPtr = (byte*)firstStatePtr + (int)control.m_StateBlock.byteOffset;
  537. var secondPtr = (byte*)secondStatePtr + (int)control.m_StateBlock.byteOffset;
  538. var mask = maskPtr != null ? (byte*)maskPtr + (int)control.m_StateBlock.byteOffset : null;
  539. if (control.m_StateBlock.sizeInBits == 1)
  540. {
  541. // If we have a mask and the bit is set in the mask, the control is to be ignored
  542. // and thus we consider it at default value.
  543. if (mask != null && MemoryHelpers.ReadSingleBit(mask, control.m_StateBlock.bitOffset))
  544. return true;
  545. return MemoryHelpers.ReadSingleBit(secondPtr, control.m_StateBlock.bitOffset) ==
  546. MemoryHelpers.ReadSingleBit(firstPtr, control.m_StateBlock.bitOffset);
  547. }
  548. return MemoryHelpers.MemCmpBitRegion(firstPtr, secondPtr,
  549. control.m_StateBlock.bitOffset, control.m_StateBlock.sizeInBits, mask);
  550. }
  551. public static unsafe bool CompareState(this InputControl control, void* statePtr, void* maskPtr = null)
  552. {
  553. if (control == null)
  554. throw new ArgumentNullException(nameof(control));
  555. if (statePtr == null)
  556. throw new ArgumentNullException(nameof(statePtr));
  557. return control.CompareState(control.currentStatePtr, statePtr, maskPtr);
  558. }
  559. /// <summary>
  560. /// Return true if the current value of <paramref name="control"/> is different to the one found
  561. /// in <paramref name="statePtr"/>.
  562. /// </summary>
  563. /// <param name="control">Control whose state to compare to what is stored in <paramref name="statePtr"/>.</param>
  564. /// <param name="statePtr">A block of input state memory containing the <see cref="InputControl.stateBlock"/>
  565. /// of <paramref name="control."/></param>
  566. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c> or <paramref name="statePtr"/>
  567. /// is <c>null</c>.</exception>
  568. /// <returns>True if the value of <paramref name="control"/> stored in <paramref name="statePtr"/> is different
  569. /// compared to what <see cref="InputControl{T}.ReadValue"/> of the control returns.</returns>
  570. public static unsafe bool HasValueChangeInState(this InputControl control, void* statePtr)
  571. {
  572. if (control == null)
  573. throw new ArgumentNullException(nameof(control));
  574. if (statePtr == null)
  575. throw new ArgumentNullException(nameof(statePtr));
  576. return control.CompareValue(control.currentStatePtr, statePtr);
  577. }
  578. /// <summary>
  579. /// Return true if <paramref name="control"/> has a different value (from its current one) in
  580. /// <paramref name="eventPtr"/>.
  581. /// </summary>
  582. /// <param name="control">An input control.</param>
  583. /// <param name="eventPtr">An input event. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  584. /// <returns>True if <paramref name="eventPtr"/> contains a value for <paramref name="control"/> that is different
  585. /// from the control's current value (see <see cref="InputControl{TValue}.ReadValue"/>).</returns>
  586. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c> -or- <paramref name="eventPtr"/> is a <c>null</c> pointer (see <see cref="InputEventPtr.valid"/>).</exception>
  587. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  588. public static unsafe bool HasValueChangeInEvent(this InputControl control, InputEventPtr eventPtr)
  589. {
  590. if (control == null)
  591. throw new ArgumentNullException(nameof(control));
  592. if (!eventPtr.valid)
  593. throw new ArgumentNullException(nameof(eventPtr));
  594. var statePtr = control.GetStatePtrFromStateEvent(eventPtr);
  595. if (statePtr == null)
  596. return false;
  597. return control.CompareValue(control.currentStatePtr, statePtr);
  598. }
  599. /// <summary>
  600. /// Given a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>, return the raw memory pointer that can
  601. /// be used, for example, with <see cref="InputControl{T}.ReadValueFromState"/> to read out the value of <paramref name="control"/>
  602. /// contained in the event.
  603. /// </summary>
  604. /// <param name="control">Control to access state for in the given state event.</param>
  605. /// <param name="eventPtr">A <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/> containing input state.</param>
  606. /// <returns>A pointer that can be used with methods such as <see cref="InputControl{TValue}.ReadValueFromState"/> or <c>null</c>
  607. /// if <paramref name="eventPtr"/> does not contain state for the given <paramref name="control"/>.</returns>
  608. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c> -or- <paramref name="eventPtr"/> is invalid.</exception>
  609. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  610. /// <remarks>
  611. /// Note that the given state event must have the same state format (see <see cref="InputStateBlock.format"/>) as the device
  612. /// to which <paramref name="control"/> belongs. If this is not the case, the method will invariably return <c>null</c>.
  613. ///
  614. /// In practice, this means that the method cannot be used with touch events or, in general, with events sent to devices
  615. /// that implement <see cref="IInputStateCallbackReceiver"/> (which <see cref="Touchscreen"/> does) except if the event
  616. /// is in the same state format as the device. Touch events will generally be sent as state events containing only the
  617. /// state of a single <see cref="Controls.TouchControl"/>, not the state of the entire <see cref="Touchscreen"/>.
  618. /// </remarks>
  619. public static unsafe void* GetStatePtrFromStateEvent(this InputControl control, InputEventPtr eventPtr)
  620. {
  621. if (control == null)
  622. throw new ArgumentNullException(nameof(control));
  623. if (!eventPtr.valid)
  624. throw new ArgumentNullException(nameof(eventPtr));
  625. return GetStatePtrFromStateEventUnchecked(control, eventPtr, eventPtr.type);
  626. }
  627. internal static unsafe void* GetStatePtrFromStateEventUnchecked(this InputControl control, InputEventPtr eventPtr, FourCC eventType)
  628. {
  629. uint stateOffset;
  630. FourCC stateFormat;
  631. uint stateSizeInBytes;
  632. void* statePtr;
  633. if (eventType == StateEvent.Type)
  634. {
  635. var stateEvent = StateEvent.FromUnchecked(eventPtr);
  636. stateOffset = 0;
  637. stateFormat = stateEvent->stateFormat;
  638. stateSizeInBytes = stateEvent->stateSizeInBytes;
  639. statePtr = stateEvent->state;
  640. }
  641. else if (eventType == DeltaStateEvent.Type)
  642. {
  643. var deltaEvent = DeltaStateEvent.FromUnchecked(eventPtr);
  644. // 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
  645. stateOffset = deltaEvent->stateOffset;
  646. stateFormat = deltaEvent->stateFormat;
  647. stateSizeInBytes = deltaEvent->deltaStateSizeInBytes;
  648. statePtr = deltaEvent->deltaState;
  649. }
  650. else
  651. {
  652. throw new ArgumentException($"Event must be a StateEvent or DeltaStateEvent but is a {eventType} instead",
  653. nameof(eventPtr));
  654. }
  655. // Make sure we have a state event compatible with our device. The event doesn't
  656. // have to be specifically for our device (we don't require device IDs to match) but
  657. // the formats have to match and the size must be within range of what we're trying
  658. // to read.
  659. var device = control.device;
  660. if (stateFormat != device.m_StateBlock.format)
  661. {
  662. // If the device is an IInputStateCallbackReceiver, there's a chance it actually recognizes
  663. // the state format in the event and can correlate it to the state as found on the device.
  664. if (!device.hasStateCallbacks ||
  665. !((IInputStateCallbackReceiver)device).GetStateOffsetForEvent(control, eventPtr, ref stateOffset))
  666. return null;
  667. }
  668. // Once a device has been added, global state buffer offsets are baked into control hierarchies.
  669. // We need to unsubtract those offsets here.
  670. // NOTE: If the given device has not actually been added to the system, the offset is simply 0
  671. // and this is a harmless NOP.
  672. stateOffset += device.m_StateBlock.byteOffset;
  673. // Return null if state is out of range.
  674. ref var controlStateBlock = ref control.m_StateBlock;
  675. var controlOffset = (int)controlStateBlock.effectiveByteOffset - stateOffset;
  676. if (controlOffset < 0 || controlOffset + controlStateBlock.alignedSizeInBytes > stateSizeInBytes)
  677. return null;
  678. return (byte*)statePtr - (int)stateOffset;
  679. }
  680. /// <summary>
  681. /// Writes the default state of <paramref name="control"/> into <paramref name="eventPtr"/>.
  682. /// </summary>
  683. /// <param name="control">A control whose default state to write.</param>
  684. /// <param name="eventPtr">A valid pointer to either a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  685. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c> -or- <paramref name="eventPtr"/> contains
  686. /// a null pointer.</exception>
  687. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</exception>
  688. /// <returns>True if the default state for <paramref name="control"/> was written to <paramref name="eventPtr"/>, false if the
  689. /// given state or delta state event did not include memory for the given control.</returns>
  690. /// <remarks>
  691. /// Note that the default state of a control does not necessarily need to correspond to zero-initialized memory. For example, if
  692. /// an axis control yields a range of [-1..1] and is stored as a signed 8-bit value, the default state will be 127, not 0.
  693. ///
  694. /// <example>
  695. /// <code>
  696. /// // Reset the left gamepad stick to its default state (which results in a
  697. /// // value of (0,0).
  698. /// using (StateEvent.From(Gamepad.all[0], out var eventPtr))
  699. /// {
  700. /// Gamepad.all[0].leftStick.ResetToDefaultStateInEvent(eventPtr);
  701. /// InputSystem.QueueEvent(eventPtr);
  702. /// }
  703. /// </code>
  704. /// </example>
  705. /// </remarks>
  706. /// <seealso cref="InputControl.defaultStatePtr"/>
  707. public static unsafe bool ResetToDefaultStateInEvent(this InputControl control, InputEventPtr eventPtr)
  708. {
  709. if (control == null)
  710. throw new ArgumentNullException(nameof(control));
  711. if (!eventPtr.valid)
  712. throw new ArgumentNullException(nameof(eventPtr));
  713. var eventType = eventPtr.type;
  714. if (eventType != StateEvent.Type && eventType != DeltaStateEvent.Type)
  715. throw new ArgumentException("Given event is not a StateEvent or a DeltaStateEvent", nameof(eventPtr));
  716. var statePtr = (byte*)control.GetStatePtrFromStateEvent(eventPtr);
  717. if (statePtr == null)
  718. return false;
  719. var defaultStatePtr = (byte*)control.defaultStatePtr;
  720. ref var stateBlock = ref control.m_StateBlock;
  721. var offset = stateBlock.byteOffset;
  722. MemoryHelpers.MemCpyBitRegion(statePtr + offset, defaultStatePtr + offset, stateBlock.bitOffset, stateBlock.sizeInBits);
  723. return true;
  724. }
  725. /// <summary>
  726. /// Queue a value change on the given <paramref name="control"/> which will be processed and take effect
  727. /// in the next input update.
  728. /// </summary>
  729. /// <param name="control">Control to change the value of.</param>
  730. /// <param name="value">New value for the control.</param>
  731. /// <param name="time">Optional time at which the value change should take effect. If set, this will become
  732. /// the <see cref="InputEvent.time"/> of the queued event. If the time is in the future and the update mode is
  733. /// set to <see cref="InputSettings.UpdateMode.ProcessEventsInFixedUpdate"/>, the event will not be processed until
  734. /// it falls within the time of an input update slice. Otherwise, the event will invariably be consumed in the
  735. /// next input update (see <see cref="InputSystem.Update"/>).</param>
  736. /// <typeparam name="TValue">Type of value.</typeparam>
  737. /// <exception cref="ArgumentNullException"><paramref name="control"/> is null.</exception>
  738. public static void QueueValueChange<TValue>(this InputControl<TValue> control, TValue value, double time = -1)
  739. where TValue : struct
  740. {
  741. if (control == null)
  742. throw new ArgumentNullException(nameof(control));
  743. ////TODO: if it's not a bit-addressing control, send a delta state change only
  744. using (StateEvent.From(control.device, out var eventPtr))
  745. {
  746. if (time >= 0)
  747. eventPtr.time = time;
  748. control.WriteValueIntoEvent(value, eventPtr);
  749. InputSystem.QueueEvent(eventPtr);
  750. }
  751. }
  752. /// <summary>
  753. /// Modify <paramref name="newState"/> to write an accumulated value of the control
  754. /// rather than the value currently found in the event.
  755. /// </summary>
  756. /// <param name="control">Control to perform the accumulation on.</param>
  757. /// <param name="currentStatePtr">Memory containing the control's current state. See <see
  758. /// cref="InputControl.currentStatePtr"/>.</param>
  759. /// <param name="newState">Event containing the new state about to be written to the device.</param>
  760. /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception>
  761. /// <remarks>
  762. /// This method reads the current, unprocessed value of the control from <see cref="InputControl.currentStatePtr"/>
  763. /// and then adds it to the value of the control found in <paramref name="newState"/>.
  764. ///
  765. /// Note that the method does nothing if a value for the control is not contained in <paramref name="newState"/>.
  766. /// This can be the case, for example, for <see cref="DeltaStateEvent"/>s.
  767. /// </remarks>
  768. /// <seealso cref="Pointer.delta"/>
  769. public static unsafe void AccumulateValueInEvent(this InputControl<float> control, void* currentStatePtr, InputEventPtr newState)
  770. {
  771. if (control == null)
  772. throw new ArgumentNullException(nameof(control));
  773. if (!control.ReadUnprocessedValueFromEvent(newState, out var newValue))
  774. return; // Value for the control not contained in the given event.
  775. var oldValue = control.ReadUnprocessedValueFromState(currentStatePtr);
  776. control.WriteValueIntoEvent(oldValue + newValue, newState);
  777. }
  778. internal static unsafe void AccumulateValueInEvent(this InputControl<Vector2> control, void* currentStatePtr, InputEventPtr newState)
  779. {
  780. if (control == null)
  781. throw new ArgumentNullException(nameof(control));
  782. if (!control.ReadUnprocessedValueFromEvent(newState, out var newValue))
  783. return; // Value for the control not contained in the given event.
  784. var oldDelta = control.ReadUnprocessedValueFromState(currentStatePtr);
  785. control.WriteValueIntoEvent(oldDelta + newValue, newState);
  786. }
  787. public static void FindControlsRecursive<TControl>(this InputControl parent, IList<TControl> controls, Func<TControl, bool> predicate)
  788. where TControl : InputControl
  789. {
  790. if (parent == null)
  791. throw new ArgumentNullException(nameof(parent));
  792. if (controls == null)
  793. throw new ArgumentNullException(nameof(controls));
  794. if (predicate == null)
  795. throw new ArgumentNullException(nameof(predicate));
  796. if (parent is TControl parentAsTControl && predicate(parentAsTControl))
  797. controls.Add(parentAsTControl);
  798. var children = parent.children;
  799. var childCount = children.Count;
  800. for (var i = 0; i < childCount; ++i)
  801. {
  802. var child = parent.children[i];
  803. FindControlsRecursive(child, controls, predicate);
  804. }
  805. }
  806. internal static string BuildPath(this InputControl control, string deviceLayout, StringBuilder builder = null)
  807. {
  808. if (control == null)
  809. throw new ArgumentNullException(nameof(control));
  810. if (string.IsNullOrEmpty(deviceLayout))
  811. throw new ArgumentNullException(nameof(deviceLayout));
  812. if (builder == null)
  813. builder = new StringBuilder();
  814. var device = control.device;
  815. builder.Append('<');
  816. builder.Append(deviceLayout.Escape("\\>", "\\>"));
  817. builder.Append('>');
  818. // Add usages of device, if any.
  819. var deviceUsages = device.usages;
  820. for (var i = 0; i < deviceUsages.Count; ++i)
  821. {
  822. builder.Append('{');
  823. builder.Append(deviceUsages[i].ToString().Escape("\\}", "\\}"));
  824. builder.Append('}');
  825. }
  826. builder.Append(InputControlPath.Separator);
  827. // If any of the components contains a backslash, double it up as in control paths,
  828. // these serve as escape characters.
  829. var devicePath = device.path.Replace("\\", "\\\\");
  830. var controlPath = control.path.Replace("\\", "\\\\");
  831. builder.Append(controlPath, devicePath.Length + 1, controlPath.Length - devicePath.Length - 1);
  832. return builder.ToString();
  833. }
  834. /// <summary>
  835. /// Flags that control which controls are returned by <see cref="InputControlExtensions.EnumerateControls"/>.
  836. /// </summary>
  837. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1714:Flags enums should have plural names", Justification = "False positive: `IgnoreControlsInDefaultState` is a plural form.")]
  838. [Flags]
  839. public enum Enumerate
  840. {
  841. /// <summary>
  842. /// Ignore controls whose value is at default (see <see cref="InputControl{TValue}.ReadDefaultValue"/>).
  843. /// </summary>
  844. IgnoreControlsInDefaultState = 1 << 0,
  845. /// <summary>
  846. /// Ignore controls whose value is the same as their current value (see <see cref="InputControl{TValue}.ReadValue"/>).
  847. /// </summary>
  848. IgnoreControlsInCurrentState = 1 << 1,
  849. /// <summary>
  850. /// Include controls that are <see cref="InputControl.synthetic"/> and/or use state from other other controls (see
  851. /// <see cref="Layouts.InputControlLayout.ControlItem.useStateFrom"/>). These are excluded by default.
  852. /// </summary>
  853. IncludeSyntheticControls = 1 << 2,
  854. /// <summary>
  855. /// Include noisy controls (see <see cref="InputControl.noisy"/>). These are excluded by default.
  856. /// </summary>
  857. IncludeNoisyControls = 1 << 3,
  858. /// <summary>
  859. /// For any leaf control returned by the enumeration, also return all the parent controls (see <see cref="InputControl.parent"/>)
  860. /// in turn (but not the root <see cref="InputDevice"/> itself).
  861. /// </summary>
  862. IncludeNonLeafControls = 1 << 4,
  863. }
  864. /// <summary>
  865. /// Go through the controls that have values in <paramref name="eventPtr"/>, apply the given filters, and return each
  866. /// control one by one.
  867. /// </summary>
  868. /// <param name="eventPtr">An input event. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  869. /// <param name="flags">Filter settings that determine which controls to return.</param>
  870. /// <param name="device">Input device from which to enumerate controls. If this is <c>null</c>, then the <see cref="InputEvent.deviceId"/>
  871. /// from the given <paramref name="eventPtr"/> will be used to locate the device via <see cref="InputSystem.GetDeviceById"/>. If the device
  872. /// cannot be found, an exception will be thrown. Note that type of device must match the state stored in the given event.</param>
  873. /// <param name="magnitudeThreshold">If not zero, minimum actuation threshold (see <see cref="InputControl.EvaluateMagnitude()"/>) that
  874. /// a control must reach (as per value in the given <paramref name="eventPtr"/>) in order for it to be included in the enumeration.</param>
  875. /// <returns>An enumerator for the controls with values in <paramref name="eventPtr"/>.</returns>
  876. /// <exception cref="ArgumentNullException"><paramref name="eventPtr"/> is a <c>null</c> pointer (see <see cref="InputEventPtr.valid"/>).</exception>
  877. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is not a <see cref="StateEvent"/> and not a <see cref="DeltaStateEvent"/> -or-
  878. /// <paramref name="device"/> is <c>null</c> and no device was found with a <see cref="InputDevice.deviceId"/> matching that of <see cref="InputEvent.deviceId"/>
  879. /// found in <paramref name="eventPtr"/>.</exception>
  880. /// <remarks>
  881. /// This method is much more efficient than manually iterating over the controls of <paramref name="device"/> and locating
  882. /// the ones that have changed in <paramref name="eventPtr"/>. See <see cref="InputEventControlEnumerator"/> for details.
  883. ///
  884. /// This method will not allocate GC memory and can safely be used with <c>foreach</c> loops.
  885. /// </remarks>
  886. /// <seealso cref="InputEventControlEnumerator"/>
  887. /// <seealso cref="StateEvent"/>
  888. /// <seealso cref="DeltaStateEvent"/>
  889. /// <seealso cref="EnumerateChangedControls"/>
  890. public static InputEventControlCollection EnumerateControls(this InputEventPtr eventPtr, Enumerate flags, InputDevice device = null, float magnitudeThreshold = 0)
  891. {
  892. if (!eventPtr.valid)
  893. throw new ArgumentNullException(nameof(eventPtr), "Given event pointer must not be null");
  894. var eventType = eventPtr.type;
  895. if (eventType != StateEvent.Type && eventType != DeltaStateEvent.Type)
  896. throw new ArgumentException($"Event must be a StateEvent or DeltaStateEvent but is a {eventType} instead", nameof(eventPtr));
  897. // Look up device from event, if no device was supplied.
  898. if (device == null)
  899. {
  900. var deviceId = eventPtr.deviceId;
  901. device = InputSystem.GetDeviceById(deviceId);
  902. if (device == null)
  903. throw new ArgumentException($"Cannot find device with ID {deviceId} referenced by event", nameof(eventPtr));
  904. }
  905. return new InputEventControlCollection { m_Device = device, m_EventPtr = eventPtr, m_Flags = flags, m_MagnitudeThreshold = magnitudeThreshold };
  906. }
  907. /// <summary>
  908. /// Go through all controls in the given <paramref name="eventPtr"/> that have changed value.
  909. /// </summary>
  910. /// <param name="eventPtr">An input event. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  911. /// <param name="device">Input device from which to enumerate controls. If this is <c>null</c>, then the <see cref="InputEvent.deviceId"/>
  912. /// from the given <paramref name="eventPtr"/> will be used to locate the device via <see cref="InputSystem.GetDeviceById"/>. If the device
  913. /// cannot be found, an exception will be thrown. Note that type of device must match the state stored in the given event.</param>
  914. /// <param name="magnitudeThreshold">If not zero, minimum actuation threshold (see <see cref="InputControl.EvaluateMagnitude()"/>) that
  915. /// a control must reach (as per value in the given <paramref name="eventPtr"/>) in order for it to be included in the enumeration.</param>
  916. /// <returns>An enumerator for the controls that have changed values in <paramref name="eventPtr"/>.</returns>
  917. /// <remarks>
  918. /// This method is a shorthand for calling <see cref="EnumerateControls"/> with <see cref="Enumerate.IgnoreControlsInCurrentState"/>.
  919. ///
  920. /// <example>
  921. /// <code>
  922. /// // Detect button presses.
  923. /// InputSystem.onEvent +=
  924. /// (eventPtr, device) =>
  925. /// {
  926. /// // Ignore anything that is not a state event.
  927. /// var eventType = eventPtr.type;
  928. /// if (eventType != StateEvent.Type &amp;&amp; eventType != DeltaStateEvent.Type)
  929. /// return;
  930. ///
  931. /// // Find all changed controls actuated above the button press threshold.
  932. /// foreach (var control in eventPtr.EnumerateChangedControls
  933. /// (device: device, magnitudeThreshold: InputSystem.settings.defaultButtonPressThreshold))
  934. /// if (control is ButtonControl button)
  935. /// Debug.Log($"Button {button} was pressed");
  936. /// }
  937. /// </code>
  938. /// </example>
  939. /// </remarks>
  940. /// <seealso cref="InputSystem.onEvent"/>
  941. /// <seealso cref="EnumerateControls"/>
  942. /// <seealso cref="InputEventControlEnumerator"/>
  943. public static InputEventControlCollection EnumerateChangedControls(this InputEventPtr eventPtr, InputDevice device = null, float magnitudeThreshold = 0)
  944. {
  945. return eventPtr.EnumerateControls
  946. (Enumerate.IgnoreControlsInCurrentState, device, magnitudeThreshold);
  947. }
  948. /// <summary>
  949. /// Return true if the given <paramref name="eventPtr"/> has any <see cref="Input"/>
  950. /// </summary>
  951. /// <param name="eventPtr">An event. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  952. /// <param name="magnitude">The threshold value that a button must be actuated by to be considered pressed.</param>
  953. /// <param name="buttonControlsOnly">Whether the method should only consider button controls.</param>
  954. /// <returns></returns>
  955. /// <exception cref="ArgumentNullException"><paramref name="eventPtr"/> is a <c>null</c> pointer.</exception>
  956. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/> -or-
  957. /// the <see cref="InputDevice"/> referenced by the <see cref="InputEvent.deviceId"/> in the event cannot be found.</exception>
  958. /// <seealso cref="EnumerateChangedControls"/>
  959. /// <seealso cref="ButtonControl.isPressed"/>
  960. public static bool HasButtonPress(this InputEventPtr eventPtr, float magnitude = -1, bool buttonControlsOnly = true)
  961. {
  962. return eventPtr.GetFirstButtonPressOrNull(magnitude, buttonControlsOnly) != null;
  963. }
  964. /// <summary>
  965. /// Get the first pressed button from the given event or null if the event doesn't contain a new button press.
  966. /// </summary>
  967. /// <param name="eventPtr">An event. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  968. /// <param name="magnitude">The threshold value that a control must be actuated by (see
  969. /// <see cref="InputControl.EvaluateMagnitude()"/>) to be considered pressed. If not given, defaults to <see
  970. /// cref="InputSettings.defaultButtonPressPoint"/>.</param>
  971. /// <param name="buttonControlsOnly">Whether the method should only consider <see cref="ButtonControl"/>s. Otherwise,
  972. /// any <see cref="InputControl"/> that has an actuation (see <see cref="InputControl.EvaluateMagnitude()"/>) equal to
  973. /// or greater than the given <paramref name="magnitude"/> will be considered a pressed button. This is 'true' by
  974. /// default.</param>
  975. /// <returns>The control that was pressed.</returns>
  976. /// <exception cref="ArgumentNullException"><paramref name="eventPtr"/> is a <c>null</c> pointer.</exception>
  977. /// <exception cref="ArgumentException">The <see cref="InputDevice"/> referenced by the <see cref="InputEvent.deviceId"/> in the event cannot
  978. /// be found.</exception>
  979. /// <seealso cref="EnumerateChangedControls"/>
  980. /// <seealso cref="ButtonControl.isPressed"/>
  981. /// <remarks>Buttons will be evaluated in the order that they appear in the devices layout i.e. the bit position of each control
  982. /// in the devices state memory. For example, in the gamepad state, button north (bit position 4) will be evaluated before button
  983. /// east (bit position 5), so if both buttons were pressed in the given event, button north would be returned.
  984. /// Note that the function returns null if the <paramref name="eventPtr"/> is not a StateEvent or DeltaStateEvent.</remarks>
  985. public static InputControl GetFirstButtonPressOrNull(this InputEventPtr eventPtr, float magnitude = -1, bool buttonControlsOnly = true)
  986. {
  987. if (eventPtr.type != StateEvent.Type && eventPtr.type != DeltaStateEvent.Type)
  988. return null;
  989. if (magnitude < 0)
  990. magnitude = InputSystem.settings.defaultButtonPressPoint;
  991. foreach (var control in eventPtr.EnumerateControls(Enumerate.IgnoreControlsInDefaultState, magnitudeThreshold: magnitude))
  992. {
  993. if (buttonControlsOnly && !control.isButton)
  994. continue;
  995. return control;
  996. }
  997. return null;
  998. }
  999. /// <summary>
  1000. /// Enumerate all pressed buttons in the given event.
  1001. /// </summary>
  1002. /// <param name="eventPtr">An event. Must be a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</param>
  1003. /// <param name="magnitude">The threshold value that a button must be actuated by to be considered pressed.</param>
  1004. /// <param name="buttonControlsOnly">Whether the method should only consider button controls.</param>
  1005. /// <returns>An enumerable collection containing all buttons that were pressed in the given event.</returns>
  1006. /// <exception cref="ArgumentNullException"><paramref name="eventPtr"/> is a <c>null</c> pointer.</exception>
  1007. /// <exception cref="ArgumentException">The <see cref="InputDevice"/> referenced by the <see cref="InputEvent.deviceId"/> in the event cannot be found.</exception>
  1008. /// <remarks>Returns an empty enumerable if the <paramref name="eventPtr"/> is not a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.</remarks>
  1009. /// <seealso cref="EnumerateChangedControls"/>
  1010. /// <seealso cref="ButtonControl.isPressed"/>
  1011. public static IEnumerable<InputControl> GetAllButtonPresses(this InputEventPtr eventPtr, float magnitude = -1, bool buttonControlsOnly = true)
  1012. {
  1013. if (eventPtr.type != StateEvent.Type && eventPtr.type != DeltaStateEvent.Type)
  1014. yield break;
  1015. if (magnitude < 0)
  1016. magnitude = InputSystem.settings.defaultButtonPressPoint;
  1017. foreach (var control in eventPtr.EnumerateControls(Enumerate.IgnoreControlsInDefaultState, magnitudeThreshold: magnitude))
  1018. {
  1019. if (buttonControlsOnly && !control.isButton)
  1020. continue;
  1021. yield return control;
  1022. }
  1023. }
  1024. /// <summary>
  1025. /// Allows iterating over the controls referenced by an <see cref="InputEvent"/> via <see cref="InputEventControlEnumerator"/>.
  1026. /// </summary>
  1027. /// <seealso cref="InputControlExtensions.EnumerateControls"/>
  1028. /// <seealso cref="InputControlExtensions.EnumerateChangedControls"/>
  1029. public struct InputEventControlCollection : IEnumerable<InputControl>
  1030. {
  1031. internal InputDevice m_Device;
  1032. internal InputEventPtr m_EventPtr;
  1033. internal Enumerate m_Flags;
  1034. internal float m_MagnitudeThreshold;
  1035. /// <summary>
  1036. /// The event being iterated over. A <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>.
  1037. /// </summary>
  1038. public InputEventPtr eventPtr => m_EventPtr;
  1039. /// <summary>
  1040. /// Enumerate the controls in the event.
  1041. /// </summary>
  1042. /// <returns>An enumerator.</returns>
  1043. public InputEventControlEnumerator GetEnumerator()
  1044. {
  1045. return new InputEventControlEnumerator(m_EventPtr, m_Device, m_Flags, m_MagnitudeThreshold);
  1046. }
  1047. IEnumerator<InputControl> IEnumerable<InputControl>.GetEnumerator()
  1048. {
  1049. return GetEnumerator();
  1050. }
  1051. IEnumerator IEnumerable.GetEnumerator()
  1052. {
  1053. return GetEnumerator();
  1054. }
  1055. }
  1056. /// <summary>
  1057. /// Iterates over the controls in a <see cref="StateEvent"/> or <see cref="DeltaStateEvent"/>
  1058. /// while optionally applying certain filtering criteria.
  1059. /// </summary>
  1060. /// <remarks>
  1061. /// One problem with state events (that is, <see cref="StateEvent"/> and <see cref="DeltaStateEvent"/>)
  1062. /// is that they contain raw blocks of memory which may contain state changes for arbitrary many
  1063. /// controls on a device at the same time. Locating individual controls and determining which have
  1064. /// changed state and how can thus be quite inefficient.
  1065. ///
  1066. /// This helper aims to provide an easy and efficient way to iterate over controls relevant to a
  1067. /// given state event. Instead of iterating over the controls of a device looking for the ones
  1068. /// relevant to a given event, enumeration is done the opposite by efficiently searching through
  1069. /// the memory contained in an event and then mapping data found in the event back to controls
  1070. /// on a given device.
  1071. ///
  1072. /// <example>
  1073. /// <code>
  1074. /// // Inefficient:
  1075. /// foreach (var control in device.allControls)
  1076. /// {
  1077. /// // Skip control if it is noisy, synthetic, or not a leaf control.
  1078. /// if (control.synthetic || control.noisy || control.children.Count > 0)
  1079. /// continue;
  1080. ///
  1081. /// // Locate the control in the event.
  1082. /// var statePtr = eventPtr.GetStatePtrFromStateEvent(eventPtr);
  1083. /// if (statePtr == null)
  1084. /// continue; // Control not included in event.
  1085. ///
  1086. /// // See if the control is actuated beyond a minimum threshold.
  1087. /// if (control.EvaluateMagnitude(statePtr) &lt; 0.001f)
  1088. /// continue;
  1089. ///
  1090. /// Debug.Log($"Found actuated control {control}");
  1091. /// }
  1092. ///
  1093. /// // Much more efficient:
  1094. /// foreach (var control in eventPtr.EnumerateControls(
  1095. /// InputControlExtensions.Enumerate.IgnoreControlsInDefaultState,
  1096. /// device: device,
  1097. /// magnitudeThreshold: 0.001f))
  1098. /// {
  1099. /// Debug.Log($"Found actuated control {control}");
  1100. /// }
  1101. /// </code>
  1102. /// </example>
  1103. /// </remarks>
  1104. /// <seealso cref="InputControlExtensions.EnumerateControls"/>
  1105. /// <seealso cref="InputControlExtensions.EnumerateChangedControls"/>
  1106. public unsafe struct InputEventControlEnumerator : IEnumerator<InputControl>
  1107. {
  1108. private Enumerate m_Flags;
  1109. private readonly InputDevice m_Device;
  1110. private readonly uint[] m_StateOffsetToControlIndex;
  1111. private readonly int m_StateOffsetToControlIndexLength;
  1112. private readonly InputControl[] m_AllControls;
  1113. private byte* m_DefaultState; // Already offset by device offset.
  1114. private byte* m_CurrentState;
  1115. private byte* m_NoiseMask; // Already offset by device offset.
  1116. private InputEventPtr m_EventPtr;
  1117. private InputControl m_CurrentControl;
  1118. private int m_CurrentIndexInStateOffsetToControlIndexMap;
  1119. private uint m_CurrentControlStateBitOffset;
  1120. private byte* m_EventState;
  1121. private uint m_CurrentBitOffset;
  1122. private uint m_EndBitOffset;
  1123. private float m_MagnitudeThreshold;
  1124. internal InputEventControlEnumerator(InputEventPtr eventPtr, InputDevice device, Enumerate flags, float magnitudeThreshold = 0)
  1125. {
  1126. Debug.Assert(eventPtr.valid, "eventPtr should be valid at this point");
  1127. Debug.Assert(device != null, "Need to have valid device at this point");
  1128. m_Device = device;
  1129. m_StateOffsetToControlIndex = device.m_StateOffsetToControlMap;
  1130. m_StateOffsetToControlIndexLength = m_StateOffsetToControlIndex.LengthSafe();
  1131. m_AllControls = device.m_ChildrenForEachControl;
  1132. m_EventPtr = eventPtr;
  1133. m_Flags = flags;
  1134. m_CurrentControl = null;
  1135. m_CurrentIndexInStateOffsetToControlIndexMap = default;
  1136. m_CurrentControlStateBitOffset = 0;
  1137. m_EventState = default;
  1138. m_CurrentBitOffset = default;
  1139. m_EndBitOffset = default;
  1140. m_MagnitudeThreshold = magnitudeThreshold;
  1141. if ((flags & Enumerate.IncludeNoisyControls) == 0)
  1142. m_NoiseMask = (byte*)device.noiseMaskPtr + device.m_StateBlock.byteOffset;
  1143. else
  1144. m_NoiseMask = default;
  1145. if ((flags & Enumerate.IgnoreControlsInDefaultState) != 0)
  1146. m_DefaultState = (byte*)device.defaultStatePtr + device.m_StateBlock.byteOffset;
  1147. else
  1148. m_DefaultState = default;
  1149. if ((flags & Enumerate.IgnoreControlsInCurrentState) != 0)
  1150. m_CurrentState = (byte*)device.currentStatePtr + device.m_StateBlock.byteOffset;
  1151. else
  1152. m_CurrentState = default;
  1153. Reset();
  1154. }
  1155. private bool CheckDefault(uint numBits)
  1156. {
  1157. return MemoryHelpers.MemCmpBitRegion(m_EventState, m_DefaultState, m_CurrentBitOffset, numBits, m_NoiseMask);
  1158. }
  1159. private bool CheckCurrent(uint numBits)
  1160. {
  1161. return MemoryHelpers.MemCmpBitRegion(m_EventState, m_CurrentState, m_CurrentBitOffset, numBits, m_NoiseMask);
  1162. }
  1163. public bool MoveNext()
  1164. {
  1165. if (!m_EventPtr.valid)
  1166. throw new ObjectDisposedException("Enumerator has already been disposed");
  1167. // If we are to include non-leaf controls and we have a current control, walk
  1168. // up the tree until we reach the device.
  1169. if (m_CurrentControl != null && (m_Flags & Enumerate.IncludeNonLeafControls) != 0)
  1170. {
  1171. var parent = m_CurrentControl.parent;
  1172. if (parent != m_Device)
  1173. {
  1174. m_CurrentControl = parent;
  1175. return true;
  1176. }
  1177. }
  1178. var ignoreDefault = m_DefaultState != null;
  1179. var ignoreCurrent = m_CurrentState != null;
  1180. // Search for the next control that matches our filter criteria.
  1181. while (true)
  1182. {
  1183. m_CurrentControl = null;
  1184. // If we are ignoring certain state values, try to skip over as much memory as we can.
  1185. if (ignoreCurrent || ignoreDefault)
  1186. {
  1187. // If we are not byte-aligned, search whatever bits are left in the current byte.
  1188. if ((m_CurrentBitOffset & 0x7) != 0)
  1189. {
  1190. var bitsLeftInByte = (m_CurrentBitOffset + 8) & 0x7;
  1191. if ((ignoreCurrent && CheckCurrent(bitsLeftInByte))
  1192. || (ignoreDefault && CheckDefault(bitsLeftInByte)))
  1193. m_CurrentBitOffset += bitsLeftInByte;
  1194. }
  1195. // Search byte by byte.
  1196. while (m_CurrentBitOffset < m_EndBitOffset)
  1197. {
  1198. var byteOffset = m_CurrentBitOffset >> 3;
  1199. var eventByte = m_EventState[byteOffset];
  1200. var maskByte = m_NoiseMask != null ? m_NoiseMask[byteOffset] : 0xff;
  1201. if (ignoreCurrent)
  1202. {
  1203. var currentByte = m_CurrentState[byteOffset];
  1204. if ((currentByte & maskByte) == (eventByte & maskByte))
  1205. {
  1206. m_CurrentBitOffset += 8;
  1207. continue;
  1208. }
  1209. }
  1210. if (ignoreDefault)
  1211. {
  1212. var defaultByte = m_DefaultState[byteOffset];
  1213. if ((defaultByte & maskByte) == (eventByte & maskByte))
  1214. {
  1215. m_CurrentBitOffset += 8;
  1216. continue;
  1217. }
  1218. }
  1219. break;
  1220. }
  1221. }
  1222. // See if we've reached the end.
  1223. if (m_CurrentBitOffset >= m_EndBitOffset
  1224. || m_CurrentIndexInStateOffsetToControlIndexMap >= m_StateOffsetToControlIndexLength) // No more controls.
  1225. return false;
  1226. // No, so find the control at the current bit offset.
  1227. for (;
  1228. m_CurrentIndexInStateOffsetToControlIndexMap < m_StateOffsetToControlIndexLength;
  1229. ++m_CurrentIndexInStateOffsetToControlIndexMap)
  1230. {
  1231. InputDevice.DecodeStateOffsetToControlMapEntry(
  1232. m_StateOffsetToControlIndex[m_CurrentIndexInStateOffsetToControlIndexMap],
  1233. out var controlIndex,
  1234. out var controlBitOffset,
  1235. out var controlBitSize);
  1236. // If the control's bit region lies *before* the memory we're looking at,
  1237. // skip it.
  1238. if (controlBitOffset < m_CurrentControlStateBitOffset ||
  1239. m_CurrentBitOffset >= (controlBitOffset + controlBitSize - m_CurrentControlStateBitOffset))
  1240. continue;
  1241. // If the bit region we're looking at lies *before* the current control,
  1242. // keep searching through memory.
  1243. if ((controlBitOffset - m_CurrentControlStateBitOffset) >= m_CurrentBitOffset + 8)
  1244. {
  1245. // Jump to location of control.
  1246. m_CurrentBitOffset = controlBitOffset - m_CurrentControlStateBitOffset;
  1247. break;
  1248. }
  1249. // If the control's bit region runs past of what we actually have (may be the case both
  1250. // with delta events and normal state events), skip it.
  1251. if (controlBitOffset + controlBitSize - m_CurrentControlStateBitOffset > m_EndBitOffset)
  1252. continue;
  1253. // If the control is byte-aligned both in its start offset and its length,
  1254. // we have what we're looking for.
  1255. if ((controlBitOffset & 0x7) == 0 && (controlBitSize & 0x7) == 0)
  1256. {
  1257. m_CurrentControl = m_AllControls[controlIndex];
  1258. }
  1259. else
  1260. {
  1261. // Otherwise, we may need to check the bit region specifically for the control.
  1262. if ((ignoreCurrent && MemoryHelpers.MemCmpBitRegion(m_EventState, m_CurrentState, controlBitOffset - m_CurrentControlStateBitOffset, controlBitSize, m_NoiseMask))
  1263. || (ignoreDefault && MemoryHelpers.MemCmpBitRegion(m_EventState, m_DefaultState, controlBitOffset - m_CurrentControlStateBitOffset, controlBitSize, m_NoiseMask)))
  1264. continue;
  1265. m_CurrentControl = m_AllControls[controlIndex];
  1266. }
  1267. if ((m_Flags & Enumerate.IncludeNoisyControls) == 0 && m_CurrentControl.noisy)
  1268. {
  1269. m_CurrentControl = null;
  1270. continue;
  1271. }
  1272. if ((m_Flags & Enumerate.IncludeSyntheticControls) == 0)
  1273. {
  1274. var controlHasSharedState = (m_CurrentControl.m_ControlFlags &
  1275. (InputControl.ControlFlags.UsesStateFromOtherControl |
  1276. InputControl.ControlFlags.IsSynthetic)) != 0;
  1277. // Filter out synthetic and useStateFrom controls.
  1278. if (controlHasSharedState)
  1279. {
  1280. m_CurrentControl = null;
  1281. continue;
  1282. }
  1283. }
  1284. ++m_CurrentIndexInStateOffsetToControlIndexMap;
  1285. break;
  1286. }
  1287. if (m_CurrentControl != null)
  1288. {
  1289. // If we are the filter by magnitude, last check is to go let the control evaluate
  1290. // its magnitude based on the data in the event and if it's too low, keep searching.
  1291. if (m_MagnitudeThreshold != 0)
  1292. {
  1293. var statePtr = m_EventState - (m_CurrentControlStateBitOffset >> 3) - m_Device.m_StateBlock.byteOffset;
  1294. var magnitude = m_CurrentControl.EvaluateMagnitude(statePtr);
  1295. if (magnitude >= 0 && magnitude < m_MagnitudeThreshold)
  1296. continue;
  1297. }
  1298. return true;
  1299. }
  1300. }
  1301. }
  1302. public void Reset()
  1303. {
  1304. if (!m_EventPtr.valid)
  1305. throw new ObjectDisposedException("Enumerator has already been disposed");
  1306. var eventType = m_EventPtr.type;
  1307. FourCC stateFormat;
  1308. if (eventType == StateEvent.Type)
  1309. {
  1310. var stateEvent = StateEvent.FromUnchecked(m_EventPtr);
  1311. m_EventState = (byte*)stateEvent->state;
  1312. m_EndBitOffset = stateEvent->stateSizeInBytes * 8;
  1313. m_CurrentBitOffset = 0;
  1314. stateFormat = stateEvent->stateFormat;
  1315. }
  1316. else if (eventType == DeltaStateEvent.Type)
  1317. {
  1318. var deltaEvent = DeltaStateEvent.FromUnchecked(m_EventPtr);
  1319. m_EventState = (byte*)deltaEvent->deltaState - deltaEvent->stateOffset; // We access m_EventState as if it contains a full state event.
  1320. m_CurrentBitOffset = deltaEvent->stateOffset * 8;
  1321. m_EndBitOffset = m_CurrentBitOffset + deltaEvent->deltaStateSizeInBytes * 8;
  1322. stateFormat = deltaEvent->stateFormat;
  1323. }
  1324. else
  1325. {
  1326. throw new NotSupportedException($"Cannot iterate over controls in event of type '{eventType}'");
  1327. }
  1328. m_CurrentIndexInStateOffsetToControlIndexMap = 0;
  1329. m_CurrentControlStateBitOffset = 0;
  1330. m_CurrentControl = null;
  1331. // If the state format of the event does not match that of the device,
  1332. // we need to go through the IInputStateCallbackReceiver machinery to adapt.
  1333. if (stateFormat != m_Device.m_StateBlock.format)
  1334. {
  1335. var stateOffset = 0u;
  1336. if (m_Device.hasStateCallbacks &&
  1337. ((IInputStateCallbackReceiver)m_Device).GetStateOffsetForEvent(null, m_EventPtr, ref stateOffset))
  1338. {
  1339. m_CurrentControlStateBitOffset = stateOffset * 8;
  1340. if (m_CurrentState != null)
  1341. m_CurrentState += stateOffset;
  1342. if (m_DefaultState != null)
  1343. m_DefaultState += stateOffset;
  1344. if (m_NoiseMask != null)
  1345. m_NoiseMask += stateOffset;
  1346. }
  1347. else
  1348. {
  1349. // https://fogbugz.unity3d.com/f/cases/1395648/
  1350. if (m_Device is Touchscreen && m_EventPtr.IsA<StateEvent>() &&
  1351. StateEvent.FromUnchecked(m_EventPtr)->stateFormat == TouchState.Format)
  1352. {
  1353. // if GetStateOffsetForEvent(null, ...) return false on touchscreen it means that
  1354. // we don't have a free slot for incoming touch, so ignore it for now
  1355. }
  1356. else
  1357. throw new InvalidOperationException(
  1358. $"{eventType} event with state format {stateFormat} cannot be used with device '{m_Device}'");
  1359. }
  1360. }
  1361. // NOTE: We *could* run a CheckDefault() or even CheckCurrent() over the entire event here to rule
  1362. // it out entirely. However, we don't do so based on the assumption that *in general* this will
  1363. // only *add* time. Rationale:
  1364. //
  1365. // - We assume that it is very rare for devices to send events matching the state the device
  1366. // already has (i.e. *entire* event is just == current state).
  1367. // - We assume that it is less common than the opposite for devices to send StateEvents containing
  1368. // nothing but default state. This happens frequently for the keyboard but is very uncommon for mice,
  1369. // touchscreens, and gamepads (where the sticks will almost never be exactly at default).
  1370. // - We assume that for DeltaStateEvents it is in fact quite common to contain only default state but
  1371. // that since in most cases these will contain state for either a very small set of controls or even
  1372. // just a single one, the work we do in MoveNext somewhat closely matches that we'd here with a CheckXXX()
  1373. // call but that we'd add work to every DeltaStateEvent if we were to have the upfront comparison here.
  1374. }
  1375. public void Dispose()
  1376. {
  1377. m_EventPtr = default;
  1378. }
  1379. public InputControl Current => m_CurrentControl;
  1380. object IEnumerator.Current => Current;
  1381. }
  1382. // Undocumented APIs. Meant to be used only by auto-generated, precompiled layouts.
  1383. // These APIs exist solely to keep access to the various properties/fields internal
  1384. // and only allow their contents to be modified in a controlled manner.
  1385. #region Undocumented
  1386. public static ControlBuilder Setup(this InputControl control)
  1387. {
  1388. if (control == null)
  1389. throw new ArgumentNullException(nameof(control));
  1390. if (control.isSetupFinished)
  1391. throw new InvalidOperationException($"The setup of {control} cannot be modified; control is already in use");
  1392. return new ControlBuilder { control = control };
  1393. }
  1394. public static DeviceBuilder Setup(this InputDevice device, int controlCount, int usageCount, int aliasCount)
  1395. {
  1396. if (device == null)
  1397. throw new ArgumentNullException(nameof(device));
  1398. if (device.isSetupFinished)
  1399. throw new InvalidOperationException($"The setup of {device} cannot be modified; control is already in use");
  1400. if (controlCount < 1)
  1401. throw new ArgumentOutOfRangeException(nameof(controlCount));
  1402. if (usageCount < 0)
  1403. throw new ArgumentOutOfRangeException(nameof(usageCount));
  1404. if (aliasCount < 0)
  1405. throw new ArgumentOutOfRangeException(nameof(aliasCount));
  1406. device.m_Device = device;
  1407. device.m_ChildrenForEachControl = new InputControl[controlCount];
  1408. if (usageCount > 0)
  1409. {
  1410. device.m_UsagesForEachControl = new InternedString[usageCount];
  1411. device.m_UsageToControl = new InputControl[usageCount];
  1412. }
  1413. if (aliasCount > 0)
  1414. device.m_AliasesForEachControl = new InternedString[aliasCount];
  1415. return new DeviceBuilder { device = device };
  1416. }
  1417. public struct ControlBuilder
  1418. {
  1419. public InputControl control { get; internal set; }
  1420. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1421. public ControlBuilder At(InputDevice device, int index)
  1422. {
  1423. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1424. if (device == null)
  1425. throw new ArgumentNullException(nameof(device));
  1426. if (index < 0 || index >= device.m_ChildrenForEachControl.Length)
  1427. throw new ArgumentOutOfRangeException(nameof(index));
  1428. #endif
  1429. device.m_ChildrenForEachControl[index] = control;
  1430. control.m_Device = device;
  1431. return this;
  1432. }
  1433. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1434. public ControlBuilder WithParent(InputControl parent)
  1435. {
  1436. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1437. if (parent == null)
  1438. throw new ArgumentNullException(nameof(parent));
  1439. if (parent == control)
  1440. throw new ArgumentException("Control cannot be its own parent", nameof(parent));
  1441. #endif
  1442. control.m_Parent = parent;
  1443. return this;
  1444. }
  1445. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1446. public ControlBuilder WithName(string name)
  1447. {
  1448. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1449. if (string.IsNullOrEmpty(name))
  1450. throw new ArgumentNullException(nameof(name));
  1451. #endif
  1452. control.m_Name = new InternedString(name);
  1453. return this;
  1454. }
  1455. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1456. public ControlBuilder WithDisplayName(string displayName)
  1457. {
  1458. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1459. if (string.IsNullOrEmpty(displayName))
  1460. throw new ArgumentNullException(nameof(displayName));
  1461. #endif
  1462. control.m_DisplayNameFromLayout = new InternedString(displayName);
  1463. return this;
  1464. }
  1465. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1466. public ControlBuilder WithShortDisplayName(string shortDisplayName)
  1467. {
  1468. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1469. if (string.IsNullOrEmpty(shortDisplayName))
  1470. throw new ArgumentNullException(nameof(shortDisplayName));
  1471. #endif
  1472. control.m_ShortDisplayNameFromLayout = new InternedString(shortDisplayName);
  1473. return this;
  1474. }
  1475. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1476. public ControlBuilder WithLayout(InternedString layout)
  1477. {
  1478. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1479. if (layout.IsEmpty())
  1480. throw new ArgumentException("Layout name cannot be empty", nameof(layout));
  1481. #endif
  1482. control.m_Layout = layout;
  1483. return this;
  1484. }
  1485. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1486. public ControlBuilder WithUsages(int startIndex, int count)
  1487. {
  1488. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1489. if (startIndex < 0 || startIndex >= control.device.m_UsagesForEachControl.Length)
  1490. throw new ArgumentOutOfRangeException(nameof(startIndex));
  1491. if (count < 0 || startIndex + count > control.device.m_UsagesForEachControl.Length)
  1492. throw new ArgumentOutOfRangeException(nameof(count));
  1493. #endif
  1494. control.m_UsageStartIndex = startIndex;
  1495. control.m_UsageCount = count;
  1496. return this;
  1497. }
  1498. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1499. public ControlBuilder WithAliases(int startIndex, int count)
  1500. {
  1501. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1502. if (startIndex < 0 || startIndex >= control.device.m_AliasesForEachControl.Length)
  1503. throw new ArgumentOutOfRangeException(nameof(startIndex));
  1504. if (count < 0 || startIndex + count > control.device.m_AliasesForEachControl.Length)
  1505. throw new ArgumentOutOfRangeException(nameof(count));
  1506. #endif
  1507. control.m_AliasStartIndex = startIndex;
  1508. control.m_AliasCount = count;
  1509. return this;
  1510. }
  1511. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1512. public ControlBuilder WithChildren(int startIndex, int count)
  1513. {
  1514. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1515. if (startIndex < 0 || startIndex >= control.device.m_ChildrenForEachControl.Length)
  1516. throw new ArgumentOutOfRangeException(nameof(startIndex));
  1517. if (count < 0 || startIndex + count > control.device.m_ChildrenForEachControl.Length)
  1518. throw new ArgumentOutOfRangeException(nameof(count));
  1519. #endif
  1520. control.m_ChildStartIndex = startIndex;
  1521. control.m_ChildCount = count;
  1522. return this;
  1523. }
  1524. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1525. public ControlBuilder WithStateBlock(InputStateBlock stateBlock)
  1526. {
  1527. control.m_StateBlock = stateBlock;
  1528. return this;
  1529. }
  1530. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1531. public ControlBuilder WithDefaultState(PrimitiveValue value)
  1532. {
  1533. control.m_DefaultState = value;
  1534. control.m_Device.hasControlsWithDefaultState = true;
  1535. return this;
  1536. }
  1537. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1538. public ControlBuilder WithMinAndMax(PrimitiveValue min, PrimitiveValue max)
  1539. {
  1540. control.m_MinValue = min;
  1541. control.m_MaxValue = max;
  1542. return this;
  1543. }
  1544. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1545. public ControlBuilder WithProcessor<TProcessor, TValue>(TProcessor processor)
  1546. where TValue : struct
  1547. where TProcessor : InputProcessor<TValue>
  1548. {
  1549. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1550. if (processor == null)
  1551. throw new ArgumentNullException(nameof(processor));
  1552. #endif
  1553. ////REVIEW: have a parameterized version of ControlBuilder<TValue> so we don't need the cast?
  1554. ////TODO: size array to exact needed size before-hand
  1555. ((InputControl<TValue>)control).m_ProcessorStack.Append(processor);
  1556. return this;
  1557. }
  1558. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1559. public ControlBuilder IsNoisy(bool value)
  1560. {
  1561. control.noisy = value;
  1562. return this;
  1563. }
  1564. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1565. public ControlBuilder IsSynthetic(bool value)
  1566. {
  1567. control.synthetic = value;
  1568. return this;
  1569. }
  1570. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1571. public ControlBuilder DontReset(bool value)
  1572. {
  1573. control.dontReset = value;
  1574. if (value)
  1575. control.m_Device.hasDontResetControls = true;
  1576. return this;
  1577. }
  1578. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1579. public ControlBuilder IsButton(bool value)
  1580. {
  1581. control.isButton = value;
  1582. return this;
  1583. }
  1584. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1585. public void Finish()
  1586. {
  1587. control.isSetupFinished = true;
  1588. }
  1589. }
  1590. public struct DeviceBuilder
  1591. {
  1592. public InputDevice device { get; internal set; }
  1593. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1594. public DeviceBuilder WithName(string name)
  1595. {
  1596. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1597. if (string.IsNullOrEmpty(name))
  1598. throw new ArgumentNullException(nameof(name));
  1599. #endif
  1600. device.m_Name = new InternedString(name);
  1601. return this;
  1602. }
  1603. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1604. public DeviceBuilder WithDisplayName(string displayName)
  1605. {
  1606. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1607. if (string.IsNullOrEmpty(displayName))
  1608. throw new ArgumentNullException(nameof(displayName));
  1609. #endif
  1610. device.m_DisplayNameFromLayout = new InternedString(displayName);
  1611. return this;
  1612. }
  1613. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1614. public DeviceBuilder WithShortDisplayName(string shortDisplayName)
  1615. {
  1616. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1617. if (string.IsNullOrEmpty(shortDisplayName))
  1618. throw new ArgumentNullException(nameof(shortDisplayName));
  1619. #endif
  1620. device.m_ShortDisplayNameFromLayout = new InternedString(shortDisplayName);
  1621. return this;
  1622. }
  1623. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1624. public DeviceBuilder WithLayout(InternedString layout)
  1625. {
  1626. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1627. if (layout.IsEmpty())
  1628. throw new ArgumentException("Layout name cannot be empty", nameof(layout));
  1629. #endif
  1630. device.m_Layout = layout;
  1631. return this;
  1632. }
  1633. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1634. public DeviceBuilder WithChildren(int startIndex, int count)
  1635. {
  1636. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1637. if (startIndex < 0 || startIndex >= device.device.m_ChildrenForEachControl.Length)
  1638. throw new ArgumentOutOfRangeException(nameof(startIndex));
  1639. if (count < 0 || startIndex + count > device.device.m_ChildrenForEachControl.Length)
  1640. throw new ArgumentOutOfRangeException(nameof(count));
  1641. #endif
  1642. device.m_ChildStartIndex = startIndex;
  1643. device.m_ChildCount = count;
  1644. return this;
  1645. }
  1646. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1647. public DeviceBuilder WithStateBlock(InputStateBlock stateBlock)
  1648. {
  1649. device.m_StateBlock = stateBlock;
  1650. return this;
  1651. }
  1652. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1653. public DeviceBuilder IsNoisy(bool value)
  1654. {
  1655. device.noisy = value;
  1656. return this;
  1657. }
  1658. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1659. public DeviceBuilder WithControlUsage(int controlIndex, InternedString usage, InputControl control)
  1660. {
  1661. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1662. if (controlIndex < 0 || controlIndex >= device.m_UsagesForEachControl.Length)
  1663. throw new ArgumentOutOfRangeException(nameof(controlIndex));
  1664. if (usage.IsEmpty())
  1665. throw new ArgumentException(nameof(usage));
  1666. if (control == null)
  1667. throw new ArgumentNullException(nameof(control));
  1668. #endif
  1669. device.m_UsagesForEachControl[controlIndex] = usage;
  1670. device.m_UsageToControl[controlIndex] = control;
  1671. return this;
  1672. }
  1673. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1674. public DeviceBuilder WithControlAlias(int controlIndex, InternedString alias)
  1675. {
  1676. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  1677. if (controlIndex < 0 || controlIndex >= device.m_AliasesForEachControl.Length)
  1678. throw new ArgumentOutOfRangeException(nameof(controlIndex));
  1679. if (alias.IsEmpty())
  1680. throw new ArgumentException(nameof(alias));
  1681. #endif
  1682. device.m_AliasesForEachControl[controlIndex] = alias;
  1683. return this;
  1684. }
  1685. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1686. public DeviceBuilder WithStateOffsetToControlIndexMap(uint[] map)
  1687. {
  1688. device.m_StateOffsetToControlMap = map;
  1689. return this;
  1690. }
  1691. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1692. public unsafe DeviceBuilder WithControlTree(byte[] controlTreeNodes, ushort[] controlTreeIndicies)
  1693. {
  1694. var sizeOfNode = UnsafeUtility.SizeOf<InputDevice.ControlBitRangeNode>();
  1695. var numNodes = controlTreeNodes.Length / sizeOfNode;
  1696. device.m_ControlTreeNodes = new InputDevice.ControlBitRangeNode[numNodes];
  1697. fixed(byte* nodePtr = controlTreeNodes)
  1698. {
  1699. for (var i = 0; i < numNodes; i++)
  1700. {
  1701. device.m_ControlTreeNodes[i] = *(InputDevice.ControlBitRangeNode*)(nodePtr + i * sizeOfNode);
  1702. }
  1703. }
  1704. device.m_ControlTreeIndices = controlTreeIndicies;
  1705. return this;
  1706. }
  1707. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1708. public void Finish()
  1709. {
  1710. device.isSetupFinished = true;
  1711. }
  1712. }
  1713. #endregion
  1714. }
  1715. }