using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.XR.GoogleVr; using Unity.XR.Oculus.Input; using Unity.XR.OpenVR; using UnityEngine.Analytics; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Experimental.Rendering; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Composites; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.DualShock; using UnityEngine.InputSystem.DualShock.LowLevel; using UnityEngine.InputSystem.HID; using UnityEngine.InputSystem.Haptics; using UnityEngine.InputSystem.Interactions; using UnityEngine.InputSystem.Layouts; using UnityEngine.InputSystem.LowLevel; using UnityEngine.InputSystem.Processors; using UnityEngine.InputSystem.Switch; using UnityEngine.InputSystem.Switch.LowLevel; using UnityEngine.InputSystem.UI; using UnityEngine.InputSystem.Users; using UnityEngine.InputSystem.Utilities; using UnityEngine.InputSystem.XInput; using UnityEngine.InputSystem.XInput.LowLevel; using UnityEngine.InputSystem.XR; using UnityEngine.InputSystem.XR.Haptics; using UnityEngine.Networking.PlayerConnection; using UnityEngine.Pool; using UnityEngine.Scripting; using UnityEngine.Serialization; using UnityEngine.UI; using UnityEngine.UIElements; using UnityEngine.XR; using UnityEngine.XR.WindowsMR.Input; using UnityEngineInternal.Input; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Unity.InputSystem.TestFramework")] [assembly: InternalsVisibleTo("Unity.InputSystem.Tests.Editor")] [assembly: InternalsVisibleTo("Unity.InputSystem.Tests")] [assembly: InternalsVisibleTo("Unity.InputSystem.IntegrationTests")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.6.3.0")] [module: UnverifiableCode] internal static class UISupport { public static void Initialize() { InputSystem.RegisterLayout("\n {\n \"name\" : \"VirtualMouse\",\n \"extend\" : \"Mouse\"\n }\n "); } } namespace Unity.XR.OpenVR { [InputControlLayout(displayName = "OpenVR Headset", hideInUI = true)] public class OpenVRHMD : XRHMD { [InputControl(noisy = true)] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control leftEyeVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control leftEyeAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control rightEyeVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control rightEyeAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control centerEyeVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control centerEyeAngularVelocity { get; private set; } protected override void FinishSetup() { base.FinishSetup(); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); leftEyeVelocity = GetChildControl("leftEyeVelocity"); leftEyeAngularVelocity = GetChildControl("leftEyeAngularVelocity"); rightEyeVelocity = GetChildControl("rightEyeVelocity"); rightEyeAngularVelocity = GetChildControl("rightEyeAngularVelocity"); centerEyeVelocity = GetChildControl("centerEyeVelocity"); centerEyeAngularVelocity = GetChildControl("centerEyeAngularVelocity"); } } [InputControlLayout(displayName = "Windows MR Controller (OpenVR)", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class OpenVRControllerWMR : XRController { [InputControl(noisy = true)] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } [InputControl(aliases = new string[] { "primary2DAxisClick", "joystickOrPadPressed" })] public ButtonControl touchpadClick { get; private set; } [InputControl(aliases = new string[] { "primary2DAxisTouch", "joystickOrPadTouched" })] public ButtonControl touchpadTouch { get; private set; } [InputControl] public ButtonControl gripPressed { get; private set; } [InputControl] public ButtonControl triggerPressed { get; private set; } [InputControl(aliases = new string[] { "primary" })] public ButtonControl menu { get; private set; } [InputControl] public AxisControl trigger { get; private set; } [InputControl] public AxisControl grip { get; private set; } [InputControl(aliases = new string[] { "secondary2DAxis" })] public Vector2Control touchpad { get; private set; } [InputControl(aliases = new string[] { "primary2DAxis" })] public Vector2Control joystick { get; private set; } protected override void FinishSetup() { base.FinishSetup(); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); touchpadClick = GetChildControl("touchpadClick"); touchpadTouch = GetChildControl("touchpadTouch"); gripPressed = GetChildControl("gripPressed"); triggerPressed = GetChildControl("triggerPressed"); menu = GetChildControl("menu"); trigger = GetChildControl("trigger"); grip = GetChildControl("grip"); touchpad = GetChildControl("touchpad"); joystick = GetChildControl("joystick"); } } [InputControlLayout(displayName = "Vive Wand", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class ViveWand : XRControllerWithRumble { [InputControl] public AxisControl grip { get; private set; } [InputControl] public ButtonControl gripPressed { get; private set; } [InputControl] public ButtonControl primary { get; private set; } [InputControl(aliases = new string[] { "primary2DAxisClick", "joystickOrPadPressed" })] public ButtonControl trackpadPressed { get; private set; } [InputControl(aliases = new string[] { "primary2DAxisTouch", "joystickOrPadTouched" })] public ButtonControl trackpadTouched { get; private set; } [InputControl(aliases = new string[] { "Primary2DAxis" })] public Vector2Control trackpad { get; private set; } [InputControl] public AxisControl trigger { get; private set; } [InputControl] public ButtonControl triggerPressed { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } protected override void FinishSetup() { base.FinishSetup(); grip = GetChildControl("grip"); primary = GetChildControl("primary"); gripPressed = GetChildControl("gripPressed"); trackpadPressed = GetChildControl("trackpadPressed"); trackpadTouched = GetChildControl("trackpadTouched"); trackpad = GetChildControl("trackpad"); trigger = GetChildControl("trigger"); triggerPressed = GetChildControl("triggerPressed"); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); } } [InputControlLayout(displayName = "Vive Lighthouse", hideInUI = true)] public class ViveLighthouse : TrackedDevice { } [InputControlLayout(displayName = "Vive Tracker")] public class ViveTracker : TrackedDevice { [InputControl(noisy = true)] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } protected override void FinishSetup() { base.FinishSetup(); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); } } [InputControlLayout(displayName = "Handed Vive Tracker", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class HandedViveTracker : ViveTracker { [InputControl] public AxisControl grip { get; private set; } [InputControl] public ButtonControl gripPressed { get; private set; } [InputControl] public ButtonControl primary { get; private set; } [InputControl(aliases = new string[] { "JoystickOrPadPressed" })] public ButtonControl trackpadPressed { get; private set; } [InputControl] public ButtonControl triggerPressed { get; private set; } protected override void FinishSetup() { grip = GetChildControl("grip"); primary = GetChildControl("primary"); gripPressed = GetChildControl("gripPressed"); trackpadPressed = GetChildControl("trackpadPressed"); triggerPressed = GetChildControl("triggerPressed"); base.FinishSetup(); } } [InputControlLayout(displayName = "Oculus Touch Controller (OpenVR)", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class OpenVROculusTouchController : XRControllerWithRumble { [InputControl] public Vector2Control thumbstick { get; private set; } [InputControl] public AxisControl trigger { get; private set; } [InputControl] public AxisControl grip { get; private set; } [InputControl(aliases = new string[] { "Alternate" })] public ButtonControl primaryButton { get; private set; } [InputControl(aliases = new string[] { "Primary" })] public ButtonControl secondaryButton { get; private set; } [InputControl] public ButtonControl gripPressed { get; private set; } [InputControl] public ButtonControl triggerPressed { get; private set; } [InputControl(aliases = new string[] { "primary2DAxisClicked" })] public ButtonControl thumbstickClicked { get; private set; } [InputControl(aliases = new string[] { "primary2DAxisTouch" })] public ButtonControl thumbstickTouched { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } protected override void FinishSetup() { base.FinishSetup(); thumbstick = GetChildControl("thumbstick"); trigger = GetChildControl("trigger"); grip = GetChildControl("grip"); primaryButton = GetChildControl("primaryButton"); secondaryButton = GetChildControl("secondaryButton"); gripPressed = GetChildControl("gripPressed"); thumbstickClicked = GetChildControl("thumbstickClicked"); thumbstickTouched = GetChildControl("thumbstickTouched"); triggerPressed = GetChildControl("triggerPressed"); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); } } } namespace Unity.XR.Oculus.Input { [InputControlLayout(displayName = "Oculus Headset", hideInUI = true)] public class OculusHMD : XRHMD { [InputControl] [InputControl(name = "trackingState", layout = "Integer", aliases = new string[] { "devicetrackingstate" })] [InputControl(name = "isTracked", layout = "Button", aliases = new string[] { "deviceistracked" })] public ButtonControl userPresence { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control leftEyeAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control leftEyeAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control leftEyeAngularAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control rightEyeAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control rightEyeAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control rightEyeAngularAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control centerEyeAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control centerEyeAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control centerEyeAngularAcceleration { get; private set; } protected override void FinishSetup() { base.FinishSetup(); userPresence = GetChildControl("userPresence"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); deviceAcceleration = GetChildControl("deviceAcceleration"); deviceAngularAcceleration = GetChildControl("deviceAngularAcceleration"); leftEyeAngularVelocity = GetChildControl("leftEyeAngularVelocity"); leftEyeAcceleration = GetChildControl("leftEyeAcceleration"); leftEyeAngularAcceleration = GetChildControl("leftEyeAngularAcceleration"); rightEyeAngularVelocity = GetChildControl("rightEyeAngularVelocity"); rightEyeAcceleration = GetChildControl("rightEyeAcceleration"); rightEyeAngularAcceleration = GetChildControl("rightEyeAngularAcceleration"); centerEyeAngularVelocity = GetChildControl("centerEyeAngularVelocity"); centerEyeAcceleration = GetChildControl("centerEyeAcceleration"); centerEyeAngularAcceleration = GetChildControl("centerEyeAngularAcceleration"); } } [InputControlLayout(displayName = "Oculus Touch Controller", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class OculusTouchController : XRControllerWithRumble { [InputControl(aliases = new string[] { "Primary2DAxis", "Joystick" })] public Vector2Control thumbstick { get; private set; } [InputControl] public AxisControl trigger { get; private set; } [InputControl] public AxisControl grip { get; private set; } [InputControl(aliases = new string[] { "A", "X", "Alternate" })] public ButtonControl primaryButton { get; private set; } [InputControl(aliases = new string[] { "B", "Y", "Primary" })] public ButtonControl secondaryButton { get; private set; } [InputControl(aliases = new string[] { "GripButton" })] public ButtonControl gripPressed { get; private set; } [InputControl] public ButtonControl start { get; private set; } [InputControl(aliases = new string[] { "JoystickOrPadPressed", "thumbstickClick" })] public ButtonControl thumbstickClicked { get; private set; } [InputControl(aliases = new string[] { "ATouched", "XTouched", "ATouch", "XTouch" })] public ButtonControl primaryTouched { get; private set; } [InputControl(aliases = new string[] { "BTouched", "YTouched", "BTouch", "YTouch" })] public ButtonControl secondaryTouched { get; private set; } [InputControl(aliases = new string[] { "indexTouch", "indexNearTouched" })] public AxisControl triggerTouched { get; private set; } [InputControl(aliases = new string[] { "indexButton", "indexTouched" })] public ButtonControl triggerPressed { get; private set; } [InputControl(aliases = new string[] { "JoystickOrPadTouched", "thumbstickTouch" })] [InputControl(name = "trackingState", layout = "Integer", aliases = new string[] { "controllerTrackingState" })] [InputControl(name = "isTracked", layout = "Button", aliases = new string[] { "ControllerIsTracked" })] [InputControl(name = "devicePosition", layout = "Vector3", aliases = new string[] { "controllerPosition" })] [InputControl(name = "deviceRotation", layout = "Quaternion", aliases = new string[] { "controllerRotation" })] public ButtonControl thumbstickTouched { get; private set; } [InputControl(noisy = true, aliases = new string[] { "controllerVelocity" })] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true, aliases = new string[] { "controllerAngularVelocity" })] public Vector3Control deviceAngularVelocity { get; private set; } [InputControl(noisy = true, aliases = new string[] { "controllerAcceleration" })] public Vector3Control deviceAcceleration { get; private set; } [InputControl(noisy = true, aliases = new string[] { "controllerAngularAcceleration" })] public Vector3Control deviceAngularAcceleration { get; private set; } protected override void FinishSetup() { base.FinishSetup(); thumbstick = GetChildControl("thumbstick"); trigger = GetChildControl("trigger"); triggerTouched = GetChildControl("triggerTouched"); grip = GetChildControl("grip"); primaryButton = GetChildControl("primaryButton"); secondaryButton = GetChildControl("secondaryButton"); gripPressed = GetChildControl("gripPressed"); start = GetChildControl("start"); thumbstickClicked = GetChildControl("thumbstickClicked"); primaryTouched = GetChildControl("primaryTouched"); secondaryTouched = GetChildControl("secondaryTouched"); thumbstickTouched = GetChildControl("thumbstickTouched"); triggerPressed = GetChildControl("triggerPressed"); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); deviceAcceleration = GetChildControl("deviceAcceleration"); deviceAngularAcceleration = GetChildControl("deviceAngularAcceleration"); } } public class OculusTrackingReference : TrackedDevice { [InputControl(aliases = new string[] { "trackingReferenceTrackingState" })] public new IntegerControl trackingState { get; private set; } [InputControl(aliases = new string[] { "trackingReferenceIsTracked" })] public new ButtonControl isTracked { get; private set; } protected override void FinishSetup() { base.FinishSetup(); trackingState = GetChildControl("trackingState"); isTracked = GetChildControl("isTracked"); } } [InputControlLayout(displayName = "Oculus Remote", hideInUI = true)] public class OculusRemote : InputDevice { [InputControl] public ButtonControl back { get; private set; } [InputControl] public ButtonControl start { get; private set; } [InputControl] public Vector2Control touchpad { get; private set; } protected override void FinishSetup() { base.FinishSetup(); back = GetChildControl("back"); start = GetChildControl("start"); touchpad = GetChildControl("touchpad"); } } [InputControlLayout(displayName = "Oculus Headset (w/ on-headset controls)", hideInUI = true)] public class OculusHMDExtended : OculusHMD { [InputControl] public ButtonControl back { get; private set; } [InputControl] public Vector2Control touchpad { get; private set; } protected override void FinishSetup() { base.FinishSetup(); back = GetChildControl("back"); touchpad = GetChildControl("touchpad"); } } [InputControlLayout(displayName = "GearVR Controller", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class GearVRTrackedController : XRController { [InputControl] public Vector2Control touchpad { get; private set; } [InputControl] public AxisControl trigger { get; private set; } [InputControl] public ButtonControl back { get; private set; } [InputControl] public ButtonControl triggerPressed { get; private set; } [InputControl] public ButtonControl touchpadClicked { get; private set; } [InputControl] public ButtonControl touchpadTouched { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAcceleration { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAngularAcceleration { get; private set; } protected override void FinishSetup() { base.FinishSetup(); touchpad = GetChildControl("touchpad"); trigger = GetChildControl("trigger"); back = GetChildControl("back"); triggerPressed = GetChildControl("triggerPressed"); touchpadClicked = GetChildControl("touchpadClicked"); touchpadTouched = GetChildControl("touchpadTouched"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); deviceAcceleration = GetChildControl("deviceAcceleration"); deviceAngularAcceleration = GetChildControl("deviceAngularAcceleration"); } } } namespace Unity.XR.GoogleVr { [InputControlLayout(displayName = "Daydream Headset", hideInUI = true)] public class DaydreamHMD : XRHMD { } [InputControlLayout(displayName = "Daydream Controller", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class DaydreamController : XRController { [InputControl] public Vector2Control touchpad { get; private set; } [InputControl] public ButtonControl volumeUp { get; private set; } [InputControl] public ButtonControl recentered { get; private set; } [InputControl] public ButtonControl volumeDown { get; private set; } [InputControl] public ButtonControl recentering { get; private set; } [InputControl] public ButtonControl app { get; private set; } [InputControl] public ButtonControl home { get; private set; } [InputControl] public ButtonControl touchpadClicked { get; private set; } [InputControl] public ButtonControl touchpadTouched { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true)] public Vector3Control deviceAcceleration { get; private set; } protected override void FinishSetup() { base.FinishSetup(); touchpad = GetChildControl("touchpad"); volumeUp = GetChildControl("volumeUp"); recentered = GetChildControl("recentered"); volumeDown = GetChildControl("volumeDown"); recentering = GetChildControl("recentering"); app = GetChildControl("app"); home = GetChildControl("home"); touchpadClicked = GetChildControl("touchpadClicked"); touchpadTouched = GetChildControl("touchpadTouched"); deviceVelocity = GetChildControl("deviceVelocity"); deviceAcceleration = GetChildControl("deviceAcceleration"); } } } namespace UnityEngine.XR.WindowsMR.Input { [InputControlLayout(displayName = "Windows MR Headset", hideInUI = true)] public class WMRHMD : XRHMD { [InputControl] [InputControl(name = "devicePosition", layout = "Vector3", aliases = new string[] { "HeadPosition" })] [InputControl(name = "deviceRotation", layout = "Quaternion", aliases = new string[] { "HeadRotation" })] public ButtonControl userPresence { get; private set; } protected override void FinishSetup() { base.FinishSetup(); userPresence = GetChildControl("userPresence"); } } [InputControlLayout(displayName = "HoloLens Hand", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class HololensHand : XRController { [InputControl(noisy = true, aliases = new string[] { "gripVelocity" })] public Vector3Control deviceVelocity { get; private set; } [InputControl(aliases = new string[] { "triggerbutton" })] public ButtonControl airTap { get; private set; } [InputControl(noisy = true)] public AxisControl sourceLossRisk { get; private set; } [InputControl(noisy = true)] public Vector3Control sourceLossMitigationDirection { get; private set; } protected override void FinishSetup() { base.FinishSetup(); airTap = GetChildControl("airTap"); deviceVelocity = GetChildControl("deviceVelocity"); sourceLossRisk = GetChildControl("sourceLossRisk"); sourceLossMitigationDirection = GetChildControl("sourceLossMitigationDirection"); } } [InputControlLayout(displayName = "Windows MR Controller", commonUsages = new string[] { "LeftHand", "RightHand" }, hideInUI = true)] public class WMRSpatialController : XRControllerWithRumble { [InputControl(aliases = new string[] { "Primary2DAxis", "thumbstickaxes" })] public Vector2Control joystick { get; private set; } [InputControl(aliases = new string[] { "Secondary2DAxis", "touchpadaxes" })] public Vector2Control touchpad { get; private set; } [InputControl(aliases = new string[] { "gripaxis" })] public AxisControl grip { get; private set; } [InputControl(aliases = new string[] { "gripbutton" })] public ButtonControl gripPressed { get; private set; } [InputControl(aliases = new string[] { "Primary", "menubutton" })] public ButtonControl menu { get; private set; } [InputControl(aliases = new string[] { "triggeraxis" })] public AxisControl trigger { get; private set; } [InputControl(aliases = new string[] { "triggerbutton" })] public ButtonControl triggerPressed { get; private set; } [InputControl(aliases = new string[] { "thumbstickpressed" })] public ButtonControl joystickClicked { get; private set; } [InputControl(aliases = new string[] { "joystickorpadpressed", "touchpadpressed" })] public ButtonControl touchpadClicked { get; private set; } [InputControl(aliases = new string[] { "joystickorpadtouched", "touchpadtouched" })] public ButtonControl touchpadTouched { get; private set; } [InputControl(noisy = true, aliases = new string[] { "gripVelocity" })] public Vector3Control deviceVelocity { get; private set; } [InputControl(noisy = true, aliases = new string[] { "gripAngularVelocity" })] public Vector3Control deviceAngularVelocity { get; private set; } [InputControl(noisy = true)] public AxisControl batteryLevel { get; private set; } [InputControl(noisy = true)] public AxisControl sourceLossRisk { get; private set; } [InputControl(noisy = true)] public Vector3Control sourceLossMitigationDirection { get; private set; } [InputControl(noisy = true)] public Vector3Control pointerPosition { get; private set; } [InputControl(noisy = true, aliases = new string[] { "PointerOrientation" })] public QuaternionControl pointerRotation { get; private set; } protected override void FinishSetup() { base.FinishSetup(); joystick = GetChildControl("joystick"); trigger = GetChildControl("trigger"); touchpad = GetChildControl("touchpad"); grip = GetChildControl("grip"); gripPressed = GetChildControl("gripPressed"); menu = GetChildControl("menu"); joystickClicked = GetChildControl("joystickClicked"); triggerPressed = GetChildControl("triggerPressed"); touchpadClicked = GetChildControl("touchpadClicked"); touchpadTouched = GetChildControl("touchPadTouched"); deviceVelocity = GetChildControl("deviceVelocity"); deviceAngularVelocity = GetChildControl("deviceAngularVelocity"); batteryLevel = GetChildControl("batteryLevel"); sourceLossRisk = GetChildControl("sourceLossRisk"); sourceLossMitigationDirection = GetChildControl("sourceLossMitigationDirection"); pointerPosition = GetChildControl("pointerPosition"); pointerRotation = GetChildControl("pointerRotation"); } } } namespace UnityEngine.InputSystem { public interface IInputActionCollection : IEnumerable, IEnumerable { InputBinding? bindingMask { get; set; } ReadOnlyArray? devices { get; set; } ReadOnlyArray controlSchemes { get; } bool Contains(InputAction action); void Enable(); void Disable(); } public interface IInputActionCollection2 : IInputActionCollection, IEnumerable, IEnumerable { IEnumerable bindings { get; } InputAction FindAction(string actionNameOrId, bool throwIfNotFound = false); int FindBinding(InputBinding mask, out InputAction action); } public interface IInputInteraction { void Process(ref InputInteractionContext context); void Reset(); } public interface IInputInteraction : IInputInteraction where TValue : struct { } internal static class InputInteraction { public static TypeTable s_Interactions; public static Type GetValueType(Type interactionType) { if (interactionType == null) { throw new ArgumentNullException("interactionType"); } return TypeHelpers.GetGenericTypeArgumentFromHierarchy(interactionType, typeof(IInputInteraction<>), 0); } public static string GetDisplayName(string interaction) { if (string.IsNullOrEmpty(interaction)) { throw new ArgumentNullException("interaction"); } Type type = s_Interactions.LookupTypeRegistration(interaction); if (type == null) { return interaction; } return GetDisplayName(type); } public static string GetDisplayName(Type interactionType) { if (interactionType == null) { throw new ArgumentNullException("interactionType"); } DisplayNameAttribute customAttribute = interactionType.GetCustomAttribute(); if (customAttribute == null) { if (interactionType.Name.EndsWith("Interaction")) { return interactionType.Name.Substring(0, interactionType.Name.Length - "Interaction".Length); } return interactionType.Name; } return customAttribute.DisplayName; } } [Serializable] public sealed class InputAction : ICloneable, IDisposable { [Flags] internal enum ActionFlags { WantsInitialStateCheck = 1 } public struct CallbackContext { internal InputActionState m_State; internal int m_ActionIndex; private int actionIndex => m_ActionIndex; private unsafe int bindingIndex => m_State.actionStates[actionIndex].bindingIndex; private unsafe int controlIndex => m_State.actionStates[actionIndex].controlIndex; private unsafe int interactionIndex => m_State.actionStates[actionIndex].interactionIndex; public unsafe InputActionPhase phase { get { if (m_State == null) { return InputActionPhase.Disabled; } return m_State.actionStates[actionIndex].phase; } } public bool started => phase == InputActionPhase.Started; public bool performed => phase == InputActionPhase.Performed; public bool canceled => phase == InputActionPhase.Canceled; public InputAction action => m_State?.GetActionOrNull(bindingIndex); public InputControl control { get { InputActionState state = m_State; if (state == null) { return null; } return state.controls[controlIndex]; } } public IInputInteraction interaction { get { if (m_State == null) { return null; } int num = interactionIndex; if (num == -1) { return null; } return m_State.interactions[num]; } } public unsafe double time { get { if (m_State == null) { return 0.0; } return m_State.actionStates[actionIndex].time; } } public unsafe double startTime { get { if (m_State == null) { return 0.0; } return m_State.actionStates[actionIndex].startTime; } } public double duration => time - startTime; public Type valueType => m_State?.GetValueType(bindingIndex, controlIndex); public int valueSizeInBytes { get { if (m_State == null) { return 0; } return m_State.GetValueSizeInBytes(bindingIndex, controlIndex); } } public unsafe void ReadValue(void* buffer, int bufferSize) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (m_State != null && phase.IsInProgress()) { m_State.ReadValue(bindingIndex, controlIndex, buffer, bufferSize); return; } int num = valueSizeInBytes; if (bufferSize < num) { throw new ArgumentException($"Expected buffer of at least {num} bytes but got buffer of only {bufferSize} bytes", "bufferSize"); } UnsafeUtility.MemClear(buffer, (long)valueSizeInBytes); } public TValue ReadValue() where TValue : struct { TValue val = default(TValue); if (m_State != null) { return phase.IsInProgress() ? m_State.ReadValue(bindingIndex, controlIndex) : m_State.ApplyProcessors(bindingIndex, val); } return val; } public bool ReadValueAsButton() { bool result = false; if (m_State != null && phase.IsInProgress()) { result = m_State.ReadValueAsButton(bindingIndex, controlIndex); } return result; } public object ReadValueAsObject() { if (m_State != null && phase.IsInProgress()) { return m_State.ReadValueAsObject(bindingIndex, controlIndex); } return null; } public override string ToString() { return $"{{ action={action} phase={phase} time={time} control={control} value={ReadValueAsObject()} interaction={interaction} }}"; } } [Tooltip("Human readable name of the action. Must be unique within its action map (case is ignored). Can be changed without breaking references to the action.")] [SerializeField] internal string m_Name; [Tooltip("Determines how the action triggers.\n\nA Value action will start and perform when a control moves from its default value and then perform on every value change. It will cancel when controls go back to default value. Also, when enabled, a Value action will respond right away to a control's current value.\n\nA Button action will start when a button is pressed and perform when the press threshold (see 'Default Button Press Point' in settings) is reached. It will cancel when the button is going below the release threshold (see 'Button Release Threshold' in settings). Also, if a button is already pressed when the action is enabled, the button has to be released first.\n\nA Pass-Through action will not explicitly start and will never cancel. Instead, for every value change on any bound control, the action will perform.")] [SerializeField] internal InputActionType m_Type; [FormerlySerializedAs("m_ExpectedControlLayout")] [Tooltip("The type of control expected by the action (e.g. \"Button\" or \"Stick\"). This will limit the controls shown when setting up bindings in the UI and will also limit which controls can be bound interactively to the action.")] [SerializeField] internal string m_ExpectedControlType; [Tooltip("Unique ID of the action (GUID). Used to reference the action from bindings such that actions can be renamed without breaking references.")] [SerializeField] internal string m_Id; [SerializeField] internal string m_Processors; [SerializeField] internal string m_Interactions; [SerializeField] internal InputBinding[] m_SingletonActionBindings; [SerializeField] internal ActionFlags m_Flags; [NonSerialized] internal InputBinding? m_BindingMask; [NonSerialized] internal int m_BindingsStartIndex; [NonSerialized] internal int m_BindingsCount; [NonSerialized] internal int m_ControlStartIndex; [NonSerialized] internal int m_ControlCount; [NonSerialized] internal int m_ActionIndexInState = -1; [NonSerialized] internal InputActionMap m_ActionMap; [NonSerialized] internal CallbackArray> m_OnStarted; [NonSerialized] internal CallbackArray> m_OnCanceled; [NonSerialized] internal CallbackArray> m_OnPerformed; public string name => m_Name; public InputActionType type => m_Type; public Guid id { get { MakeSureIdIsInPlace(); return new Guid(m_Id); } } internal Guid idDontGenerate { get { if (string.IsNullOrEmpty(m_Id)) { return default(Guid); } return new Guid(m_Id); } } public string expectedControlType { get { return m_ExpectedControlType; } set { m_ExpectedControlType = value; } } public string processors => m_Processors; public string interactions => m_Interactions; public InputActionMap actionMap { get { if (!isSingletonAction) { return m_ActionMap; } return null; } } public InputBinding? bindingMask { get { return m_BindingMask; } set { if (!(value == m_BindingMask)) { if (value.HasValue) { InputBinding value2 = value.Value; value2.action = name; value = value2; } m_BindingMask = value; InputActionMap orCreateActionMap = GetOrCreateActionMap(); if (orCreateActionMap.m_State != null) { orCreateActionMap.LazyResolveBindings(fullResolve: true); } } } } public ReadOnlyArray bindings => GetOrCreateActionMap().GetBindingsForSingleAction(this); public ReadOnlyArray controls { get { InputActionMap orCreateActionMap = GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); return orCreateActionMap.GetControlsForSingleAction(this); } } public InputActionPhase phase => currentState.phase; public bool inProgress => phase.IsInProgress(); public bool enabled => phase != InputActionPhase.Disabled; public bool triggered => WasPerformedThisFrame(); public unsafe InputControl activeControl { get { InputActionState state = GetOrCreateActionMap().m_State; if (state != null) { int controlIndex = state.actionStates[m_ActionIndexInState].controlIndex; if (controlIndex != -1) { return state.controls[controlIndex]; } } return null; } } public bool wantsInitialStateCheck { get { if (type != InputActionType.Value) { return (m_Flags & ActionFlags.WantsInitialStateCheck) != 0; } return true; } set { if (value) { m_Flags |= ActionFlags.WantsInitialStateCheck; } else { m_Flags &= ~ActionFlags.WantsInitialStateCheck; } } } internal bool isSingletonAction { get { if (m_ActionMap != null) { return m_ActionMap.m_SingletonAction == this; } return true; } } private InputActionState.TriggerState currentState { get { if (m_ActionIndexInState == -1) { return default(InputActionState.TriggerState); } return m_ActionMap.m_State.FetchActionState(this); } } public event Action started { add { m_OnStarted.AddCallback(value); } remove { m_OnStarted.RemoveCallback(value); } } public event Action canceled { add { m_OnCanceled.AddCallback(value); } remove { m_OnCanceled.RemoveCallback(value); } } public event Action performed { add { m_OnPerformed.AddCallback(value); } remove { m_OnPerformed.RemoveCallback(value); } } public InputAction() { } public InputAction(string name = null, InputActionType type = InputActionType.Value, string binding = null, string interactions = null, string processors = null, string expectedControlType = null) { m_Name = name; m_Type = type; if (!string.IsNullOrEmpty(binding)) { m_SingletonActionBindings = new InputBinding[1] { new InputBinding { path = binding, interactions = interactions, processors = processors, action = m_Name } }; m_BindingsStartIndex = 0; m_BindingsCount = 1; } else { m_Interactions = interactions; m_Processors = processors; } m_ExpectedControlType = expectedControlType; } public void Dispose() { m_ActionMap?.m_State?.Dispose(); } public override string ToString() { string text = ((m_Name == null) ? "" : ((m_ActionMap == null || isSingletonAction || string.IsNullOrEmpty(m_ActionMap.name)) ? m_Name : (m_ActionMap.name + "/" + m_Name))); ReadOnlyArray readOnlyArray = controls; if (readOnlyArray.Count > 0) { text += "["; bool flag = true; foreach (InputControl item in readOnlyArray) { if (!flag) { text += ","; } text += item.path; flag = false; } text += "]"; } return text; } public void Enable() { if (!enabled) { InputActionMap orCreateActionMap = GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); orCreateActionMap.m_State.EnableSingleAction(this); } } public void Disable() { if (enabled) { m_ActionMap.m_State.DisableSingleAction(this); } } public InputAction Clone() { return new InputAction(m_Name, m_Type) { m_SingletonActionBindings = bindings.ToArray(), m_BindingsCount = m_BindingsCount, m_ExpectedControlType = m_ExpectedControlType, m_Interactions = m_Interactions, m_Processors = m_Processors }; } object ICloneable.Clone() { return Clone(); } public unsafe TValue ReadValue() where TValue : struct { InputActionState state = GetOrCreateActionMap().m_State; if (state == null) { return default(TValue); } InputActionState.TriggerState* ptr = state.actionStates + m_ActionIndexInState; if (!ptr->phase.IsInProgress()) { return state.ApplyProcessors(ptr->bindingIndex, default(TValue)); } return state.ReadValue(ptr->bindingIndex, ptr->controlIndex); } public unsafe object ReadValueAsObject() { InputActionState state = GetOrCreateActionMap().m_State; if (state == null) { return null; } InputActionState.TriggerState* ptr = state.actionStates + m_ActionIndexInState; if (ptr->phase.IsInProgress()) { int controlIndex = ptr->controlIndex; if (controlIndex != -1) { return state.ReadValueAsObject(ptr->bindingIndex, controlIndex); } } return null; } public void Reset() { GetOrCreateActionMap().m_State?.ResetActionState(m_ActionIndexInState, enabled ? InputActionPhase.Waiting : InputActionPhase.Disabled, hardReset: true); } public unsafe bool IsPressed() { InputActionState state = GetOrCreateActionMap().m_State; if (state != null) { return state.actionStates[m_ActionIndexInState].isPressed; } return false; } public unsafe bool IsInProgress() { InputActionState state = GetOrCreateActionMap().m_State; if (state != null) { return state.actionStates[m_ActionIndexInState].phase.IsInProgress(); } return false; } public unsafe bool WasPressedThisFrame() { InputActionState state = GetOrCreateActionMap().m_State; if (state != null) { InputActionState.TriggerState* num = state.actionStates + m_ActionIndexInState; uint s_UpdateStepCount = InputUpdate.s_UpdateStepCount; if (num->pressedInUpdate == s_UpdateStepCount) { return s_UpdateStepCount != 0; } return false; } return false; } public unsafe bool WasReleasedThisFrame() { InputActionState state = GetOrCreateActionMap().m_State; if (state != null) { InputActionState.TriggerState* num = state.actionStates + m_ActionIndexInState; uint s_UpdateStepCount = InputUpdate.s_UpdateStepCount; if (num->releasedInUpdate == s_UpdateStepCount) { return s_UpdateStepCount != 0; } return false; } return false; } public unsafe bool WasPerformedThisFrame() { InputActionState state = GetOrCreateActionMap().m_State; if (state != null) { InputActionState.TriggerState* num = state.actionStates + m_ActionIndexInState; uint s_UpdateStepCount = InputUpdate.s_UpdateStepCount; if (num->lastPerformedInUpdate == s_UpdateStepCount) { return s_UpdateStepCount != 0; } return false; } return false; } public unsafe float GetTimeoutCompletionPercentage() { InputActionState state = GetOrCreateActionMap().m_State; if (state == null) { return 0f; } ref InputActionState.TriggerState reference = ref state.actionStates[m_ActionIndexInState]; int interactionIndex = reference.interactionIndex; if (interactionIndex == -1) { return (reference.phase == InputActionPhase.Performed) ? 1 : 0; } ref InputActionState.InteractionState reference2 = ref state.interactionStates[interactionIndex]; switch (reference2.phase) { case InputActionPhase.Started: { float num = 0f; if (reference2.isTimerRunning) { float timerDuration = reference2.timerDuration; double num2 = reference2.timerStartTime + (double)timerDuration - InputState.currentTime; num = ((!(num2 <= 0.0)) ? ((float)(((double)timerDuration - num2) / (double)timerDuration)) : 1f); } if (reference2.totalTimeoutCompletionTimeRemaining > 0f) { return (reference2.totalTimeoutCompletionDone + num * reference2.timerDuration) / (reference2.totalTimeoutCompletionDone + reference2.totalTimeoutCompletionTimeRemaining); } return num; } case InputActionPhase.Performed: return 1f; default: return 0f; } } internal string MakeSureIdIsInPlace() { if (string.IsNullOrEmpty(m_Id)) { GenerateId(); } return m_Id; } internal void GenerateId() { m_Id = Guid.NewGuid().ToString(); } internal InputActionMap GetOrCreateActionMap() { if (m_ActionMap == null) { CreateInternalActionMapForSingletonAction(); } return m_ActionMap; } private void CreateInternalActionMapForSingletonAction() { m_ActionMap = new InputActionMap { m_Actions = new InputAction[1] { this }, m_SingletonAction = this, m_Bindings = m_SingletonActionBindings }; } internal void RequestInitialStateCheckOnEnabledAction() { GetOrCreateActionMap().m_State.SetInitialStateCheckPending(m_ActionIndexInState); } internal bool ActiveControlIsValid(InputControl control) { if (control == null) { return false; } InputDevice device = control.device; if (!device.added) { return false; } ReadOnlyArray? devices = GetOrCreateActionMap().devices; if (devices.HasValue && !devices.Value.ContainsReference(device)) { return false; } return true; } internal InputBinding? FindEffectiveBindingMask() { if (m_BindingMask.HasValue) { return m_BindingMask; } InputActionMap inputActionMap = m_ActionMap; if (inputActionMap != null && inputActionMap.m_BindingMask.HasValue) { return m_ActionMap.m_BindingMask; } return m_ActionMap?.m_Asset?.m_BindingMask; } internal int BindingIndexOnActionToBindingIndexOnMap(int indexOfBindingOnAction) { InputBinding[] array = GetOrCreateActionMap().m_Bindings; int num = array.LengthSafe(); _ = name; int num2 = -1; for (int i = 0; i < num; i++) { if (array[i].TriggersAction(this)) { num2++; if (num2 == indexOfBindingOnAction) { return i; } } } throw new ArgumentOutOfRangeException("indexOfBindingOnAction", $"Binding index {indexOfBindingOnAction} is out of range for action '{this}' with {num2 + 1} bindings"); } internal int BindingIndexOnMapToBindingIndexOnAction(int indexOfBindingOnMap) { InputBinding[] array = GetOrCreateActionMap().m_Bindings; string strB = name; int num = 0; for (int num2 = indexOfBindingOnMap - 1; num2 >= 0; num2--) { ref InputBinding reference = ref array[num2]; if (string.Compare(reference.action, strB, StringComparison.InvariantCultureIgnoreCase) == 0 || reference.action == m_Id) { num++; } } return num; } } public class InputActionAsset : ScriptableObject, IInputActionCollection2, IInputActionCollection, IEnumerable, IEnumerable { [Serializable] internal struct WriteFileJson { public string name; public InputActionMap.WriteMapJson[] maps; public InputControlScheme.SchemeJson[] controlSchemes; } [Serializable] internal struct ReadFileJson { public string name; public InputActionMap.ReadMapJson[] maps; public InputControlScheme.SchemeJson[] controlSchemes; public void ToAsset(InputActionAsset asset) { ((Object)asset).name = name; InputActionMap.ReadFileJson readFileJson = new InputActionMap.ReadFileJson { maps = maps }; asset.m_ActionMaps = readFileJson.ToMaps(); asset.m_ControlSchemes = InputControlScheme.SchemeJson.ToSchemes(controlSchemes); if (asset.m_ActionMaps != null) { InputActionMap[] actionMaps = asset.m_ActionMaps; for (int i = 0; i < actionMaps.Length; i++) { actionMaps[i].m_Asset = asset; } } } } public const string Extension = "inputactions"; [SerializeField] internal InputActionMap[] m_ActionMaps; [SerializeField] internal InputControlScheme[] m_ControlSchemes; [NonSerialized] internal InputActionState m_SharedStateForAllMaps; [NonSerialized] internal InputBinding? m_BindingMask; [NonSerialized] internal int m_ParameterOverridesCount; [NonSerialized] internal InputActionRebindingExtensions.ParameterOverride[] m_ParameterOverrides; [NonSerialized] internal InputActionMap.DeviceArray m_Devices; public bool enabled { get { foreach (InputActionMap actionMap in actionMaps) { if (actionMap.enabled) { return true; } } return false; } } public ReadOnlyArray actionMaps => new ReadOnlyArray(m_ActionMaps); public ReadOnlyArray controlSchemes => new ReadOnlyArray(m_ControlSchemes); public IEnumerable bindings { get { int numActionMaps = m_ActionMaps.LengthSafe(); if (numActionMaps == 0) { yield break; } int i = 0; while (i < numActionMaps) { InputActionMap inputActionMap = m_ActionMaps[i]; InputBinding[] bindings = inputActionMap.m_Bindings; int numBindings = bindings.LengthSafe(); int num; for (int n = 0; n < numBindings; n = num) { yield return bindings[n]; num = n + 1; } num = i + 1; i = num; } } } public InputBinding? bindingMask { get { return m_BindingMask; } set { if (!(m_BindingMask == value)) { m_BindingMask = value; ReResolveIfNecessary(fullResolve: true); } } } public ReadOnlyArray? devices { get { return m_Devices.Get(); } set { if (m_Devices.Set(value)) { ReResolveIfNecessary(fullResolve: false); } } } public InputAction this[string actionNameOrId] => FindAction(actionNameOrId) ?? throw new KeyNotFoundException($"Cannot find action '{actionNameOrId}' in '{this}'"); public string ToJson() { return JsonUtility.ToJson((object)new WriteFileJson { name = ((Object)this).name, maps = InputActionMap.WriteFileJson.FromMaps(m_ActionMaps).maps, controlSchemes = InputControlScheme.SchemeJson.ToJson(m_ControlSchemes) }, true); } public void LoadFromJson(string json) { if (string.IsNullOrEmpty(json)) { throw new ArgumentNullException("json"); } JsonUtility.FromJson(json).ToAsset(this); } public static InputActionAsset FromJson(string json) { if (string.IsNullOrEmpty(json)) { throw new ArgumentNullException("json"); } InputActionAsset inputActionAsset = ScriptableObject.CreateInstance(); inputActionAsset.LoadFromJson(json); return inputActionAsset; } public InputAction FindAction(string actionNameOrId, bool throwIfNotFound = false) { if (actionNameOrId == null) { throw new ArgumentNullException("actionNameOrId"); } if (m_ActionMaps != null) { int num = actionNameOrId.IndexOf('/'); if (num == -1) { InputAction inputAction = null; for (int i = 0; i < m_ActionMaps.Length; i++) { InputAction inputAction2 = m_ActionMaps[i].FindAction(actionNameOrId); if (inputAction2 != null) { if (inputAction2.enabled || inputAction2.m_Id == actionNameOrId) { return inputAction2; } if (inputAction == null) { inputAction = inputAction2; } } } if (inputAction != null) { return inputAction; } } else { Substring right = new Substring(actionNameOrId, 0, num); Substring right2 = new Substring(actionNameOrId, num + 1); if (right.isEmpty || right2.isEmpty) { throw new ArgumentException("Malformed action path: " + actionNameOrId, "actionNameOrId"); } for (int j = 0; j < m_ActionMaps.Length; j++) { InputActionMap inputActionMap = m_ActionMaps[j]; if (Substring.Compare(inputActionMap.name, right, StringComparison.InvariantCultureIgnoreCase) != 0) { continue; } InputAction[] actions = inputActionMap.m_Actions; foreach (InputAction inputAction3 in actions) { if (Substring.Compare(inputAction3.name, right2, StringComparison.InvariantCultureIgnoreCase) == 0) { return inputAction3; } } break; } } } if (throwIfNotFound) { throw new ArgumentException($"No action '{actionNameOrId}' in '{this}'"); } return null; } public int FindBinding(InputBinding mask, out InputAction action) { int num = m_ActionMaps.LengthSafe(); for (int i = 0; i < num; i++) { int num2 = m_ActionMaps[i].FindBinding(mask, out action); if (num2 >= 0) { return num2; } } action = null; return -1; } public InputActionMap FindActionMap(string nameOrId, bool throwIfNotFound = false) { if (nameOrId == null) { throw new ArgumentNullException("nameOrId"); } if (m_ActionMaps == null) { return null; } if (nameOrId.Contains('-') && Guid.TryParse(nameOrId, out var result)) { for (int i = 0; i < m_ActionMaps.Length; i++) { InputActionMap inputActionMap = m_ActionMaps[i]; if (inputActionMap.idDontGenerate == result) { return inputActionMap; } } } for (int j = 0; j < m_ActionMaps.Length; j++) { InputActionMap inputActionMap2 = m_ActionMaps[j]; if (string.Compare(nameOrId, inputActionMap2.name, StringComparison.InvariantCultureIgnoreCase) == 0) { return inputActionMap2; } } if (throwIfNotFound) { throw new ArgumentException($"Cannot find action map '{nameOrId}' in '{this}'"); } return null; } public InputActionMap FindActionMap(Guid id) { if (m_ActionMaps == null) { return null; } for (int i = 0; i < m_ActionMaps.Length; i++) { InputActionMap inputActionMap = m_ActionMaps[i]; if (inputActionMap.idDontGenerate == id) { return inputActionMap; } } return null; } public InputAction FindAction(Guid guid) { if (m_ActionMaps == null) { return null; } for (int i = 0; i < m_ActionMaps.Length; i++) { InputAction inputAction = m_ActionMaps[i].FindAction(guid); if (inputAction != null) { return inputAction; } } return null; } public int FindControlSchemeIndex(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (m_ControlSchemes == null) { return -1; } for (int i = 0; i < m_ControlSchemes.Length; i++) { if (string.Compare(name, m_ControlSchemes[i].name, StringComparison.InvariantCultureIgnoreCase) == 0) { return i; } } return -1; } public InputControlScheme? FindControlScheme(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } int num = FindControlSchemeIndex(name); if (num == -1) { return null; } return m_ControlSchemes[num]; } public bool IsUsableWithDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } int num = m_ControlSchemes.LengthSafe(); if (num > 0) { for (int i = 0; i < num; i++) { if (m_ControlSchemes[i].SupportsDevice(device)) { return true; } } } else { int num2 = m_ActionMaps.LengthSafe(); for (int j = 0; j < num2; j++) { if (m_ActionMaps[j].IsUsableWithDevice(device)) { return true; } } } return false; } public void Enable() { foreach (InputActionMap actionMap in actionMaps) { actionMap.Enable(); } } public void Disable() { foreach (InputActionMap actionMap in actionMaps) { actionMap.Disable(); } } public bool Contains(InputAction action) { InputActionMap inputActionMap = action?.actionMap; if (inputActionMap == null) { return false; } return (Object)(object)inputActionMap.asset == (Object)(object)this; } public IEnumerator GetEnumerator() { if (m_ActionMaps == null) { yield break; } int i = 0; while (i < m_ActionMaps.Length) { ReadOnlyArray actions = m_ActionMaps[i].actions; int actionCount = actions.Count; int num; for (int n = 0; n < actionCount; n = num) { yield return actions[n]; num = n + 1; } num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal void MarkAsDirty() { } internal void OnWantToChangeSetup() { if (m_ActionMaps.LengthSafe() > 0) { m_ActionMaps[0].OnWantToChangeSetup(); } } internal void OnSetupChanged() { MarkAsDirty(); if (m_ActionMaps.LengthSafe() > 0) { m_ActionMaps[0].OnSetupChanged(); } else { m_SharedStateForAllMaps = null; } } private void ReResolveIfNecessary(bool fullResolve) { if (m_SharedStateForAllMaps != null) { m_ActionMaps[0].LazyResolveBindings(fullResolve); } } internal void ResolveBindingsIfNecessary() { if (m_ActionMaps.LengthSafe() > 0) { InputActionMap[] array = m_ActionMaps; for (int i = 0; i < array.Length && !array[i].ResolveBindingsIfNecessary(); i++) { } } } private void OnDestroy() { Disable(); if (m_SharedStateForAllMaps != null) { m_SharedStateForAllMaps.Dispose(); m_SharedStateForAllMaps = null; } } } public enum InputActionChange { ActionEnabled, ActionDisabled, ActionMapEnabled, ActionMapDisabled, ActionStarted, ActionPerformed, ActionCanceled, BoundControlsAboutToChange, BoundControlsChanged } [Serializable] public sealed class InputActionMap : ICloneable, ISerializationCallbackReceiver, IInputActionCollection2, IInputActionCollection, IEnumerable, IEnumerable, IDisposable { [Flags] private enum Flags { NeedToResolveBindings = 1, BindingResolutionNeedsFullReResolve = 2, ControlsForEachActionInitialized = 4, BindingsForEachActionInitialized = 8 } internal struct DeviceArray { private bool m_HaveValue; private int m_DeviceCount; private InputDevice[] m_DeviceArray; public int IndexOf(InputDevice device) { return m_DeviceArray.IndexOfReference(device, m_DeviceCount); } public bool Remove(InputDevice device) { int num = IndexOf(device); if (num < 0) { return false; } m_DeviceArray.EraseAtWithCapacity(ref m_DeviceCount, num); return true; } public ReadOnlyArray? Get() { if (!m_HaveValue) { return null; } return new ReadOnlyArray(m_DeviceArray, 0, m_DeviceCount); } public bool Set(ReadOnlyArray? devices) { if (!devices.HasValue) { if (!m_HaveValue) { return false; } if (m_DeviceCount > 0) { Array.Clear(m_DeviceArray, 0, m_DeviceCount); } m_DeviceCount = 0; m_HaveValue = false; } else { ReadOnlyArray value = devices.Value; if (m_HaveValue && value.Count == m_DeviceCount && value.HaveEqualReferences(m_DeviceArray, m_DeviceCount)) { return false; } if (m_DeviceCount > 0) { m_DeviceArray.Clear(ref m_DeviceCount); } m_HaveValue = true; m_DeviceCount = 0; ArrayHelpers.AppendListWithCapacity(ref m_DeviceArray, ref m_DeviceCount, value); } return true; } } [Serializable] internal struct BindingOverrideListJson { public List bindings; } [Serializable] internal struct BindingOverrideJson { public string action; public string id; public string path; public string interactions; public string processors; public static BindingOverrideJson FromBinding(InputBinding binding, string actionName) { return new BindingOverrideJson { action = actionName, id = binding.id.ToString(), path = (binding.overridePath ?? "null"), interactions = (binding.overrideInteractions ?? "null"), processors = (binding.overrideProcessors ?? "null") }; } public static BindingOverrideJson FromBinding(InputBinding binding) { return FromBinding(binding, binding.action); } public static InputBinding ToBinding(BindingOverrideJson bindingOverride) { return new InputBinding { overridePath = ((bindingOverride.path != "null") ? bindingOverride.path : null), overrideInteractions = ((bindingOverride.interactions != "null") ? bindingOverride.interactions : null), overrideProcessors = ((bindingOverride.processors != "null") ? bindingOverride.processors : null) }; } } [Serializable] internal struct BindingJson { public string name; public string id; public string path; public string interactions; public string processors; public string groups; public string action; public bool isComposite; public bool isPartOfComposite; public InputBinding ToBinding() { return new InputBinding { name = (string.IsNullOrEmpty(name) ? null : name), m_Id = (string.IsNullOrEmpty(id) ? null : id), path = path, action = (string.IsNullOrEmpty(action) ? null : action), interactions = (string.IsNullOrEmpty(interactions) ? null : interactions), processors = (string.IsNullOrEmpty(processors) ? null : processors), groups = (string.IsNullOrEmpty(groups) ? null : groups), isComposite = isComposite, isPartOfComposite = isPartOfComposite }; } public static BindingJson FromBinding(ref InputBinding binding) { return new BindingJson { name = binding.name, id = binding.m_Id, path = binding.path, action = binding.action, interactions = binding.interactions, processors = binding.processors, groups = binding.groups, isComposite = binding.isComposite, isPartOfComposite = binding.isPartOfComposite }; } } [Serializable] internal struct ReadActionJson { public string name; public string type; public string id; public string expectedControlType; public string expectedControlLayout; public string processors; public string interactions; public bool passThrough; public bool initialStateCheck; public BindingJson[] bindings; public InputAction ToAction(string actionName = null) { if (!string.IsNullOrEmpty(expectedControlLayout)) { expectedControlType = expectedControlLayout; } InputActionType inputActionType = InputActionType.Value; if (!string.IsNullOrEmpty(type)) { inputActionType = (InputActionType)Enum.Parse(typeof(InputActionType), type, ignoreCase: true); } else if (passThrough) { inputActionType = InputActionType.PassThrough; } else if (initialStateCheck) { inputActionType = InputActionType.Value; } else if (!string.IsNullOrEmpty(expectedControlType) && (expectedControlType == "Button" || expectedControlType == "Key")) { inputActionType = InputActionType.Button; } return new InputAction(actionName ?? name, inputActionType) { m_Id = (string.IsNullOrEmpty(id) ? null : id), m_ExpectedControlType = ((!string.IsNullOrEmpty(expectedControlType)) ? expectedControlType : null), m_Processors = processors, m_Interactions = interactions, wantsInitialStateCheck = initialStateCheck }; } } [Serializable] internal struct WriteActionJson { public string name; public string type; public string id; public string expectedControlType; public string processors; public string interactions; public bool initialStateCheck; public static WriteActionJson FromAction(InputAction action) { return new WriteActionJson { name = action.m_Name, type = action.m_Type.ToString(), id = action.m_Id, expectedControlType = action.m_ExpectedControlType, processors = action.processors, interactions = action.interactions, initialStateCheck = action.wantsInitialStateCheck }; } } [Serializable] internal struct ReadMapJson { public string name; public string id; public ReadActionJson[] actions; public BindingJson[] bindings; } [Serializable] internal struct WriteMapJson { public string name; public string id; public WriteActionJson[] actions; public BindingJson[] bindings; public static WriteMapJson FromMap(InputActionMap map) { WriteActionJson[] array = null; BindingJson[] array2 = null; InputAction[] array3 = map.m_Actions; if (array3 != null) { int num = array3.Length; array = new WriteActionJson[num]; for (int i = 0; i < num; i++) { array[i] = WriteActionJson.FromAction(array3[i]); } } InputBinding[] array4 = map.m_Bindings; if (array4 != null) { int num2 = array4.Length; array2 = new BindingJson[num2]; for (int j = 0; j < num2; j++) { array2[j] = BindingJson.FromBinding(ref array4[j]); } } return new WriteMapJson { name = map.name, id = map.id.ToString(), actions = array, bindings = array2 }; } } [Serializable] internal struct WriteFileJson { public WriteMapJson[] maps; public static WriteFileJson FromMap(InputActionMap map) { return new WriteFileJson { maps = new WriteMapJson[1] { WriteMapJson.FromMap(map) } }; } public static WriteFileJson FromMaps(IEnumerable maps) { int num = maps.Count(); if (num == 0) { return default(WriteFileJson); } WriteMapJson[] array = new WriteMapJson[num]; int num2 = 0; foreach (InputActionMap map in maps) { array[num2++] = WriteMapJson.FromMap(map); } return new WriteFileJson { maps = array }; } } [Serializable] internal struct ReadFileJson { public ReadActionJson[] actions; public ReadMapJson[] maps; public InputActionMap[] ToMaps() { List list = new List(); List> list2 = new List>(); List> list3 = new List>(); ReadActionJson[] array = actions; int num = ((array != null) ? array.Length : 0); for (int i = 0; i < num; i++) { ReadActionJson readActionJson = actions[i]; if (string.IsNullOrEmpty(readActionJson.name)) { throw new InvalidOperationException($"Action number {i + 1} has no name"); } string text = null; string text2 = readActionJson.name; int num2 = text2.IndexOf('/'); if (num2 != -1) { text = text2.Substring(0, num2); text2 = text2.Substring(num2 + 1); if (string.IsNullOrEmpty(text2)) { throw new InvalidOperationException("Invalid action name '" + readActionJson.name + "' (missing action name after '/')"); } } InputActionMap inputActionMap = null; int j; for (j = 0; j < list.Count; j++) { if (string.Compare(list[j].name, text, StringComparison.InvariantCultureIgnoreCase) == 0) { inputActionMap = list[j]; break; } } if (inputActionMap == null) { inputActionMap = new InputActionMap(text); j = list.Count; list.Add(inputActionMap); list2.Add(new List()); list3.Add(new List()); } InputAction inputAction = readActionJson.ToAction(text2); list2[j].Add(inputAction); if (readActionJson.bindings != null) { List list4 = list3[j]; for (int k = 0; k < readActionJson.bindings.Length; k++) { BindingJson bindingJson = readActionJson.bindings[k]; InputBinding item = bindingJson.ToBinding(); item.action = inputAction.m_Name; list4.Add(item); } } } ReadMapJson[] array2 = maps; int num3 = ((array2 != null) ? array2.Length : 0); for (int l = 0; l < num3; l++) { ReadMapJson readMapJson = maps[l]; string name = readMapJson.name; if (string.IsNullOrEmpty(name)) { throw new InvalidOperationException($"Map number {l + 1} has no name"); } InputActionMap inputActionMap2 = null; int m; for (m = 0; m < list.Count; m++) { if (string.Compare(list[m].name, name, StringComparison.InvariantCultureIgnoreCase) == 0) { inputActionMap2 = list[m]; break; } } if (inputActionMap2 == null) { inputActionMap2 = new InputActionMap(name) { m_Id = (string.IsNullOrEmpty(readMapJson.id) ? null : readMapJson.id) }; m = list.Count; list.Add(inputActionMap2); list2.Add(new List()); list3.Add(new List()); } ReadActionJson[] array3 = readMapJson.actions; int num4 = ((array3 != null) ? array3.Length : 0); for (int n = 0; n < num4; n++) { ReadActionJson readActionJson2 = readMapJson.actions[n]; if (string.IsNullOrEmpty(readActionJson2.name)) { throw new InvalidOperationException($"Action number {l + 1} in map '{name}' has no name"); } InputAction inputAction2 = readActionJson2.ToAction(); list2[m].Add(inputAction2); if (readActionJson2.bindings != null) { List list5 = list3[m]; for (int num5 = 0; num5 < readActionJson2.bindings.Length; num5++) { BindingJson bindingJson2 = readActionJson2.bindings[num5]; InputBinding item2 = bindingJson2.ToBinding(); item2.action = inputAction2.m_Name; list5.Add(item2); } } } BindingJson[] bindings = readMapJson.bindings; int num6 = ((bindings != null) ? bindings.Length : 0); List list6 = list3[m]; for (int num7 = 0; num7 < num6; num7++) { BindingJson bindingJson3 = readMapJson.bindings[num7]; InputBinding item3 = bindingJson3.ToBinding(); list6.Add(item3); } } for (int num8 = 0; num8 < list.Count; num8++) { InputActionMap inputActionMap3 = list[num8]; InputAction[] array4 = list2[num8].ToArray(); InputBinding[] bindings2 = list3[num8].ToArray(); inputActionMap3.m_Actions = array4; inputActionMap3.m_Bindings = bindings2; for (int num9 = 0; num9 < array4.Length; num9++) { array4[num9].m_ActionMap = inputActionMap3; } } return list.ToArray(); } } [SerializeField] internal string m_Name; [SerializeField] internal string m_Id; [SerializeField] internal InputActionAsset m_Asset; [SerializeField] internal InputAction[] m_Actions; [SerializeField] internal InputBinding[] m_Bindings; [NonSerialized] private InputBinding[] m_BindingsForEachAction; [NonSerialized] private InputControl[] m_ControlsForEachAction; [NonSerialized] internal int m_EnabledActionsCount; [NonSerialized] internal InputAction m_SingletonAction; [NonSerialized] internal int m_MapIndexInState = -1; [NonSerialized] internal InputActionState m_State; [NonSerialized] internal InputBinding? m_BindingMask; [NonSerialized] private Flags m_Flags; [NonSerialized] internal int m_ParameterOverridesCount; [NonSerialized] internal InputActionRebindingExtensions.ParameterOverride[] m_ParameterOverrides; [NonSerialized] internal DeviceArray m_Devices; [NonSerialized] internal CallbackArray> m_ActionCallbacks; [NonSerialized] internal Dictionary m_ActionIndexByNameOrId; internal static int s_DeferBindingResolution; public string name => m_Name; public InputActionAsset asset => m_Asset; public Guid id { get { if (string.IsNullOrEmpty(m_Id)) { GenerateId(); } return new Guid(m_Id); } } internal Guid idDontGenerate { get { if (string.IsNullOrEmpty(m_Id)) { return default(Guid); } return new Guid(m_Id); } } public bool enabled => m_EnabledActionsCount > 0; public ReadOnlyArray actions => new ReadOnlyArray(m_Actions); public ReadOnlyArray bindings => new ReadOnlyArray(m_Bindings); IEnumerable IInputActionCollection2.bindings => bindings; public ReadOnlyArray controlSchemes { get { if ((Object)(object)m_Asset == (Object)null) { return default(ReadOnlyArray); } return m_Asset.controlSchemes; } } public InputBinding? bindingMask { get { return m_BindingMask; } set { if (!(m_BindingMask == value)) { m_BindingMask = value; LazyResolveBindings(fullResolve: true); } } } public ReadOnlyArray? devices { get { return m_Devices.Get() ?? m_Asset?.devices; } set { if (m_Devices.Set(value)) { LazyResolveBindings(fullResolve: false); } } } public InputAction this[string actionNameOrId] { get { if (actionNameOrId == null) { throw new ArgumentNullException("actionNameOrId"); } return FindAction(actionNameOrId) ?? throw new KeyNotFoundException("Cannot find action '" + actionNameOrId + "'"); } } private bool needToResolveBindings { get { return (m_Flags & Flags.NeedToResolveBindings) != 0; } set { if (value) { m_Flags |= Flags.NeedToResolveBindings; } else { m_Flags &= ~Flags.NeedToResolveBindings; } } } private bool bindingResolutionNeedsFullReResolve { get { return (m_Flags & Flags.BindingResolutionNeedsFullReResolve) != 0; } set { if (value) { m_Flags |= Flags.BindingResolutionNeedsFullReResolve; } else { m_Flags &= ~Flags.BindingResolutionNeedsFullReResolve; } } } private bool controlsForEachActionInitialized { get { return (m_Flags & Flags.ControlsForEachActionInitialized) != 0; } set { if (value) { m_Flags |= Flags.ControlsForEachActionInitialized; } else { m_Flags &= ~Flags.ControlsForEachActionInitialized; } } } private bool bindingsForEachActionInitialized { get { return (m_Flags & Flags.BindingsForEachActionInitialized) != 0; } set { if (value) { m_Flags |= Flags.BindingsForEachActionInitialized; } else { m_Flags &= ~Flags.BindingsForEachActionInitialized; } } } public event Action actionTriggered { add { m_ActionCallbacks.AddCallback(value); } remove { m_ActionCallbacks.RemoveCallback(value); } } public InputActionMap() { } public InputActionMap(string name) : this() { m_Name = name; } public void Dispose() { m_State?.Dispose(); } internal int FindActionIndex(string nameOrId) { if (string.IsNullOrEmpty(nameOrId)) { return -1; } if (m_Actions == null) { return -1; } SetUpActionLookupTable(); int num = m_Actions.Length; if (nameOrId.StartsWith("{") && nameOrId.EndsWith("}")) { int length = nameOrId.Length - 2; for (int i = 0; i < num; i++) { if (string.Compare(m_Actions[i].m_Id, 0, nameOrId, 1, length) == 0) { return i; } } } if (m_ActionIndexByNameOrId.TryGetValue(nameOrId, out var value)) { return value; } for (int j = 0; j < num; j++) { if (m_Actions[j].m_Id == nameOrId || string.Compare(m_Actions[j].m_Name, nameOrId, StringComparison.InvariantCultureIgnoreCase) == 0) { return j; } } return -1; } private void SetUpActionLookupTable() { if (m_ActionIndexByNameOrId == null && m_Actions != null) { m_ActionIndexByNameOrId = new Dictionary(); int num = m_Actions.Length; for (int i = 0; i < num; i++) { InputAction inputAction = m_Actions[i]; inputAction.MakeSureIdIsInPlace(); m_ActionIndexByNameOrId[inputAction.name] = i; m_ActionIndexByNameOrId[inputAction.m_Id] = i; } } } internal void ClearActionLookupTable() { m_ActionIndexByNameOrId?.Clear(); } private int FindActionIndex(Guid id) { if (m_Actions == null) { return -1; } int num = m_Actions.Length; for (int i = 0; i < num; i++) { if (m_Actions[i].idDontGenerate == id) { return i; } } return -1; } public InputAction FindAction(string actionNameOrId, bool throwIfNotFound = false) { if (actionNameOrId == null) { throw new ArgumentNullException("actionNameOrId"); } int num = FindActionIndex(actionNameOrId); if (num == -1) { if (throwIfNotFound) { throw new ArgumentException($"No action '{actionNameOrId}' in '{this}'", "actionNameOrId"); } return null; } return m_Actions[num]; } public InputAction FindAction(Guid id) { int num = FindActionIndex(id); if (num == -1) { return null; } return m_Actions[num]; } public bool IsUsableWithDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (m_Bindings == null) { return false; } InputBinding[] array = m_Bindings; foreach (InputBinding inputBinding in array) { string effectivePath = inputBinding.effectivePath; if (!string.IsNullOrEmpty(effectivePath) && InputControlPath.Matches(effectivePath, device)) { return true; } } return false; } public void Enable() { if (m_Actions != null && m_EnabledActionsCount != m_Actions.Length) { ResolveBindingsIfNecessary(); m_State.EnableAllActions(this); } } public void Disable() { if (enabled) { m_State.DisableAllActions(this); } } public InputActionMap Clone() { InputActionMap inputActionMap = new InputActionMap { m_Name = m_Name }; if (m_Actions != null) { int num = m_Actions.Length; InputAction[] array = new InputAction[num]; for (int i = 0; i < num; i++) { InputAction inputAction = m_Actions[i]; array[i] = new InputAction { m_Name = inputAction.m_Name, m_ActionMap = inputActionMap, m_Type = inputAction.m_Type, m_Interactions = inputAction.m_Interactions, m_Processors = inputAction.m_Processors, m_ExpectedControlType = inputAction.m_ExpectedControlType }; } inputActionMap.m_Actions = array; } if (m_Bindings != null) { int num2 = m_Bindings.Length; InputBinding[] array2 = new InputBinding[num2]; Array.Copy(m_Bindings, 0, array2, 0, num2); for (int j = 0; j < num2; j++) { array2[j].m_Id = null; } inputActionMap.m_Bindings = array2; } return inputActionMap; } object ICloneable.Clone() { return Clone(); } public bool Contains(InputAction action) { if (action == null) { return false; } return action.actionMap == this; } public override string ToString() { if ((Object)(object)m_Asset != (Object)null) { return $"{m_Asset}:{m_Name}"; } if (!string.IsNullOrEmpty(m_Name)) { return m_Name; } return ""; } public IEnumerator GetEnumerator() { return actions.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal ReadOnlyArray GetBindingsForSingleAction(InputAction action) { if (!bindingsForEachActionInitialized) { SetUpPerActionControlAndBindingArrays(); } return new ReadOnlyArray(m_BindingsForEachAction, action.m_BindingsStartIndex, action.m_BindingsCount); } internal ReadOnlyArray GetControlsForSingleAction(InputAction action) { if (!controlsForEachActionInitialized) { SetUpPerActionControlAndBindingArrays(); } return new ReadOnlyArray(m_ControlsForEachAction, action.m_ControlStartIndex, action.m_ControlCount); } private unsafe void SetUpPerActionControlAndBindingArrays() { if (m_Bindings == null) { m_ControlsForEachAction = null; m_BindingsForEachAction = null; controlsForEachActionInitialized = true; bindingsForEachActionInitialized = true; return; } if (m_SingletonAction != null) { m_BindingsForEachAction = m_Bindings; m_ControlsForEachAction = m_State?.controls; m_SingletonAction.m_BindingsStartIndex = 0; m_SingletonAction.m_BindingsCount = m_Bindings.Length; m_SingletonAction.m_ControlStartIndex = 0; m_SingletonAction.m_ControlCount = m_State?.totalControlCount ?? 0; if (m_ControlsForEachAction.HaveDuplicateReferences(0, m_SingletonAction.m_ControlCount)) { int num = 0; InputControl[] array = new InputControl[m_SingletonAction.m_ControlCount]; for (int i = 0; i < m_SingletonAction.m_ControlCount; i++) { if (!array.ContainsReference(m_ControlsForEachAction[i])) { array[num] = m_ControlsForEachAction[i]; num++; } } m_ControlsForEachAction = array; m_SingletonAction.m_ControlCount = num; } } else { InputActionState.ActionMapIndices actionMapIndices = m_State?.FetchMapIndices(this) ?? default(InputActionState.ActionMapIndices); for (int j = 0; j < m_Actions.Length; j++) { InputAction obj = m_Actions[j]; obj.m_BindingsCount = 0; obj.m_BindingsStartIndex = -1; obj.m_ControlCount = 0; obj.m_ControlStartIndex = -1; } int num2 = m_Bindings.Length; for (int k = 0; k < num2; k++) { InputAction inputAction = FindAction(m_Bindings[k].action); if (inputAction != null) { inputAction.m_BindingsCount++; } } int num3 = 0; if (m_State != null && (m_ControlsForEachAction == null || m_ControlsForEachAction.Length != actionMapIndices.controlCount)) { if (actionMapIndices.controlCount == 0) { m_ControlsForEachAction = null; } else { m_ControlsForEachAction = new InputControl[actionMapIndices.controlCount]; } } InputBinding[] array2 = null; int num4 = 0; int num5 = 0; while (num5 < m_Bindings.Length) { InputAction inputAction2 = FindAction(m_Bindings[num5].action); if (inputAction2 == null || inputAction2.m_BindingsStartIndex != -1) { num5++; continue; } inputAction2.m_BindingsStartIndex = ((array2 != null) ? num3 : num5); inputAction2.m_ControlStartIndex = num4; int bindingsCount = inputAction2.m_BindingsCount; int num6 = num5; for (int l = 0; l < bindingsCount; l++) { if (FindAction(m_Bindings[num6].action) != inputAction2) { if (array2 == null) { array2 = new InputBinding[m_Bindings.Length]; num3 = num6; Array.Copy(m_Bindings, 0, array2, 0, num6); } do { num6++; } while (FindAction(m_Bindings[num6].action) != inputAction2); } else if (num5 == num6) { num5++; } if (array2 != null) { array2[num3++] = m_Bindings[num6]; } if (m_State != null && !m_Bindings[num6].isComposite) { ref InputActionState.BindingState reference = ref m_State.bindingStates[actionMapIndices.bindingStartIndex + num6]; int controlCount = reference.controlCount; if (controlCount > 0) { int controlStartIndex = reference.controlStartIndex; for (int m = 0; m < controlCount; m++) { InputControl inputControl = m_State.controls[controlStartIndex + m]; if (!m_ControlsForEachAction.ContainsReference(inputAction2.m_ControlStartIndex, inputAction2.m_ControlCount, inputControl)) { m_ControlsForEachAction[num4] = inputControl; num4++; inputAction2.m_ControlCount++; } } } } num6++; } } if (array2 == null) { m_BindingsForEachAction = m_Bindings; } else { m_BindingsForEachAction = array2; } } controlsForEachActionInitialized = true; bindingsForEachActionInitialized = true; } internal void OnWantToChangeSetup() { if ((Object)(object)asset != (Object)null) { foreach (InputActionMap actionMap in asset.actionMaps) { if (actionMap.enabled) { throw new InvalidOperationException($"Cannot add, remove, or change elements of InputActionAsset {asset} while one or more of its actions are enabled"); } } return; } if (enabled) { throw new InvalidOperationException($"Cannot add, remove, or change elements of InputActionMap {this} while one or more of its actions are enabled"); } } internal void OnSetupChanged() { if ((Object)(object)m_Asset != (Object)null) { m_Asset.MarkAsDirty(); foreach (InputActionMap actionMap in m_Asset.actionMaps) { actionMap.m_State = null; } } else { m_State = null; } ClearCachedActionData(); LazyResolveBindings(fullResolve: true); } internal void OnBindingModified() { ClearCachedActionData(); LazyResolveBindings(fullResolve: true); } internal void ClearCachedActionData(bool onlyControls = false) { if (!onlyControls) { bindingsForEachActionInitialized = false; m_BindingsForEachAction = null; m_ActionIndexByNameOrId = null; } controlsForEachActionInitialized = false; m_ControlsForEachAction = null; } internal void GenerateId() { m_Id = Guid.NewGuid().ToString(); } internal bool LazyResolveBindings(bool fullResolve) { m_ControlsForEachAction = null; controlsForEachActionInitialized = false; if (m_State == null) { return false; } needToResolveBindings = true; bindingResolutionNeedsFullReResolve |= fullResolve; if (s_DeferBindingResolution > 0) { return false; } ResolveBindings(); return true; } internal bool ResolveBindingsIfNecessary() { if (m_State == null || needToResolveBindings) { if (m_State != null && m_State.isProcessingControlStateChange) { return false; } ResolveBindings(); return true; } return false; } internal void ResolveBindings() { using (InputActionRebindingExtensions.DeferBindingResolution()) { InputActionState.UnmanagedMemory oldMemory = default(InputActionState.UnmanagedMemory); try { InputBindingResolver resolver = default(InputBindingResolver); bool flag = m_State == null; OneOrMore> oneOrMore; if ((Object)(object)m_Asset != (Object)null) { oneOrMore = m_Asset.actionMaps; resolver.bindingMask = m_Asset.m_BindingMask; foreach (InputActionMap item in oneOrMore) { flag |= item.bindingResolutionNeedsFullReResolve; item.needToResolveBindings = false; item.bindingResolutionNeedsFullReResolve = false; item.controlsForEachActionInitialized = false; } } else { oneOrMore = this; flag |= bindingResolutionNeedsFullReResolve; needToResolveBindings = false; bindingResolutionNeedsFullReResolve = false; controlsForEachActionInitialized = false; } bool hasEnabledActions = false; InputControlList activeControls = default(InputControlList); if (m_State != null) { oldMemory = m_State.memory.Clone(); m_State.PrepareForBindingReResolution(flag, ref activeControls, ref hasEnabledActions); resolver.StartWithPreviousResolve(m_State, flag); m_State.memory.Dispose(); } foreach (InputActionMap item2 in oneOrMore) { resolver.AddActionMap(item2); } if (m_State == null) { m_State = new InputActionState(); m_State.Initialize(resolver); } else { m_State.ClaimDataFrom(resolver); } if ((Object)(object)m_Asset != (Object)null) { foreach (InputActionMap item3 in oneOrMore) { item3.m_State = m_State; } m_Asset.m_SharedStateForAllMaps = m_State; } m_State.FinishBindingResolution(hasEnabledActions, oldMemory, activeControls, flag); } finally { oldMemory.Dispose(); } } } public int FindBinding(InputBinding mask, out InputAction action) { int num = FindBindingRelativeToMap(mask); if (num == -1) { action = null; return -1; } action = m_SingletonAction ?? FindAction(bindings[num].action); return action.BindingIndexOnMapToBindingIndexOnAction(num); } internal int FindBindingRelativeToMap(InputBinding mask) { InputBinding[] array = m_Bindings; int num = array.LengthSafe(); for (int i = 0; i < num; i++) { if (mask.Matches(ref array[i])) { return i; } } return -1; } public static InputActionMap[] FromJson(string json) { if (json == null) { throw new ArgumentNullException("json"); } return JsonUtility.FromJson(json).ToMaps(); } public static string ToJson(IEnumerable maps) { if (maps == null) { throw new ArgumentNullException("maps"); } return JsonUtility.ToJson((object)WriteFileJson.FromMaps(maps), true); } public string ToJson() { return JsonUtility.ToJson((object)WriteFileJson.FromMap(this), true); } public void OnBeforeSerialize() { } public void OnAfterDeserialize() { m_State = null; m_MapIndexInState = -1; if (m_Actions != null) { int num = m_Actions.Length; for (int i = 0; i < num; i++) { m_Actions[i].m_ActionMap = this; } } ClearCachedActionData(); ClearActionLookupTable(); } } public static class InputActionRebindingExtensions { internal struct Parameter { public object instance; public FieldInfo field; public int bindingIndex; } private struct ParameterEnumerable : IEnumerable, IEnumerable { private InputActionState m_State; private ParameterOverride m_Parameter; private int m_MapIndex; public ParameterEnumerable(InputActionState state, ParameterOverride parameter, int mapIndex = -1) { m_State = state; m_Parameter = parameter; m_MapIndex = mapIndex; } public ParameterEnumerator GetEnumerator() { return new ParameterEnumerator(m_State, m_Parameter, m_MapIndex); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private struct ParameterEnumerator : IEnumerator, IDisposable, IEnumerator { private InputActionState m_State; private int m_MapIndex; private int m_BindingCurrentIndex; private int m_BindingEndIndex; private int m_InteractionCurrentIndex; private int m_InteractionEndIndex; private int m_ProcessorCurrentIndex; private int m_ProcessorEndIndex; private InputBinding m_BindingMask; private Type m_ObjectType; private string m_ParameterName; private bool m_MayBeInteraction; private bool m_MayBeProcessor; private bool m_MayBeComposite; private bool m_CurrentBindingIsComposite; private object m_CurrentObject; private FieldInfo m_CurrentParameter; public Parameter Current => new Parameter { instance = m_CurrentObject, field = m_CurrentParameter, bindingIndex = m_BindingCurrentIndex }; object IEnumerator.Current => Current; public ParameterEnumerator(InputActionState state, ParameterOverride parameter, int mapIndex = -1) { this = default(ParameterEnumerator); m_State = state; m_ParameterName = parameter.parameter; m_MapIndex = mapIndex; m_ObjectType = parameter.objectType; m_MayBeComposite = m_ObjectType == null || typeof(InputBindingComposite).IsAssignableFrom(m_ObjectType); m_MayBeProcessor = m_ObjectType == null || typeof(InputProcessor).IsAssignableFrom(m_ObjectType); m_MayBeInteraction = m_ObjectType == null || typeof(IInputInteraction).IsAssignableFrom(m_ObjectType); m_BindingMask = parameter.bindingMask; Reset(); } private bool MoveToNextBinding() { ref InputBinding binding; ref InputActionState.BindingState bindingState; do { m_BindingCurrentIndex++; if (m_BindingCurrentIndex >= m_BindingEndIndex) { return false; } binding = ref m_State.GetBinding(m_BindingCurrentIndex); bindingState = ref m_State.GetBindingState(m_BindingCurrentIndex); } while ((bindingState.processorCount == 0 && bindingState.interactionCount == 0 && !binding.isComposite) || (m_MayBeComposite && !m_MayBeProcessor && !m_MayBeInteraction && !binding.isComposite) || (m_MayBeProcessor && !m_MayBeComposite && !m_MayBeInteraction && bindingState.processorCount == 0) || (m_MayBeInteraction && !m_MayBeComposite && !m_MayBeProcessor && bindingState.interactionCount == 0) || !m_BindingMask.Matches(ref binding)); if (m_MayBeComposite) { m_CurrentBindingIsComposite = binding.isComposite; } m_ProcessorCurrentIndex = bindingState.processorStartIndex - 1; m_ProcessorEndIndex = bindingState.processorStartIndex + bindingState.processorCount; m_InteractionCurrentIndex = bindingState.interactionStartIndex - 1; m_InteractionEndIndex = bindingState.interactionStartIndex + bindingState.interactionCount; return true; } private bool MoveToNextInteraction() { while (m_InteractionCurrentIndex < m_InteractionEndIndex) { m_InteractionCurrentIndex++; if (m_InteractionCurrentIndex == m_InteractionEndIndex) { break; } IInputInteraction instance = m_State.interactions[m_InteractionCurrentIndex]; if (FindParameter(instance)) { return true; } } return false; } private bool MoveToNextProcessor() { while (m_ProcessorCurrentIndex < m_ProcessorEndIndex) { m_ProcessorCurrentIndex++; if (m_ProcessorCurrentIndex == m_ProcessorEndIndex) { break; } InputProcessor instance = m_State.processors[m_ProcessorCurrentIndex]; if (FindParameter(instance)) { return true; } } return false; } private bool FindParameter(object instance) { if (m_ObjectType != null && !m_ObjectType.IsInstanceOfType(instance)) { return false; } FieldInfo field = instance.GetType().GetField(m_ParameterName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (field == null) { return false; } m_CurrentParameter = field; m_CurrentObject = instance; return true; } public bool MoveNext() { while (true) { if (m_MayBeInteraction && MoveToNextInteraction()) { return true; } if (m_MayBeProcessor && MoveToNextProcessor()) { return true; } if (!MoveToNextBinding()) { return false; } if (m_MayBeComposite && m_CurrentBindingIsComposite) { int compositeOrCompositeBindingIndex = m_State.GetBindingState(m_BindingCurrentIndex).compositeOrCompositeBindingIndex; InputBindingComposite instance = m_State.composites[compositeOrCompositeBindingIndex]; if (FindParameter(instance)) { break; } } } return true; } public unsafe void Reset() { m_CurrentObject = null; m_CurrentParameter = null; m_InteractionCurrentIndex = 0; m_InteractionEndIndex = 0; m_ProcessorCurrentIndex = 0; m_ProcessorEndIndex = 0; m_CurrentBindingIsComposite = false; if (m_MapIndex < 0) { m_BindingCurrentIndex = -1; m_BindingEndIndex = m_State.totalBindingCount; } else { m_BindingCurrentIndex = m_State.mapIndices[m_MapIndex].bindingStartIndex - 1; m_BindingEndIndex = m_State.mapIndices[m_MapIndex].bindingStartIndex + m_State.mapIndices[m_MapIndex].bindingCount; } } public void Dispose() { } } internal struct ParameterOverride { public string objectRegistrationName; public string parameter; public InputBinding bindingMask; public PrimitiveValue value; public Type objectType => InputProcessor.s_Processors.LookupTypeRegistration(objectRegistrationName) ?? InputInteraction.s_Interactions.LookupTypeRegistration(objectRegistrationName) ?? InputBindingComposite.s_Composites.LookupTypeRegistration(objectRegistrationName); public ParameterOverride(string parameterName, InputBinding bindingMask, PrimitiveValue value = default(PrimitiveValue)) { int num = parameterName.IndexOf(':'); if (num < 0) { objectRegistrationName = null; parameter = parameterName; } else { objectRegistrationName = parameterName.Substring(0, num); parameter = parameterName.Substring(num + 1); } this.bindingMask = bindingMask; this.value = value; } public ParameterOverride(string objectRegistrationName, string parameterName, InputBinding bindingMask, PrimitiveValue value = default(PrimitiveValue)) { this.objectRegistrationName = objectRegistrationName; parameter = parameterName; this.bindingMask = bindingMask; this.value = value; } public static ParameterOverride? Find(InputActionMap actionMap, ref InputBinding binding, string parameterName, string objectRegistrationName) { ParameterOverride? first = Find(actionMap.m_ParameterOverrides, actionMap.m_ParameterOverridesCount, ref binding, parameterName, objectRegistrationName); InputActionAsset asset = actionMap.asset; ParameterOverride? second = (((Object)(object)asset != (Object)null) ? Find(asset.m_ParameterOverrides, asset.m_ParameterOverridesCount, ref binding, parameterName, objectRegistrationName) : ((ParameterOverride?)null)); return PickMoreSpecificOne(first, second); } private static ParameterOverride? Find(ParameterOverride[] overrides, int overrideCount, ref InputBinding binding, string parameterName, string objectRegistrationName) { ParameterOverride? parameterOverride = null; for (int i = 0; i < overrideCount; i++) { ref ParameterOverride reference = ref overrides[i]; if (string.Equals(parameterName, reference.parameter, StringComparison.OrdinalIgnoreCase) && reference.bindingMask.Matches(binding) && (reference.objectRegistrationName == null || string.Equals(reference.objectRegistrationName, objectRegistrationName, StringComparison.OrdinalIgnoreCase))) { parameterOverride = (parameterOverride.HasValue ? PickMoreSpecificOne(parameterOverride, reference) : new ParameterOverride?(reference)); } } return parameterOverride; } private static ParameterOverride? PickMoreSpecificOne(ParameterOverride? first, ParameterOverride? second) { if (!first.HasValue) { return second; } if (!second.HasValue) { return first; } if (first.Value.objectRegistrationName != null && second.Value.objectRegistrationName == null) { return first; } if (second.Value.objectRegistrationName != null && first.Value.objectRegistrationName == null) { return second; } if (first.Value.bindingMask.effectivePath != null && second.Value.bindingMask.effectivePath == null) { return first; } if (second.Value.bindingMask.effectivePath != null && first.Value.bindingMask.effectivePath == null) { return second; } if (first.Value.bindingMask.action != null && second.Value.bindingMask.action == null) { return first; } if (second.Value.bindingMask.action != null && first.Value.bindingMask.action == null) { return second; } return first; } } public sealed class RebindingOperation : IDisposable { [Flags] private enum Flags { Started = 1, Completed = 2, Canceled = 4, OnEventHooked = 8, OnAfterUpdateHooked = 0x10, DontIgnoreNoisyControls = 0x40, DontGeneralizePathOfSelectedControl = 0x80, AddNewBinding = 0x100, SuppressMatchingEvents = 0x200 } public const float kDefaultMagnitudeThreshold = 0.2f; private InputAction m_ActionToRebind; private InputBinding? m_BindingMask; private Type m_ControlType; private InternedString m_ExpectedLayout; private int m_IncludePathCount; private string[] m_IncludePaths; private int m_ExcludePathCount; private string[] m_ExcludePaths; private int m_TargetBindingIndex = -1; private string m_BindingGroupForNewBinding; private string m_CancelBinding; private float m_MagnitudeThreshold = 0.2f; private float[] m_Scores; private float[] m_Magnitudes; private double m_LastMatchTime; private double m_StartTime; private float m_Timeout; private float m_WaitSecondsAfterMatch; private InputControlList m_Candidates; private Action m_OnComplete; private Action m_OnCancel; private Action m_OnPotentialMatch; private Func m_OnGeneratePath; private Func m_OnComputeScore; private Action m_OnApplyBinding; private Action m_OnEventDelegate; private Action m_OnAfterUpdateDelegate; private InputControlLayout.Cache m_LayoutCache; private StringBuilder m_PathBuilder; private Flags m_Flags; private Dictionary m_StartingActuations = new Dictionary(); public InputAction action => m_ActionToRebind; public InputBinding? bindingMask => m_BindingMask; public InputControlList candidates => m_Candidates; public ReadOnlyArray scores => new ReadOnlyArray(m_Scores, 0, m_Candidates.Count); public ReadOnlyArray magnitudes => new ReadOnlyArray(m_Magnitudes, 0, m_Candidates.Count); public InputControl selectedControl { get { if (m_Candidates.Count == 0) { return null; } return m_Candidates[0]; } } public bool started => (m_Flags & Flags.Started) != 0; public bool completed => (m_Flags & Flags.Completed) != 0; public bool canceled => (m_Flags & Flags.Canceled) != 0; public double startTime => m_StartTime; public float timeout => m_Timeout; public string expectedControlType => m_ExpectedLayout; public RebindingOperation WithAction(InputAction action) { ThrowIfRebindInProgress(); if (action == null) { throw new ArgumentNullException("action"); } if (action.enabled) { throw new InvalidOperationException($"Cannot rebind action '{action}' while it is enabled"); } m_ActionToRebind = action; if (!string.IsNullOrEmpty(action.expectedControlType)) { WithExpectedControlType(action.expectedControlType); } else if (action.type == InputActionType.Button) { WithExpectedControlType("Button"); } return this; } public RebindingOperation WithMatchingEventsBeingSuppressed(bool value = true) { ThrowIfRebindInProgress(); if (value) { m_Flags |= Flags.SuppressMatchingEvents; } else { m_Flags &= ~Flags.SuppressMatchingEvents; } return this; } public RebindingOperation WithCancelingThrough(string binding) { ThrowIfRebindInProgress(); m_CancelBinding = binding; return this; } public RebindingOperation WithCancelingThrough(InputControl control) { ThrowIfRebindInProgress(); if (control == null) { throw new ArgumentNullException("control"); } return WithCancelingThrough(control.path); } public RebindingOperation WithExpectedControlType(string layoutName) { ThrowIfRebindInProgress(); m_ExpectedLayout = new InternedString(layoutName); return this; } public RebindingOperation WithExpectedControlType(Type type) { ThrowIfRebindInProgress(); if (type != null && !typeof(InputControl).IsAssignableFrom(type)) { throw new ArgumentException("Type '" + type.Name + "' is not an InputControl", "type"); } m_ControlType = type; return this; } public RebindingOperation WithExpectedControlType() where TControl : InputControl { ThrowIfRebindInProgress(); return WithExpectedControlType(typeof(TControl)); } public RebindingOperation WithTargetBinding(int bindingIndex) { if (bindingIndex < 0) { throw new ArgumentOutOfRangeException("bindingIndex"); } m_TargetBindingIndex = bindingIndex; if (m_ActionToRebind != null && bindingIndex < m_ActionToRebind.bindings.Count) { InputBinding inputBinding = m_ActionToRebind.bindings[bindingIndex]; if (inputBinding.isPartOfComposite) { string nameOfComposite = m_ActionToRebind.ChangeBinding(bindingIndex).PreviousCompositeBinding().binding.GetNameOfComposite(); string name = inputBinding.name; string expectedControlLayoutName = InputBindingComposite.GetExpectedControlLayoutName(nameOfComposite, name); if (!string.IsNullOrEmpty(expectedControlLayoutName)) { WithExpectedControlType(expectedControlLayoutName); } } InputActionAsset inputActionAsset = action.actionMap?.asset; if ((Object)(object)inputActionAsset != (Object)null && !string.IsNullOrEmpty(inputBinding.groups)) { string[] array = inputBinding.groups.Split(';'); foreach (string group in array) { int num = inputActionAsset.controlSchemes.IndexOf((InputControlScheme x) => group.Equals(x.bindingGroup, StringComparison.InvariantCultureIgnoreCase)); if (num == -1) { continue; } foreach (InputControlScheme.DeviceRequirement deviceRequirement in inputActionAsset.controlSchemes[num].deviceRequirements) { WithControlsHavingToMatchPath(deviceRequirement.controlPath); } } } } return this; } public RebindingOperation WithBindingMask(InputBinding? bindingMask) { m_BindingMask = bindingMask; return this; } public RebindingOperation WithBindingGroup(string group) { return WithBindingMask(new InputBinding { groups = group }); } public RebindingOperation WithoutGeneralizingPathOfSelectedControl() { m_Flags |= Flags.DontGeneralizePathOfSelectedControl; return this; } public RebindingOperation WithRebindAddingNewBinding(string group = null) { m_Flags |= Flags.AddNewBinding; m_BindingGroupForNewBinding = group; return this; } public RebindingOperation WithMagnitudeHavingToBeGreaterThan(float magnitude) { ThrowIfRebindInProgress(); if (magnitude < 0f) { throw new ArgumentException($"Magnitude has to be positive but was {magnitude}", "magnitude"); } m_MagnitudeThreshold = magnitude; return this; } public RebindingOperation WithoutIgnoringNoisyControls() { ThrowIfRebindInProgress(); m_Flags |= Flags.DontIgnoreNoisyControls; return this; } public RebindingOperation WithControlsHavingToMatchPath(string path) { ThrowIfRebindInProgress(); if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } for (int i = 0; i < m_IncludePathCount; i++) { if (string.Compare(m_IncludePaths[i], path, StringComparison.InvariantCultureIgnoreCase) == 0) { return this; } } ArrayHelpers.AppendWithCapacity(ref m_IncludePaths, ref m_IncludePathCount, path); return this; } public RebindingOperation WithControlsExcluding(string path) { ThrowIfRebindInProgress(); if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } for (int i = 0; i < m_ExcludePathCount; i++) { if (string.Compare(m_ExcludePaths[i], path, StringComparison.InvariantCultureIgnoreCase) == 0) { return this; } } ArrayHelpers.AppendWithCapacity(ref m_ExcludePaths, ref m_ExcludePathCount, path); return this; } public RebindingOperation WithTimeout(float timeInSeconds) { m_Timeout = timeInSeconds; return this; } public RebindingOperation OnComplete(Action callback) { m_OnComplete = callback; return this; } public RebindingOperation OnCancel(Action callback) { m_OnCancel = callback; return this; } public RebindingOperation OnPotentialMatch(Action callback) { m_OnPotentialMatch = callback; return this; } public RebindingOperation OnGeneratePath(Func callback) { m_OnGeneratePath = callback; return this; } public RebindingOperation OnComputeScore(Func callback) { m_OnComputeScore = callback; return this; } public RebindingOperation OnApplyBinding(Action callback) { m_OnApplyBinding = callback; return this; } public RebindingOperation OnMatchWaitForAnother(float seconds) { m_WaitSecondsAfterMatch = seconds; return this; } public RebindingOperation Start() { if (started) { return this; } if (m_ActionToRebind != null && m_ActionToRebind.bindings.Count == 0 && (m_Flags & Flags.AddNewBinding) == 0) { throw new InvalidOperationException($"Action '{action}' must have at least one existing binding or must be used with WithRebindingAddNewBinding()"); } if (m_ActionToRebind == null && m_OnApplyBinding == null) { throw new InvalidOperationException("Must either have an action (call WithAction()) to apply binding to or have a custom callback to apply the binding (call OnApplyBinding())"); } m_StartTime = InputState.currentTime; if (m_WaitSecondsAfterMatch > 0f || m_Timeout > 0f) { HookOnAfterUpdate(); m_LastMatchTime = -1.0; } HookOnEvent(); m_Flags |= Flags.Started; m_Flags &= ~Flags.Canceled; m_Flags &= ~Flags.Completed; return this; } public void Cancel() { if (started) { OnCancel(); } } public void Complete() { if (started) { OnComplete(); } } public void AddCandidate(InputControl control, float score, float magnitude = -1f) { if (control == null) { throw new ArgumentNullException("control"); } int num = m_Candidates.IndexOf(control); if (num != -1) { m_Scores[num] = score; } else { int count = m_Candidates.Count; int count2 = m_Candidates.Count; m_Candidates.Add(control); ArrayHelpers.AppendWithCapacity(ref m_Scores, ref count, score); ArrayHelpers.AppendWithCapacity(ref m_Magnitudes, ref count2, magnitude); } SortCandidatesByScore(); } public void RemoveCandidate(InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } int num = m_Candidates.IndexOf(control); if (num != -1) { int count = m_Candidates.Count; m_Candidates.RemoveAt(num); m_Scores.EraseAtWithCapacity(ref count, num); } } public void Dispose() { UnhookOnEvent(); UnhookOnAfterUpdate(); m_Candidates.Dispose(); m_LayoutCache.Clear(); } ~RebindingOperation() { Dispose(); } public RebindingOperation Reset() { Cancel(); m_ActionToRebind = null; m_BindingMask = null; m_ControlType = null; m_ExpectedLayout = default(InternedString); m_IncludePathCount = 0; m_ExcludePathCount = 0; m_TargetBindingIndex = -1; m_BindingGroupForNewBinding = null; m_CancelBinding = null; m_MagnitudeThreshold = 0.2f; m_Timeout = 0f; m_WaitSecondsAfterMatch = 0f; m_Flags = (Flags)0; m_StartingActuations?.Clear(); return this; } private void HookOnEvent() { if ((m_Flags & Flags.OnEventHooked) == 0) { if (m_OnEventDelegate == null) { m_OnEventDelegate = OnEvent; } InputSystem.onEvent += m_OnEventDelegate; m_Flags |= Flags.OnEventHooked; } } private void UnhookOnEvent() { if ((m_Flags & Flags.OnEventHooked) != 0) { InputSystem.onEvent -= m_OnEventDelegate; m_Flags &= ~Flags.OnEventHooked; } } private unsafe void OnEvent(InputEventPtr eventPtr, InputDevice device) { FourCC type = eventPtr.type; if (type != 1398030676 && type != 1145852993) { return; } bool flag = false; bool flag2 = false; InputControlExtensions.Enumerate enumerate = InputControlExtensions.Enumerate.IncludeSyntheticControls | InputControlExtensions.Enumerate.IncludeNonLeafControls; if ((m_Flags & Flags.DontIgnoreNoisyControls) != 0) { enumerate |= InputControlExtensions.Enumerate.IncludeNoisyControls; } foreach (InputControl item in eventPtr.EnumerateControls(enumerate, device)) { void* statePtrFromStateEventUnchecked = item.GetStatePtrFromStateEventUnchecked(eventPtr, type); if (!string.IsNullOrEmpty(m_CancelBinding) && InputControlPath.Matches(m_CancelBinding, item) && item.HasValueChangeInState(statePtrFromStateEventUnchecked)) { OnCancel(); break; } if ((m_ExcludePathCount > 0 && HavePathMatch(item, m_ExcludePaths, m_ExcludePathCount)) || (m_IncludePathCount > 0 && !HavePathMatch(item, m_IncludePaths, m_IncludePathCount)) || (m_ControlType != null && !m_ControlType.IsInstanceOfType(item)) || (!m_ExpectedLayout.IsEmpty() && m_ExpectedLayout != item.m_Layout && !InputControlLayout.s_Layouts.IsBasedOn(m_ExpectedLayout, item.m_Layout))) { continue; } if (item.CheckStateIsAtDefault(statePtrFromStateEventUnchecked, null)) { if (!m_StartingActuations.ContainsKey(item)) { m_StartingActuations.Add(item, 0f); } m_StartingActuations[item] = 0f; continue; } flag2 = true; float num = item.EvaluateMagnitude(statePtrFromStateEventUnchecked); if (num >= 0f) { if (!m_StartingActuations.TryGetValue(item, out var value)) { value = item.magnitude; m_StartingActuations.Add(item, value); } if (Mathf.Abs(value - num) < m_MagnitudeThreshold) { continue; } } float num2; if (m_OnComputeScore != null) { num2 = m_OnComputeScore(item, eventPtr); } else { num2 = num; if (!item.synthetic) { num2 += 1f; } } int num3 = m_Candidates.IndexOf(item); if (num3 != -1) { if (m_Scores[num3] < num2) { flag = true; m_Scores[num3] = num2; if (m_WaitSecondsAfterMatch > 0f) { m_LastMatchTime = InputState.currentTime; } } continue; } int count = m_Candidates.Count; int count2 = m_Candidates.Count; m_Candidates.Add(item); ArrayHelpers.AppendWithCapacity(ref m_Scores, ref count, num2); ArrayHelpers.AppendWithCapacity(ref m_Magnitudes, ref count2, num); flag = true; if (m_WaitSecondsAfterMatch > 0f) { m_LastMatchTime = InputState.currentTime; } } if (flag2 && (m_Flags & Flags.SuppressMatchingEvents) != 0) { eventPtr.handled = true; } if (flag && !canceled) { if (m_OnPotentialMatch != null) { SortCandidatesByScore(); m_OnPotentialMatch(this); } else if (m_WaitSecondsAfterMatch <= 0f) { OnComplete(); } else { SortCandidatesByScore(); } } } private void SortCandidatesByScore() { int count = m_Candidates.Count; if (count <= 1) { return; } for (int i = 1; i < count; i++) { int num = i; while (num > 0 && m_Scores[num - 1] < m_Scores[num]) { int index = num - 1; m_Scores.SwapElements(num, index); m_Candidates.SwapElements(num, index); m_Magnitudes.SwapElements(num, index); num--; } } } private static bool HavePathMatch(InputControl control, string[] paths, int pathCount) { for (int i = 0; i < pathCount; i++) { if (InputControlPath.MatchesPrefix(paths[i], control)) { return true; } } return false; } private void HookOnAfterUpdate() { if ((m_Flags & Flags.OnAfterUpdateHooked) == 0) { if (m_OnAfterUpdateDelegate == null) { m_OnAfterUpdateDelegate = OnAfterUpdate; } InputSystem.onAfterUpdate += m_OnAfterUpdateDelegate; m_Flags |= Flags.OnAfterUpdateHooked; } } private void UnhookOnAfterUpdate() { if ((m_Flags & Flags.OnAfterUpdateHooked) != 0) { InputSystem.onAfterUpdate -= m_OnAfterUpdateDelegate; m_Flags &= ~Flags.OnAfterUpdateHooked; } } private void OnAfterUpdate() { if (m_LastMatchTime < 0.0 && m_Timeout > 0f && InputState.currentTime - m_StartTime > (double)m_Timeout) { Cancel(); } else if (!(m_WaitSecondsAfterMatch <= 0f) && !(m_LastMatchTime < 0.0) && InputState.currentTime >= m_LastMatchTime + (double)m_WaitSecondsAfterMatch) { Complete(); } } private void OnComplete() { SortCandidatesByScore(); if (m_Candidates.Count > 0) { InputControl inputControl = m_Candidates[0]; string text = inputControl.path; if (m_OnGeneratePath != null) { string text2 = m_OnGeneratePath(inputControl); if (!string.IsNullOrEmpty(text2)) { text = text2; } else if ((m_Flags & Flags.DontGeneralizePathOfSelectedControl) == 0) { text = GeneratePathForControl(inputControl); } } else if ((m_Flags & Flags.DontGeneralizePathOfSelectedControl) == 0) { text = GeneratePathForControl(inputControl); } if (m_OnApplyBinding != null) { m_OnApplyBinding(this, text); } else if ((m_Flags & Flags.AddNewBinding) != 0) { m_ActionToRebind.AddBinding(text, null, null, m_BindingGroupForNewBinding); } else if (m_TargetBindingIndex >= 0) { if (m_TargetBindingIndex >= m_ActionToRebind.bindings.Count) { throw new InvalidOperationException($"Target binding index {m_TargetBindingIndex} out of range for action '{m_ActionToRebind}' with {m_ActionToRebind.bindings.Count} bindings"); } m_ActionToRebind.ApplyBindingOverride(m_TargetBindingIndex, text); } else if (m_BindingMask.HasValue) { InputBinding value = m_BindingMask.Value; value.overridePath = text; m_ActionToRebind.ApplyBindingOverride(value); } else { m_ActionToRebind.ApplyBindingOverride(text); } } m_Flags |= Flags.Completed; m_OnComplete?.Invoke(this); ResetAfterMatchCompleted(); } private void OnCancel() { m_Flags |= Flags.Canceled; m_OnCancel?.Invoke(this); ResetAfterMatchCompleted(); } private void ResetAfterMatchCompleted() { m_Flags &= ~Flags.Started; m_Candidates.Clear(); m_Candidates.Capacity = 0; m_StartTime = -1.0; m_StartingActuations.Clear(); UnhookOnEvent(); UnhookOnAfterUpdate(); } private void ThrowIfRebindInProgress() { if (started) { throw new InvalidOperationException("Cannot reconfigure rebinding while operation is in progress"); } } private string GeneratePathForControl(InputControl control) { _ = control.device; InternedString internedString = InputControlLayout.s_Layouts.FindLayoutThatIntroducesControl(control, m_LayoutCache); if (m_PathBuilder == null) { m_PathBuilder = new StringBuilder(); } else { m_PathBuilder.Length = 0; } control.BuildPath(internedString, m_PathBuilder); return m_PathBuilder.ToString(); } } internal class DeferBindingResolutionWrapper : IDisposable { public void Acquire() { InputActionMap.s_DeferBindingResolution++; } public void Dispose() { if (InputActionMap.s_DeferBindingResolution > 0) { InputActionMap.s_DeferBindingResolution--; } if (InputActionMap.s_DeferBindingResolution == 0) { InputActionState.DeferredResolutionOfBindings(); } } } private static DeferBindingResolutionWrapper s_DeferBindingResolutionWrapper; public static PrimitiveValue? GetParameterValue(this InputAction action, string name, InputBinding bindingMask = default(InputBinding)) { if (action == null) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } return action.GetParameterValue(new ParameterOverride(name, bindingMask)); } private static PrimitiveValue? GetParameterValue(this InputAction action, ParameterOverride parameterOverride) { parameterOverride.bindingMask.action = action.name; InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); using (ParameterEnumerator parameterEnumerator = new ParameterEnumerable(orCreateActionMap.m_State, parameterOverride, orCreateActionMap.m_MapIndexInState).GetEnumerator()) { if (parameterEnumerator.MoveNext()) { Parameter current = parameterEnumerator.Current; return PrimitiveValue.FromObject(current.field.GetValue(current.instance)); } } return null; } public static PrimitiveValue? GetParameterValue(this InputAction action, string name, int bindingIndex) { if (action == null) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (bindingIndex < 0) { throw new ArgumentOutOfRangeException("bindingIndex"); } int index = action.BindingIndexOnActionToBindingIndexOnMap(bindingIndex); InputBinding bindingMask = new InputBinding { id = action.GetOrCreateActionMap().bindings[index].id }; return action.GetParameterValue(name, bindingMask); } public unsafe static TValue? GetParameterValue(this InputAction action, Expression> expr, InputBinding bindingMask = default(InputBinding)) where TValue : struct { if (action == null) { throw new ArgumentNullException("action"); } if (expr == null) { throw new ArgumentNullException("expr"); } ParameterOverride parameterOverride = ExtractParameterOverride(expr, bindingMask); PrimitiveValue? parameterValue = action.GetParameterValue(parameterOverride); if (!parameterValue.HasValue) { return null; } if (Type.GetTypeCode(typeof(TValue)) == parameterValue.Value.type) { PrimitiveValue value = parameterValue.Value; TValue value2 = default(TValue); UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref value2), (void*)value.valuePtr, (long)UnsafeUtility.SizeOf()); return value2; } return (TValue)Convert.ChangeType(parameterValue.Value.ToObject(), typeof(TValue)); } public static void ApplyParameterOverride(this InputAction action, Expression> expr, TValue value, InputBinding bindingMask = default(InputBinding)) where TValue : struct { if (action == null) { throw new ArgumentNullException("action"); } if (expr == null) { throw new ArgumentNullException("expr"); } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); bindingMask.action = action.name; ParameterOverride parameterOverride = ExtractParameterOverride(expr, bindingMask, PrimitiveValue.From(value)); ApplyParameterOverride(orCreateActionMap.m_State, orCreateActionMap.m_MapIndexInState, ref orCreateActionMap.m_ParameterOverrides, ref orCreateActionMap.m_ParameterOverridesCount, parameterOverride); } public static void ApplyParameterOverride(this InputActionMap actionMap, Expression> expr, TValue value, InputBinding bindingMask = default(InputBinding)) where TValue : struct { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (expr == null) { throw new ArgumentNullException("expr"); } actionMap.ResolveBindingsIfNecessary(); ParameterOverride parameterOverride = ExtractParameterOverride(expr, bindingMask, PrimitiveValue.From(value)); ApplyParameterOverride(actionMap.m_State, actionMap.m_MapIndexInState, ref actionMap.m_ParameterOverrides, ref actionMap.m_ParameterOverridesCount, parameterOverride); } public static void ApplyParameterOverride(this InputActionAsset asset, Expression> expr, TValue value, InputBinding bindingMask = default(InputBinding)) where TValue : struct { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (expr == null) { throw new ArgumentNullException("expr"); } asset.ResolveBindingsIfNecessary(); ParameterOverride parameterOverride = ExtractParameterOverride(expr, bindingMask, PrimitiveValue.From(value)); ApplyParameterOverride(asset.m_SharedStateForAllMaps, -1, ref asset.m_ParameterOverrides, ref asset.m_ParameterOverridesCount, parameterOverride); } private static ParameterOverride ExtractParameterOverride(Expression> expr, InputBinding bindingMask = default(InputBinding), PrimitiveValue value = default(PrimitiveValue)) { if (expr == null) { throw new ArgumentException("Expression must be a LambdaExpression but was a " + expr.GetType().Name + " instead", "expr"); } MemberExpression memberExpression = expr.Body as MemberExpression; if (memberExpression == null) { if (!(expr.Body is UnaryExpression { NodeType: ExpressionType.Convert, Operand: MemberExpression operand })) { throw new ArgumentException("Body in LambdaExpression must be a MemberExpression (x.name) but was a " + expr.GetType().Name + " instead", "expr"); } memberExpression = operand; } string objectRegistrationName; if (typeof(InputProcessor).IsAssignableFrom(typeof(TObject))) { objectRegistrationName = InputProcessor.s_Processors.FindNameForType(typeof(TObject)); } else if (typeof(IInputInteraction).IsAssignableFrom(typeof(TObject))) { objectRegistrationName = InputInteraction.s_Interactions.FindNameForType(typeof(TObject)); } else { if (!typeof(InputBindingComposite).IsAssignableFrom(typeof(TObject))) { throw new ArgumentException("Given type must be an InputProcessor, IInputInteraction, or InputBindingComposite (was " + typeof(TObject).Name + ")", "TObject"); } objectRegistrationName = InputBindingComposite.s_Composites.FindNameForType(typeof(TObject)); } return new ParameterOverride(objectRegistrationName, memberExpression.Member.Name, bindingMask, value); } public static void ApplyParameterOverride(this InputActionMap actionMap, string name, PrimitiveValue value, InputBinding bindingMask = default(InputBinding)) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } actionMap.ResolveBindingsIfNecessary(); ApplyParameterOverride(actionMap.m_State, actionMap.m_MapIndexInState, ref actionMap.m_ParameterOverrides, ref actionMap.m_ParameterOverridesCount, new ParameterOverride(name, bindingMask, value)); } public static void ApplyParameterOverride(this InputActionAsset asset, string name, PrimitiveValue value, InputBinding bindingMask = default(InputBinding)) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } asset.ResolveBindingsIfNecessary(); ApplyParameterOverride(asset.m_SharedStateForAllMaps, -1, ref asset.m_ParameterOverrides, ref asset.m_ParameterOverridesCount, new ParameterOverride(name, bindingMask, value)); } public static void ApplyParameterOverride(this InputAction action, string name, PrimitiveValue value, InputBinding bindingMask = default(InputBinding)) { if (action == null) { throw new ArgumentNullException("action"); } if (name == null) { throw new ArgumentNullException("name"); } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); bindingMask.action = action.name; ApplyParameterOverride(orCreateActionMap.m_State, orCreateActionMap.m_MapIndexInState, ref orCreateActionMap.m_ParameterOverrides, ref orCreateActionMap.m_ParameterOverridesCount, new ParameterOverride(name, bindingMask, value)); } public static void ApplyParameterOverride(this InputAction action, string name, PrimitiveValue value, int bindingIndex) { if (action == null) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (bindingIndex < 0) { throw new ArgumentOutOfRangeException("bindingIndex"); } int index = action.BindingIndexOnActionToBindingIndexOnMap(bindingIndex); InputBinding bindingMask = new InputBinding { id = action.GetOrCreateActionMap().bindings[index].id }; action.ApplyParameterOverride(name, value, bindingMask); } private static void ApplyParameterOverride(InputActionState state, int mapIndex, ref ParameterOverride[] parameterOverrides, ref int parameterOverridesCount, ParameterOverride parameterOverride) { bool flag = false; if (parameterOverrides != null) { for (int i = 0; i < parameterOverridesCount; i++) { ref ParameterOverride reference = ref parameterOverrides[i]; if (string.Equals(reference.objectRegistrationName, parameterOverride.objectRegistrationName, StringComparison.OrdinalIgnoreCase) && string.Equals(reference.parameter, parameterOverride.parameter, StringComparison.OrdinalIgnoreCase) && reference.bindingMask == parameterOverride.bindingMask) { flag = true; reference = parameterOverride; break; } } } if (!flag) { ArrayHelpers.AppendWithCapacity(ref parameterOverrides, ref parameterOverridesCount, parameterOverride); } foreach (Parameter item in new ParameterEnumerable(state, parameterOverride, mapIndex)) { ParameterOverride? parameterOverride2 = ParameterOverride.Find(state.GetActionMap(item.bindingIndex), ref state.GetBinding(item.bindingIndex), parameterOverride.parameter, parameterOverride.objectRegistrationName); if (parameterOverride2.HasValue) { TypeCode typeCode = Type.GetTypeCode(item.field.FieldType); item.field.SetValue(item.instance, parameterOverride2.Value.value.ConvertTo(typeCode).ToObject()); } } } public static int GetBindingIndex(this InputAction action, InputBinding bindingMask) { if (action == null) { throw new ArgumentNullException("action"); } ReadOnlyArray bindings = action.bindings; for (int i = 0; i < bindings.Count; i++) { if (bindingMask.Matches(bindings[i])) { return i; } } return -1; } public static int GetBindingIndex(this InputActionMap actionMap, InputBinding bindingMask) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } ReadOnlyArray bindings = actionMap.bindings; for (int i = 0; i < bindings.Count; i++) { if (bindingMask.Matches(bindings[i])) { return i; } } return -1; } public static int GetBindingIndex(this InputAction action, string group = null, string path = null) { if (action == null) { throw new ArgumentNullException("action"); } return action.GetBindingIndex(new InputBinding(path, null, group)); } public static InputBinding? GetBindingForControl(this InputAction action, InputControl control) { if (action == null) { throw new ArgumentNullException("action"); } if (control == null) { throw new ArgumentNullException("control"); } int bindingIndexForControl = action.GetBindingIndexForControl(control); if (bindingIndexForControl == -1) { return null; } return action.bindings[bindingIndexForControl]; } public unsafe static int GetBindingIndexForControl(this InputAction action, InputControl control) { if (action == null) { throw new ArgumentNullException("action"); } if (control == null) { throw new ArgumentNullException("control"); } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); InputActionState state = orCreateActionMap.m_State; InputControl[] controls = state.controls; int totalControlCount = state.totalControlCount; InputActionState.BindingState* bindingStates = state.bindingStates; int* controlIndexToBindingIndex = state.controlIndexToBindingIndex; int actionIndexInState = action.m_ActionIndexInState; for (int i = 0; i < totalControlCount; i++) { if (controls[i] == control) { int num = controlIndexToBindingIndex[i]; if (bindingStates[num].actionIndex == actionIndexInState) { int bindingIndexInMap = state.GetBindingIndexInMap(num); return action.BindingIndexOnMapToBindingIndexOnAction(bindingIndexInMap); } } } return -1; } public static string GetBindingDisplayString(this InputAction action, InputBinding.DisplayStringOptions options = (InputBinding.DisplayStringOptions)0, string group = null) { if (action == null) { throw new ArgumentNullException("action"); } InputBinding bindingMask; if (!string.IsNullOrEmpty(group)) { bindingMask = InputBinding.MaskByGroup(group); } else { InputBinding? inputBinding = action.FindEffectiveBindingMask(); bindingMask = ((!inputBinding.HasValue) ? default(InputBinding) : inputBinding.Value); } return action.GetBindingDisplayString(bindingMask, options); } public static string GetBindingDisplayString(this InputAction action, InputBinding bindingMask, InputBinding.DisplayStringOptions options = (InputBinding.DisplayStringOptions)0) { if (action == null) { throw new ArgumentNullException("action"); } string text = string.Empty; ReadOnlyArray bindings = action.bindings; for (int i = 0; i < bindings.Count; i++) { if (!bindings[i].isPartOfComposite && bindingMask.Matches(bindings[i])) { string bindingDisplayString = action.GetBindingDisplayString(i, options); text = ((!(text != "")) ? bindingDisplayString : (text + " | " + bindingDisplayString)); } } return text; } public static string GetBindingDisplayString(this InputAction action, int bindingIndex, InputBinding.DisplayStringOptions options = (InputBinding.DisplayStringOptions)0) { if (action == null) { throw new ArgumentNullException("action"); } string deviceLayoutName; string controlPath; return action.GetBindingDisplayString(bindingIndex, out deviceLayoutName, out controlPath, options); } public unsafe static string GetBindingDisplayString(this InputAction action, int bindingIndex, out string deviceLayoutName, out string controlPath, InputBinding.DisplayStringOptions options = (InputBinding.DisplayStringOptions)0) { if (action == null) { throw new ArgumentNullException("action"); } deviceLayoutName = null; controlPath = null; ReadOnlyArray bindings = action.bindings; int count = bindings.Count; if (bindingIndex < 0 || bindingIndex >= count) { throw new ArgumentOutOfRangeException($"Binding index {bindingIndex} is out of range on action '{action}' with {bindings.Count} bindings", "bindingIndex"); } if (bindings[bindingIndex].isComposite) { string name = NameAndParameters.Parse(bindings[bindingIndex].effectivePath).name; int firstPartIndex = bindingIndex + 1; int i; for (i = firstPartIndex; i < count && bindings[i].isPartOfComposite; i++) { } int partCount = i - firstPartIndex; string[] partStrings = new string[partCount]; for (int j = 0; j < partCount; j++) { string text = action.GetBindingDisplayString(firstPartIndex + j, options); if (string.IsNullOrEmpty(text)) { text = " "; } partStrings[j] = text; } string displayFormatString = InputBindingComposite.GetDisplayFormatString(name); if (string.IsNullOrEmpty(displayFormatString)) { return StringHelpers.Join("/", partStrings); } return StringHelpers.ExpandTemplateString(displayFormatString, delegate(string fragment) { string text2 = string.Empty; for (int k = 0; k < partCount; k++) { if (string.Equals(bindings[firstPartIndex + k].name, fragment, StringComparison.InvariantCultureIgnoreCase)) { text2 = (string.IsNullOrEmpty(text2) ? partStrings[k] : (text2 + "|" + partStrings[k])); } } if (string.IsNullOrEmpty(text2)) { text2 = " "; } return text2; }); } InputControl control = null; InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); InputActionState state = orCreateActionMap.m_State; int bindingIndexInMap = action.BindingIndexOnActionToBindingIndexOnMap(bindingIndex); int bindingIndexInState = state.GetBindingIndexInState(orCreateActionMap.m_MapIndexInState, bindingIndexInMap); InputActionState.BindingState* ptr = state.bindingStates + bindingIndexInState; if (ptr->controlCount > 0) { control = state.controls[ptr->controlStartIndex]; } InputBinding inputBinding = bindings[bindingIndex]; if (string.IsNullOrEmpty(inputBinding.effectiveInteractions)) { inputBinding.overrideInteractions = action.interactions; } else if (!string.IsNullOrEmpty(action.interactions)) { inputBinding.overrideInteractions = inputBinding.effectiveInteractions + ";action.interactions"; } return inputBinding.ToDisplayString(out deviceLayoutName, out controlPath, options, control); } public static void ApplyBindingOverride(this InputAction action, string newPath, string group = null, string path = null) { if (action == null) { throw new ArgumentNullException("action"); } action.ApplyBindingOverride(new InputBinding { overridePath = newPath, groups = group, path = path }); } public static void ApplyBindingOverride(this InputAction action, InputBinding bindingOverride) { if (action == null) { throw new ArgumentNullException("action"); } bool enabled = action.enabled; if (enabled) { action.Disable(); } bindingOverride.action = action.name; action.GetOrCreateActionMap().ApplyBindingOverride(bindingOverride); if (enabled) { action.Enable(); action.RequestInitialStateCheckOnEnabledAction(); } } public static void ApplyBindingOverride(this InputAction action, int bindingIndex, InputBinding bindingOverride) { if (action == null) { throw new ArgumentNullException("action"); } int bindingIndex2 = action.BindingIndexOnActionToBindingIndexOnMap(bindingIndex); bindingOverride.action = action.name; action.GetOrCreateActionMap().ApplyBindingOverride(bindingIndex2, bindingOverride); } public static void ApplyBindingOverride(this InputAction action, int bindingIndex, string path) { if (path == null) { throw new ArgumentException("Binding path cannot be null", "path"); } action.ApplyBindingOverride(bindingIndex, new InputBinding { overridePath = path }); } public static int ApplyBindingOverride(this InputActionMap actionMap, InputBinding bindingOverride) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } InputBinding[] bindings = actionMap.m_Bindings; if (bindings == null) { return 0; } int num = bindings.Length; int num2 = 0; for (int i = 0; i < num; i++) { if (bindingOverride.Matches(ref bindings[i])) { bindings[i].overridePath = bindingOverride.overridePath; bindings[i].overrideInteractions = bindingOverride.overrideInteractions; bindings[i].overrideProcessors = bindingOverride.overrideProcessors; num2++; } } if (num2 > 0) { actionMap.OnBindingModified(); } return num2; } public static void ApplyBindingOverride(this InputActionMap actionMap, int bindingIndex, InputBinding bindingOverride) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } InputBinding[] bindings = actionMap.m_Bindings; int num = ((bindings != null) ? bindings.Length : 0); if (bindingIndex < 0 || bindingIndex >= num) { throw new ArgumentOutOfRangeException("bindingIndex", $"Cannot apply override to binding at index {bindingIndex} in map '{actionMap}' with only {num} bindings"); } actionMap.m_Bindings[bindingIndex].overridePath = bindingOverride.overridePath; actionMap.m_Bindings[bindingIndex].overrideInteractions = bindingOverride.overrideInteractions; actionMap.m_Bindings[bindingIndex].overrideProcessors = bindingOverride.overrideProcessors; actionMap.OnBindingModified(); } public static void RemoveBindingOverride(this InputAction action, int bindingIndex) { if (action == null) { throw new ArgumentNullException("action"); } action.ApplyBindingOverride(bindingIndex, default(InputBinding)); } public static void RemoveBindingOverride(this InputAction action, InputBinding bindingMask) { if (action == null) { throw new ArgumentNullException("action"); } bindingMask.overridePath = null; bindingMask.overrideInteractions = null; bindingMask.overrideProcessors = null; action.ApplyBindingOverride(bindingMask); } private static void RemoveBindingOverride(this InputActionMap actionMap, InputBinding bindingMask) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } bindingMask.overridePath = null; bindingMask.overrideInteractions = null; bindingMask.overrideProcessors = null; actionMap.ApplyBindingOverride(bindingMask); } public static void RemoveAllBindingOverrides(this IInputActionCollection2 actions) { if (actions == null) { throw new ArgumentNullException("actions"); } using (DeferBindingResolution()) { foreach (InputAction action in actions) { InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); InputBinding[] bindings = orCreateActionMap.m_Bindings; int num = bindings.LengthSafe(); for (int i = 0; i < num; i++) { ref InputBinding reference = ref bindings[i]; if (reference.TriggersAction(action)) { reference.RemoveOverrides(); } } orCreateActionMap.OnBindingModified(); } } } public static void RemoveAllBindingOverrides(this InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } string name = action.name; InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); InputBinding[] bindings = orCreateActionMap.m_Bindings; if (bindings == null) { return; } int num = bindings.Length; for (int i = 0; i < num; i++) { if (string.Compare(bindings[i].action, name, StringComparison.InvariantCultureIgnoreCase) == 0) { bindings[i].overridePath = null; bindings[i].overrideInteractions = null; bindings[i].overrideProcessors = null; } } orCreateActionMap.OnBindingModified(); } public static void ApplyBindingOverrides(this InputActionMap actionMap, IEnumerable overrides) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (overrides == null) { throw new ArgumentNullException("overrides"); } foreach (InputBinding @override in overrides) { actionMap.ApplyBindingOverride(@override); } } public static void RemoveBindingOverrides(this InputActionMap actionMap, IEnumerable overrides) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (overrides == null) { throw new ArgumentNullException("overrides"); } foreach (InputBinding @override in overrides) { actionMap.RemoveBindingOverride(@override); } } public static int ApplyBindingOverridesOnMatchingControls(this InputAction action, InputControl control) { if (action == null) { throw new ArgumentNullException("action"); } if (control == null) { throw new ArgumentNullException("control"); } ReadOnlyArray bindings = action.bindings; int count = bindings.Count; int num = 0; for (int i = 0; i < count; i++) { InputControl inputControl = InputControlPath.TryFindControl(control, bindings[i].path); if (inputControl != null) { action.ApplyBindingOverride(i, inputControl.path); num++; } } return num; } public static int ApplyBindingOverridesOnMatchingControls(this InputActionMap actionMap, InputControl control) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (control == null) { throw new ArgumentNullException("control"); } ReadOnlyArray actions = actionMap.actions; int count = actions.Count; int result = 0; for (int i = 0; i < count; i++) { result = actions[i].ApplyBindingOverridesOnMatchingControls(control); } return result; } public static string SaveBindingOverridesAsJson(this IInputActionCollection2 actions) { if (actions == null) { throw new ArgumentNullException("actions"); } List list = new List(); foreach (InputBinding binding in actions.bindings) { actions.AddBindingOverrideJsonTo(binding, list); } if (list.Count == 0) { return string.Empty; } return JsonUtility.ToJson((object)new InputActionMap.BindingOverrideListJson { bindings = list }); } public static string SaveBindingOverridesAsJson(this InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } bool isSingletonAction = action.isSingletonAction; InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); List list = new List(); foreach (InputBinding binding in action.bindings) { if (isSingletonAction || binding.TriggersAction(action)) { orCreateActionMap.AddBindingOverrideJsonTo(binding, list, isSingletonAction ? action : null); } } if (list.Count == 0) { return string.Empty; } return JsonUtility.ToJson((object)new InputActionMap.BindingOverrideListJson { bindings = list }); } private static void AddBindingOverrideJsonTo(this IInputActionCollection2 actions, InputBinding binding, List list, InputAction action = null) { if (binding.hasOverrides) { if (action == null) { action = actions.FindAction(binding.action); } string actionName = ((action != null && !action.isSingletonAction) ? (action.actionMap.name + "/" + action.name) : ""); InputActionMap.BindingOverrideJson item = InputActionMap.BindingOverrideJson.FromBinding(binding, actionName); list.Add(item); } } public static void LoadBindingOverridesFromJson(this IInputActionCollection2 actions, string json, bool removeExisting = true) { if (actions == null) { throw new ArgumentNullException("actions"); } using (DeferBindingResolution()) { if (removeExisting) { actions.RemoveAllBindingOverrides(); } actions.LoadBindingOverridesFromJsonInternal(json); } } public static void LoadBindingOverridesFromJson(this InputAction action, string json, bool removeExisting = true) { if (action == null) { throw new ArgumentNullException("action"); } using (DeferBindingResolution()) { if (removeExisting) { action.RemoveAllBindingOverrides(); } action.GetOrCreateActionMap().LoadBindingOverridesFromJsonInternal(json); } } private static void LoadBindingOverridesFromJsonInternal(this IInputActionCollection2 actions, string json) { if (string.IsNullOrEmpty(json)) { return; } foreach (InputActionMap.BindingOverrideJson binding in JsonUtility.FromJson(json).bindings) { if (!string.IsNullOrEmpty(binding.id)) { InputAction action; int num = actions.FindBinding(new InputBinding { m_Id = binding.id }, out action); if (num != -1) { action.ApplyBindingOverride(num, InputActionMap.BindingOverrideJson.ToBinding(binding)); continue; } } Debug.LogWarning((object)("Could not override binding as no existing binding was found with the id: " + binding.id)); } } public static RebindingOperation PerformInteractiveRebinding(this InputAction action, int bindingIndex = -1) { if (action == null) { throw new ArgumentNullException("action"); } RebindingOperation rebindingOperation = new RebindingOperation().WithAction(action).OnMatchWaitForAnother(0.05f).WithControlsExcluding("/delta") .WithControlsExcluding("/position") .WithControlsExcluding("/touch*/position") .WithControlsExcluding("/touch*/delta") .WithControlsExcluding("/clickCount") .WithMatchingEventsBeingSuppressed(); if (rebindingOperation.expectedControlType != "Button") { rebindingOperation.WithCancelingThrough("/escape"); } if (bindingIndex >= 0) { ReadOnlyArray bindings = action.bindings; if (bindingIndex >= bindings.Count) { throw new ArgumentOutOfRangeException($"Binding index {bindingIndex} is out of range for action '{action}' with {bindings.Count} bindings", "bindings"); } if (bindings[bindingIndex].isComposite) { throw new InvalidOperationException($"Cannot perform rebinding on composite binding '{bindings[bindingIndex]}' of '{action}'"); } rebindingOperation.WithTargetBinding(bindingIndex); } return rebindingOperation; } internal static DeferBindingResolutionWrapper DeferBindingResolution() { if (s_DeferBindingResolutionWrapper == null) { s_DeferBindingResolutionWrapper = new DeferBindingResolutionWrapper(); } s_DeferBindingResolutionWrapper.Acquire(); return s_DeferBindingResolutionWrapper; } } public enum InputActionPhase { Disabled, Waiting, Started, Performed, Canceled } [Serializable] public struct InputActionProperty : IEquatable, IEquatable, IEquatable { [SerializeField] private bool m_UseReference; [SerializeField] private InputAction m_Action; [SerializeField] private InputActionReference m_Reference; public InputAction action { get { if (!m_UseReference) { return m_Action; } if (!((Object)(object)m_Reference != (Object)null)) { return null; } return m_Reference.action; } } public InputActionReference reference { get { if (!m_UseReference) { return null; } return m_Reference; } } public InputActionProperty(InputAction action) { m_UseReference = false; m_Action = action; m_Reference = null; } public InputActionProperty(InputActionReference reference) { m_UseReference = true; m_Action = null; m_Reference = reference; } public bool Equals(InputActionProperty other) { if ((Object)(object)m_Reference == (Object)(object)other.m_Reference && m_UseReference == other.m_UseReference) { return m_Action == other.m_Action; } return false; } public bool Equals(InputAction other) { return action == other; } public bool Equals(InputActionReference other) { return (Object)(object)m_Reference == (Object)(object)other; } public override bool Equals(object obj) { if (m_UseReference) { return Equals(obj as InputActionReference); } return Equals(obj as InputAction); } public override int GetHashCode() { if (m_UseReference) { if (!((Object)(object)m_Reference != (Object)null)) { return 0; } return ((object)m_Reference).GetHashCode(); } if (m_Action == null) { return 0; } return m_Action.GetHashCode(); } public static bool operator ==(InputActionProperty left, InputActionProperty right) { return left.Equals(right); } public static bool operator !=(InputActionProperty left, InputActionProperty right) { return !left.Equals(right); } } public class InputActionReference : ScriptableObject { [SerializeField] internal InputActionAsset m_Asset; [SerializeField] internal string m_ActionId; [NonSerialized] private InputAction m_Action; public InputActionAsset asset => m_Asset; public InputAction action { get { if (m_Action == null) { if ((Object)(object)m_Asset == (Object)null) { return null; } m_Action = m_Asset.FindAction(new Guid(m_ActionId)); } return m_Action; } } public void Set(InputAction action) { if (action == null) { m_Asset = null; m_ActionId = null; return; } InputActionMap actionMap = action.actionMap; if (actionMap == null || (Object)(object)actionMap.asset == (Object)null) { throw new InvalidOperationException($"Action '{action}' must be part of an InputActionAsset in order to be able to create an InputActionReference for it"); } SetInternal(actionMap.asset, action); } public void Set(InputActionAsset asset, string mapName, string actionName) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (string.IsNullOrEmpty(mapName)) { throw new ArgumentNullException("mapName"); } if (string.IsNullOrEmpty(actionName)) { throw new ArgumentNullException("actionName"); } InputAction inputAction = (asset.FindActionMap(mapName) ?? throw new ArgumentException($"No action map '{mapName}' in '{asset}'", "mapName")).FindAction(actionName); if (inputAction == null) { throw new ArgumentException($"No action '{actionName}' in map '{mapName}' of asset '{asset}'", "actionName"); } SetInternal(asset, inputAction); } private void SetInternal(InputActionAsset asset, InputAction action) { InputActionMap actionMap = action.actionMap; if (!Enumerable.Contains(asset.actionMaps, actionMap)) { throw new ArgumentException($"Action '{action}' is not contained in asset '{asset}'", "action"); } m_Asset = asset; m_ActionId = action.id.ToString(); ((Object)this).name = GetDisplayName(action); } public override string ToString() { try { InputAction inputAction = action; return ((Object)m_Asset).name + ":" + inputAction.actionMap.name + "/" + inputAction.name; } catch { if ((Object)(object)m_Asset != (Object)null) { return ((Object)m_Asset).name + ":" + m_ActionId; } } return ((Object)this).ToString(); } private static string GetDisplayName(InputAction action) { if (string.IsNullOrEmpty(action?.actionMap?.name)) { return action?.name; } return action.actionMap?.name + "/" + action.name; } internal string ToDisplayName() { if (!string.IsNullOrEmpty(((Object)this).name)) { return ((Object)this).name; } return GetDisplayName(action); } public static implicit operator InputAction(InputActionReference reference) { return reference?.action; } public static InputActionReference Create(InputAction action) { if (action == null) { return null; } InputActionReference inputActionReference = ScriptableObject.CreateInstance(); inputActionReference.Set(action); return inputActionReference; } public InputAction ToInputAction() { return action; } } public static class InputActionSetupExtensions { public struct BindingSyntax { private readonly InputActionMap m_ActionMap; private readonly InputAction m_Action; internal readonly int m_BindingIndexInMap; public bool valid { get { if (m_ActionMap != null && m_BindingIndexInMap >= 0) { return m_BindingIndexInMap < m_ActionMap.m_Bindings.LengthSafe(); } return false; } } public int bindingIndex { get { if (!valid) { return -1; } if (m_Action != null) { return m_Action.BindingIndexOnMapToBindingIndexOnAction(m_BindingIndexInMap); } return m_BindingIndexInMap; } } public InputBinding binding { get { if (!valid) { throw new InvalidOperationException("BindingSyntax accessor is not valid"); } return m_ActionMap.m_Bindings[m_BindingIndexInMap]; } } internal BindingSyntax(InputActionMap map, int bindingIndexInMap, InputAction action = null) { m_ActionMap = map; m_BindingIndexInMap = bindingIndexInMap; m_Action = action; } public BindingSyntax WithName(string name) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } m_ActionMap.m_Bindings[m_BindingIndexInMap].name = name; m_ActionMap.OnBindingModified(); return this; } public BindingSyntax WithPath(string path) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } m_ActionMap.m_Bindings[m_BindingIndexInMap].path = path; m_ActionMap.OnBindingModified(); return this; } public BindingSyntax WithGroup(string group) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (string.IsNullOrEmpty(group)) { throw new ArgumentException("Group name cannot be null or empty", "group"); } if (group.IndexOf(';') != -1) { throw new ArgumentException($"Group name cannot contain separator character '{';'}'", "group"); } return WithGroups(group); } public BindingSyntax WithGroups(string groups) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (string.IsNullOrEmpty(groups)) { return this; } string groups2 = m_ActionMap.m_Bindings[m_BindingIndexInMap].groups; if (!string.IsNullOrEmpty(groups2)) { groups = string.Join(";", groups2, groups); } m_ActionMap.m_Bindings[m_BindingIndexInMap].groups = groups; m_ActionMap.OnBindingModified(); return this; } public BindingSyntax WithInteraction(string interaction) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (string.IsNullOrEmpty(interaction)) { throw new ArgumentException("Interaction cannot be null or empty", "interaction"); } if (interaction.IndexOf(';') != -1) { throw new ArgumentException($"Interaction string cannot contain separator character '{';'}'", "interaction"); } return WithInteractions(interaction); } public BindingSyntax WithInteractions(string interactions) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (string.IsNullOrEmpty(interactions)) { return this; } string interactions2 = m_ActionMap.m_Bindings[m_BindingIndexInMap].interactions; if (!string.IsNullOrEmpty(interactions2)) { interactions = string.Join(";", interactions2, interactions); } m_ActionMap.m_Bindings[m_BindingIndexInMap].interactions = interactions; m_ActionMap.OnBindingModified(); return this; } public BindingSyntax WithInteraction() where TInteraction : IInputInteraction { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } InternedString internedString = InputProcessor.s_Processors.FindNameForType(typeof(TInteraction)); if (internedString.IsEmpty()) { throw new NotSupportedException($"Type '{typeof(TInteraction)}' has not been registered as a processor"); } return WithInteraction(internedString); } public BindingSyntax WithProcessor(string processor) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (string.IsNullOrEmpty(processor)) { throw new ArgumentException("Processor cannot be null or empty", "processor"); } if (processor.IndexOf(';') != -1) { throw new ArgumentException($"Processor string cannot contain separator character '{';'}'", "processor"); } return WithProcessors(processor); } public BindingSyntax WithProcessors(string processors) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (string.IsNullOrEmpty(processors)) { return this; } string processors2 = m_ActionMap.m_Bindings[m_BindingIndexInMap].processors; if (!string.IsNullOrEmpty(processors2)) { processors = string.Join(";", processors2, processors); } m_ActionMap.m_Bindings[m_BindingIndexInMap].processors = processors; m_ActionMap.OnBindingModified(); return this; } public BindingSyntax WithProcessor() { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } InternedString internedString = InputProcessor.s_Processors.FindNameForType(typeof(TProcessor)); if (internedString.IsEmpty()) { throw new NotSupportedException($"Type '{typeof(TProcessor)}' has not been registered as a processor"); } return WithProcessor(internedString); } public BindingSyntax Triggering(InputAction action) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } if (action == null) { throw new ArgumentNullException("action"); } if (action.isSingletonAction) { throw new ArgumentException($"Cannot change the action a binding triggers on singleton action '{action}'", "action"); } m_ActionMap.m_Bindings[m_BindingIndexInMap].action = action.name; m_ActionMap.OnBindingModified(); return this; } public BindingSyntax To(InputBinding binding) { if (!valid) { throw new InvalidOperationException("Accessor is not valid"); } m_ActionMap.m_Bindings[m_BindingIndexInMap] = binding; if (m_ActionMap.m_SingletonAction != null) { m_ActionMap.m_Bindings[m_BindingIndexInMap].action = m_ActionMap.m_SingletonAction.name; } m_ActionMap.OnBindingModified(); return this; } public BindingSyntax NextBinding() { return Iterate(next: true); } public BindingSyntax PreviousBinding() { return Iterate(next: false); } public BindingSyntax NextPartBinding(string partName) { if (string.IsNullOrEmpty(partName)) { throw new ArgumentNullException("partName"); } return IteratePartBinding(next: true, partName); } public BindingSyntax PreviousPartBinding(string partName) { if (string.IsNullOrEmpty(partName)) { throw new ArgumentNullException("partName"); } return IteratePartBinding(next: false, partName); } public BindingSyntax NextCompositeBinding(string compositeName = null) { return IterateCompositeBinding(next: true, compositeName); } public BindingSyntax PreviousCompositeBinding(string compositeName = null) { return IterateCompositeBinding(next: false, compositeName); } private BindingSyntax Iterate(bool next) { if (m_ActionMap == null) { return default(BindingSyntax); } InputBinding[] bindings = m_ActionMap.m_Bindings; if (bindings == null) { return default(BindingSyntax); } int num = m_BindingIndexInMap; do { num += (next ? 1 : (-1)); if (num < 0 || num >= bindings.Length) { return default(BindingSyntax); } } while (m_Action != null && !bindings[num].TriggersAction(m_Action)); return new BindingSyntax(m_ActionMap, num, m_Action); } private BindingSyntax IterateCompositeBinding(bool next, string compositeName) { BindingSyntax result = Iterate(next); while (result.valid) { if (result.binding.isComposite) { if (compositeName == null) { return result; } if (compositeName.Equals(result.binding.name, StringComparison.InvariantCultureIgnoreCase)) { return result; } string value = NameAndParameters.ParseName(result.binding.path); if (compositeName.Equals(value, StringComparison.InvariantCultureIgnoreCase)) { return result; } } result = result.Iterate(next); } return default(BindingSyntax); } private BindingSyntax IteratePartBinding(bool next, string partName) { if (!valid) { return default(BindingSyntax); } if (binding.isComposite) { if (!next) { return default(BindingSyntax); } } else if (!binding.isPartOfComposite) { return default(BindingSyntax); } BindingSyntax result = Iterate(next); while (result.valid) { if (!result.binding.isPartOfComposite) { return default(BindingSyntax); } if (partName.Equals(result.binding.name, StringComparison.InvariantCultureIgnoreCase)) { return result; } result = result.Iterate(next); } return default(BindingSyntax); } public void Erase() { if (!valid) { throw new InvalidOperationException("Instance not valid"); } bool isComposite = m_ActionMap.m_Bindings[m_BindingIndexInMap].isComposite; ArrayHelpers.EraseAt(ref m_ActionMap.m_Bindings, m_BindingIndexInMap); if (isComposite) { while (m_BindingIndexInMap < m_ActionMap.m_Bindings.LengthSafe() && m_ActionMap.m_Bindings[m_BindingIndexInMap].isPartOfComposite) { ArrayHelpers.EraseAt(ref m_ActionMap.m_Bindings, m_BindingIndexInMap); } } m_Action.m_BindingsCount = m_ActionMap.m_Bindings.LengthSafe(); m_ActionMap.OnBindingModified(); if (m_ActionMap.m_SingletonAction != null) { m_ActionMap.m_SingletonAction.m_SingletonActionBindings = m_ActionMap.m_Bindings; } } public BindingSyntax InsertPartBinding(string partName, string path) { if (string.IsNullOrEmpty(partName)) { throw new ArgumentNullException("partName"); } if (!valid) { throw new InvalidOperationException("Binding accessor is not valid"); } InputBinding inputBinding = binding; if (!inputBinding.isPartOfComposite && !inputBinding.isComposite) { throw new InvalidOperationException("Binding accessor must point to composite or part binding"); } AddBindingInternal(m_ActionMap, new InputBinding { path = path, isPartOfComposite = true, name = partName }, m_BindingIndexInMap + 1); return new BindingSyntax(m_ActionMap, m_BindingIndexInMap + 1, m_Action); } } public struct CompositeSyntax { private readonly InputAction m_Action; private readonly InputActionMap m_ActionMap; private int m_BindingIndexInMap; public int bindingIndex { get { if (m_ActionMap == null) { return -1; } if (m_Action != null) { return m_Action.BindingIndexOnMapToBindingIndexOnAction(m_BindingIndexInMap); } return m_BindingIndexInMap; } } internal CompositeSyntax(InputActionMap map, InputAction action, int compositeIndex) { m_Action = action; m_ActionMap = map; m_BindingIndexInMap = compositeIndex; } public CompositeSyntax With(string name, string binding, string groups = null, string processors = null) { using (InputActionRebindingExtensions.DeferBindingResolution()) { int bindingIndexInMap; if (m_Action != null) { bindingIndexInMap = m_Action.AddBinding(binding, null, processors, groups).m_BindingIndexInMap; } else { bindingIndexInMap = m_ActionMap.AddBinding(binding, null, groups, null, processors).m_BindingIndexInMap; } m_ActionMap.m_Bindings[bindingIndexInMap].name = name; m_ActionMap.m_Bindings[bindingIndexInMap].isPartOfComposite = true; } return this; } } public struct ControlSchemeSyntax { private readonly InputActionAsset m_Asset; private readonly int m_ControlSchemeIndex; private InputControlScheme m_ControlScheme; internal ControlSchemeSyntax(InputActionAsset asset, int index) { m_Asset = asset; m_ControlSchemeIndex = index; m_ControlScheme = default(InputControlScheme); } internal ControlSchemeSyntax(InputControlScheme controlScheme) { m_Asset = null; m_ControlSchemeIndex = -1; m_ControlScheme = controlScheme; } public ControlSchemeSyntax WithBindingGroup(string bindingGroup) { if (string.IsNullOrEmpty(bindingGroup)) { throw new ArgumentNullException("bindingGroup"); } if ((Object)(object)m_Asset == (Object)null) { m_ControlScheme.m_BindingGroup = bindingGroup; } else { m_Asset.m_ControlSchemes[m_ControlSchemeIndex].bindingGroup = bindingGroup; } return this; } public ControlSchemeSyntax WithRequiredDevice() where TDevice : InputDevice { return WithRequiredDevice(DeviceTypeToControlPath()); } public ControlSchemeSyntax WithOptionalDevice() where TDevice : InputDevice { return WithOptionalDevice(DeviceTypeToControlPath()); } public ControlSchemeSyntax OrWithRequiredDevice() where TDevice : InputDevice { return OrWithRequiredDevice(DeviceTypeToControlPath()); } public ControlSchemeSyntax OrWithOptionalDevice() where TDevice : InputDevice { return OrWithOptionalDevice(DeviceTypeToControlPath()); } public ControlSchemeSyntax WithRequiredDevice(string controlPath) { AddDeviceEntry(controlPath, InputControlScheme.DeviceRequirement.Flags.None); return this; } public ControlSchemeSyntax WithOptionalDevice(string controlPath) { AddDeviceEntry(controlPath, InputControlScheme.DeviceRequirement.Flags.Optional); return this; } public ControlSchemeSyntax OrWithRequiredDevice(string controlPath) { AddDeviceEntry(controlPath, InputControlScheme.DeviceRequirement.Flags.Or); return this; } public ControlSchemeSyntax OrWithOptionalDevice(string controlPath) { AddDeviceEntry(controlPath, InputControlScheme.DeviceRequirement.Flags.Optional | InputControlScheme.DeviceRequirement.Flags.Or); return this; } private string DeviceTypeToControlPath() where TDevice : InputDevice { string text = InputControlLayout.s_Layouts.TryFindLayoutForType(typeof(TDevice)).ToString(); if (string.IsNullOrEmpty(text)) { text = typeof(TDevice).Name; } return "<" + text + ">"; } public InputControlScheme Done() { if ((Object)(object)m_Asset != (Object)null) { return m_Asset.m_ControlSchemes[m_ControlSchemeIndex]; } return m_ControlScheme; } private void AddDeviceEntry(string controlPath, InputControlScheme.DeviceRequirement.Flags flags) { if (string.IsNullOrEmpty(controlPath)) { throw new ArgumentNullException("controlPath"); } InputControlScheme inputControlScheme = (((Object)(object)m_Asset != (Object)null) ? m_Asset.m_ControlSchemes[m_ControlSchemeIndex] : m_ControlScheme); ArrayHelpers.Append(ref inputControlScheme.m_DeviceRequirements, new InputControlScheme.DeviceRequirement { m_ControlPath = controlPath, m_Flags = flags }); if ((Object)(object)m_Asset == (Object)null) { m_ControlScheme = inputControlScheme; } else { m_Asset.m_ControlSchemes[m_ControlSchemeIndex] = inputControlScheme; } } } public static InputActionMap AddActionMap(this InputActionAsset asset, string name) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (asset.FindActionMap(name) != null) { throw new InvalidOperationException("An action map called '" + name + "' already exists in the asset"); } InputActionMap inputActionMap = new InputActionMap(name); inputActionMap.GenerateId(); asset.AddActionMap(inputActionMap); return inputActionMap; } public static void AddActionMap(this InputActionAsset asset, InputActionMap map) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (map == null) { throw new ArgumentNullException("map"); } if (string.IsNullOrEmpty(map.name)) { throw new InvalidOperationException("Maps added to an input action asset must be named"); } if ((Object)(object)map.asset != (Object)null) { throw new InvalidOperationException($"Cannot add map '{map}' to asset '{asset}' as it has already been added to asset '{map.asset}'"); } if (asset.FindActionMap(map.name) != null) { throw new InvalidOperationException("An action map called '" + map.name + "' already exists in the asset"); } map.OnWantToChangeSetup(); asset.OnWantToChangeSetup(); ArrayHelpers.Append(ref asset.m_ActionMaps, map); map.m_Asset = asset; asset.OnSetupChanged(); } public static void RemoveActionMap(this InputActionAsset asset, InputActionMap map) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (map == null) { throw new ArgumentNullException("map"); } map.OnWantToChangeSetup(); asset.OnWantToChangeSetup(); if (!((Object)(object)map.m_Asset != (Object)(object)asset)) { ArrayHelpers.Erase(ref asset.m_ActionMaps, map); map.m_Asset = null; asset.OnSetupChanged(); } } public static void RemoveActionMap(this InputActionAsset asset, string nameOrId) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (nameOrId == null) { throw new ArgumentNullException("nameOrId"); } InputActionMap inputActionMap = asset.FindActionMap(nameOrId); if (inputActionMap != null) { asset.RemoveActionMap(inputActionMap); } } public static InputAction AddAction(this InputActionMap map, string name, InputActionType type = InputActionType.Value, string binding = null, string interactions = null, string processors = null, string groups = null, string expectedControlLayout = null) { if (map == null) { throw new ArgumentNullException("map"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Action must have name", "name"); } map.OnWantToChangeSetup(); if (map.FindAction(name) != null) { throw new InvalidOperationException("Cannot add action with duplicate name '" + name + "' to set '" + map.name + "'"); } InputAction inputAction = new InputAction(name, type) { expectedControlType = expectedControlLayout }; inputAction.GenerateId(); ArrayHelpers.Append(ref map.m_Actions, inputAction); inputAction.m_ActionMap = map; if (!string.IsNullOrEmpty(binding)) { inputAction.AddBinding(binding, interactions, processors, groups); } else { if (!string.IsNullOrEmpty(groups)) { throw new ArgumentException($"No binding path was specified for action '{inputAction}' but groups was specified ('{groups}'); cannot apply groups without binding", "groups"); } inputAction.m_Interactions = interactions; inputAction.m_Processors = processors; map.OnSetupChanged(); } return inputAction; } public static void RemoveAction(this InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } InputActionMap actionMap = action.actionMap; if (actionMap == null) { throw new ArgumentException($"Action '{action}' does not belong to an action map; nowhere to remove from", "action"); } actionMap.OnWantToChangeSetup(); InputBinding[] array = action.bindings.ToArray(); int index = actionMap.m_Actions.IndexOfReference(action); ArrayHelpers.EraseAt(ref actionMap.m_Actions, index); action.m_ActionMap = null; action.m_SingletonActionBindings = array; int num = actionMap.m_Bindings.Length - array.Length; if (num == 0) { actionMap.m_Bindings = null; } else { InputBinding[] array2 = new InputBinding[num]; InputBinding[] bindings = actionMap.m_Bindings; int num2 = 0; foreach (InputBinding binding in bindings) { if (array.IndexOf((InputBinding b) => b == binding) == -1) { array2[num2++] = binding; } } actionMap.m_Bindings = array2; } actionMap.OnSetupChanged(); } public static void RemoveAction(this InputActionAsset asset, string nameOrId) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (nameOrId == null) { throw new ArgumentNullException("nameOrId"); } asset.FindAction(nameOrId)?.RemoveAction(); } public static BindingSyntax AddBinding(this InputAction action, string path, string interactions = null, string processors = null, string groups = null) { return action.AddBinding(new InputBinding { path = path, interactions = interactions, processors = processors, groups = groups }); } public static BindingSyntax AddBinding(this InputAction action, InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } return action.AddBinding(control.path); } public static BindingSyntax AddBinding(this InputAction action, InputBinding binding = default(InputBinding)) { if (action == null) { throw new ArgumentNullException("action"); } binding.action = action.name; InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); int bindingIndexInMap = AddBindingInternal(orCreateActionMap, binding); return new BindingSyntax(orCreateActionMap, bindingIndexInMap); } public static BindingSyntax AddBinding(this InputActionMap actionMap, string path, string interactions = null, string groups = null, string action = null, string processors = null) { if (path == null) { throw new ArgumentNullException("path", "Binding path cannot be null"); } return actionMap.AddBinding(new InputBinding { path = path, interactions = interactions, groups = groups, action = action, processors = processors }); } public static BindingSyntax AddBinding(this InputActionMap actionMap, string path, InputAction action, string interactions = null, string groups = null) { if (action != null && action.actionMap != actionMap) { throw new ArgumentException($"Action '{action}' is not part of action map '{actionMap}'", "action"); } if (action == null) { return actionMap.AddBinding(path, interactions, groups); } return actionMap.AddBinding(path, action.id, interactions, groups); } public static BindingSyntax AddBinding(this InputActionMap actionMap, string path, Guid action, string interactions = null, string groups = null) { if (action == Guid.Empty) { return actionMap.AddBinding(path, interactions, groups); } return actionMap.AddBinding(path, interactions, groups, action.ToString()); } public static BindingSyntax AddBinding(this InputActionMap actionMap, InputBinding binding) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (binding.path == null) { throw new ArgumentException("Binding path cannot be null", "binding"); } int bindingIndexInMap = AddBindingInternal(actionMap, binding); return new BindingSyntax(actionMap, bindingIndexInMap); } public static CompositeSyntax AddCompositeBinding(this InputAction action, string composite, string interactions = null, string processors = null) { if (action == null) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(composite)) { throw new ArgumentException("Composite name cannot be null or empty", "composite"); } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); InputBinding binding = new InputBinding { name = NameAndParameters.ParseName(composite), path = composite, interactions = interactions, processors = processors, isComposite = true, action = action.name }; int compositeIndex = AddBindingInternal(orCreateActionMap, binding); return new CompositeSyntax(orCreateActionMap, action, compositeIndex); } private static int AddBindingInternal(InputActionMap map, InputBinding binding, int bindingIndex = -1) { if (string.IsNullOrEmpty(binding.m_Id)) { binding.GenerateId(); } if (bindingIndex < 0) { bindingIndex = ArrayHelpers.Append(ref map.m_Bindings, binding); } else { ArrayHelpers.InsertAt(ref map.m_Bindings, bindingIndex, binding); } if ((Object)(object)map.asset != (Object)null) { map.asset.MarkAsDirty(); } if (map.m_SingletonAction != null) { map.m_SingletonAction.m_SingletonActionBindings = map.m_Bindings; } map.OnBindingModified(); return bindingIndex; } public static BindingSyntax ChangeBinding(this InputAction action, int index) { if (action == null) { throw new ArgumentNullException("action"); } int bindingIndexInMap = action.BindingIndexOnActionToBindingIndexOnMap(index); return new BindingSyntax(action.GetOrCreateActionMap(), bindingIndexInMap, action); } public static BindingSyntax ChangeBinding(this InputAction action, string name) { return action.ChangeBinding(new InputBinding { name = name }); } public static BindingSyntax ChangeBinding(this InputActionMap actionMap, int index) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (index < 0 || index >= actionMap.m_Bindings.LengthSafe()) { throw new ArgumentOutOfRangeException("index"); } return new BindingSyntax(actionMap, index); } public static BindingSyntax ChangeBindingWithId(this InputAction action, string id) { if (action == null) { throw new ArgumentNullException("action"); } return action.ChangeBinding(new InputBinding { m_Id = id }); } public static BindingSyntax ChangeBindingWithId(this InputAction action, Guid id) { if (action == null) { throw new ArgumentNullException("action"); } return action.ChangeBinding(new InputBinding { id = id }); } public static BindingSyntax ChangeBindingWithGroup(this InputAction action, string group) { if (action == null) { throw new ArgumentNullException("action"); } return action.ChangeBinding(new InputBinding { groups = group }); } public static BindingSyntax ChangeBindingWithPath(this InputAction action, string path) { if (action == null) { throw new ArgumentNullException("action"); } return action.ChangeBinding(new InputBinding { path = path }); } public static BindingSyntax ChangeBinding(this InputAction action, InputBinding match) { if (action == null) { throw new ArgumentNullException("action"); } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); int num = -1; _ = action.idDontGenerate; match.action = action.id.ToString(); num = orCreateActionMap.FindBindingRelativeToMap(match); if (num == -1) { match.action = action.name; num = orCreateActionMap.FindBindingRelativeToMap(match); } if (num == -1) { return default(BindingSyntax); } return new BindingSyntax(orCreateActionMap, num, action); } public static BindingSyntax ChangeCompositeBinding(this InputAction action, string compositeName) { if (action == null) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(compositeName)) { throw new ArgumentNullException("compositeName"); } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); InputBinding[] bindings = orCreateActionMap.m_Bindings; int num = bindings.LengthSafe(); for (int i = 0; i < num; i++) { ref InputBinding reference = ref bindings[i]; if (reference.isComposite && reference.TriggersAction(action) && (compositeName.Equals(reference.name, StringComparison.InvariantCultureIgnoreCase) || compositeName.Equals(NameAndParameters.ParseName(reference.path), StringComparison.InvariantCultureIgnoreCase))) { return new BindingSyntax(orCreateActionMap, i, action); } } return default(BindingSyntax); } public static void Rename(this InputAction action, string newName) { if (action == null) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(newName)) { throw new ArgumentNullException("newName"); } if (action.name == newName) { return; } InputActionMap actionMap = action.actionMap; if (actionMap?.FindAction(newName) != null) { throw new InvalidOperationException($"Cannot rename '{action}' to '{newName}' in map '{actionMap}' as the map already contains an action with that name"); } string name = action.m_Name; action.m_Name = newName; actionMap?.ClearActionLookupTable(); if ((Object)(object)actionMap?.asset != (Object)null) { actionMap?.asset.MarkAsDirty(); } InputBinding[] bindings = action.GetOrCreateActionMap().m_Bindings; int num = bindings.LengthSafe(); for (int i = 0; i < num; i++) { if (string.Compare(bindings[i].action, name, StringComparison.InvariantCultureIgnoreCase) == 0) { bindings[i].action = newName; } } } public static void AddControlScheme(this InputActionAsset asset, InputControlScheme controlScheme) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (string.IsNullOrEmpty(controlScheme.name)) { throw new ArgumentException("Cannot add control scheme without name to asset " + ((Object)asset).name, "controlScheme"); } if (asset.FindControlScheme(controlScheme.name).HasValue) { throw new InvalidOperationException("Asset '" + ((Object)asset).name + "' already contains a control scheme called '" + controlScheme.name + "'"); } ArrayHelpers.Append(ref asset.m_ControlSchemes, controlScheme); asset.MarkAsDirty(); } public static ControlSchemeSyntax AddControlScheme(this InputActionAsset asset, string name) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } int count = asset.controlSchemes.Count; asset.AddControlScheme(new InputControlScheme(name)); return new ControlSchemeSyntax(asset, count); } public static void RemoveControlScheme(this InputActionAsset asset, string name) { if ((Object)(object)asset == (Object)null) { throw new ArgumentNullException("asset"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } int num = asset.FindControlSchemeIndex(name); if (num != -1) { ArrayHelpers.EraseAt(ref asset.m_ControlSchemes, num); } asset.MarkAsDirty(); } public static InputControlScheme WithBindingGroup(this InputControlScheme scheme, string bindingGroup) { return new ControlSchemeSyntax(scheme).WithBindingGroup(bindingGroup).Done(); } public static InputControlScheme WithDevice(this InputControlScheme scheme, string controlPath, bool required) { if (required) { return new ControlSchemeSyntax(scheme).WithRequiredDevice(controlPath).Done(); } return new ControlSchemeSyntax(scheme).WithOptionalDevice(controlPath).Done(); } public static InputControlScheme WithRequiredDevice(this InputControlScheme scheme, string controlPath) { return new ControlSchemeSyntax(scheme).WithRequiredDevice(controlPath).Done(); } public static InputControlScheme WithOptionalDevice(this InputControlScheme scheme, string controlPath) { return new ControlSchemeSyntax(scheme).WithOptionalDevice(controlPath).Done(); } public static InputControlScheme OrWithRequiredDevice(this InputControlScheme scheme, string controlPath) { return new ControlSchemeSyntax(scheme).OrWithRequiredDevice(controlPath).Done(); } public static InputControlScheme OrWithOptionalDevice(this InputControlScheme scheme, string controlPath) { return new ControlSchemeSyntax(scheme).OrWithOptionalDevice(controlPath).Done(); } } internal class InputActionState : IInputStateChangeMonitor, ICloneable, IDisposable { [StructLayout(LayoutKind.Explicit, Size = 48)] internal struct InteractionState { [Flags] private enum Flags { TimerRunning = 1 } [FieldOffset(0)] private ushort m_TriggerControlIndex; [FieldOffset(2)] private byte m_Phase; [FieldOffset(3)] private byte m_Flags; [FieldOffset(4)] private float m_TimerDuration; [FieldOffset(8)] private double m_StartTime; [FieldOffset(16)] private double m_TimerStartTime; [FieldOffset(24)] private double m_PerformedTime; [FieldOffset(32)] private float m_TotalTimeoutCompletionTimeDone; [FieldOffset(36)] private float m_TotalTimeoutCompletionTimeRemaining; [FieldOffset(40)] private long m_TimerMonitorIndex; public int triggerControlIndex { get { if (m_TriggerControlIndex == ushort.MaxValue) { return -1; } return m_TriggerControlIndex; } set { if (value == -1) { m_TriggerControlIndex = ushort.MaxValue; return; } if (value < 0 || value >= 65535) { throw new NotSupportedException("More than ushort.MaxValue-1 controls in a single InputActionState"); } m_TriggerControlIndex = (ushort)value; } } public double startTime { get { return m_StartTime; } set { m_StartTime = value; } } public double performedTime { get { return m_PerformedTime; } set { m_PerformedTime = value; } } public double timerStartTime { get { return m_TimerStartTime; } set { m_TimerStartTime = value; } } public float timerDuration { get { return m_TimerDuration; } set { m_TimerDuration = value; } } public float totalTimeoutCompletionDone { get { return m_TotalTimeoutCompletionTimeDone; } set { m_TotalTimeoutCompletionTimeDone = value; } } public float totalTimeoutCompletionTimeRemaining { get { return m_TotalTimeoutCompletionTimeRemaining; } set { m_TotalTimeoutCompletionTimeRemaining = value; } } public long timerMonitorIndex { get { return m_TimerMonitorIndex; } set { m_TimerMonitorIndex = value; } } public bool isTimerRunning { get { return (m_Flags & 1) == 1; } set { if (value) { m_Flags |= 1; return; } Flags flags = ~Flags.TimerRunning; m_Flags &= (byte)flags; } } public InputActionPhase phase { get { return (InputActionPhase)m_Phase; } set { m_Phase = (byte)value; } } } [StructLayout(LayoutKind.Explicit, Size = 32)] internal struct BindingState { [Flags] public enum Flags { ChainsWithNext = 1, EndOfChain = 2, Composite = 4, PartOfComposite = 8, InitialStateCheckPending = 0x10, WantsInitialStateCheck = 0x20 } [FieldOffset(0)] private byte m_ControlCount; [FieldOffset(1)] private byte m_InteractionCount; [FieldOffset(2)] private byte m_ProcessorCount; [FieldOffset(3)] private byte m_MapIndex; [FieldOffset(4)] private byte m_Flags; [FieldOffset(5)] private byte m_PartIndex; [FieldOffset(6)] private ushort m_ActionIndex; [FieldOffset(8)] private ushort m_CompositeOrCompositeBindingIndex; [FieldOffset(10)] private ushort m_ProcessorStartIndex; [FieldOffset(12)] private ushort m_InteractionStartIndex; [FieldOffset(14)] private ushort m_ControlStartIndex; [FieldOffset(16)] private double m_PressTime; [FieldOffset(24)] private int m_TriggerEventIdForComposite; [FieldOffset(28)] private int __padding; public int controlStartIndex { get { return m_ControlStartIndex; } set { if (value >= 65535) { throw new NotSupportedException("Total control count in state cannot exceed byte.MaxValue=" + ushort.MaxValue); } m_ControlStartIndex = (ushort)value; } } public int controlCount { get { return m_ControlCount; } set { if (value >= 255) { throw new NotSupportedException("Control count per binding cannot exceed byte.MaxValue=" + byte.MaxValue); } m_ControlCount = (byte)value; } } public int interactionStartIndex { get { if (m_InteractionStartIndex == ushort.MaxValue) { return -1; } return m_InteractionStartIndex; } set { if (value == -1) { m_InteractionStartIndex = ushort.MaxValue; return; } if (value >= 65535) { throw new NotSupportedException("Interaction count cannot exceed ushort.MaxValue=" + ushort.MaxValue); } m_InteractionStartIndex = (ushort)value; } } public int interactionCount { get { return m_InteractionCount; } set { if (value >= 255) { throw new NotSupportedException("Interaction count per binding cannot exceed byte.MaxValue=" + byte.MaxValue); } m_InteractionCount = (byte)value; } } public int processorStartIndex { get { if (m_ProcessorStartIndex == ushort.MaxValue) { return -1; } return m_ProcessorStartIndex; } set { if (value == -1) { m_ProcessorStartIndex = ushort.MaxValue; return; } if (value >= 65535) { throw new NotSupportedException("Processor count cannot exceed ushort.MaxValue=" + ushort.MaxValue); } m_ProcessorStartIndex = (ushort)value; } } public int processorCount { get { return m_ProcessorCount; } set { if (value >= 255) { throw new NotSupportedException("Processor count per binding cannot exceed byte.MaxValue=" + byte.MaxValue); } m_ProcessorCount = (byte)value; } } public int actionIndex { get { if (m_ActionIndex == ushort.MaxValue) { return -1; } return m_ActionIndex; } set { if (value == -1) { m_ActionIndex = ushort.MaxValue; return; } if (value >= 65535) { throw new NotSupportedException("Action count cannot exceed ushort.MaxValue=" + ushort.MaxValue); } m_ActionIndex = (ushort)value; } } public int mapIndex { get { return m_MapIndex; } set { if (value >= 255) { throw new NotSupportedException("Map count cannot exceed byte.MaxValue=" + byte.MaxValue); } m_MapIndex = (byte)value; } } public int compositeOrCompositeBindingIndex { get { if (m_CompositeOrCompositeBindingIndex == ushort.MaxValue) { return -1; } return m_CompositeOrCompositeBindingIndex; } set { if (value == -1) { m_CompositeOrCompositeBindingIndex = ushort.MaxValue; return; } if (value >= 65535) { throw new NotSupportedException("Composite count cannot exceed ushort.MaxValue=" + ushort.MaxValue); } m_CompositeOrCompositeBindingIndex = (ushort)value; } } public int triggerEventIdForComposite { get { return m_TriggerEventIdForComposite; } set { m_TriggerEventIdForComposite = value; } } public double pressTime { get { return m_PressTime; } set { m_PressTime = value; } } public Flags flags { get { return (Flags)m_Flags; } set { m_Flags = (byte)value; } } public bool chainsWithNext { get { return (flags & Flags.ChainsWithNext) == Flags.ChainsWithNext; } set { if (value) { flags |= Flags.ChainsWithNext; } else { flags &= ~Flags.ChainsWithNext; } } } public bool isEndOfChain { get { return (flags & Flags.EndOfChain) == Flags.EndOfChain; } set { if (value) { flags |= Flags.EndOfChain; } else { flags &= ~Flags.EndOfChain; } } } public bool isPartOfChain { get { if (!chainsWithNext) { return isEndOfChain; } return true; } } public bool isComposite { get { return (flags & Flags.Composite) == Flags.Composite; } set { if (value) { flags |= Flags.Composite; } else { flags &= ~Flags.Composite; } } } public bool isPartOfComposite { get { return (flags & Flags.PartOfComposite) == Flags.PartOfComposite; } set { if (value) { flags |= Flags.PartOfComposite; } else { flags &= ~Flags.PartOfComposite; } } } public bool initialStateCheckPending { get { return (flags & Flags.InitialStateCheckPending) != 0; } set { if (value) { flags |= Flags.InitialStateCheckPending; } else { flags &= ~Flags.InitialStateCheckPending; } } } public bool wantsInitialStateCheck { get { return (flags & Flags.WantsInitialStateCheck) != 0; } set { if (value) { flags |= Flags.WantsInitialStateCheck; } else { flags &= ~Flags.WantsInitialStateCheck; } } } public int partIndex { get { return m_PartIndex; } set { if (partIndex < 0) { throw new ArgumentOutOfRangeException("value", "Part index must not be negative"); } if (partIndex > 255) { throw new InvalidOperationException("Part count must not exceed byte.MaxValue=" + byte.MaxValue); } m_PartIndex = (byte)value; } } } [StructLayout(LayoutKind.Explicit, Size = 48)] public struct TriggerState { [Flags] public enum Flags { HaveMagnitude = 1, PassThrough = 2, MayNeedConflictResolution = 4, HasMultipleConcurrentActuations = 8, InProcessing = 0x10, Button = 0x20, Pressed = 0x40 } public const int kMaxNumMaps = 255; public const int kMaxNumControls = 65535; public const int kMaxNumBindings = 65535; [FieldOffset(0)] private byte m_Phase; [FieldOffset(1)] private byte m_Flags; [FieldOffset(2)] private byte m_MapIndex; [FieldOffset(4)] private ushort m_ControlIndex; [FieldOffset(8)] private double m_Time; [FieldOffset(16)] private double m_StartTime; [FieldOffset(24)] private ushort m_BindingIndex; [FieldOffset(26)] private ushort m_InteractionIndex; [FieldOffset(28)] private float m_Magnitude; [FieldOffset(32)] private uint m_LastPerformedInUpdate; [FieldOffset(36)] private uint m_LastCanceledInUpdate; [FieldOffset(40)] private uint m_PressedInUpdate; [FieldOffset(44)] private uint m_ReleasedInUpdate; public InputActionPhase phase { get { return (InputActionPhase)m_Phase; } set { m_Phase = (byte)value; } } public bool isDisabled => phase == InputActionPhase.Disabled; public bool isWaiting => phase == InputActionPhase.Waiting; public bool isStarted => phase == InputActionPhase.Started; public bool isPerformed => phase == InputActionPhase.Performed; public bool isCanceled => phase == InputActionPhase.Canceled; public double time { get { return m_Time; } set { m_Time = value; } } public double startTime { get { return m_StartTime; } set { m_StartTime = value; } } public float magnitude { get { return m_Magnitude; } set { flags |= Flags.HaveMagnitude; m_Magnitude = value; } } public bool haveMagnitude => (flags & Flags.HaveMagnitude) != 0; public int mapIndex { get { return m_MapIndex; } set { if (value < 0 || value > 255) { throw new NotSupportedException("More than byte.MaxValue InputActionMaps in a single InputActionState"); } m_MapIndex = (byte)value; } } public int controlIndex { get { if (m_ControlIndex == ushort.MaxValue) { return -1; } return m_ControlIndex; } set { if (value == -1) { m_ControlIndex = ushort.MaxValue; return; } if (value < 0 || value >= 65535) { throw new NotSupportedException("More than ushort.MaxValue-1 controls in a single InputActionState"); } m_ControlIndex = (ushort)value; } } public int bindingIndex { get { return m_BindingIndex; } set { if (value < 0 || value > 65535) { throw new NotSupportedException("More than ushort.MaxValue bindings in a single InputActionState"); } m_BindingIndex = (ushort)value; } } public int interactionIndex { get { if (m_InteractionIndex == ushort.MaxValue) { return -1; } return m_InteractionIndex; } set { if (value == -1) { m_InteractionIndex = ushort.MaxValue; return; } if (value < 0 || value >= 65535) { throw new NotSupportedException("More than ushort.MaxValue-1 interactions in a single InputActionState"); } m_InteractionIndex = (ushort)value; } } public uint lastPerformedInUpdate { get { return m_LastPerformedInUpdate; } set { m_LastPerformedInUpdate = value; } } public uint lastCanceledInUpdate { get { return m_LastCanceledInUpdate; } set { m_LastCanceledInUpdate = value; } } public uint pressedInUpdate { get { return m_PressedInUpdate; } set { m_PressedInUpdate = value; } } public uint releasedInUpdate { get { return m_ReleasedInUpdate; } set { m_ReleasedInUpdate = value; } } public bool isPassThrough { get { return (flags & Flags.PassThrough) != 0; } set { if (value) { flags |= Flags.PassThrough; } else { flags &= ~Flags.PassThrough; } } } public bool isButton { get { return (flags & Flags.Button) != 0; } set { if (value) { flags |= Flags.Button; } else { flags &= ~Flags.Button; } } } public bool isPressed { get { return (flags & Flags.Pressed) != 0; } set { if (value) { flags |= Flags.Pressed; } else { flags &= ~Flags.Pressed; } } } public bool mayNeedConflictResolution { get { return (flags & Flags.MayNeedConflictResolution) != 0; } set { if (value) { flags |= Flags.MayNeedConflictResolution; } else { flags &= ~Flags.MayNeedConflictResolution; } } } public bool hasMultipleConcurrentActuations { get { return (flags & Flags.HasMultipleConcurrentActuations) != 0; } set { if (value) { flags |= Flags.HasMultipleConcurrentActuations; } else { flags &= ~Flags.HasMultipleConcurrentActuations; } } } public bool inProcessing { get { return (flags & Flags.InProcessing) != 0; } set { if (value) { flags |= Flags.InProcessing; } else { flags &= ~Flags.InProcessing; } } } public Flags flags { get { return (Flags)m_Flags; } set { m_Flags = (byte)value; } } } public struct ActionMapIndices { public int actionStartIndex; public int actionCount; public int controlStartIndex; public int controlCount; public int bindingStartIndex; public int bindingCount; public int interactionStartIndex; public int interactionCount; public int processorStartIndex; public int processorCount; public int compositeStartIndex; public int compositeCount; } public struct UnmanagedMemory : IDisposable { public unsafe void* basePtr; public int mapCount; public int actionCount; public int interactionCount; public int bindingCount; public int controlCount; public int compositeCount; public unsafe TriggerState* actionStates; public unsafe BindingState* bindingStates; public unsafe InteractionState* interactionStates; public unsafe float* controlMagnitudes; public unsafe float* compositeMagnitudes; public unsafe int* enabledControls; public unsafe ushort* actionBindingIndicesAndCounts; public unsafe ushort* actionBindingIndices; public unsafe int* controlIndexToBindingIndex; public unsafe ushort* controlGroupingAndComplexity; public bool controlGroupingInitialized; public unsafe ActionMapIndices* mapIndices; public unsafe bool isAllocated => basePtr != null; public unsafe int sizeInBytes => mapCount * sizeof(ActionMapIndices) + actionCount * sizeof(TriggerState) + bindingCount * sizeof(BindingState) + interactionCount * sizeof(InteractionState) + controlCount * 4 + compositeCount * 4 + controlCount * 4 + controlCount * 2 * 2 + actionCount * 2 * 2 + bindingCount * 2 + (controlCount + 31) / 32 * 4; public unsafe void Allocate(int mapCount, int actionCount, int bindingCount, int controlCount, int interactionCount, int compositeCount) { this.mapCount = mapCount; this.actionCount = actionCount; this.interactionCount = interactionCount; this.bindingCount = bindingCount; this.controlCount = controlCount; this.compositeCount = compositeCount; int num = sizeInBytes; byte* ptr = (byte*)UnsafeUtility.Malloc((long)num, 8, (Allocator)4); UnsafeUtility.MemClear((void*)ptr, (long)num); basePtr = ptr; actionStates = (TriggerState*)ptr; ptr = (byte*)(enabledControls = (int*)((byte*)(actionBindingIndices = (ushort*)((byte*)(actionBindingIndicesAndCounts = (ushort*)((byte*)(controlGroupingAndComplexity = (ushort*)((byte*)(controlIndexToBindingIndex = (int*)((byte*)(compositeMagnitudes = (float*)((byte*)(controlMagnitudes = (float*)((byte*)(mapIndices = (ActionMapIndices*)((byte*)(bindingStates = (BindingState*)((byte*)(interactionStates = (InteractionState*)(ptr + actionCount * sizeof(TriggerState))) + interactionCount * sizeof(InteractionState))) + bindingCount * sizeof(BindingState))) + mapCount * sizeof(ActionMapIndices))) + controlCount * 4)) + compositeCount * 4)) + controlCount * 4)) + controlCount * 2 * 2)) + actionCount * 2 * 2)) + bindingCount * 2)) + (controlCount + 31) / 32 * 4; } public unsafe void Dispose() { if (basePtr != null) { UnsafeUtility.Free(basePtr, (Allocator)4); basePtr = null; actionStates = null; interactionStates = null; bindingStates = null; mapIndices = null; controlMagnitudes = null; compositeMagnitudes = null; controlIndexToBindingIndex = null; controlGroupingAndComplexity = null; actionBindingIndices = null; actionBindingIndicesAndCounts = null; mapCount = 0; actionCount = 0; bindingCount = 0; controlCount = 0; interactionCount = 0; compositeCount = 0; } } public unsafe void CopyDataFrom(UnmanagedMemory memory) { UnsafeUtility.MemCpy((void*)mapIndices, (void*)memory.mapIndices, (long)(memory.mapCount * sizeof(ActionMapIndices))); UnsafeUtility.MemCpy((void*)actionStates, (void*)memory.actionStates, (long)(memory.actionCount * sizeof(TriggerState))); UnsafeUtility.MemCpy((void*)bindingStates, (void*)memory.bindingStates, (long)(memory.bindingCount * sizeof(BindingState))); UnsafeUtility.MemCpy((void*)interactionStates, (void*)memory.interactionStates, (long)(memory.interactionCount * sizeof(InteractionState))); UnsafeUtility.MemCpy((void*)controlMagnitudes, (void*)memory.controlMagnitudes, (long)(memory.controlCount * 4)); UnsafeUtility.MemCpy((void*)compositeMagnitudes, (void*)memory.compositeMagnitudes, (long)(memory.compositeCount * 4)); UnsafeUtility.MemCpy((void*)controlIndexToBindingIndex, (void*)memory.controlIndexToBindingIndex, (long)(memory.controlCount * 4)); UnsafeUtility.MemCpy((void*)controlGroupingAndComplexity, (void*)memory.controlGroupingAndComplexity, (long)(memory.controlCount * 2 * 2)); UnsafeUtility.MemCpy((void*)actionBindingIndicesAndCounts, (void*)memory.actionBindingIndicesAndCounts, (long)(memory.actionCount * 2 * 2)); UnsafeUtility.MemCpy((void*)actionBindingIndices, (void*)memory.actionBindingIndices, (long)(memory.bindingCount * 2)); UnsafeUtility.MemCpy((void*)enabledControls, (void*)memory.enabledControls, (long)((memory.controlCount + 31) / 32 * 4)); } public UnmanagedMemory Clone() { if (!isAllocated) { return default(UnmanagedMemory); } UnmanagedMemory result = default(UnmanagedMemory); result.Allocate(mapCount, actionCount, controlCount: controlCount, bindingCount: bindingCount, interactionCount: interactionCount, compositeCount: compositeCount); result.CopyDataFrom(this); return result; } } internal struct GlobalState { internal InlinedArray globalList; internal CallbackArray> onActionChange; internal CallbackArray> onActionControlsChanged; } public const int kInvalidIndex = -1; public InputActionMap[] maps; public InputControl[] controls; public IInputInteraction[] interactions; public InputProcessor[] processors; public InputBindingComposite[] composites; public int totalProcessorCount; public UnmanagedMemory memory; private bool m_OnBeforeUpdateHooked; private bool m_OnAfterUpdateHooked; private bool m_InProcessControlStateChange; private InputEventPtr m_CurrentlyProcessingThisEvent; private Action m_OnBeforeUpdateDelegate; private Action m_OnAfterUpdateDelegate; internal static GlobalState s_GlobalState; public int totalCompositeCount => memory.compositeCount; public int totalMapCount => memory.mapCount; public int totalActionCount => memory.actionCount; public int totalBindingCount => memory.bindingCount; public int totalInteractionCount => memory.interactionCount; public int totalControlCount => memory.controlCount; public unsafe ActionMapIndices* mapIndices => memory.mapIndices; public unsafe TriggerState* actionStates => memory.actionStates; public unsafe BindingState* bindingStates => memory.bindingStates; public unsafe InteractionState* interactionStates => memory.interactionStates; public unsafe int* controlIndexToBindingIndex => memory.controlIndexToBindingIndex; public unsafe ushort* controlGroupingAndComplexity => memory.controlGroupingAndComplexity; public unsafe float* controlMagnitudes => memory.controlMagnitudes; public unsafe uint* enabledControls => (uint*)memory.enabledControls; public bool isProcessingControlStateChange => m_InProcessControlStateChange; public void Initialize(InputBindingResolver resolver) { ClaimDataFrom(resolver); AddToGlobalList(); } private unsafe void ComputeControlGroupingIfNecessary() { if (memory.controlGroupingInitialized) { return; } bool flag = !InputSystem.settings.shortcutKeysConsumeInput; uint num = 1u; for (int i = 0; i < totalControlCount; i++) { InputControl inputControl = controls[i]; int num2 = controlIndexToBindingIndex[i]; ref BindingState reference = ref bindingStates[num2]; int num3 = 1; if (reference.isPartOfComposite && !flag) { int compositeOrCompositeBindingIndex = reference.compositeOrCompositeBindingIndex; for (int j = compositeOrCompositeBindingIndex + 1; j < totalBindingCount; j++) { ref BindingState reference2 = ref bindingStates[j]; if (!reference2.isPartOfComposite || reference2.compositeOrCompositeBindingIndex != compositeOrCompositeBindingIndex) { break; } num3++; } } controlGroupingAndComplexity[i * 2 + 1] = (ushort)num3; if (controlGroupingAndComplexity[i * 2] != 0) { continue; } if (!flag) { for (int k = 0; k < totalControlCount; k++) { InputControl inputControl2 = controls[k]; if (inputControl == inputControl2) { controlGroupingAndComplexity[k * 2] = (ushort)num; } } } controlGroupingAndComplexity[i * 2] = (ushort)num; num++; } memory.controlGroupingInitialized = true; } public void ClaimDataFrom(InputBindingResolver resolver) { totalProcessorCount = resolver.totalProcessorCount; maps = resolver.maps; interactions = resolver.interactions; processors = resolver.processors; composites = resolver.composites; controls = resolver.controls; memory = resolver.memory; resolver.memory = default(UnmanagedMemory); ComputeControlGroupingIfNecessary(); } ~InputActionState() { Destroy(isFinalizing: true); } public void Dispose() { Destroy(); } private unsafe void Destroy(bool isFinalizing = false) { if (!isFinalizing) { for (int i = 0; i < totalMapCount; i++) { InputActionMap inputActionMap = maps[i]; if (inputActionMap.enabled) { DisableControls(i, mapIndices[i].controlStartIndex, mapIndices[i].controlCount); } if ((Object)(object)inputActionMap.m_Asset != (Object)null) { inputActionMap.m_Asset.m_SharedStateForAllMaps = null; } inputActionMap.m_State = null; inputActionMap.m_MapIndexInState = -1; inputActionMap.m_EnabledActionsCount = 0; InputAction[] actions = inputActionMap.m_Actions; if (actions != null) { for (int j = 0; j < actions.Length; j++) { actions[j].m_ActionIndexInState = -1; } } } RemoveMapFromGlobalList(); } memory.Dispose(); } public InputActionState Clone() { return new InputActionState { maps = ArrayHelpers.Copy(maps), controls = ArrayHelpers.Copy(controls), interactions = ArrayHelpers.Copy(interactions), processors = ArrayHelpers.Copy(processors), composites = ArrayHelpers.Copy(composites), totalProcessorCount = totalProcessorCount, memory = memory.Clone() }; } object ICloneable.Clone() { return Clone(); } private bool IsUsingDevice(InputDevice device) { bool flag = false; for (int i = 0; i < totalMapCount; i++) { ReadOnlyArray? devices = maps[i].devices; if (!devices.HasValue) { flag = true; } else if (Enumerable.Contains(devices.Value, device)) { return true; } } if (!flag) { return false; } for (int j = 0; j < totalControlCount; j++) { if (controls[j].device == device) { return true; } } return false; } private bool CanUseDevice(InputDevice device) { bool flag = false; for (int i = 0; i < totalMapCount; i++) { ReadOnlyArray? devices = maps[i].devices; if (!devices.HasValue) { flag = true; } else if (Enumerable.Contains(devices.Value, device)) { return true; } } if (!flag) { return false; } for (int j = 0; j < totalMapCount; j++) { InputBinding[] bindings = maps[j].m_Bindings; if (bindings == null) { continue; } int num = bindings.Length; for (int k = 0; k < num; k++) { if (InputControlPath.TryFindControl(device, bindings[k].effectivePath) != null) { return true; } } } return false; } public bool HasEnabledActions() { for (int i = 0; i < totalMapCount; i++) { if (maps[i].enabled) { return true; } } return false; } private unsafe void FinishBindingCompositeSetups() { for (int i = 0; i < totalBindingCount; i++) { ref BindingState reference = ref bindingStates[i]; if (reference.isComposite && reference.compositeOrCompositeBindingIndex != -1) { InputBindingComposite obj = composites[reference.compositeOrCompositeBindingIndex]; InputBindingCompositeContext context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = i }; obj.CallFinishSetup(ref context); } } } internal unsafe void PrepareForBindingReResolution(bool needFullResolve, ref InputControlList activeControls, ref bool hasEnabledActions) { bool flag = false; for (int i = 0; i < totalMapCount; i++) { InputActionMap inputActionMap = maps[i]; if (inputActionMap.enabled) { hasEnabledActions = true; if (needFullResolve) { DisableAllActions(inputActionMap); } else { foreach (InputAction action in inputActionMap.actions) { if (!action.phase.IsInProgress()) { continue; } if (action.ActiveControlIsValid(action.activeControl)) { if (!flag) { activeControls = new InputControlList((Allocator)2); activeControls.Resize(totalControlCount); flag = true; } ref TriggerState reference = ref actionStates[action.m_ActionIndexInState]; int controlIndex = reference.controlIndex; activeControls[controlIndex] = controls[controlIndex]; BindingState bindingState = bindingStates[reference.bindingIndex]; for (int j = 0; j < bindingState.interactionCount; j++) { int num = bindingState.interactionStartIndex + j; if (interactionStates[num].phase.IsInProgress()) { controlIndex = interactionStates[num].triggerControlIndex; if (action.ActiveControlIsValid(controls[controlIndex])) { activeControls[controlIndex] = controls[controlIndex]; } else { ResetInteractionState(num); } } } } else { ResetActionState(action.m_ActionIndexInState); } } DisableControls(inputActionMap); } } inputActionMap.ClearCachedActionData(!needFullResolve); } NotifyListenersOfActionChange(InputActionChange.BoundControlsAboutToChange); } public void FinishBindingResolution(bool hasEnabledActions, UnmanagedMemory oldMemory, InputControlList activeControls, bool isFullResolve) { FinishBindingCompositeSetups(); if (hasEnabledActions) { RestoreActionStatesAfterReResolvingBindings(oldMemory, activeControls, isFullResolve); } else { NotifyListenersOfActionChange(InputActionChange.BoundControlsChanged); } } private unsafe void RestoreActionStatesAfterReResolvingBindings(UnmanagedMemory oldState, InputControlList activeControls, bool isFullResolve) { for (int i = 0; i < totalActionCount; i++) { ref TriggerState reference = ref oldState.actionStates[i]; ref TriggerState reference2 = ref actionStates[i]; reference2.lastCanceledInUpdate = reference.lastCanceledInUpdate; reference2.lastPerformedInUpdate = reference.lastPerformedInUpdate; reference2.pressedInUpdate = reference.pressedInUpdate; reference2.releasedInUpdate = reference.releasedInUpdate; reference2.startTime = reference.startTime; if (reference.phase != InputActionPhase.Disabled) { reference2.phase = InputActionPhase.Waiting; if (isFullResolve) { maps[reference2.mapIndex].m_EnabledActionsCount++; } } } for (int j = 0; j < totalBindingCount; j++) { ref BindingState reference3 = ref memory.bindingStates[j]; if (reference3.isPartOfComposite) { continue; } if (reference3.isComposite) { int compositeOrCompositeBindingIndex = reference3.compositeOrCompositeBindingIndex; memory.compositeMagnitudes[compositeOrCompositeBindingIndex] = oldState.compositeMagnitudes[compositeOrCompositeBindingIndex]; } int actionIndex = reference3.actionIndex; if (actionIndex == -1) { continue; } ref TriggerState reference4 = ref actionStates[actionIndex]; if (reference4.isDisabled) { continue; } reference3.initialStateCheckPending = reference3.wantsInitialStateCheck; EnableControls(reference3.mapIndex, reference3.controlStartIndex, reference3.controlCount); if (isFullResolve) { continue; } ref BindingState reference5 = ref memory.bindingStates[j]; reference3.triggerEventIdForComposite = reference5.triggerEventIdForComposite; ref TriggerState reference6 = ref oldState.actionStates[actionIndex]; if (j != reference6.bindingIndex || !reference6.phase.IsInProgress() || activeControls.Count <= 0 || activeControls[reference6.controlIndex] == null) { continue; } InputControl control = activeControls[reference6.controlIndex]; int num = FindControlIndexOnBinding(j, control); if (num != -1) { reference4.phase = reference6.phase; reference4.controlIndex = num; reference4.magnitude = reference6.magnitude; reference4.interactionIndex = reference6.interactionIndex; memory.controlMagnitudes[num] = reference6.magnitude; } for (int k = 0; k < reference3.interactionCount; k++) { ref InteractionState reference7 = ref oldState.interactionStates[reference5.interactionStartIndex + k]; if (!reference7.phase.IsInProgress()) { continue; } control = activeControls[reference7.triggerControlIndex]; if (control != null) { num = FindControlIndexOnBinding(j, control); ref InteractionState reference8 = ref interactionStates[reference3.interactionStartIndex + k]; reference8.phase = reference7.phase; reference8.performedTime = reference7.performedTime; reference8.startTime = reference7.startTime; reference8.triggerControlIndex = num; if (reference7.isTimerRunning) { TriggerState trigger = new TriggerState { mapIndex = reference3.mapIndex, controlIndex = num, bindingIndex = j, time = reference7.timerStartTime, interactionIndex = reference3.interactionStartIndex + k }; StartTimeout(reference7.timerDuration, ref trigger); reference8.totalTimeoutCompletionDone = reference7.totalTimeoutCompletionDone; reference8.totalTimeoutCompletionTimeRemaining = reference7.totalTimeoutCompletionTimeRemaining; } } } } HookOnBeforeUpdate(); NotifyListenersOfActionChange(InputActionChange.BoundControlsChanged); if (!isFullResolve || s_GlobalState.onActionChange.length <= 0) { return; } for (int l = 0; l < totalMapCount; l++) { InputActionMap inputActionMap = maps[l]; if (inputActionMap.m_SingletonAction == null && inputActionMap.m_EnabledActionsCount == inputActionMap.m_Actions.LengthSafe()) { NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, inputActionMap); continue; } foreach (InputAction action in inputActionMap.actions) { if (action.enabled) { NotifyListenersOfActionChange(InputActionChange.ActionEnabled, action); } } } } private unsafe bool IsActiveControl(int bindingIndex, int controlIndex) { ref BindingState reference = ref bindingStates[bindingIndex]; int actionIndex = reference.actionIndex; if (actionIndex == -1) { return false; } if (actionStates[actionIndex].controlIndex == controlIndex) { return true; } for (int i = 0; i < reference.interactionCount; i++) { if (interactionStates[bindingStates->interactionStartIndex + i].triggerControlIndex == controlIndex) { return true; } } return false; } private unsafe int FindControlIndexOnBinding(int bindingIndex, InputControl control) { int controlStartIndex = bindingStates[bindingIndex].controlStartIndex; int controlCount = bindingStates[bindingIndex].controlCount; for (int i = 0; i < controlCount; i++) { if (control == controls[controlStartIndex + i]) { return controlStartIndex + i; } } return -1; } private unsafe void ResetActionStatesDrivenBy(InputDevice device) { using (InputActionRebindingExtensions.DeferBindingResolution()) { for (int i = 0; i < totalActionCount; i++) { TriggerState* ptr = actionStates + i; if (ptr->phase == InputActionPhase.Waiting || ptr->phase == InputActionPhase.Disabled) { continue; } if (ptr->isPassThrough) { if (!IsActionBoundToControlFromDevice(device, i)) { continue; } } else { int controlIndex = ptr->controlIndex; if (controlIndex == -1 || controls[controlIndex].device != device) { continue; } } ResetActionState(i); } } } private unsafe bool IsActionBoundToControlFromDevice(InputDevice device, int actionIndex) { bool result = false; ushort bindingCount; ushort actionBindingStartIndexAndCount = GetActionBindingStartIndexAndCount(actionIndex, out bindingCount); for (int i = 0; i < bindingCount; i++) { ushort num = memory.actionBindingIndices[actionBindingStartIndexAndCount + i]; int controlCount = bindingStates[(int)num].controlCount; int controlStartIndex = bindingStates[(int)num].controlStartIndex; for (int j = 0; j < controlCount; j++) { if (controls[controlStartIndex + j].device == device) { result = true; break; } } } return result; } public unsafe void ResetActionState(int actionIndex, InputActionPhase toPhase = InputActionPhase.Waiting, bool hardReset = false) { TriggerState* ptr = actionStates + actionIndex; if (ptr->phase != InputActionPhase.Waiting && ptr->phase != InputActionPhase.Disabled) { ptr->time = InputState.currentTime; if (ptr->interactionIndex != -1) { int bindingIndex = ptr->bindingIndex; if (bindingIndex != -1) { int mapIndex = ptr->mapIndex; int interactionCount = bindingStates[bindingIndex].interactionCount; int interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex; for (int i = 0; i < interactionCount; i++) { int interactionIndex = interactionStartIndex + i; ResetInteractionStateAndCancelIfNecessary(mapIndex, bindingIndex, interactionIndex); } } } else if (ptr->phase != InputActionPhase.Canceled) { ChangePhaseOfAction(InputActionPhase.Canceled, ref actionStates[actionIndex]); } } ptr->phase = toPhase; ptr->controlIndex = -1; ptr->bindingIndex = memory.actionBindingIndices[(int)memory.actionBindingIndicesAndCounts[actionIndex]]; ptr->interactionIndex = -1; ptr->startTime = 0.0; ptr->time = 0.0; ptr->hasMultipleConcurrentActuations = false; ptr->inProcessing = false; ptr->isPressed = false; if (hardReset) { ptr->lastCanceledInUpdate = 0u; ptr->lastPerformedInUpdate = 0u; ptr->pressedInUpdate = 0u; ptr->releasedInUpdate = 0u; } } public unsafe ref TriggerState FetchActionState(InputAction action) { return ref actionStates[action.m_ActionIndexInState]; } public unsafe ActionMapIndices FetchMapIndices(InputActionMap map) { return mapIndices[map.m_MapIndexInState]; } public unsafe void EnableAllActions(InputActionMap map) { EnableControls(map); int mapIndexInState = map.m_MapIndexInState; int actionCount = mapIndices[mapIndexInState].actionCount; int actionStartIndex = mapIndices[mapIndexInState].actionStartIndex; for (int i = 0; i < actionCount; i++) { int num = actionStartIndex + i; TriggerState* ptr = actionStates + num; if (ptr->isDisabled) { ptr->phase = InputActionPhase.Waiting; } ptr->inProcessing = false; } map.m_EnabledActionsCount = actionCount; HookOnBeforeUpdate(); if (map.m_SingletonAction != null) { NotifyListenersOfActionChange(InputActionChange.ActionEnabled, map.m_SingletonAction); } else { NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map); } } private unsafe void EnableControls(InputActionMap map) { int mapIndexInState = map.m_MapIndexInState; int controlCount = mapIndices[mapIndexInState].controlCount; int controlStartIndex = mapIndices[mapIndexInState].controlStartIndex; if (controlCount > 0) { EnableControls(mapIndexInState, controlStartIndex, controlCount); } } public unsafe void EnableSingleAction(InputAction action) { EnableControls(action); int actionIndexInState = action.m_ActionIndexInState; actionStates[actionIndexInState].phase = InputActionPhase.Waiting; action.m_ActionMap.m_EnabledActionsCount++; HookOnBeforeUpdate(); NotifyListenersOfActionChange(InputActionChange.ActionEnabled, action); } private unsafe void EnableControls(InputAction action) { int actionIndexInState = action.m_ActionIndexInState; int mapIndexInState = action.m_ActionMap.m_MapIndexInState; int bindingStartIndex = mapIndices[mapIndexInState].bindingStartIndex; int bindingCount = mapIndices[mapIndexInState].bindingCount; BindingState* ptr = memory.bindingStates; for (int i = 0; i < bindingCount; i++) { int num = bindingStartIndex + i; BindingState* ptr2 = ptr + num; if (ptr2->actionIndex == actionIndexInState && !ptr2->isPartOfComposite) { int controlCount = ptr2->controlCount; if (controlCount != 0) { EnableControls(mapIndexInState, ptr2->controlStartIndex, controlCount); } } } } public unsafe void DisableAllActions(InputActionMap map) { DisableControls(map); int mapIndexInState = map.m_MapIndexInState; int actionStartIndex = mapIndices[mapIndexInState].actionStartIndex; int actionCount = mapIndices[mapIndexInState].actionCount; bool flag = map.m_EnabledActionsCount == actionCount; for (int i = 0; i < actionCount; i++) { int num = actionStartIndex + i; if (actionStates[num].phase != InputActionPhase.Disabled) { ResetActionState(num, InputActionPhase.Disabled); if (!flag) { NotifyListenersOfActionChange(InputActionChange.ActionDisabled, map.m_Actions[i]); } } } map.m_EnabledActionsCount = 0; if (map.m_SingletonAction != null) { NotifyListenersOfActionChange(InputActionChange.ActionDisabled, map.m_SingletonAction); } else if (flag) { NotifyListenersOfActionChange(InputActionChange.ActionMapDisabled, map); } } public unsafe void DisableControls(InputActionMap map) { int mapIndexInState = map.m_MapIndexInState; int controlCount = mapIndices[mapIndexInState].controlCount; int controlStartIndex = mapIndices[mapIndexInState].controlStartIndex; if (controlCount > 0) { DisableControls(mapIndexInState, controlStartIndex, controlCount); } } public void DisableSingleAction(InputAction action) { DisableControls(action); ResetActionState(action.m_ActionIndexInState, InputActionPhase.Disabled); action.m_ActionMap.m_EnabledActionsCount--; NotifyListenersOfActionChange(InputActionChange.ActionDisabled, action); } private unsafe void DisableControls(InputAction action) { int actionIndexInState = action.m_ActionIndexInState; int mapIndexInState = action.m_ActionMap.m_MapIndexInState; int bindingStartIndex = mapIndices[mapIndexInState].bindingStartIndex; int bindingCount = mapIndices[mapIndexInState].bindingCount; BindingState* ptr = memory.bindingStates; for (int i = 0; i < bindingCount; i++) { int num = bindingStartIndex + i; BindingState* ptr2 = ptr + num; if (ptr2->actionIndex == actionIndexInState && !ptr2->isPartOfComposite) { int controlCount = ptr2->controlCount; if (controlCount != 0) { DisableControls(mapIndexInState, ptr2->controlStartIndex, controlCount); } } } } private unsafe void EnableControls(int mapIndex, int controlStartIndex, int numControls) { InputManager s_Manager = InputSystem.s_Manager; for (int i = 0; i < numControls; i++) { int num = controlStartIndex + i; if (!IsControlEnabled(num)) { int num2 = controlIndexToBindingIndex[num]; long monitorIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, num, num2); BindingState* ptr = bindingStates + num2; if (ptr->wantsInitialStateCheck) { SetInitialStateCheckPending(ptr, value: true); } s_Manager.AddStateChangeMonitor(controls[num], this, monitorIndex, controlGroupingAndComplexity[num * 2]); SetControlEnabled(num, state: true); } } } private unsafe void DisableControls(int mapIndex, int controlStartIndex, int numControls) { InputManager s_Manager = InputSystem.s_Manager; for (int i = 0; i < numControls; i++) { int num = controlStartIndex + i; if (IsControlEnabled(num)) { int num2 = controlIndexToBindingIndex[num]; long monitorIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, num, num2); BindingState* ptr = bindingStates + num2; if (ptr->wantsInitialStateCheck) { SetInitialStateCheckPending(ptr, value: false); } s_Manager.RemoveStateChangeMonitor(controls[num], this, monitorIndex); SetControlEnabled(num, state: false); } } } public unsafe void SetInitialStateCheckPending(int actionIndex, bool value = true) { int mapIndex = actionStates[actionIndex].mapIndex; int bindingStartIndex = mapIndices[mapIndex].bindingStartIndex; int bindingCount = mapIndices[mapIndex].bindingCount; for (int i = 0; i < bindingCount; i++) { ref BindingState reference = ref bindingStates[bindingStartIndex + i]; if (reference.actionIndex == actionIndex && !reference.isPartOfComposite) { reference.initialStateCheckPending = value; } } } private unsafe void SetInitialStateCheckPending(BindingState* bindingStatePtr, bool value) { if (bindingStatePtr->isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStatePtr->compositeOrCompositeBindingIndex; bindingStates[compositeOrCompositeBindingIndex].initialStateCheckPending = value; } else { bindingStatePtr->initialStateCheckPending = value; } } private unsafe bool IsControlEnabled(int controlIndex) { int num = controlIndex / 32; uint num2 = (uint)(1 << controlIndex % 32); return (enabledControls[num] & num2) != 0; } private unsafe void SetControlEnabled(int controlIndex, bool state) { int num = controlIndex / 32; uint num2 = (uint)(1 << controlIndex % 32); if (state) { enabledControls[num] |= num2; } else { enabledControls[num] &= ~num2; } } private void HookOnBeforeUpdate() { if (!m_OnBeforeUpdateHooked) { if (m_OnBeforeUpdateDelegate == null) { m_OnBeforeUpdateDelegate = OnBeforeInitialUpdate; } InputSystem.s_Manager.onBeforeUpdate += m_OnBeforeUpdateDelegate; m_OnBeforeUpdateHooked = true; } } private void UnhookOnBeforeUpdate() { if (m_OnBeforeUpdateHooked) { InputSystem.s_Manager.onBeforeUpdate -= m_OnBeforeUpdateDelegate; m_OnBeforeUpdateHooked = false; } } private unsafe void OnBeforeInitialUpdate() { if (InputState.currentUpdateType == InputUpdateType.BeforeRender) { return; } UnhookOnBeforeUpdate(); double currentTime = InputState.currentTime; InputManager s_Manager = InputSystem.s_Manager; for (int i = 0; i < totalBindingCount; i++) { ref BindingState reference = ref bindingStates[i]; if (!reference.initialStateCheckPending) { continue; } reference.initialStateCheckPending = false; int controlStartIndex = reference.controlStartIndex; int controlCount = reference.controlCount; bool isComposite = reference.isComposite; bool flag = false; for (int j = 0; j < controlCount; j++) { int num = controlStartIndex + j; InputControl inputControl = controls[num]; if (!IsActiveControl(i, num) && !inputControl.CheckStateIsAtDefault()) { if (inputControl.IsValueConsideredPressed(inputControl.magnitude) && (reference.pressTime == 0.0 || reference.pressTime > currentTime)) { reference.pressTime = currentTime; } if (!(isComposite && flag)) { s_Manager.SignalStateChangeMonitor(inputControl, this); flag = true; } } } } s_Manager.FireStateChangeNotifications(); } void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time, InputEventPtr eventPtr, long mapControlAndBindingIndex) { SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex); ProcessControlStateChange(mapIndex, controlIndex, bindingIndex, time, eventPtr); } void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time, long mapControlAndBindingIndex, int interactionIndex) { SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex); ProcessTimeout(time, mapIndex, controlIndex, bindingIndex, interactionIndex); } private unsafe long ToCombinedMapAndControlAndBindingIndex(int mapIndex, int controlIndex, int bindingIndex) { ushort num = controlGroupingAndComplexity[controlIndex * 2 + 1]; return controlIndex | ((long)bindingIndex << 24) | ((long)mapIndex << 40) | (long)((ulong)num << 48); } private void SplitUpMapAndControlAndBindingIndex(long mapControlAndBindingIndex, out int mapIndex, out int controlIndex, out int bindingIndex) { controlIndex = (int)(mapControlAndBindingIndex & 0xFFFFFF); bindingIndex = (int)((mapControlAndBindingIndex >> 24) & 0xFFFF); mapIndex = (int)((mapControlAndBindingIndex >> 40) & 0xFF); } internal static int GetComplexityFromMonitorIndex(long mapControlAndBindingIndex) { return (int)((mapControlAndBindingIndex >> 48) & 0xFF); } private unsafe void ProcessControlStateChange(int mapIndex, int controlIndex, int bindingIndex, double time, InputEventPtr eventPtr) { using (InputActionRebindingExtensions.DeferBindingResolution()) { m_InProcessControlStateChange = true; m_CurrentlyProcessingThisEvent = eventPtr; try { BindingState* ptr = bindingStates + bindingIndex; int actionIndex = ptr->actionIndex; TriggerState trigger = new TriggerState { mapIndex = mapIndex, controlIndex = controlIndex, bindingIndex = bindingIndex, interactionIndex = -1, time = time, startTime = time, isPassThrough = (actionIndex != -1 && actionStates[actionIndex].isPassThrough), isButton = (actionIndex != -1 && actionStates[actionIndex].isButton) }; if (m_OnBeforeUpdateHooked) { ptr->initialStateCheckPending = false; } InputControl inputControl = controls[controlIndex]; trigger.magnitude = (inputControl.CheckStateIsAtDefault() ? 0f : inputControl.magnitude); controlMagnitudes[controlIndex] = trigger.magnitude; if (inputControl.IsValueConsideredPressed(trigger.magnitude) && (ptr->pressTime == 0.0 || ptr->pressTime > trigger.time)) { ptr->pressTime = trigger.time; } bool flag = false; if (ptr->isPartOfComposite) { int compositeOrCompositeBindingIndex = ptr->compositeOrCompositeBindingIndex; BindingState* ptr2 = bindingStates + compositeOrCompositeBindingIndex; if (ShouldIgnoreInputOnCompositeBinding(ptr2, eventPtr)) { return; } int compositeOrCompositeBindingIndex2 = bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; InputBindingCompositeContext context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = compositeOrCompositeBindingIndex }; trigger.magnitude = composites[compositeOrCompositeBindingIndex2].EvaluateMagnitude(ref context); memory.compositeMagnitudes[compositeOrCompositeBindingIndex2] = trigger.magnitude; int interactionCount = ptr2->interactionCount; if (interactionCount > 0) { flag = true; ProcessInteractions(ref trigger, ptr2->interactionStartIndex, interactionCount); } } bool flag2 = IsConflictingInput(ref trigger, actionIndex); ptr = bindingStates + trigger.bindingIndex; if (!flag2) { ProcessButtonState(ref trigger, actionIndex, ptr); } int interactionCount2 = ptr->interactionCount; if (interactionCount2 > 0 && !ptr->isPartOfComposite) { ProcessInteractions(ref trigger, ptr->interactionStartIndex, interactionCount2); } else if (!flag && !flag2) { ProcessDefaultInteraction(ref trigger, actionIndex); } } finally { m_InProcessControlStateChange = false; m_CurrentlyProcessingThisEvent = default(InputEventPtr); } } } private unsafe void ProcessButtonState(ref TriggerState trigger, int actionIndex, BindingState* bindingStatePtr) { InputControl inputControl = controls[trigger.controlIndex]; float num = (inputControl.isButton ? ((ButtonControl)inputControl).pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint); if (controlMagnitudes[trigger.controlIndex] <= num * ButtonControl.s_GlobalDefaultButtonReleaseThreshold) { bindingStatePtr->pressTime = 0.0; } float magnitude = trigger.magnitude; TriggerState* ptr = actionStates + actionIndex; if (!ptr->isPressed && magnitude >= num) { ptr->pressedInUpdate = InputUpdate.s_UpdateStepCount; ptr->isPressed = true; } else if (ptr->isPressed) { float num2 = num * ButtonControl.s_GlobalDefaultButtonReleaseThreshold; if (magnitude <= num2) { ptr->releasedInUpdate = InputUpdate.s_UpdateStepCount; ptr->isPressed = false; } } } private unsafe static bool ShouldIgnoreInputOnCompositeBinding(BindingState* binding, InputEvent* eventPtr) { if (eventPtr == null) { return false; } int eventId = eventPtr->eventId; if (eventId != 0 && binding->triggerEventIdForComposite == eventId) { return true; } binding->triggerEventIdForComposite = eventId; return false; } private unsafe bool IsConflictingInput(ref TriggerState trigger, int actionIndex) { TriggerState* ptr = actionStates + actionIndex; if (!ptr->mayNeedConflictResolution) { return false; } int num = trigger.controlIndex; if (bindingStates[trigger.bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStates[trigger.bindingIndex].compositeOrCompositeBindingIndex; num = bindingStates[compositeOrCompositeBindingIndex].controlStartIndex; } int num2 = ptr->controlIndex; if (bindingStates[ptr->bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex2 = bindingStates[ptr->bindingIndex].compositeOrCompositeBindingIndex; num2 = bindingStates[compositeOrCompositeBindingIndex2].controlStartIndex; } if (num2 == -1) { ptr->magnitude = trigger.magnitude; return false; } bool flag = num == num2 || controls[num] == controls[num2]; if (trigger.magnitude > ptr->magnitude) { if (trigger.magnitude > 0f && !flag && ptr->magnitude > 0f) { ptr->hasMultipleConcurrentActuations = true; } ptr->magnitude = trigger.magnitude; return false; } if (trigger.magnitude < ptr->magnitude) { if (!flag) { if (trigger.magnitude > 0f) { ptr->hasMultipleConcurrentActuations = true; } return true; } if (!ptr->hasMultipleConcurrentActuations) { ptr->magnitude = trigger.magnitude; return false; } ushort bindingCount; ushort actionBindingStartIndexAndCount = GetActionBindingStartIndexAndCount(actionIndex, out bindingCount); float num3 = trigger.magnitude; int num4 = -1; int num5 = -1; int num6 = 0; for (int i = 0; i < bindingCount; i++) { ushort num7 = memory.actionBindingIndices[actionBindingStartIndexAndCount + i]; BindingState* ptr2 = memory.bindingStates + (int)num7; if (ptr2->isComposite) { int controlStartIndex = ptr2->controlStartIndex; int compositeOrCompositeBindingIndex3 = ptr2->compositeOrCompositeBindingIndex; float num8 = memory.compositeMagnitudes[compositeOrCompositeBindingIndex3]; if (num8 > 0f) { num6++; } if (num8 > num3) { num4 = controlStartIndex; num5 = controlIndexToBindingIndex[controlStartIndex]; num3 = num8; } } else { if (ptr2->isPartOfComposite) { continue; } for (int j = 0; j < ptr2->controlCount; j++) { int num9 = ptr2->controlStartIndex + j; float num10 = memory.controlMagnitudes[num9]; if (num10 > 0f) { num6++; } if (num10 > num3) { num4 = num9; num5 = num7; num3 = num10; } } } } if (num6 <= 1) { ptr->hasMultipleConcurrentActuations = false; } if (num4 != -1) { trigger.controlIndex = num4; trigger.bindingIndex = num5; trigger.magnitude = num3; if (ptr->bindingIndex != num5) { if (ptr->interactionIndex != -1) { ResetInteractionState(ptr->interactionIndex); } BindingState* num11 = bindingStates + num5; int interactionCount = num11->interactionCount; int interactionStartIndex = num11->interactionStartIndex; for (int k = 0; k < interactionCount; k++) { if (interactionStates[interactionStartIndex + k].phase.IsInProgress()) { ptr->interactionIndex = interactionStartIndex + k; trigger.interactionIndex = interactionStartIndex + k; break; } } } ptr->controlIndex = num4; ptr->bindingIndex = num5; ptr->magnitude = num3; return false; } } if (!flag && Mathf.Approximately(trigger.magnitude, ptr->magnitude)) { if (trigger.magnitude > 0f) { ptr->hasMultipleConcurrentActuations = true; } return true; } return false; } private unsafe ushort GetActionBindingStartIndexAndCount(int actionIndex, out ushort bindingCount) { bindingCount = memory.actionBindingIndicesAndCounts[actionIndex * 2 + 1]; return memory.actionBindingIndicesAndCounts[actionIndex * 2]; } private unsafe void ProcessDefaultInteraction(ref TriggerState trigger, int actionIndex) { TriggerState* ptr = actionStates + actionIndex; switch (ptr->phase) { case InputActionPhase.Waiting: if (trigger.isPassThrough) { ChangePhaseOfAction(InputActionPhase.Performed, ref trigger); } else if (trigger.isButton) { float magnitude3 = trigger.magnitude; if (magnitude3 > 0f) { ChangePhaseOfAction(InputActionPhase.Started, ref trigger); } float num4 = ((controls[trigger.controlIndex] is ButtonControl buttonControl3) ? buttonControl3.pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint); if (magnitude3 >= num4) { ChangePhaseOfAction(InputActionPhase.Performed, ref trigger, InputActionPhase.Performed); } } else if (IsActuated(ref trigger)) { ChangePhaseOfAction(InputActionPhase.Started, ref trigger); ChangePhaseOfAction(InputActionPhase.Performed, ref trigger, InputActionPhase.Started); } break; case InputActionPhase.Started: if (ptr->isButton) { float magnitude2 = trigger.magnitude; float num3 = ((controls[trigger.controlIndex] is ButtonControl buttonControl2) ? buttonControl2.pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint); if (magnitude2 >= num3) { ChangePhaseOfAction(InputActionPhase.Performed, ref trigger, InputActionPhase.Performed); } else if (Mathf.Approximately(magnitude2, 0f)) { ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger); } } else if (!IsActuated(ref trigger)) { ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger); } else { ChangePhaseOfAction(InputActionPhase.Performed, ref trigger, InputActionPhase.Started); } break; case InputActionPhase.Performed: if (ptr->isButton) { float magnitude = trigger.magnitude; float num = ((controls[trigger.controlIndex] is ButtonControl buttonControl) ? buttonControl.pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint); if (Mathf.Approximately(0f, magnitude)) { ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger); break; } float num2 = num * ButtonControl.s_GlobalDefaultButtonReleaseThreshold; if (magnitude <= num2) { ChangePhaseOfAction(InputActionPhase.Started, ref trigger); } } else if (ptr->isPassThrough) { ChangePhaseOfAction(InputActionPhase.Performed, ref trigger, InputActionPhase.Performed); } break; } } private unsafe void ProcessInteractions(ref TriggerState trigger, int interactionStartIndex, int interactionCount) { InputInteractionContext context = new InputInteractionContext { m_State = this, m_TriggerState = trigger }; for (int i = 0; i < interactionCount; i++) { int num = interactionStartIndex + i; InteractionState interactionState = interactionStates[num]; IInputInteraction obj = interactions[num]; context.m_TriggerState.phase = interactionState.phase; context.m_TriggerState.startTime = interactionState.startTime; context.m_TriggerState.interactionIndex = num; obj.Process(ref context); } } private unsafe void ProcessTimeout(double time, int mapIndex, int controlIndex, int bindingIndex, int interactionIndex) { ref InteractionState reference = ref interactionStates[interactionIndex]; InputInteractionContext context = new InputInteractionContext { m_State = this, m_TriggerState = new TriggerState { phase = reference.phase, time = time, mapIndex = mapIndex, controlIndex = controlIndex, bindingIndex = bindingIndex, interactionIndex = interactionIndex, startTime = reference.startTime }, timerHasExpired = true }; reference.isTimerRunning = false; reference.totalTimeoutCompletionTimeRemaining = Mathf.Max(reference.totalTimeoutCompletionTimeRemaining - reference.timerDuration, 0f); reference.timerDuration = 0f; interactions[interactionIndex].Process(ref context); } internal unsafe void SetTotalTimeoutCompletionTime(float seconds, ref TriggerState trigger) { InteractionState* num = interactionStates + trigger.interactionIndex; num->totalTimeoutCompletionDone = 0f; num->totalTimeoutCompletionTimeRemaining = seconds; } internal unsafe void StartTimeout(float seconds, ref TriggerState trigger) { InputManager s_Manager = InputSystem.s_Manager; double time = trigger.time; InputControl control = controls[trigger.controlIndex]; int interactionIndex = trigger.interactionIndex; long num = ToCombinedMapAndControlAndBindingIndex(trigger.mapIndex, trigger.controlIndex, trigger.bindingIndex); InteractionState* num2 = interactionStates + interactionIndex; if (num2->isTimerRunning) { StopTimeout(interactionIndex); } s_Manager.AddStateChangeMonitorTimeout(control, this, time + (double)seconds, num, interactionIndex); num2->isTimerRunning = true; num2->timerStartTime = time; num2->timerDuration = seconds; num2->timerMonitorIndex = num; } private unsafe void StopTimeout(int interactionIndex) { ref InteractionState reference = ref interactionStates[interactionIndex]; InputSystem.s_Manager.RemoveStateChangeMonitorTimeout(this, reference.timerMonitorIndex, interactionIndex); reference.isTimerRunning = false; reference.totalTimeoutCompletionDone += reference.timerDuration; reference.totalTimeoutCompletionTimeRemaining = Mathf.Max(reference.totalTimeoutCompletionTimeRemaining - reference.timerDuration, 0f); reference.timerDuration = 0f; reference.timerStartTime = 0.0; reference.timerMonitorIndex = 0L; } internal unsafe void ChangePhaseOfInteraction(InputActionPhase newPhase, ref TriggerState trigger, InputActionPhase phaseAfterPerformed = InputActionPhase.Waiting, bool processNextInteractionOnCancel = true) { int interactionIndex = trigger.interactionIndex; int bindingIndex = trigger.bindingIndex; InputActionPhase phaseAfterPerformedOrCanceled = InputActionPhase.Waiting; if (newPhase == InputActionPhase.Performed) { phaseAfterPerformedOrCanceled = phaseAfterPerformed; } ref InteractionState reference = ref interactionStates[interactionIndex]; if (reference.isTimerRunning) { StopTimeout(trigger.interactionIndex); } reference.phase = newPhase; reference.triggerControlIndex = trigger.controlIndex; reference.startTime = trigger.startTime; if (newPhase == InputActionPhase.Performed) { reference.performedTime = trigger.time; } int actionIndex = bindingStates[bindingIndex].actionIndex; if (actionIndex != -1) { if (actionStates[actionIndex].phase == InputActionPhase.Waiting) { if (!ChangePhaseOfAction(newPhase, ref trigger, phaseAfterPerformedOrCanceled)) { return; } } else if (newPhase == InputActionPhase.Canceled && actionStates[actionIndex].interactionIndex == trigger.interactionIndex) { if (!ChangePhaseOfAction(newPhase, ref trigger) || !processNextInteractionOnCancel) { return; } int interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex; int interactionCount = bindingStates[bindingIndex].interactionCount; for (int i = 0; i < interactionCount; i++) { int num = interactionStartIndex + i; if (num == trigger.interactionIndex || (interactionStates[num].phase != InputActionPhase.Started && interactionStates[num].phase != InputActionPhase.Performed)) { continue; } double startTime = interactionStates[num].startTime; TriggerState trigger2 = new TriggerState { phase = InputActionPhase.Started, controlIndex = interactionStates[num].triggerControlIndex, bindingIndex = trigger.bindingIndex, interactionIndex = num, mapIndex = trigger.mapIndex, time = startTime, startTime = startTime }; if (ChangePhaseOfAction(InputActionPhase.Started, ref trigger2)) { if (interactionStates[num].phase != InputActionPhase.Performed) { break; } trigger2 = new TriggerState { phase = InputActionPhase.Performed, controlIndex = interactionStates[num].triggerControlIndex, bindingIndex = trigger.bindingIndex, interactionIndex = num, mapIndex = trigger.mapIndex, time = interactionStates[num].performedTime, startTime = startTime }; if (ChangePhaseOfAction(InputActionPhase.Performed, ref trigger2)) { break; } } return; } } else if (actionStates[actionIndex].interactionIndex == trigger.interactionIndex) { if (!ChangePhaseOfAction(newPhase, ref trigger, phaseAfterPerformedOrCanceled)) { return; } if (newPhase == InputActionPhase.Performed) { int interactionStartIndex2 = bindingStates[bindingIndex].interactionStartIndex; int interactionCount2 = bindingStates[bindingIndex].interactionCount; for (int j = 0; j < interactionCount2; j++) { int num2 = interactionStartIndex2 + j; if (num2 != trigger.interactionIndex) { ResetInteractionState(num2); } } } } } if (newPhase != InputActionPhase.Performed || actionStates[actionIndex].interactionIndex == trigger.interactionIndex) { if (newPhase == InputActionPhase.Performed && phaseAfterPerformed != InputActionPhase.Waiting) { reference.phase = phaseAfterPerformed; } else if (newPhase == InputActionPhase.Performed || newPhase == InputActionPhase.Canceled) { ResetInteractionState(trigger.interactionIndex); } } } private unsafe bool ChangePhaseOfAction(InputActionPhase newPhase, ref TriggerState trigger, InputActionPhase phaseAfterPerformedOrCanceled = InputActionPhase.Waiting) { int actionIndex = bindingStates[trigger.bindingIndex].actionIndex; if (actionIndex == -1) { return true; } TriggerState* ptr = actionStates + actionIndex; if (ptr->isDisabled) { return true; } ptr->inProcessing = true; try { if (ptr->isPassThrough && trigger.interactionIndex == -1) { ChangePhaseOfActionInternal(actionIndex, ptr, newPhase, ref trigger); if (!ptr->inProcessing) { return false; } } else if (newPhase == InputActionPhase.Performed && ptr->phase == InputActionPhase.Waiting) { ChangePhaseOfActionInternal(actionIndex, ptr, InputActionPhase.Started, ref trigger); if (!ptr->inProcessing) { return false; } ChangePhaseOfActionInternal(actionIndex, ptr, newPhase, ref trigger); if (!ptr->inProcessing) { return false; } if (phaseAfterPerformedOrCanceled == InputActionPhase.Waiting) { ChangePhaseOfActionInternal(actionIndex, ptr, InputActionPhase.Canceled, ref trigger); } if (!ptr->inProcessing) { return false; } ptr->phase = phaseAfterPerformedOrCanceled; } else if (ptr->phase != newPhase || newPhase == InputActionPhase.Performed) { ChangePhaseOfActionInternal(actionIndex, ptr, newPhase, ref trigger); if (!ptr->inProcessing) { return false; } if (newPhase == InputActionPhase.Performed || newPhase == InputActionPhase.Canceled) { ptr->phase = phaseAfterPerformedOrCanceled; } } } finally { ptr->inProcessing = false; } if (ptr->phase == InputActionPhase.Waiting) { ptr->controlIndex = -1; ptr->flags &= ~TriggerState.Flags.HaveMagnitude; } return true; } private unsafe void ChangePhaseOfActionInternal(int actionIndex, TriggerState* actionState, InputActionPhase newPhase, ref TriggerState trigger) { TriggerState triggerState = trigger; triggerState.flags = actionState->flags; if (newPhase != InputActionPhase.Canceled) { triggerState.magnitude = trigger.magnitude; } else { triggerState.magnitude = 0f; } triggerState.phase = newPhase; switch (newPhase) { case InputActionPhase.Performed: triggerState.lastPerformedInUpdate = InputUpdate.s_UpdateStepCount; triggerState.lastCanceledInUpdate = actionState->lastCanceledInUpdate; if (controlGroupingAndComplexity[trigger.controlIndex * 2 + 1] > 1 && m_CurrentlyProcessingThisEvent.valid) { m_CurrentlyProcessingThisEvent.handled = true; } break; case InputActionPhase.Canceled: triggerState.lastCanceledInUpdate = InputUpdate.s_UpdateStepCount; triggerState.lastPerformedInUpdate = actionState->lastPerformedInUpdate; break; default: triggerState.lastPerformedInUpdate = actionState->lastPerformedInUpdate; triggerState.lastCanceledInUpdate = actionState->lastCanceledInUpdate; break; } triggerState.pressedInUpdate = actionState->pressedInUpdate; triggerState.releasedInUpdate = actionState->releasedInUpdate; if (newPhase == InputActionPhase.Started) { triggerState.startTime = triggerState.time; } *actionState = triggerState; InputActionMap inputActionMap = maps[trigger.mapIndex]; InputAction inputAction = inputActionMap.m_Actions[actionIndex - mapIndices[trigger.mapIndex].actionStartIndex]; trigger.phase = newPhase; switch (newPhase) { case InputActionPhase.Started: CallActionListeners(actionIndex, inputActionMap, newPhase, ref inputAction.m_OnStarted, "started"); break; case InputActionPhase.Performed: CallActionListeners(actionIndex, inputActionMap, newPhase, ref inputAction.m_OnPerformed, "performed"); break; case InputActionPhase.Canceled: CallActionListeners(actionIndex, inputActionMap, newPhase, ref inputAction.m_OnCanceled, "canceled"); break; } } private void CallActionListeners(int actionIndex, InputActionMap actionMap, InputActionPhase phase, ref CallbackArray> listeners, string callbackName) { CallbackArray> callbacks = actionMap.m_ActionCallbacks; if (listeners.length == 0 && callbacks.length == 0 && s_GlobalState.onActionChange.length == 0) { return; } InputAction.CallbackContext argument = new InputAction.CallbackContext { m_State = this, m_ActionIndex = actionIndex }; InputAction action = argument.action; if (s_GlobalState.onActionChange.length > 0) { InputActionChange argument2; switch (phase) { default: return; case InputActionPhase.Started: argument2 = InputActionChange.ActionStarted; break; case InputActionPhase.Performed: argument2 = InputActionChange.ActionPerformed; break; case InputActionPhase.Canceled: argument2 = InputActionChange.ActionCanceled; break; } DelegateHelpers.InvokeCallbacksSafe(ref s_GlobalState.onActionChange, action, argument2, "InputSystem.onActionChange"); } DelegateHelpers.InvokeCallbacksSafe(ref listeners, argument, callbackName, action); DelegateHelpers.InvokeCallbacksSafe(ref callbacks, argument, callbackName, actionMap); } private object GetActionOrNoneString(ref TriggerState trigger) { InputAction actionOrNull = GetActionOrNull(ref trigger); if (actionOrNull == null) { return ""; } return actionOrNull; } internal unsafe InputAction GetActionOrNull(int bindingIndex) { int actionIndex = bindingStates[bindingIndex].actionIndex; if (actionIndex == -1) { return null; } int mapIndex = bindingStates[bindingIndex].mapIndex; int actionStartIndex = mapIndices[mapIndex].actionStartIndex; return maps[mapIndex].m_Actions[actionIndex - actionStartIndex]; } internal unsafe InputAction GetActionOrNull(ref TriggerState trigger) { int actionIndex = bindingStates[trigger.bindingIndex].actionIndex; if (actionIndex == -1) { return null; } int actionStartIndex = mapIndices[trigger.mapIndex].actionStartIndex; return maps[trigger.mapIndex].m_Actions[actionIndex - actionStartIndex]; } internal InputControl GetControl(ref TriggerState trigger) { return controls[trigger.controlIndex]; } private IInputInteraction GetInteractionOrNull(ref TriggerState trigger) { if (trigger.interactionIndex == -1) { return null; } return interactions[trigger.interactionIndex]; } internal unsafe int GetBindingIndexInMap(int bindingIndex) { int mapIndex = bindingStates[bindingIndex].mapIndex; int bindingStartIndex = mapIndices[mapIndex].bindingStartIndex; return bindingIndex - bindingStartIndex; } internal unsafe int GetBindingIndexInState(int mapIndex, int bindingIndexInMap) { return mapIndices[mapIndex].bindingStartIndex + bindingIndexInMap; } internal unsafe ref BindingState GetBindingState(int bindingIndex) { return ref bindingStates[bindingIndex]; } internal unsafe ref InputBinding GetBinding(int bindingIndex) { int mapIndex = bindingStates[bindingIndex].mapIndex; int bindingStartIndex = mapIndices[mapIndex].bindingStartIndex; return ref maps[mapIndex].m_Bindings[bindingIndex - bindingStartIndex]; } internal unsafe InputActionMap GetActionMap(int bindingIndex) { int mapIndex = bindingStates[bindingIndex].mapIndex; return maps[mapIndex]; } private unsafe void ResetInteractionStateAndCancelIfNecessary(int mapIndex, int bindingIndex, int interactionIndex) { int actionIndex = bindingStates[bindingIndex].actionIndex; if (actionStates[actionIndex].interactionIndex == interactionIndex) { InputActionPhase phase = interactionStates[interactionIndex].phase; if ((uint)(phase - 2) <= 1u) { ChangePhaseOfInteraction(InputActionPhase.Canceled, ref actionStates[actionIndex], InputActionPhase.Waiting, processNextInteractionOnCancel: false); } actionStates[actionIndex].interactionIndex = -1; } ResetInteractionState(interactionIndex); } private unsafe void ResetInteractionState(int interactionIndex) { interactions[interactionIndex].Reset(); if (interactionStates[interactionIndex].isTimerRunning) { StopTimeout(interactionIndex); } interactionStates[interactionIndex] = new InteractionState { phase = InputActionPhase.Waiting, triggerControlIndex = -1 }; } internal unsafe int GetValueSizeInBytes(int bindingIndex, int controlIndex) { if (bindingStates[bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex; int compositeOrCompositeBindingIndex2 = bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; return composites[compositeOrCompositeBindingIndex2].valueSizeInBytes; } return controls[controlIndex].valueSizeInBytes; } internal unsafe Type GetValueType(int bindingIndex, int controlIndex) { if (bindingStates[bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex; int compositeOrCompositeBindingIndex2 = bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; return composites[compositeOrCompositeBindingIndex2].valueType; } return controls[controlIndex].valueType; } internal static bool IsActuated(ref TriggerState trigger, float threshold = 0f) { float magnitude = trigger.magnitude; if (magnitude < 0f) { return true; } if (Mathf.Approximately(threshold, 0f)) { return magnitude > 0f; } return magnitude >= threshold; } internal unsafe void ReadValue(int bindingIndex, int controlIndex, void* buffer, int bufferSize, bool ignoreComposites = false) { InputControl control = null; if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex; int compositeOrCompositeBindingIndex2 = bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; InputBindingComposite obj = composites[compositeOrCompositeBindingIndex2]; InputBindingCompositeContext context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = compositeOrCompositeBindingIndex }; obj.ReadValue(ref context, buffer, bufferSize); bindingIndex = compositeOrCompositeBindingIndex; } else { control = controls[controlIndex]; control.ReadValueIntoBuffer(buffer, bufferSize); } int processorCount = bindingStates[bindingIndex].processorCount; if (processorCount > 0) { int processorStartIndex = bindingStates[bindingIndex].processorStartIndex; for (int i = 0; i < processorCount; i++) { processors[processorStartIndex + i].Process(buffer, bufferSize, control); } } } internal unsafe TValue ReadValue(int bindingIndex, int controlIndex, bool ignoreComposites = false) where TValue : struct { TValue value = default(TValue); InputControl inputControl = null; if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex; int compositeOrCompositeBindingIndex2 = bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; InputBindingComposite inputBindingComposite = composites[compositeOrCompositeBindingIndex2]; InputBindingCompositeContext context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = compositeOrCompositeBindingIndex }; if (!(inputBindingComposite is InputBindingComposite inputBindingComposite2)) { Type valueType = inputBindingComposite.valueType; if (!valueType.IsAssignableFrom(typeof(TValue))) { throw new InvalidOperationException($"Cannot read value of type '{typeof(TValue).Name}' from composite '{inputBindingComposite}' bound to action '{GetActionOrNull(bindingIndex)}' (composite is a '{compositeOrCompositeBindingIndex2.GetType().Name}' with value type '{valueType.GetNiceTypeName()}')"); } inputBindingComposite.ReadValue(ref context, UnsafeUtility.AddressOf(ref value), UnsafeUtility.SizeOf()); } else { value = inputBindingComposite2.ReadValue(ref context); } bindingIndex = compositeOrCompositeBindingIndex; } else if (controlIndex != -1) { InputControl inputControl2 = controls[controlIndex]; inputControl = inputControl2 as InputControl; if (inputControl == null) { throw new InvalidOperationException($"Cannot read value of type '{typeof(TValue).GetNiceTypeName()}' from control '{inputControl2.path}' bound to action '{GetActionOrNull(bindingIndex)}' (control is a '{inputControl2.GetType().Name}' with value type '{inputControl2.valueType.GetNiceTypeName()}')"); } value = inputControl.value; } return ApplyProcessors(bindingIndex, value, inputControl); } internal unsafe TValue ApplyProcessors(int bindingIndex, TValue value, InputControl controlOfType = null) where TValue : struct { int processorCount = bindingStates[bindingIndex].processorCount; if (processorCount > 0) { int processorStartIndex = bindingStates[bindingIndex].processorStartIndex; for (int i = 0; i < processorCount; i++) { if (processors[processorStartIndex + i] is InputProcessor inputProcessor) { value = inputProcessor.Process(value, controlOfType); } } } return value; } public unsafe float EvaluateCompositePartMagnitude(int bindingIndex, int partNumber) { int num = bindingIndex + 1; float num2 = float.MinValue; for (int i = num; i < totalBindingCount && bindingStates[i].isPartOfComposite; i++) { if (bindingStates[i].partIndex == partNumber) { int controlCount = bindingStates[i].controlCount; int controlStartIndex = bindingStates[i].controlStartIndex; for (int j = 0; j < controlCount; j++) { num2 = Mathf.Max(controls[controlStartIndex + j].magnitude, num2); } } } return num2; } internal unsafe double GetCompositePartPressTime(int bindingIndex, int partNumber) { int num = bindingIndex + 1; double num2 = double.MaxValue; for (int i = num; i < totalBindingCount && bindingStates[i].isPartOfComposite; i++) { ref BindingState reference = ref bindingStates[i]; if (reference.partIndex == partNumber && reference.pressTime != 0.0 && reference.pressTime < num2) { num2 = reference.pressTime; } } if (num2 == double.MaxValue) { return -1.0; } return num2; } internal unsafe TValue ReadCompositePartValue(int bindingIndex, int partNumber, bool* buttonValuePtr, out int controlIndex, TComparer comparer = default(TComparer)) where TValue : struct where TComparer : IComparer { TValue val = default(TValue); int num = bindingIndex + 1; bool flag = true; controlIndex = -1; for (int i = num; i < totalBindingCount && bindingStates[i].isPartOfComposite; i++) { if (bindingStates[i].partIndex != partNumber) { continue; } int controlCount = bindingStates[i].controlCount; int controlStartIndex = bindingStates[i].controlStartIndex; for (int j = 0; j < controlCount; j++) { int num2 = controlStartIndex + j; TValue val2 = ReadValue(i, num2, ignoreComposites: true); if (flag) { val = val2; controlIndex = num2; flag = false; } else if (comparer.Compare(val2, val) > 0) { val = val2; controlIndex = num2; } if (buttonValuePtr != null && controlIndex == num2) { InputControl inputControl = controls[num2]; if (inputControl is ButtonControl buttonControl) { *buttonValuePtr = buttonControl.isPressed; } else if (inputControl is InputControl) { void* ptr = UnsafeUtility.AddressOf(ref val2); *buttonValuePtr = *(float*)ptr >= ButtonControl.s_GlobalDefaultButtonPressPoint; } } } } return val; } internal unsafe bool ReadCompositePartValue(int bindingIndex, int partNumber, void* buffer, int bufferSize) { int num = bindingIndex + 1; float num2 = float.MinValue; for (int i = num; i < totalBindingCount && bindingStates[i].isPartOfComposite; i++) { if (bindingStates[i].partIndex != partNumber) { continue; } int controlCount = bindingStates[i].controlCount; int controlStartIndex = bindingStates[i].controlStartIndex; for (int j = 0; j < controlCount; j++) { int num3 = controlStartIndex + j; float magnitude = controls[num3].magnitude; if (!(magnitude < num2)) { ReadValue(i, num3, buffer, bufferSize, ignoreComposites: true); num2 = magnitude; } } } return num2 > float.MinValue; } internal unsafe object ReadCompositePartValueAsObject(int bindingIndex, int partNumber) { int num = bindingIndex + 1; float num2 = float.MinValue; object result = null; for (int i = num; i < totalBindingCount && bindingStates[i].isPartOfComposite; i++) { if (bindingStates[i].partIndex != partNumber) { continue; } int controlCount = bindingStates[i].controlCount; int controlStartIndex = bindingStates[i].controlStartIndex; for (int j = 0; j < controlCount; j++) { int num3 = controlStartIndex + j; float magnitude = controls[num3].magnitude; if (!(magnitude < num2)) { result = ReadValueAsObject(i, num3, ignoreComposites: true); num2 = magnitude; } } } return result; } internal unsafe object ReadValueAsObject(int bindingIndex, int controlIndex, bool ignoreComposites = false) { InputControl control = null; object obj = null; if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex; int compositeOrCompositeBindingIndex2 = bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; InputBindingComposite obj2 = composites[compositeOrCompositeBindingIndex2]; InputBindingCompositeContext context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = compositeOrCompositeBindingIndex }; obj = obj2.ReadValueAsObject(ref context); bindingIndex = compositeOrCompositeBindingIndex; } else if (controlIndex != -1) { control = controls[controlIndex]; obj = control.ReadValueAsObject(); } if (obj != null) { int processorCount = bindingStates[bindingIndex].processorCount; if (processorCount > 0) { int processorStartIndex = bindingStates[bindingIndex].processorStartIndex; for (int i = 0; i < processorCount; i++) { obj = processors[processorStartIndex + i].ProcessAsObject(obj, control); } } } return obj; } internal unsafe bool ReadValueAsButton(int bindingIndex, int controlIndex) { ButtonControl buttonControl = null; if (!bindingStates[bindingIndex].isPartOfComposite) { buttonControl = controls[controlIndex] as ButtonControl; } float num = ReadValue(bindingIndex, controlIndex); if (buttonControl != null) { return num >= buttonControl.pressPointOrDefault; } return num >= ButtonControl.s_GlobalDefaultButtonPressPoint; } internal static ISavedState SaveAndResetState() { SavedStructState result = new SavedStructState(ref s_GlobalState, delegate(ref GlobalState state) { s_GlobalState = state; }, delegate { ResetGlobals(); }); s_GlobalState = default(GlobalState); return result; } private void AddToGlobalList() { CompactGlobalList(); GCHandle value = GCHandle.Alloc(this, GCHandleType.Weak); s_GlobalState.globalList.AppendWithCapacity(value); } private void RemoveMapFromGlobalList() { int length = s_GlobalState.globalList.length; for (int i = 0; i < length; i++) { if (s_GlobalState.globalList[i].Target == this) { s_GlobalState.globalList[i].Free(); s_GlobalState.globalList.RemoveAtByMovingTailWithCapacity(i); break; } } } private static void CompactGlobalList() { int length = s_GlobalState.globalList.length; int num = 0; for (int i = 0; i < length; i++) { GCHandle value = s_GlobalState.globalList[i]; if (value.IsAllocated && value.Target != null) { if (num != i) { s_GlobalState.globalList[num] = value; } num++; } else { if (value.IsAllocated) { s_GlobalState.globalList[i].Free(); } s_GlobalState.globalList[i] = default(GCHandle); } } s_GlobalState.globalList.length = num; } internal void NotifyListenersOfActionChange(InputActionChange change) { for (int i = 0; i < totalMapCount; i++) { InputActionMap inputActionMap = maps[i]; if (inputActionMap.m_SingletonAction != null) { NotifyListenersOfActionChange(change, inputActionMap.m_SingletonAction); continue; } if ((Object)(object)inputActionMap.m_Asset == (Object)null) { NotifyListenersOfActionChange(change, inputActionMap); continue; } NotifyListenersOfActionChange(change, inputActionMap.m_Asset); break; } } internal static void NotifyListenersOfActionChange(InputActionChange change, object actionOrMapOrAsset) { DelegateHelpers.InvokeCallbacksSafe(ref s_GlobalState.onActionChange, actionOrMapOrAsset, change, "onActionChange"); if (change == InputActionChange.BoundControlsChanged) { DelegateHelpers.InvokeCallbacksSafe(ref s_GlobalState.onActionControlsChanged, actionOrMapOrAsset, "onActionControlsChange"); } } private static void ResetGlobals() { DestroyAllActionMapStates(); for (int i = 0; i < s_GlobalState.globalList.length; i++) { if (s_GlobalState.globalList[i].IsAllocated) { s_GlobalState.globalList[i].Free(); } } s_GlobalState.globalList.length = 0; s_GlobalState.onActionChange.Clear(); s_GlobalState.onActionControlsChanged.Clear(); } internal unsafe static int FindAllEnabledActions(List result) { int num = 0; int length = s_GlobalState.globalList.length; for (int i = 0; i < length; i++) { GCHandle gCHandle = s_GlobalState.globalList[i]; if (!gCHandle.IsAllocated) { continue; } InputActionState inputActionState = (InputActionState)gCHandle.Target; if (inputActionState == null) { continue; } int num2 = inputActionState.totalMapCount; InputActionMap[] array = inputActionState.maps; for (int j = 0; j < num2; j++) { InputActionMap inputActionMap = array[j]; if (!inputActionMap.enabled) { continue; } InputAction[] actions = inputActionMap.m_Actions; int num3 = actions.Length; if (inputActionMap.m_EnabledActionsCount == num3) { result.AddRange(actions); num += num3; continue; } int actionStartIndex = inputActionState.mapIndices[inputActionMap.m_MapIndexInState].actionStartIndex; for (int k = 0; k < num3; k++) { if (inputActionState.actionStates[actionStartIndex + k].phase != InputActionPhase.Disabled) { result.Add(actions[k]); num++; } } } } return num; } internal static void OnDeviceChange(InputDevice device, InputDeviceChange change) { for (int i = 0; i < s_GlobalState.globalList.length; i++) { GCHandle gCHandle = s_GlobalState.globalList[i]; if (!gCHandle.IsAllocated || gCHandle.Target == null) { if (gCHandle.IsAllocated) { s_GlobalState.globalList[i].Free(); } s_GlobalState.globalList.RemoveAtWithCapacity(i); i--; continue; } InputActionState inputActionState = (InputActionState)gCHandle.Target; bool fullResolve = true; switch (change) { case InputDeviceChange.Added: if (!inputActionState.CanUseDevice(device)) { continue; } fullResolve = false; break; case InputDeviceChange.Removed: { if (!inputActionState.IsUsingDevice(device)) { continue; } for (int j = 0; j < inputActionState.totalMapCount; j++) { InputActionMap obj = inputActionState.maps[j]; obj.m_Devices.Remove(device); obj.asset?.m_Devices.Remove(device); } fullResolve = false; break; } case InputDeviceChange.UsageChanged: case InputDeviceChange.ConfigurationChanged: if (!inputActionState.IsUsingDevice(device) && !inputActionState.CanUseDevice(device)) { continue; } break; case InputDeviceChange.SoftReset: case InputDeviceChange.HardReset: if (inputActionState.IsUsingDevice(device)) { inputActionState.ResetActionStatesDrivenBy(device); } continue; } for (int k = 0; k < inputActionState.totalMapCount && !inputActionState.maps[k].LazyResolveBindings(fullResolve); k++) { } } } internal static void DeferredResolutionOfBindings() { InputActionMap.s_DeferBindingResolution++; try { for (int i = 0; i < s_GlobalState.globalList.length; i++) { GCHandle gCHandle = s_GlobalState.globalList[i]; if (!gCHandle.IsAllocated || gCHandle.Target == null) { if (gCHandle.IsAllocated) { s_GlobalState.globalList[i].Free(); } s_GlobalState.globalList.RemoveAtWithCapacity(i); i--; } else { InputActionState inputActionState = (InputActionState)gCHandle.Target; for (int j = 0; j < inputActionState.totalMapCount; j++) { inputActionState.maps[j].ResolveBindingsIfNecessary(); } } } } finally { InputActionMap.s_DeferBindingResolution--; } } internal static void DisableAllActions() { for (int i = 0; i < s_GlobalState.globalList.length; i++) { GCHandle gCHandle = s_GlobalState.globalList[i]; if (gCHandle.IsAllocated && gCHandle.Target != null) { InputActionState obj = (InputActionState)gCHandle.Target; int num = obj.totalMapCount; InputActionMap[] array = obj.maps; for (int j = 0; j < num; j++) { array[j].Disable(); } } } } internal static void DestroyAllActionMapStates() { while (s_GlobalState.globalList.length > 0) { int index = s_GlobalState.globalList.length - 1; GCHandle gCHandle = s_GlobalState.globalList[index]; if (!gCHandle.IsAllocated || gCHandle.Target == null) { if (gCHandle.IsAllocated) { s_GlobalState.globalList[index].Free(); } s_GlobalState.globalList.RemoveAtWithCapacity(index); } else { ((InputActionState)gCHandle.Target).Destroy(); } } } } public enum InputActionType { Value, Button, PassThrough } [Serializable] public struct InputBinding : IEquatable { [Flags] public enum DisplayStringOptions { DontUseShortDisplayNames = 1, DontOmitDevice = 2, DontIncludeInteractions = 4, IgnoreBindingOverrides = 8 } [Flags] internal enum MatchOptions { EmptyGroupMatchesAny = 1 } [Flags] internal enum Flags { None = 0, Composite = 4, PartOfComposite = 8 } public const char Separator = ';'; internal const string kSeparatorString = ";"; [SerializeField] private string m_Name; [SerializeField] internal string m_Id; [Tooltip("Path of the control to bind to. Matched at runtime to controls from InputDevices present at the time.\n\nCan either be graphically from the control picker dropdown UI or edited manually in text mode by clicking the 'T' button. Internally, both methods result in control path strings that look like, for example, \"/buttonSouth\".")] [SerializeField] private string m_Path; [SerializeField] private string m_Interactions; [SerializeField] private string m_Processors; [SerializeField] internal string m_Groups; [SerializeField] private string m_Action; [SerializeField] internal Flags m_Flags; [NonSerialized] private string m_OverridePath; [NonSerialized] private string m_OverrideInteractions; [NonSerialized] private string m_OverrideProcessors; public string name { get { return m_Name; } set { m_Name = value; } } public Guid id { get { if (string.IsNullOrEmpty(m_Id)) { return default(Guid); } return new Guid(m_Id); } set { m_Id = value.ToString(); } } public string path { get { return m_Path; } set { m_Path = value; } } public string overridePath { get { return m_OverridePath; } set { m_OverridePath = value; } } public string interactions { get { return m_Interactions; } set { m_Interactions = value; } } public string overrideInteractions { get { return m_OverrideInteractions; } set { m_OverrideInteractions = value; } } public string processors { get { return m_Processors; } set { m_Processors = value; } } public string overrideProcessors { get { return m_OverrideProcessors; } set { m_OverrideProcessors = value; } } public string groups { get { return m_Groups; } set { m_Groups = value; } } public string action { get { return m_Action; } set { m_Action = value; } } public bool isComposite { get { return (m_Flags & Flags.Composite) == Flags.Composite; } set { if (value) { m_Flags |= Flags.Composite; } else { m_Flags &= ~Flags.Composite; } } } public bool isPartOfComposite { get { return (m_Flags & Flags.PartOfComposite) == Flags.PartOfComposite; } set { if (value) { m_Flags |= Flags.PartOfComposite; } else { m_Flags &= ~Flags.PartOfComposite; } } } public bool hasOverrides { get { if (overridePath == null && overrideProcessors == null) { return overrideInteractions != null; } return true; } } public string effectivePath => overridePath ?? path; public string effectiveInteractions => overrideInteractions ?? interactions; public string effectiveProcessors => overrideProcessors ?? processors; internal bool isEmpty { get { if (string.IsNullOrEmpty(effectivePath) && string.IsNullOrEmpty(action)) { return string.IsNullOrEmpty(groups); } return false; } } public InputBinding(string path, string action = null, string groups = null, string processors = null, string interactions = null, string name = null) { m_Path = path; m_Action = action; m_Groups = groups; m_Processors = processors; m_Interactions = interactions; m_Name = name; m_Id = null; m_Flags = Flags.None; m_OverridePath = null; m_OverrideInteractions = null; m_OverrideProcessors = null; } public string GetNameOfComposite() { if (!isComposite) { return null; } return NameAndParameters.Parse(effectivePath).name; } internal void GenerateId() { m_Id = Guid.NewGuid().ToString(); } internal void RemoveOverrides() { m_OverridePath = null; m_OverrideInteractions = null; m_OverrideProcessors = null; } public static InputBinding MaskByGroup(string group) { return new InputBinding { groups = group }; } public static InputBinding MaskByGroups(params string[] groups) { return new InputBinding { groups = string.Join(";", groups.Where((string x) => !string.IsNullOrEmpty(x))) }; } public bool Equals(InputBinding other) { if (string.Equals(effectivePath, other.effectivePath, StringComparison.InvariantCultureIgnoreCase) && string.Equals(effectiveInteractions, other.effectiveInteractions, StringComparison.InvariantCultureIgnoreCase) && string.Equals(effectiveProcessors, other.effectiveProcessors, StringComparison.InvariantCultureIgnoreCase) && string.Equals(groups, other.groups, StringComparison.InvariantCultureIgnoreCase)) { return string.Equals(action, other.action, StringComparison.InvariantCultureIgnoreCase); } return false; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputBinding other) { return Equals(other); } return false; } public static bool operator ==(InputBinding left, InputBinding right) { return left.Equals(right); } public static bool operator !=(InputBinding left, InputBinding right) { return !(left == right); } public override int GetHashCode() { return (((((((((effectivePath != null) ? effectivePath.GetHashCode() : 0) * 397) ^ ((effectiveInteractions != null) ? effectiveInteractions.GetHashCode() : 0)) * 397) ^ ((effectiveProcessors != null) ? effectiveProcessors.GetHashCode() : 0)) * 397) ^ ((groups != null) ? groups.GetHashCode() : 0)) * 397) ^ ((action != null) ? action.GetHashCode() : 0); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); if (!string.IsNullOrEmpty(action)) { stringBuilder.Append(action); stringBuilder.Append(':'); } string value = effectivePath; if (!string.IsNullOrEmpty(value)) { stringBuilder.Append(value); } if (!string.IsNullOrEmpty(groups)) { stringBuilder.Append('['); stringBuilder.Append(groups); stringBuilder.Append(']'); } return stringBuilder.ToString(); } public string ToDisplayString(DisplayStringOptions options = (DisplayStringOptions)0, InputControl control = null) { string deviceLayoutName; string controlPath; return ToDisplayString(out deviceLayoutName, out controlPath, options, control); } public string ToDisplayString(out string deviceLayoutName, out string controlPath, DisplayStringOptions options = (DisplayStringOptions)0, InputControl control = null) { if (isComposite) { deviceLayoutName = null; controlPath = null; return string.Empty; } InputControlPath.HumanReadableStringOptions humanReadableStringOptions = InputControlPath.HumanReadableStringOptions.None; if ((options & DisplayStringOptions.DontOmitDevice) == 0) { humanReadableStringOptions |= InputControlPath.HumanReadableStringOptions.OmitDevice; } if ((options & DisplayStringOptions.DontUseShortDisplayNames) == 0) { humanReadableStringOptions |= InputControlPath.HumanReadableStringOptions.UseShortNames; } string text = InputControlPath.ToHumanReadableString(((options & DisplayStringOptions.IgnoreBindingOverrides) != 0) ? path : effectivePath, out deviceLayoutName, out controlPath, humanReadableStringOptions, control); if (!string.IsNullOrEmpty(effectiveInteractions) && (options & DisplayStringOptions.DontIncludeInteractions) == 0) { string text2 = string.Empty; foreach (NameAndParameters item in NameAndParameters.ParseMultiple(effectiveInteractions)) { string displayName = InputInteraction.GetDisplayName(item.name); if (!string.IsNullOrEmpty(displayName)) { text2 = (string.IsNullOrEmpty(text2) ? displayName : (text2 + " or " + displayName)); } } if (!string.IsNullOrEmpty(text2)) { text = text2 + " " + text; } } return text; } internal bool TriggersAction(InputAction action) { if (string.Compare(action.name, this.action, StringComparison.InvariantCultureIgnoreCase) != 0) { return this.action == action.m_Id; } return true; } public bool Matches(InputBinding binding) { return Matches(ref binding); } internal bool Matches(ref InputBinding binding, MatchOptions options = (MatchOptions)0) { if (name != null && (binding.name == null || !StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(name, binding.name, ';'))) { return false; } if (path != null && (binding.path == null || !StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(path, binding.path, ';'))) { return false; } if (action != null && (binding.action == null || !StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(action, binding.action, ';'))) { return false; } if (groups != null) { bool flag = !string.IsNullOrEmpty(binding.groups); if (!flag && (options & MatchOptions.EmptyGroupMatchesAny) == 0) { return false; } if (flag && !StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(groups, binding.groups, ';')) { return false; } } if (!string.IsNullOrEmpty(m_Id) && binding.id != id) { return false; } return true; } } public abstract class InputBindingComposite { internal static TypeTable s_Composites; public abstract Type valueType { get; } public abstract int valueSizeInBytes { get; } public unsafe abstract void ReadValue(ref InputBindingCompositeContext context, void* buffer, int bufferSize); public abstract object ReadValueAsObject(ref InputBindingCompositeContext context); public virtual float EvaluateMagnitude(ref InputBindingCompositeContext context) { return -1f; } protected virtual void FinishSetup(ref InputBindingCompositeContext context) { } internal void CallFinishSetup(ref InputBindingCompositeContext context) { FinishSetup(ref context); } internal static Type GetValueType(string composite) { if (string.IsNullOrEmpty(composite)) { throw new ArgumentNullException("composite"); } Type type = s_Composites.LookupTypeRegistration(composite); if (type == null) { return null; } return TypeHelpers.GetGenericTypeArgumentFromHierarchy(type, typeof(InputBindingComposite<>), 0); } public static string GetExpectedControlLayoutName(string composite, string part) { if (string.IsNullOrEmpty(composite)) { throw new ArgumentNullException("composite"); } if (string.IsNullOrEmpty(part)) { throw new ArgumentNullException("part"); } Type type = s_Composites.LookupTypeRegistration(composite); if (type == null) { return null; } FieldInfo field = type.GetField(part, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (field == null) { return null; } return ((MemberInfo)field).GetCustomAttribute(inherit: false)?.layout; } internal static IEnumerable GetPartNames(string composite) { if (string.IsNullOrEmpty(composite)) { throw new ArgumentNullException("composite"); } Type type = s_Composites.LookupTypeRegistration(composite); if (type == null) { yield break; } FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (((MemberInfo)fieldInfo).GetCustomAttribute() != null) { yield return fieldInfo.Name; } } } internal static string GetDisplayFormatString(string composite) { if (string.IsNullOrEmpty(composite)) { throw new ArgumentNullException("composite"); } Type type = s_Composites.LookupTypeRegistration(composite); if (type == null) { return null; } return type.GetCustomAttribute()?.formatString; } } public abstract class InputBindingComposite : InputBindingComposite where TValue : struct { public override Type valueType => typeof(TValue); public override int valueSizeInBytes => UnsafeUtility.SizeOf(); public abstract TValue ReadValue(ref InputBindingCompositeContext context); public unsafe override void ReadValue(ref InputBindingCompositeContext context, void* buffer, int bufferSize) { if (buffer == null) { throw new ArgumentNullException("buffer"); } int num = UnsafeUtility.SizeOf(); if (bufferSize < num) { throw new ArgumentException($"Expected buffer of at least {UnsafeUtility.SizeOf()} bytes but got buffer of only {bufferSize} bytes instead", "bufferSize"); } TValue val = ReadValue(ref context); void* ptr = UnsafeUtility.AddressOf(ref val); UnsafeUtility.MemCpy(buffer, ptr, (long)num); } public unsafe override object ReadValueAsObject(ref InputBindingCompositeContext context) { TValue val = default(TValue); void* buffer = UnsafeUtility.AddressOf(ref val); ReadValue(ref context, buffer, UnsafeUtility.SizeOf()); return val; } } public struct InputBindingCompositeContext { public struct PartBinding { public int part { get; set; } public InputControl control { get; set; } } [StructLayout(LayoutKind.Sequential, Size = 1)] private struct DefaultComparer : IComparer where TValue : IComparable { public int Compare(TValue x, TValue y) { return x.CompareTo(y); } } internal InputActionState m_State; internal int m_BindingIndex; public IEnumerable controls { get { if (m_State == null) { yield break; } int totalBindingCount = m_State.totalBindingCount; int bindingIndex = m_BindingIndex + 1; while (bindingIndex < totalBindingCount) { InputActionState.BindingState bindingState = m_State.GetBindingState(bindingIndex); if (bindingState.isPartOfComposite) { int controlStartIndex = bindingState.controlStartIndex; int num; for (int i = 0; i < bindingState.controlCount; i = num) { InputControl control = m_State.controls[controlStartIndex + i]; yield return new PartBinding { part = bindingState.partIndex, control = control }; num = i + 1; } num = bindingIndex + 1; bindingIndex = num; continue; } break; } } } public float EvaluateMagnitude(int partNumber) { return m_State.EvaluateCompositePartMagnitude(m_BindingIndex, partNumber); } public unsafe TValue ReadValue(int partNumber) where TValue : struct, IComparable { if (m_State == null) { return default(TValue); } int controlIndex; return m_State.ReadCompositePartValue>(m_BindingIndex, partNumber, null, out controlIndex); } public unsafe TValue ReadValue(int partNumber, out InputControl sourceControl) where TValue : struct, IComparable { if (m_State == null) { sourceControl = null; return default(TValue); } int controlIndex; TValue result = m_State.ReadCompositePartValue>(m_BindingIndex, partNumber, null, out controlIndex); if (controlIndex != -1) { sourceControl = m_State.controls[controlIndex]; return result; } sourceControl = null; return result; } public unsafe TValue ReadValue(int partNumber, TComparer comparer = default(TComparer)) where TValue : struct where TComparer : IComparer { if (m_State == null) { return default(TValue); } int controlIndex; return m_State.ReadCompositePartValue(m_BindingIndex, partNumber, null, out controlIndex, comparer); } public unsafe TValue ReadValue(int partNumber, out InputControl sourceControl, TComparer comparer = default(TComparer)) where TValue : struct where TComparer : IComparer { if (m_State == null) { sourceControl = null; return default(TValue); } int controlIndex; TValue result = m_State.ReadCompositePartValue(m_BindingIndex, partNumber, null, out controlIndex, comparer); if (controlIndex != -1) { sourceControl = m_State.controls[controlIndex]; return result; } sourceControl = null; return result; } public unsafe bool ReadValueAsButton(int partNumber) { if (m_State == null) { return false; } bool result = false; m_State.ReadCompositePartValue>(m_BindingIndex, partNumber, &result, out var _); return result; } public unsafe void ReadValue(int partNumber, void* buffer, int bufferSize) { m_State?.ReadCompositePartValue(m_BindingIndex, partNumber, buffer, bufferSize); } public object ReadValueAsObject(int partNumber) { return m_State.ReadCompositePartValueAsObject(m_BindingIndex, partNumber); } public double GetPressTime(int partNumber) { return m_State.GetCompositePartPressTime(m_BindingIndex, partNumber); } } internal struct InputBindingResolver : IDisposable { public int totalProcessorCount; public int totalCompositeCount; public int totalInteractionCount; public InputActionMap[] maps; public InputControl[] controls; public InputActionState.UnmanagedMemory memory; public IInputInteraction[] interactions; public InputProcessor[] processors; public InputBindingComposite[] composites; public InputBinding? bindingMask; private bool m_IsControlOnlyResolve; private List m_Parameters; public int totalMapCount => memory.mapCount; public int totalActionCount => memory.actionCount; public int totalBindingCount => memory.bindingCount; public int totalControlCount => memory.controlCount; public void Dispose() { memory.Dispose(); } public void StartWithPreviousResolve(InputActionState state, bool isFullResolve) { m_IsControlOnlyResolve = !isFullResolve; maps = state.maps; interactions = state.interactions; processors = state.processors; composites = state.composites; controls = state.controls; if (isFullResolve) { if (maps != null) { Array.Clear(maps, 0, state.totalMapCount); } if (interactions != null) { Array.Clear(interactions, 0, state.totalInteractionCount); } if (processors != null) { Array.Clear(processors, 0, state.totalProcessorCount); } if (composites != null) { Array.Clear(composites, 0, state.totalCompositeCount); } } if (controls != null) { Array.Clear(controls, 0, state.totalControlCount); } state.maps = null; state.interactions = null; state.processors = null; state.composites = null; state.controls = null; } public unsafe void AddActionMap(InputActionMap actionMap) { InputSystem.EnsureInitialized(); InputAction[] actions = actionMap.m_Actions; InputBinding[] bindings = actionMap.m_Bindings; int num = ((bindings != null) ? bindings.Length : 0); int num2 = ((actions != null) ? actions.Length : 0); int num3 = totalMapCount; int num4 = totalActionCount; int num5 = totalBindingCount; int controlStartIndex = totalControlCount; int num6 = totalInteractionCount; int num7 = totalProcessorCount; int num8 = totalCompositeCount; InputActionState.UnmanagedMemory unmanagedMemory = default(InputActionState.UnmanagedMemory); unmanagedMemory.Allocate(totalMapCount + 1, totalActionCount + num2, totalBindingCount + num, interactionCount: totalInteractionCount, compositeCount: totalCompositeCount, controlCount: totalControlCount); if (memory.isAllocated) { unmanagedMemory.CopyDataFrom(memory); } int num9 = -1; int num10 = -1; int currentCompositePartCount = 0; int num11 = -1; InputAction inputAction = null; InputBinding? inputBinding = actionMap.m_BindingMask; ReadOnlyArray? devices = actionMap.devices; bool flag = actionMap.m_SingletonAction != null; InputControlList matches = new InputControlList((Allocator)2); try { for (int i = 0; i < num; i++) { InputActionState.BindingState* bindingStates = unmanagedMemory.bindingStates; ref InputBinding reference = ref bindings[i]; int num12 = num5 + i; bool isComposite = reference.isComposite; bool flag2 = !isComposite && reference.isPartOfComposite; InputActionState.BindingState* ptr = bindingStates + num12; try { int controlStartIndex2 = 0; int num13 = -1; int num14 = -1; int actionIndex = -1; int partIndex = -1; int num15 = 0; int num16 = 0; int num17 = 0; if (flag2 && num9 == -1) { throw new InvalidOperationException($"Binding '{reference}' is marked as being part of a composite but the preceding binding is not a composite"); } int num18 = -1; string action = reference.action; InputAction inputAction2 = null; if (!flag2) { if (flag) { num18 = 0; } else if (!string.IsNullOrEmpty(action)) { num18 = actionMap.FindActionIndex(action); } if (num18 != -1) { inputAction2 = actions[num18]; } } else { num18 = num11; inputAction2 = inputAction; } if (isComposite) { num9 = num12; inputAction = inputAction2; num11 = num18; } string effectivePath = reference.effectivePath; bool flag3 = string.IsNullOrEmpty(effectivePath) || inputAction2 == null || (!isComposite && bindingMask.HasValue && !bindingMask.Value.Matches(ref reference, InputBinding.MatchOptions.EmptyGroupMatchesAny)) || (!isComposite && inputBinding.HasValue && !inputBinding.Value.Matches(ref reference, InputBinding.MatchOptions.EmptyGroupMatchesAny)) || (!isComposite && inputAction2 != null && inputAction2.m_BindingMask.HasValue && !inputAction2.m_BindingMask.Value.Matches(ref reference, InputBinding.MatchOptions.EmptyGroupMatchesAny)); if (!flag3 && !isComposite) { controlStartIndex2 = memory.controlCount + matches.Count; if (devices.HasValue) { ReadOnlyArray value = devices.Value; for (int j = 0; j < value.Count; j++) { InputDevice inputDevice = value[j]; if (inputDevice.added) { num15 += InputControlPath.TryFindControls(inputDevice, effectivePath, 0, ref matches); } } } else { num15 = InputSystem.FindControls(effectivePath, ref matches); } } if (!flag3) { string effectiveProcessors = reference.effectiveProcessors; if (!string.IsNullOrEmpty(effectiveProcessors)) { num14 = InstantiateWithParameters(InputProcessor.s_Processors, effectiveProcessors, ref processors, ref totalProcessorCount, actionMap, ref reference); if (num14 != -1) { num17 = totalProcessorCount - num14; } } if (!string.IsNullOrEmpty(inputAction2.m_Processors)) { int num19 = InstantiateWithParameters(InputProcessor.s_Processors, inputAction2.m_Processors, ref processors, ref totalProcessorCount, actionMap, ref reference); if (num19 != -1) { if (num14 == -1) { num14 = num19; } num17 += totalProcessorCount - num19; } } string effectiveInteractions = reference.effectiveInteractions; if (!string.IsNullOrEmpty(effectiveInteractions)) { num13 = InstantiateWithParameters(InputInteraction.s_Interactions, effectiveInteractions, ref interactions, ref totalInteractionCount, actionMap, ref reference); if (num13 != -1) { num16 = totalInteractionCount - num13; } } if (!string.IsNullOrEmpty(inputAction2.m_Interactions)) { int num20 = InstantiateWithParameters(InputInteraction.s_Interactions, inputAction2.m_Interactions, ref interactions, ref totalInteractionCount, actionMap, ref reference); if (num20 != -1) { if (num13 == -1) { num13 = num20; } num16 += totalInteractionCount - num20; } } if (isComposite) { InputBindingComposite value2 = InstantiateBindingComposite(ref reference, actionMap); num10 = ArrayHelpers.AppendWithCapacity(ref composites, ref totalCompositeCount, value2); controlStartIndex2 = memory.controlCount + matches.Count; } else if (!flag2 && num9 != -1) { currentCompositePartCount = 0; num9 = -1; num10 = -1; inputAction = null; num11 = -1; } } if (flag2 && num9 != -1 && num15 > 0) { if (string.IsNullOrEmpty(reference.name)) { throw new InvalidOperationException($"Binding '{reference}' that is part of composite '{composites[num10]}' is missing a name"); } partIndex = AssignCompositePartIndex(composites[num10], reference.name, ref currentCompositePartCount); bindingStates[num9].controlCount += num15; actionIndex = bindingStates[num9].actionIndex; } else if (num18 != -1) { actionIndex = num4 + num18; } *ptr = new InputActionState.BindingState { controlStartIndex = controlStartIndex2, controlCount = num15, interactionStartIndex = num13, interactionCount = num16, processorStartIndex = num14, processorCount = num17, isComposite = isComposite, isPartOfComposite = reference.isPartOfComposite, partIndex = partIndex, actionIndex = actionIndex, compositeOrCompositeBindingIndex = (isComposite ? num10 : num9), mapIndex = totalMapCount, wantsInitialStateCheck = (inputAction2?.wantsInitialStateCheck ?? false) }; } catch (Exception ex) { Debug.LogError((object)$"{ex.GetType().Name} while resolving binding '{reference}' in action map '{actionMap}'"); Debug.LogException(ex); if (ex.IsExceptionIndicatingBugInCode()) { throw; } } } int count = matches.Count; int num21 = memory.controlCount + count; if (unmanagedMemory.interactionCount != totalInteractionCount || unmanagedMemory.compositeCount != totalCompositeCount || unmanagedMemory.controlCount != num21) { InputActionState.UnmanagedMemory unmanagedMemory2 = default(InputActionState.UnmanagedMemory); unmanagedMemory2.Allocate(unmanagedMemory.mapCount, unmanagedMemory.actionCount, unmanagedMemory.bindingCount, num21, totalInteractionCount, totalCompositeCount); unmanagedMemory2.CopyDataFrom(unmanagedMemory); unmanagedMemory.Dispose(); unmanagedMemory = unmanagedMemory2; } int length = memory.controlCount; ArrayHelpers.AppendListWithCapacity(ref controls, ref length, matches); for (int k = 0; k < num; k++) { InputActionState.BindingState* num22 = unmanagedMemory.bindingStates + (num5 + k); int controlCount = num22->controlCount; int controlStartIndex3 = num22->controlStartIndex; for (int l = 0; l < controlCount; l++) { unmanagedMemory.controlIndexToBindingIndex[controlStartIndex3 + l] = num5 + k; } } for (int m = memory.interactionCount; m < unmanagedMemory.interactionCount; m++) { InputActionState.InteractionState* num23 = unmanagedMemory.interactionStates + m; num23->phase = InputActionPhase.Waiting; num23->triggerControlIndex = -1; } int num24 = memory.bindingCount; for (int n = 0; n < num2; n++) { InputAction inputAction3 = actions[n]; int num25 = (inputAction3.m_ActionIndexInState = num4 + n); unmanagedMemory.actionBindingIndicesAndCounts[num25 * 2] = (ushort)num24; int num26 = -1; int num27 = 0; int num28 = 0; for (int num29 = 0; num29 < num; num29++) { int num30 = num5 + num29; InputActionState.BindingState* ptr2 = unmanagedMemory.bindingStates + num30; if (ptr2->actionIndex != num25 || ptr2->isPartOfComposite) { continue; } unmanagedMemory.actionBindingIndices[num24] = (ushort)num30; num24++; num27++; if (num26 == -1) { num26 = num30; } if (ptr2->isComposite) { if (ptr2->controlCount > 0) { num28++; } } else { num28 += ptr2->controlCount; } } if (num26 == -1) { num26 = 0; } unmanagedMemory.actionBindingIndicesAndCounts[num25 * 2 + 1] = (ushort)num27; bool flag4 = inputAction3.type == InputActionType.PassThrough; bool isButton = inputAction3.type == InputActionType.Button; bool mayNeedConflictResolution = !flag4 && num28 > 1; unmanagedMemory.actionStates[num25] = new InputActionState.TriggerState { phase = InputActionPhase.Disabled, mapIndex = num3, controlIndex = -1, interactionIndex = -1, isPassThrough = flag4, isButton = isButton, mayNeedConflictResolution = mayNeedConflictResolution, bindingIndex = num26 }; } unmanagedMemory.mapIndices[num3] = new InputActionState.ActionMapIndices { actionStartIndex = num4, actionCount = num2, controlStartIndex = controlStartIndex, controlCount = count, bindingStartIndex = num5, bindingCount = num, interactionStartIndex = num6, interactionCount = totalInteractionCount - num6, processorStartIndex = num7, processorCount = totalProcessorCount - num7, compositeStartIndex = num8, compositeCount = totalCompositeCount - num8 }; actionMap.m_MapIndexInState = num3; int count2 = memory.mapCount; ArrayHelpers.AppendWithCapacity(ref maps, ref count2, actionMap, 4); memory.Dispose(); memory = unmanagedMemory; } catch (Exception) { unmanagedMemory.Dispose(); throw; } finally { matches.Dispose(); } } private int InstantiateWithParameters(TypeTable registrations, string namesAndParameters, ref TType[] array, ref int count, InputActionMap actionMap, ref InputBinding binding) { if (!NameAndParameters.ParseMultiple(namesAndParameters, ref m_Parameters)) { return -1; } int result = count; for (int i = 0; i < m_Parameters.Count; i++) { string name = m_Parameters[i].name; Type type = registrations.LookupTypeRegistration(name); if (type == null) { Debug.LogError((object)("No " + typeof(TType).Name + " with name '" + name + "' (mentioned in '" + namesAndParameters + "') has been registered")); } else if (!m_IsControlOnlyResolve) { if (!(Activator.CreateInstance(type) is TType val)) { Debug.LogError((object)("Type '" + type.Name + "' registered as '" + name + "' (mentioned in '" + namesAndParameters + "') is not an " + typeof(TType).Name)); } else { ApplyParameters(m_Parameters[i].parameters, val, actionMap, ref binding, name, namesAndParameters); ArrayHelpers.AppendWithCapacity(ref array, ref count, val); } } else { count++; } } return result; } private static InputBindingComposite InstantiateBindingComposite(ref InputBinding binding, InputActionMap actionMap) { NameAndParameters nameAndParameters = NameAndParameters.Parse(binding.effectivePath); Type type = InputBindingComposite.s_Composites.LookupTypeRegistration(nameAndParameters.name); if (type == null) { throw new InvalidOperationException("No binding composite with name '" + nameAndParameters.name + "' has been registered"); } if (!(Activator.CreateInstance(type) is InputBindingComposite inputBindingComposite)) { throw new InvalidOperationException("Registered type '" + type.Name + "' used for '" + nameAndParameters.name + "' is not an InputBindingComposite"); } ApplyParameters(nameAndParameters.parameters, inputBindingComposite, actionMap, ref binding, nameAndParameters.name, binding.effectivePath); return inputBindingComposite; } private static void ApplyParameters(ReadOnlyArray parameters, object instance, InputActionMap actionMap, ref InputBinding binding, string objectRegistrationName, string namesAndParameters) { foreach (NamedValue item in parameters) { FieldInfo field = instance.GetType().GetField(item.name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { Debug.LogError((object)("Type '" + instance.GetType().Name + "' registered as '" + objectRegistrationName + "' (mentioned in '" + namesAndParameters + "') has no public field called '" + item.name + "'")); } else { TypeCode typeCode = Type.GetTypeCode(field.FieldType); InputActionRebindingExtensions.ParameterOverride? parameterOverride = InputActionRebindingExtensions.ParameterOverride.Find(actionMap, ref binding, item.name, objectRegistrationName); field.SetValue(instance, (parameterOverride.HasValue ? parameterOverride.Value.value : item.value).ConvertTo(typeCode).ToObject()); } } } private static int AssignCompositePartIndex(object composite, string name, ref int currentCompositePartCount) { Type type = composite.GetType(); FieldInfo field = type.GetField(name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { throw new InvalidOperationException($"Cannot find public field '{name}' used as parameter of binding composite '{composite}' of type '{type}'"); } if (field.FieldType != typeof(int)) { throw new InvalidOperationException($"Field '{name}' used as a parameter of binding composite '{composite}' must be of type 'int' but is of type '{type.Name}' instead"); } int num = (int)field.GetValue(composite); if (num == 0) { num = ++currentCompositePartCount; field.SetValue(composite, num); } return num; } } [Serializable] public struct InputControlScheme : IEquatable { public struct MatchResult : IEnumerable, IEnumerable, IDisposable { internal enum Result { AllSatisfied, MissingRequired, MissingOptional } public struct Match { internal int m_RequirementIndex; internal DeviceRequirement[] m_Requirements; internal InputControlList m_Controls; public InputControl control => m_Controls[m_RequirementIndex]; public InputDevice device => control?.device; public int requirementIndex => m_RequirementIndex; public DeviceRequirement requirement => m_Requirements[m_RequirementIndex]; public bool isOptional => requirement.isOptional; } private struct Enumerator : IEnumerator, IDisposable, IEnumerator { internal int m_Index; internal DeviceRequirement[] m_Requirements; internal InputControlList m_Controls; public Match Current { get { if (m_Requirements == null || m_Index < 0 || m_Index >= m_Requirements.Length) { throw new InvalidOperationException("Enumerator is not valid"); } return new Match { m_RequirementIndex = m_Index, m_Requirements = m_Requirements, m_Controls = m_Controls }; } } object IEnumerator.Current => Current; public bool MoveNext() { m_Index++; if (m_Requirements != null) { return m_Index < m_Requirements.Length; } return false; } public void Reset() { m_Index = -1; } public void Dispose() { } } internal Result m_Result; internal float m_Score; internal InputControlList m_Devices; internal InputControlList m_Controls; internal DeviceRequirement[] m_Requirements; public float score => m_Score; public bool isSuccessfulMatch => m_Result != Result.MissingRequired; public bool hasMissingRequiredDevices => m_Result == Result.MissingRequired; public bool hasMissingOptionalDevices => m_Result == Result.MissingOptional; public InputControlList devices { get { if (m_Devices.Count == 0 && !hasMissingRequiredDevices) { int count = m_Controls.Count; if (count != 0) { m_Devices.Capacity = count; for (int i = 0; i < count; i++) { InputControl inputControl = m_Controls[i]; if (inputControl != null) { InputDevice device = inputControl.device; if (!m_Devices.Contains(device)) { m_Devices.Add(device); } } } } } return m_Devices; } } public Match this[int index] { get { if (index < 0 || m_Requirements == null || index >= m_Requirements.Length) { throw new ArgumentOutOfRangeException("index"); } return new Match { m_RequirementIndex = index, m_Requirements = m_Requirements, m_Controls = m_Controls }; } } public IEnumerator GetEnumerator() { return new Enumerator { m_Index = -1, m_Requirements = m_Requirements, m_Controls = m_Controls }; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { m_Controls.Dispose(); m_Devices.Dispose(); } } [Serializable] public struct DeviceRequirement : IEquatable { [Flags] internal enum Flags { None = 0, Optional = 1, Or = 2 } [SerializeField] internal string m_ControlPath; [SerializeField] internal Flags m_Flags; public string controlPath { get { return m_ControlPath; } set { m_ControlPath = value; } } public bool isOptional { get { return (m_Flags & Flags.Optional) != 0; } set { if (value) { m_Flags |= Flags.Optional; } else { m_Flags &= ~Flags.Optional; } } } public bool isAND { get { return !isOR; } set { isOR = !value; } } public bool isOR { get { return (m_Flags & Flags.Or) != 0; } set { if (value) { m_Flags |= Flags.Or; } else { m_Flags &= ~Flags.Or; } } } public override string ToString() { if (!string.IsNullOrEmpty(controlPath)) { if (isOptional) { return controlPath + " (Optional)"; } return controlPath + " (Required)"; } return base.ToString(); } public bool Equals(DeviceRequirement other) { if (string.Equals(m_ControlPath, other.m_ControlPath) && m_Flags == other.m_Flags && string.Equals(controlPath, other.controlPath)) { return isOptional == other.isOptional; } return false; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is DeviceRequirement) { return Equals((DeviceRequirement)obj); } return false; } public override int GetHashCode() { return (((((((m_ControlPath != null) ? m_ControlPath.GetHashCode() : 0) * 397) ^ m_Flags.GetHashCode()) * 397) ^ ((controlPath != null) ? controlPath.GetHashCode() : 0)) * 397) ^ isOptional.GetHashCode(); } public static bool operator ==(DeviceRequirement left, DeviceRequirement right) { return left.Equals(right); } public static bool operator !=(DeviceRequirement left, DeviceRequirement right) { return !left.Equals(right); } } [Serializable] internal struct SchemeJson { [Serializable] public struct DeviceJson { public string devicePath; public bool isOptional; public bool isOR; public DeviceRequirement ToDeviceEntry() { return new DeviceRequirement { controlPath = devicePath, isOptional = isOptional, isOR = isOR }; } public static DeviceJson From(DeviceRequirement requirement) { return new DeviceJson { devicePath = requirement.controlPath, isOptional = requirement.isOptional, isOR = requirement.isOR }; } } public string name; public string bindingGroup; public DeviceJson[] devices; public InputControlScheme ToScheme() { DeviceRequirement[] array = null; if (devices != null && devices.Length != 0) { int num = devices.Length; array = new DeviceRequirement[num]; for (int i = 0; i < num; i++) { array[i] = devices[i].ToDeviceEntry(); } } return new InputControlScheme { m_Name = (string.IsNullOrEmpty(name) ? null : name), m_BindingGroup = (string.IsNullOrEmpty(bindingGroup) ? null : bindingGroup), m_DeviceRequirements = array }; } public static SchemeJson ToJson(InputControlScheme scheme) { DeviceJson[] array = null; if (scheme.m_DeviceRequirements != null && scheme.m_DeviceRequirements.Length != 0) { int num = scheme.m_DeviceRequirements.Length; array = new DeviceJson[num]; for (int i = 0; i < num; i++) { array[i] = DeviceJson.From(scheme.m_DeviceRequirements[i]); } } return new SchemeJson { name = scheme.m_Name, bindingGroup = scheme.m_BindingGroup, devices = array }; } public static SchemeJson[] ToJson(InputControlScheme[] schemes) { if (schemes == null || schemes.Length == 0) { return null; } int num = schemes.Length; SchemeJson[] array = new SchemeJson[num]; for (int i = 0; i < num; i++) { array[i] = ToJson(schemes[i]); } return array; } public static InputControlScheme[] ToSchemes(SchemeJson[] schemes) { if (schemes == null || schemes.Length == 0) { return null; } int num = schemes.Length; InputControlScheme[] array = new InputControlScheme[num]; for (int i = 0; i < num; i++) { array[i] = schemes[i].ToScheme(); } return array; } } [SerializeField] internal string m_Name; [SerializeField] internal string m_BindingGroup; [SerializeField] internal DeviceRequirement[] m_DeviceRequirements; public string name => m_Name; public string bindingGroup { get { return m_BindingGroup; } set { m_BindingGroup = value; } } public ReadOnlyArray deviceRequirements => new ReadOnlyArray(m_DeviceRequirements); public InputControlScheme(string name, IEnumerable devices = null, string bindingGroup = null) { this = default(InputControlScheme); if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } SetNameAndBindingGroup(name, bindingGroup); m_DeviceRequirements = null; if (devices != null) { m_DeviceRequirements = devices.ToArray(); if (m_DeviceRequirements.Length == 0) { m_DeviceRequirements = null; } } } internal void SetNameAndBindingGroup(string name, string bindingGroup = null) { m_Name = name; if (!string.IsNullOrEmpty(bindingGroup)) { m_BindingGroup = bindingGroup; } else { m_BindingGroup = (name.Contains(';') ? name.Replace(";", "") : name); } } public static InputControlScheme? FindControlSchemeForDevices(TDevices devices, TSchemes schemes, InputDevice mustIncludeDevice = null, bool allowUnsuccesfulMatch = false) where TDevices : IReadOnlyList where TSchemes : IEnumerable { if (devices == null) { throw new ArgumentNullException("devices"); } if (schemes == null) { throw new ArgumentNullException("schemes"); } if (!FindControlSchemeForDevices(devices, schemes, out var controlScheme, out var matchResult, mustIncludeDevice, allowUnsuccesfulMatch)) { return null; } matchResult.Dispose(); return controlScheme; } public static bool FindControlSchemeForDevices(TDevices devices, TSchemes schemes, out InputControlScheme controlScheme, out MatchResult matchResult, InputDevice mustIncludeDevice = null, bool allowUnsuccessfulMatch = false) where TDevices : IReadOnlyList where TSchemes : IEnumerable { if (devices == null) { throw new ArgumentNullException("devices"); } if (schemes == null) { throw new ArgumentNullException("schemes"); } MatchResult? matchResult2 = null; InputControlScheme? inputControlScheme = null; foreach (InputControlScheme item in schemes) { MatchResult value = item.PickDevicesFrom(devices, mustIncludeDevice); if (!value.isSuccessfulMatch && (!allowUnsuccessfulMatch || value.score <= 0f)) { value.Dispose(); continue; } if (mustIncludeDevice != null && !value.devices.Contains(mustIncludeDevice)) { value.Dispose(); continue; } if (matchResult2.HasValue && matchResult2.Value.score >= value.score) { value.Dispose(); continue; } matchResult2?.Dispose(); matchResult2 = value; inputControlScheme = item; } matchResult = matchResult2.GetValueOrDefault(); controlScheme = inputControlScheme.GetValueOrDefault(); return matchResult2.HasValue; } public static InputControlScheme? FindControlSchemeForDevice(InputDevice device, TSchemes schemes) where TSchemes : IEnumerable { if (schemes == null) { throw new ArgumentNullException("schemes"); } if (device == null) { throw new ArgumentNullException("device"); } return FindControlSchemeForDevices(new OneOrMore>(device), schemes); } public bool SupportsDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } for (int i = 0; i < m_DeviceRequirements.Length; i++) { if (InputControlPath.TryFindControl(device, m_DeviceRequirements[i].controlPath) != null) { return true; } } return false; } public MatchResult PickDevicesFrom(TDevices devices, InputDevice favorDevice = null) where TDevices : IReadOnlyList { if (m_DeviceRequirements == null || m_DeviceRequirements.Length == 0) { return new MatchResult { m_Result = MatchResult.Result.AllSatisfied, m_Score = 0.5f }; } bool flag = true; bool flag2 = true; int num = m_DeviceRequirements.Length; float num2 = 0f; InputControlList controls = new InputControlList((Allocator)4, num); try { bool flag3 = false; bool flag4 = false; for (int i = 0; i < num; i++) { bool isOR = m_DeviceRequirements[i].isOR; bool isOptional = m_DeviceRequirements[i].isOptional; if (isOR && flag3) { controls.Add(null); continue; } string controlPath = m_DeviceRequirements[i].controlPath; if (string.IsNullOrEmpty(controlPath)) { num2 += 1f; controls.Add(null); continue; } InputControl inputControl = null; for (int j = 0; j < devices.Count; j++) { InputDevice inputDevice = devices[j]; if (favorDevice != null) { if (j == 0) { inputDevice = favorDevice; } else if (inputDevice == favorDevice) { inputDevice = devices[0]; } } InputControl inputControl2 = InputControlPath.TryFindControl(inputDevice, controlPath); if (inputControl2 != null && !controls.Contains(inputControl2)) { inputControl = inputControl2; InternedString firstLayout = new InternedString(InputControlPath.TryGetDeviceLayout(controlPath)); if (firstLayout.IsEmpty()) { num2 += 1f; break; } InternedString layout = inputControl2.device.m_Layout; num2 = ((!InputControlLayout.s_Layouts.ComputeDistanceInInheritanceHierarchy(firstLayout, layout, out var distance)) ? (num2 + 1f) : (num2 + (1f + 1f / (float)(Math.Abs(distance) + 1)))); break; } } if (i + 1 < num && m_DeviceRequirements[i + 1].isOR) { if (inputControl != null) { flag3 = true; } else if (!isOptional) { flag4 = true; } } else if (isOR && i == num - 1) { if (inputControl == null) { if (flag4) { flag = false; } else { flag2 = false; } } } else { if (inputControl == null) { if (isOptional) { flag2 = false; } else { flag = false; } } if (i > 0 && m_DeviceRequirements[i - 1].isOR) { if (!flag3) { if (flag4) { flag = false; } else { flag2 = false; } } flag3 = false; } } controls.Add(inputControl); } } catch (Exception) { controls.Dispose(); throw; } return new MatchResult { m_Result = ((!flag) ? MatchResult.Result.MissingRequired : ((!flag2) ? MatchResult.Result.MissingOptional : MatchResult.Result.AllSatisfied)), m_Controls = controls, m_Requirements = m_DeviceRequirements, m_Score = num2 }; } public bool Equals(InputControlScheme other) { if (!string.Equals(m_Name, other.m_Name, StringComparison.InvariantCultureIgnoreCase) || !string.Equals(m_BindingGroup, other.m_BindingGroup, StringComparison.InvariantCultureIgnoreCase)) { return false; } if (m_DeviceRequirements == null || m_DeviceRequirements.Length == 0) { if (other.m_DeviceRequirements != null) { return other.m_DeviceRequirements.Length == 0; } return true; } if (other.m_DeviceRequirements == null || m_DeviceRequirements.Length != other.m_DeviceRequirements.Length) { return false; } int num = m_DeviceRequirements.Length; for (int i = 0; i < num; i++) { DeviceRequirement deviceRequirement = m_DeviceRequirements[i]; bool flag = false; for (int j = 0; j < num; j++) { if (other.m_DeviceRequirements[j] == deviceRequirement) { flag = true; break; } } if (!flag) { return false; } } return true; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputControlScheme) { return Equals((InputControlScheme)obj); } return false; } public override int GetHashCode() { return (((((m_Name != null) ? m_Name.GetHashCode() : 0) * 397) ^ ((m_BindingGroup != null) ? m_BindingGroup.GetHashCode() : 0)) * 397) ^ ((m_DeviceRequirements != null) ? m_DeviceRequirements.GetHashCode() : 0); } public override string ToString() { if (string.IsNullOrEmpty(m_Name)) { return base.ToString(); } if (m_DeviceRequirements == null) { return m_Name; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(m_Name); stringBuilder.Append('('); bool flag = true; DeviceRequirement[] array = m_DeviceRequirements; foreach (DeviceRequirement deviceRequirement in array) { if (!flag) { stringBuilder.Append(','); } stringBuilder.Append(deviceRequirement.controlPath); flag = false; } stringBuilder.Append(')'); return stringBuilder.ToString(); } public static bool operator ==(InputControlScheme left, InputControlScheme right) { return left.Equals(right); } public static bool operator !=(InputControlScheme left, InputControlScheme right) { return !left.Equals(right); } } public struct InputInteractionContext { [Flags] internal enum Flags { TimerHasExpired = 2 } internal InputActionState m_State; internal Flags m_Flags; internal InputActionState.TriggerState m_TriggerState; public InputAction action => m_State.GetActionOrNull(ref m_TriggerState); public InputControl control => m_State.GetControl(ref m_TriggerState); public InputActionPhase phase => m_TriggerState.phase; public double time => m_TriggerState.time; public double startTime => m_TriggerState.startTime; public bool timerHasExpired { get { return (m_Flags & Flags.TimerHasExpired) != 0; } internal set { if (value) { m_Flags |= Flags.TimerHasExpired; } else { m_Flags &= ~Flags.TimerHasExpired; } } } public bool isWaiting => phase == InputActionPhase.Waiting; public bool isStarted => phase == InputActionPhase.Started; internal int mapIndex => m_TriggerState.mapIndex; internal int controlIndex => m_TriggerState.controlIndex; internal int bindingIndex => m_TriggerState.bindingIndex; internal int interactionIndex => m_TriggerState.interactionIndex; public float ComputeMagnitude() { return m_TriggerState.magnitude; } public bool ControlIsActuated(float threshold = 0f) { return InputActionState.IsActuated(ref m_TriggerState, threshold); } public void Started() { m_TriggerState.startTime = time; m_State.ChangePhaseOfInteraction(InputActionPhase.Started, ref m_TriggerState); } public void Performed() { if (m_TriggerState.phase == InputActionPhase.Waiting) { m_TriggerState.startTime = time; } m_State.ChangePhaseOfInteraction(InputActionPhase.Performed, ref m_TriggerState); } public void PerformedAndStayStarted() { if (m_TriggerState.phase == InputActionPhase.Waiting) { m_TriggerState.startTime = time; } m_State.ChangePhaseOfInteraction(InputActionPhase.Performed, ref m_TriggerState, InputActionPhase.Started); } public void PerformedAndStayPerformed() { if (m_TriggerState.phase == InputActionPhase.Waiting) { m_TriggerState.startTime = time; } m_State.ChangePhaseOfInteraction(InputActionPhase.Performed, ref m_TriggerState, InputActionPhase.Performed); } public void Canceled() { if (m_TriggerState.phase != InputActionPhase.Canceled) { m_State.ChangePhaseOfInteraction(InputActionPhase.Canceled, ref m_TriggerState); } } public void Waiting() { if (m_TriggerState.phase != InputActionPhase.Waiting) { m_State.ChangePhaseOfInteraction(InputActionPhase.Waiting, ref m_TriggerState); } } public void SetTimeout(float seconds) { m_State.StartTimeout(seconds, ref m_TriggerState); } public void SetTotalTimeoutCompletionTime(float seconds) { if (seconds <= 0f) { throw new ArgumentException("Seconds must be a positive value", "seconds"); } m_State.SetTotalTimeoutCompletionTime(seconds, ref m_TriggerState); } public TValue ReadValue() where TValue : struct { return m_State.ReadValue(m_TriggerState.bindingIndex, m_TriggerState.controlIndex); } } public static class InputSystem { private struct StateEventBuffer { public StateEvent stateEvent; public const int kMaxSize = 512; public unsafe fixed byte data[511]; } private struct DeltaStateEventBuffer { public DeltaStateEvent stateEvent; public const int kMaxSize = 512; public unsafe fixed byte data[511]; } internal const string kAssemblyVersion = "1.6.3"; internal const string kDocUrl = "https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6"; internal static InputManager s_Manager; internal static InputRemoting s_Remote; public static ReadOnlyArray devices => s_Manager.devices; public static ReadOnlyArray disconnectedDevices => new ReadOnlyArray(s_Manager.m_DisconnectedDevices, 0, s_Manager.m_DisconnectedDevicesCount); public static float pollingFrequency { get { return s_Manager.pollingFrequency; } set { s_Manager.pollingFrequency = value; } } internal static bool isProcessingEvents => s_Manager.isProcessingEvents; public static InputEventListener onEvent { get { return default(InputEventListener); } set { } } public static IObservable onAnyButtonPress => from e in onEvent select e.GetFirstButtonPressOrNull() into c where c != null select c; public static InputSettings settings { get { return s_Manager.settings; } set { if ((Object)(object)value == (Object)null) { throw new ArgumentNullException("value"); } if (!((Object)(object)s_Manager.m_Settings == (Object)(object)value)) { s_Manager.settings = value; } } } public static InputRemoting remoting => s_Remote; public static Version version => new Version("1.6.3"); public static bool runInBackground { get { return s_Manager.m_Runtime.runInBackground; } set { s_Manager.m_Runtime.runInBackground = value; } } public static InputMetrics metrics => s_Manager.metrics; public static event Action onLayoutChange { add { lock (s_Manager) { s_Manager.onLayoutChange += value; } } remove { lock (s_Manager) { s_Manager.onLayoutChange -= value; } } } public static event Action onDeviceChange { add { if (value == null) { throw new ArgumentNullException("value"); } lock (s_Manager) { s_Manager.onDeviceChange += value; } } remove { if (value == null) { throw new ArgumentNullException("value"); } lock (s_Manager) { s_Manager.onDeviceChange -= value; } } } public static event InputDeviceCommandDelegate onDeviceCommand { add { if (value == null) { throw new ArgumentNullException("value"); } lock (s_Manager) { s_Manager.onDeviceCommand += value; } } remove { if (value == null) { throw new ArgumentNullException("value"); } lock (s_Manager) { s_Manager.onDeviceCommand -= value; } } } public static event InputDeviceFindControlLayoutDelegate onFindLayoutForDevice { add { lock (s_Manager) { s_Manager.onFindControlLayoutForDevice += value; } } remove { lock (s_Manager) { s_Manager.onFindControlLayoutForDevice -= value; } } } public static event Action onBeforeUpdate { add { lock (s_Manager) { s_Manager.onBeforeUpdate += value; } } remove { lock (s_Manager) { s_Manager.onBeforeUpdate -= value; } } } public static event Action onAfterUpdate { add { lock (s_Manager) { s_Manager.onAfterUpdate += value; } } remove { lock (s_Manager) { s_Manager.onAfterUpdate -= value; } } } public static event Action onSettingsChange { add { s_Manager.onSettingsChange += value; } remove { s_Manager.onSettingsChange -= value; } } public static event Action onActionChange { add { if (value == null) { throw new ArgumentNullException("value"); } InputActionState.s_GlobalState.onActionChange.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } InputActionState.s_GlobalState.onActionChange.RemoveCallback(value); } } public static void RegisterLayout(Type type, string name = null, InputDeviceMatcher? matches = null) { if (type == null) { throw new ArgumentNullException("type"); } if (string.IsNullOrEmpty(name)) { name = type.Name; } s_Manager.RegisterControlLayout(name, type); if (matches.HasValue) { s_Manager.RegisterControlLayoutMatcher(name, matches.Value); } } public static void RegisterLayout(string name = null, InputDeviceMatcher? matches = null) where T : InputControl { RegisterLayout(typeof(T), name, matches); } public static void RegisterLayout(string json, string name = null, InputDeviceMatcher? matches = null) { s_Manager.RegisterControlLayout(json, name); if (matches.HasValue) { s_Manager.RegisterControlLayoutMatcher(name, matches.Value); } } public static void RegisterLayoutOverride(string json, string name = null) { s_Manager.RegisterControlLayout(json, name, isOverride: true); } public static void RegisterLayoutMatcher(string layoutName, InputDeviceMatcher matcher) { s_Manager.RegisterControlLayoutMatcher(layoutName, matcher); } public static void RegisterLayoutMatcher(InputDeviceMatcher matcher) where TDevice : InputDevice { s_Manager.RegisterControlLayoutMatcher(typeof(TDevice), matcher); } public static void RegisterLayoutBuilder(Func buildMethod, string name, string baseLayout = null, InputDeviceMatcher? matches = null) { if (buildMethod == null) { throw new ArgumentNullException("buildMethod"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } s_Manager.RegisterControlLayoutBuilder(buildMethod, name, baseLayout); if (matches.HasValue) { s_Manager.RegisterControlLayoutMatcher(name, matches.Value); } } public static void RegisterPrecompiledLayout(string metadata) where TDevice : InputDevice, new() { s_Manager.RegisterPrecompiledLayout(metadata); } public static void RemoveLayout(string name) { s_Manager.RemoveControlLayout(name); } public static string TryFindMatchingLayout(InputDeviceDescription deviceDescription) { return s_Manager.TryFindMatchingControlLayout(ref deviceDescription); } public static IEnumerable ListLayouts() { return s_Manager.ListControlLayouts(); } public static IEnumerable ListLayoutsBasedOn(string baseLayout) { if (string.IsNullOrEmpty(baseLayout)) { throw new ArgumentNullException("baseLayout"); } return s_Manager.ListControlLayouts(baseLayout); } public static InputControlLayout LoadLayout(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } return s_Manager.TryLoadControlLayout(new InternedString(name)); } public static InputControlLayout LoadLayout() where TControl : InputControl { return s_Manager.TryLoadControlLayout(typeof(TControl)); } public static string GetNameOfBaseLayout(string layoutName) { if (string.IsNullOrEmpty(layoutName)) { throw new ArgumentNullException("layoutName"); } InternedString key = new InternedString(layoutName); if (InputControlLayout.s_Layouts.baseLayoutTable.TryGetValue(key, out var value)) { return value; } return null; } public static bool IsFirstLayoutBasedOnSecond(string firstLayoutName, string secondLayoutName) { if (string.IsNullOrEmpty(firstLayoutName)) { throw new ArgumentNullException("firstLayoutName"); } if (string.IsNullOrEmpty(secondLayoutName)) { throw new ArgumentNullException("secondLayoutName"); } InternedString internedString = new InternedString(firstLayoutName); InternedString internedString2 = new InternedString(secondLayoutName); if (internedString == internedString2) { return true; } return InputControlLayout.s_Layouts.IsBasedOn(internedString2, internedString); } public static void RegisterProcessor(Type type, string name = null) { if (type == null) { throw new ArgumentNullException("type"); } if (string.IsNullOrEmpty(name)) { name = type.Name; if (name.EndsWith("Processor")) { name = name.Substring(0, name.Length - "Processor".Length); } } Dictionary precompiledLayouts = s_Manager.m_Layouts.precompiledLayouts; foreach (InternedString item in new List(precompiledLayouts.Keys)) { if (StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(precompiledLayouts[item].metadata, name, ';')) { s_Manager.m_Layouts.precompiledLayouts.Remove(item); } } s_Manager.processors.AddTypeRegistration(name, type); } public static void RegisterProcessor(string name = null) { RegisterProcessor(typeof(T), name); } public static Type TryGetProcessor(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } return s_Manager.processors.LookupTypeRegistration(name); } public static IEnumerable ListProcessors() { return s_Manager.processors.names; } public static InputDevice AddDevice(string layout, string name = null, string variants = null) { if (string.IsNullOrEmpty(layout)) { throw new ArgumentNullException("layout"); } return s_Manager.AddDevice(layout, name, new InternedString(variants)); } public static TDevice AddDevice(string name = null) where TDevice : InputDevice { InputDevice inputDevice = s_Manager.AddDevice(typeof(TDevice), name); TDevice obj = inputDevice as TDevice; if (obj == null) { if (inputDevice != null) { RemoveDevice(inputDevice); } throw new InvalidOperationException("Layout registered for type '" + typeof(TDevice).Name + "' did not produce a device of that type; layout probably has been overridden"); } return obj; } public static InputDevice AddDevice(InputDeviceDescription description) { if (description.empty) { throw new ArgumentException("Description must not be empty", "description"); } return s_Manager.AddDevice(description); } public static void AddDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } s_Manager.AddDevice(device); } public static void RemoveDevice(InputDevice device) { s_Manager.RemoveDevice(device); } public static void FlushDisconnectedDevices() { s_Manager.FlushDisconnectedDevices(); } public static InputDevice GetDevice(string nameOrLayout) { return s_Manager.TryGetDevice(nameOrLayout); } public static TDevice GetDevice() where TDevice : InputDevice { return (TDevice)GetDevice(typeof(TDevice)); } public static InputDevice GetDevice(Type type) { InputDevice inputDevice = null; double num = -1.0; foreach (InputDevice device in devices) { if (type.IsInstanceOfType(device) && (inputDevice == null || device.m_LastUpdateTimeInternal > num)) { inputDevice = device; num = inputDevice.m_LastUpdateTimeInternal; } } return inputDevice; } public static TDevice GetDevice(InternedString usage) where TDevice : InputDevice { TDevice val = null; double num = -1.0; foreach (InputDevice device in devices) { if (device is TDevice val2 && val2.usages.Contains(usage) && (val == null || val2.m_LastUpdateTimeInternal > num)) { val = val2; num = val.m_LastUpdateTimeInternal; } } return val; } public static TDevice GetDevice(string usage) where TDevice : InputDevice { return GetDevice(new InternedString(usage)); } public static InputDevice GetDeviceById(int deviceId) { return s_Manager.TryGetDeviceById(deviceId); } public static List GetUnsupportedDevices() { List list = new List(); GetUnsupportedDevices(list); return list; } public static int GetUnsupportedDevices(List descriptions) { return s_Manager.GetUnsupportedDevices(descriptions); } public static void EnableDevice(InputDevice device) { s_Manager.EnableOrDisableDevice(device, enable: true); } public static void DisableDevice(InputDevice device, bool keepSendingEvents = false) { s_Manager.EnableOrDisableDevice(device, enable: false, keepSendingEvents ? InputManager.DeviceDisableScope.InFrontendOnly : InputManager.DeviceDisableScope.Everywhere); } public static bool TrySyncDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (!device.added) { throw new InvalidOperationException($"Device '{device}' has not been added"); } return device.RequestSync(); } public static void ResetDevice(InputDevice device, bool alsoResetDontResetControls = false) { s_Manager.ResetDevice(device, alsoResetDontResetControls); } [Obsolete("Use 'ResetDevice' instead.", false)] public static bool TryResetDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } return device.RequestReset(); } public static void PauseHaptics() { ReadOnlyArray readOnlyArray = devices; int count = readOnlyArray.Count; for (int i = 0; i < count; i++) { if (readOnlyArray[i] is IHaptics haptics) { haptics.PauseHaptics(); } } } public static void ResumeHaptics() { ReadOnlyArray readOnlyArray = devices; int count = readOnlyArray.Count; for (int i = 0; i < count; i++) { if (readOnlyArray[i] is IHaptics haptics) { haptics.ResumeHaptics(); } } } public static void ResetHaptics() { ReadOnlyArray readOnlyArray = devices; int count = readOnlyArray.Count; for (int i = 0; i < count; i++) { if (readOnlyArray[i] is IHaptics haptics) { haptics.ResetHaptics(); } } } public static void SetDeviceUsage(InputDevice device, string usage) { SetDeviceUsage(device, new InternedString(usage)); } public static void SetDeviceUsage(InputDevice device, InternedString usage) { s_Manager.SetDeviceUsage(device, usage); } public static void AddDeviceUsage(InputDevice device, string usage) { s_Manager.AddDeviceUsage(device, new InternedString(usage)); } public static void AddDeviceUsage(InputDevice device, InternedString usage) { s_Manager.AddDeviceUsage(device, usage); } public static void RemoveDeviceUsage(InputDevice device, string usage) { s_Manager.RemoveDeviceUsage(device, new InternedString(usage)); } public static void RemoveDeviceUsage(InputDevice device, InternedString usage) { s_Manager.RemoveDeviceUsage(device, usage); } public static InputControl FindControl(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } ReadOnlyArray readOnlyArray = s_Manager.devices; int count = readOnlyArray.Count; for (int i = 0; i < count; i++) { InputControl inputControl = InputControlPath.TryFindControl(readOnlyArray[i], path); if (inputControl != null) { return inputControl; } } return null; } public static InputControlList FindControls(string path) { return FindControls(path); } public static InputControlList FindControls(string path) where TControl : InputControl { InputControlList controls = default(InputControlList); FindControls(path, ref controls); return controls; } public static int FindControls(string path, ref InputControlList controls) where TControl : InputControl { return s_Manager.GetControls(path, ref controls); } public static void QueueEvent(InputEventPtr eventPtr) { if (!eventPtr.valid) { throw new ArgumentException("Received a null event pointer", "eventPtr"); } s_Manager.QueueEvent(eventPtr); } public static void QueueEvent(ref TEvent inputEvent) where TEvent : struct, IInputEventTypeInfo { s_Manager.QueueEvent(ref inputEvent); } public unsafe static void QueueStateEvent(InputDevice device, TState state, double time = -1.0) where TState : struct, IInputStateTypeInfo { if (device == null) { throw new ArgumentNullException("device"); } if (device.m_DeviceIndex == -1) { throw new InvalidOperationException($"Cannot queue state event for device '{device}' because device has not been added to system"); } uint num = (uint)UnsafeUtility.SizeOf(); if (num > 512) { throw new ArgumentException($"Size of '{typeof(TState).Name}' exceeds maximum supported state size of {512}", "state"); } long num2 = UnsafeUtility.SizeOf() + num - 1; time = ((!(time < 0.0)) ? (time + InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup) : InputRuntime.s_Instance.currentTime); StateEventBuffer stateEventBuffer = default(StateEventBuffer); stateEventBuffer.stateEvent = new StateEvent { baseEvent = new InputEvent(1398030676, (int)num2, device.deviceId, time), stateFormat = state.format }; UnsafeUtility.MemCpy((void*)stateEventBuffer.stateEvent.stateData, UnsafeUtility.AddressOf(ref state), (long)num); s_Manager.QueueEvent(ref stateEventBuffer.stateEvent); } public unsafe static void QueueDeltaStateEvent(InputControl control, TDelta delta, double time = -1.0) where TDelta : struct { if (control == null) { throw new ArgumentNullException("control"); } if (control.stateBlock.bitOffset != 0) { throw new InvalidOperationException($"Cannot send delta state events against bitfield controls: {control}"); } InputDevice device = control.device; if (device.m_DeviceIndex == -1) { throw new InvalidOperationException($"Cannot queue state event for control '{control}' on device '{device}' because device has not been added to system"); } time = ((!(time < 0.0)) ? (time + InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup) : InputRuntime.s_Instance.currentTime); uint num = (uint)UnsafeUtility.SizeOf(); if (num > 512) { throw new ArgumentException($"Size of state delta '{typeof(TDelta).Name}' exceeds maximum supported state size of {512}", "delta"); } if (num != control.stateBlock.alignedSizeInBytes) { throw new ArgumentException($"Size {num} of delta state of type {typeof(TDelta).Name} provided for control '{control}' does not match size {control.stateBlock.alignedSizeInBytes} of control", "delta"); } long num2 = UnsafeUtility.SizeOf() + num - 1; DeltaStateEventBuffer deltaStateEventBuffer = default(DeltaStateEventBuffer); deltaStateEventBuffer.stateEvent = new DeltaStateEvent { baseEvent = new InputEvent(1145852993, (int)num2, device.deviceId, time), stateFormat = device.stateBlock.format, stateOffset = control.m_StateBlock.byteOffset - device.m_StateBlock.byteOffset }; UnsafeUtility.MemCpy((void*)deltaStateEventBuffer.stateEvent.stateData, UnsafeUtility.AddressOf(ref delta), (long)num); s_Manager.QueueEvent(ref deltaStateEventBuffer.stateEvent); } public static void QueueConfigChangeEvent(InputDevice device, double time = -1.0) { if (device == null) { throw new ArgumentNullException("device"); } if (device.deviceId == 0) { throw new InvalidOperationException("Device has not been added"); } time = ((!(time < 0.0)) ? (time + InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup) : InputRuntime.s_Instance.currentTime); DeviceConfigurationEvent inputEvent = DeviceConfigurationEvent.Create(device.deviceId, time); s_Manager.QueueEvent(ref inputEvent); } public static void QueueTextEvent(InputDevice device, char character, double time = -1.0) { if (device == null) { throw new ArgumentNullException("device"); } if (device.deviceId == 0) { throw new InvalidOperationException("Device has not been added"); } time = ((!(time < 0.0)) ? (time + InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup) : InputRuntime.s_Instance.currentTime); TextEvent inputEvent = TextEvent.Create(device.deviceId, character, time); s_Manager.QueueEvent(ref inputEvent); } public static void Update() { s_Manager.Update(); } internal static void Update(InputUpdateType updateType) { if (updateType != InputUpdateType.None && (s_Manager.updateMask & updateType) == 0) { throw new InvalidOperationException($"'{updateType}' updates are not enabled; InputSystem.settings.updateMode is set to '{settings.updateMode}'"); } s_Manager.Update(updateType); } public static void RegisterInteraction(Type type, string name = null) { if (type == null) { throw new ArgumentNullException("type"); } if (string.IsNullOrEmpty(name)) { name = type.Name; if (name.EndsWith("Interaction")) { name = name.Substring(0, name.Length - "Interaction".Length); } } s_Manager.interactions.AddTypeRegistration(name, type); } public static void RegisterInteraction(string name = null) { RegisterInteraction(typeof(T), name); } public static Type TryGetInteraction(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } return s_Manager.interactions.LookupTypeRegistration(name); } public static IEnumerable ListInteractions() { return s_Manager.interactions.names; } public static void RegisterBindingComposite(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (string.IsNullOrEmpty(name)) { name = type.Name; if (name.EndsWith("Composite")) { name = name.Substring(0, name.Length - "Composite".Length); } } s_Manager.composites.AddTypeRegistration(name, type); } public static void RegisterBindingComposite(string name = null) { RegisterBindingComposite(typeof(T), name); } public static Type TryGetBindingComposite(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } return s_Manager.composites.LookupTypeRegistration(name); } public static void DisableAllEnabledActions() { InputActionState.DisableAllActions(); } public static List ListEnabledActions() { List list = new List(); ListEnabledActions(list); return list; } public static int ListEnabledActions(List actions) { if (actions == null) { throw new ArgumentNullException("actions"); } return InputActionState.FindAllEnabledActions(actions); } static InputSystem() { InitializeInPlayer(); } [RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)] private static void RunInitializeInPlayer() { if (s_Manager == null) { InitializeInPlayer(); } } internal static void EnsureInitialized() { } private static void InitializeInPlayer(IInputRuntime runtime = null, InputSettings settings = null) { if ((Object)(object)settings == (Object)null) { settings = Resources.FindObjectsOfTypeAll().FirstOrDefault() ?? ScriptableObject.CreateInstance(); } s_Manager = new InputManager(); s_Manager.Initialize(runtime ?? NativeInputRuntime.instance, settings); PerformDefaultPluginInitialization(); } [RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)] private static void RunInitialUpdate() { Update(InputUpdateType.None); } private static void PerformDefaultPluginInitialization() { UISupport.Initialize(); XInputSupport.Initialize(); DualShockSupport.Initialize(); HIDSupport.Initialize(); SwitchSupportHID.Initialize(); XRSupport.Initialize(); } } public static class CommonUsages { public static readonly InternedString Primary2DMotion = new InternedString("Primary2DMotion"); public static readonly InternedString Secondary2DMotion = new InternedString("Secondary2DMotion"); public static readonly InternedString PrimaryAction = new InternedString("PrimaryAction"); public static readonly InternedString SecondaryAction = new InternedString("SecondaryAction"); public static readonly InternedString PrimaryTrigger = new InternedString("PrimaryTrigger"); public static readonly InternedString SecondaryTrigger = new InternedString("SecondaryTrigger"); public static readonly InternedString Modifier = new InternedString("Modifier"); public static readonly InternedString Position = new InternedString("Position"); public static readonly InternedString Orientation = new InternedString("Orientation"); public static readonly InternedString Hatswitch = new InternedString("Hatswitch"); public static readonly InternedString Back = new InternedString("Back"); public static readonly InternedString Forward = new InternedString("Forward"); public static readonly InternedString Menu = new InternedString("Menu"); public static readonly InternedString Submit = new InternedString("Submit"); public static readonly InternedString Cancel = new InternedString("Cancel"); public static readonly InternedString Horizontal = new InternedString("Horizontal"); public static readonly InternedString Vertical = new InternedString("Vertical"); public static readonly InternedString Twist = new InternedString("Twist"); public static readonly InternedString Pressure = new InternedString("Pressure"); public static readonly InternedString ScrollHorizontal = new InternedString("ScrollHorizontal"); public static readonly InternedString ScrollVertical = new InternedString("ScrollVertical"); public static readonly InternedString Point = new InternedString("Point"); public static readonly InternedString LowFreqMotor = new InternedString("LowFreqMotor"); public static readonly InternedString HighFreqMotor = new InternedString("HighFreqMotor"); public static readonly InternedString LeftHand = new InternedString("LeftHand"); public static readonly InternedString RightHand = new InternedString("RightHand"); public static readonly InternedString BatteryStrength = new InternedString("BatteryStrength"); } [DebuggerDisplay("{DebuggerDisplay(),nq}")] public abstract class InputControl { [Flags] internal enum ControlFlags { ConfigUpToDate = 1, IsNoisy = 2, IsSynthetic = 4, IsButton = 8, DontReset = 0x10, SetupFinished = 0x20, UsesStateFromOtherControl = 0x40 } protected internal InputStateBlock m_StateBlock; internal InternedString m_Name; internal string m_Path; internal string m_DisplayName; internal string m_DisplayNameFromLayout; internal string m_ShortDisplayName; internal string m_ShortDisplayNameFromLayout; internal InternedString m_Layout; internal InternedString m_Variants; internal InputDevice m_Device; internal InputControl m_Parent; internal int m_UsageCount; internal int m_UsageStartIndex; internal int m_AliasCount; internal int m_AliasStartIndex; internal int m_ChildCount; internal int m_ChildStartIndex; internal ControlFlags m_ControlFlags; internal bool m_CachedValueIsStale = true; internal bool m_UnprocessedCachedValueIsStale = true; internal PrimitiveValue m_DefaultState; internal PrimitiveValue m_MinValue; internal PrimitiveValue m_MaxValue; internal FourCC m_OptimizedControlDataType; public string name => m_Name; public string displayName { get { RefreshConfigurationIfNeeded(); if (m_DisplayName != null) { return m_DisplayName; } if (m_DisplayNameFromLayout != null) { return m_DisplayNameFromLayout; } return m_Name; } protected set { m_DisplayName = value; } } public string shortDisplayName { get { RefreshConfigurationIfNeeded(); if (m_ShortDisplayName != null) { return m_ShortDisplayName; } if (m_ShortDisplayNameFromLayout != null) { return m_ShortDisplayNameFromLayout; } return null; } protected set { m_ShortDisplayName = value; } } public string path { get { if (m_Path == null) { m_Path = InputControlPath.Combine(m_Parent, m_Name); } return m_Path; } } public string layout => m_Layout; public string variants => m_Variants; public InputDevice device => m_Device; public InputControl parent => m_Parent; public ReadOnlyArray children => new ReadOnlyArray(m_Device.m_ChildrenForEachControl, m_ChildStartIndex, m_ChildCount); public ReadOnlyArray usages => new ReadOnlyArray(m_Device.m_UsagesForEachControl, m_UsageStartIndex, m_UsageCount); public ReadOnlyArray aliases => new ReadOnlyArray(m_Device.m_AliasesForEachControl, m_AliasStartIndex, m_AliasCount); public InputStateBlock stateBlock => m_StateBlock; public bool noisy { get { return (m_ControlFlags & ControlFlags.IsNoisy) != 0; } internal set { if (value) { m_ControlFlags |= ControlFlags.IsNoisy; ReadOnlyArray readOnlyArray = children; for (int i = 0; i < readOnlyArray.Count; i++) { if (readOnlyArray[i] != null) { readOnlyArray[i].noisy = true; } } } else { m_ControlFlags &= ~ControlFlags.IsNoisy; } } } public bool synthetic { get { return (m_ControlFlags & ControlFlags.IsSynthetic) != 0; } internal set { if (value) { m_ControlFlags |= ControlFlags.IsSynthetic; } else { m_ControlFlags &= ~ControlFlags.IsSynthetic; } } } public InputControl this[string path] => InputControlPath.TryFindChild(this, path) ?? throw new KeyNotFoundException($"Cannot find control '{path}' as child of '{this}'"); public abstract Type valueType { get; } public abstract int valueSizeInBytes { get; } public float magnitude => EvaluateMagnitude(); protected internal unsafe void* currentStatePtr => InputStateBuffers.GetFrontBufferForDevice(GetDeviceIndex()); protected internal unsafe void* previousFrameStatePtr => InputStateBuffers.GetBackBufferForDevice(GetDeviceIndex()); protected internal unsafe void* defaultStatePtr => InputStateBuffers.s_DefaultStateBuffer; protected internal unsafe void* noiseMaskPtr => InputStateBuffers.s_NoiseMaskBuffer; protected internal uint stateOffsetRelativeToDeviceRoot { get { uint byteOffset = device.m_StateBlock.byteOffset; return m_StateBlock.byteOffset - byteOffset; } } public FourCC optimizedControlDataType => m_OptimizedControlDataType; internal bool isSetupFinished { get { return (m_ControlFlags & ControlFlags.SetupFinished) == ControlFlags.SetupFinished; } set { if (value) { m_ControlFlags |= ControlFlags.SetupFinished; } else { m_ControlFlags &= ~ControlFlags.SetupFinished; } } } internal bool isButton { get { return (m_ControlFlags & ControlFlags.IsButton) == ControlFlags.IsButton; } set { if (value) { m_ControlFlags |= ControlFlags.IsButton; } else { m_ControlFlags &= ~ControlFlags.IsButton; } } } internal bool isConfigUpToDate { get { return (m_ControlFlags & ControlFlags.ConfigUpToDate) == ControlFlags.ConfigUpToDate; } set { if (value) { m_ControlFlags |= ControlFlags.ConfigUpToDate; } else { m_ControlFlags &= ~ControlFlags.ConfigUpToDate; } } } internal bool dontReset { get { return (m_ControlFlags & ControlFlags.DontReset) == ControlFlags.DontReset; } set { if (value) { m_ControlFlags |= ControlFlags.DontReset; } else { m_ControlFlags &= ~ControlFlags.DontReset; } } } internal bool usesStateFromOtherControl { get { return (m_ControlFlags & ControlFlags.UsesStateFromOtherControl) == ControlFlags.UsesStateFromOtherControl; } set { if (value) { m_ControlFlags |= ControlFlags.UsesStateFromOtherControl; } else { m_ControlFlags &= ~ControlFlags.UsesStateFromOtherControl; } } } internal bool hasDefaultState => !m_DefaultState.isEmpty; public override string ToString() { return layout + ":" + path; } private string DebuggerDisplay() { if (!device.added) { return ToString(); } try { return $"{layout}:{path}={this.ReadValueAsObject()}"; } catch (Exception) { return ToString(); } } public unsafe float EvaluateMagnitude() { return EvaluateMagnitude(currentStatePtr); } public unsafe virtual float EvaluateMagnitude(void* statePtr) { return -1f; } public unsafe abstract object ReadValueFromBufferAsObject(void* buffer, int bufferSize); public unsafe abstract object ReadValueFromStateAsObject(void* statePtr); public unsafe abstract void ReadValueFromStateIntoBuffer(void* statePtr, void* bufferPtr, int bufferSize); public unsafe virtual void WriteValueFromBufferIntoState(void* bufferPtr, int bufferSize, void* statePtr) { throw new NotSupportedException($"Control '{this}' does not support writing"); } public unsafe virtual void WriteValueFromObjectIntoState(object value, void* statePtr) { throw new NotSupportedException($"Control '{this}' does not support writing"); } public unsafe abstract bool CompareValue(void* firstStatePtr, void* secondStatePtr); public InputControl TryGetChildControl(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } return InputControlPath.TryFindChild(this, path); } public TControl TryGetChildControl(string path) where TControl : InputControl { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } InputControl inputControl = TryGetChildControl(path); if (inputControl == null) { return null; } if (!(inputControl is TControl result)) { throw new InvalidOperationException("Expected control '" + path + "' to be of type '" + typeof(TControl).Name + "' but is of type '" + inputControl.GetType().Name + "' instead!"); } return result; } public InputControl GetChildControl(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } return TryGetChildControl(path) ?? throw new ArgumentException("Cannot find input control '" + MakeChildPath(path) + "'", "path"); } public TControl GetChildControl(string path) where TControl : InputControl { InputControl childControl = GetChildControl(path); if (!(childControl is TControl result)) { throw new ArgumentException("Expected control '" + path + "' to be of type '" + typeof(TControl).Name + "' but is of type '" + childControl.GetType().Name + "' instead!", "path"); } return result; } protected InputControl() { m_StateBlock.byteOffset = 4294967294u; } protected virtual void FinishSetup() { } protected void RefreshConfigurationIfNeeded() { if (!isConfigUpToDate) { RefreshConfiguration(); isConfigUpToDate = true; } } protected virtual void RefreshConfiguration() { } protected virtual FourCC CalculateOptimizedControlDataType() { return 0; } public void ApplyParameterChanges() { SetOptimizedControlDataTypeRecursively(); for (InputControl inputControl = parent; inputControl != null; inputControl = inputControl.parent) { inputControl.SetOptimizedControlDataType(); } MarkAsStaleRecursively(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetOptimizedControlDataType() { m_OptimizedControlDataType = (InputSettings.optimizedControlsFeatureEnabled ? CalculateOptimizedControlDataType() : ((FourCC)0)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SetOptimizedControlDataTypeRecursively() { if (m_ChildCount > 0) { foreach (InputControl child in children) { child.SetOptimizedControlDataTypeRecursively(); } } SetOptimizedControlDataType(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("DEVELOPMENT_BUILD")] [Conditional("UNITY_EDITOR")] internal void EnsureOptimizationTypeHasNotChanged() { if (!InputSettings.optimizedControlsFeatureEnabled) { return; } FourCC fourCC = CalculateOptimizedControlDataType(); if (fourCC != optimizedControlDataType) { Debug.LogError((object)("Control '" + name + "' / '" + path + "' suddenly changed optimization state due to either format " + $"change or control parameters change (was '{optimizedControlDataType}' but became '{fourCC}'), " + "this hinders control hot path optimization, please call control.ApplyParameterChanges() after the changes to the control to fix this error.")); m_OptimizedControlDataType = fourCC; } if (m_ChildCount <= 0) { return; } foreach (InputControl child in children) { _ = child; } } internal void CallFinishSetupRecursive() { ReadOnlyArray readOnlyArray = children; for (int i = 0; i < readOnlyArray.Count; i++) { readOnlyArray[i].CallFinishSetupRecursive(); } FinishSetup(); SetOptimizedControlDataTypeRecursively(); } internal string MakeChildPath(string path) { if (this is InputDevice) { return path; } return this.path + "/" + path; } internal void BakeOffsetIntoStateBlockRecursive(uint offset) { m_StateBlock.byteOffset += offset; ReadOnlyArray readOnlyArray = children; for (int i = 0; i < readOnlyArray.Count; i++) { readOnlyArray[i].BakeOffsetIntoStateBlockRecursive(offset); } } internal int GetDeviceIndex() { int deviceIndex = m_Device.m_DeviceIndex; if (deviceIndex == -1) { throw new InvalidOperationException("Cannot query value of control '" + path + "' before '" + device.name + "' has been added to system!"); } return deviceIndex; } internal bool IsValueConsideredPressed(float value) { if (isButton) { return ((ButtonControl)this).IsValueConsideredPressed(value); } return value >= ButtonControl.s_GlobalDefaultButtonPressPoint; } internal virtual void AddProcessor(object first) { } internal void MarkAsStale() { m_CachedValueIsStale = true; m_UnprocessedCachedValueIsStale = true; } internal void MarkAsStaleRecursively() { MarkAsStale(); foreach (InputControl child in children) { child.MarkAsStale(); } } } public abstract class InputControl : InputControl where TValue : struct { internal InlinedArray> m_ProcessorStack; private TValue m_CachedValue; private TValue m_UnprocessedCachedValue; internal bool evaluateProcessorsEveryRead; public override Type valueType => typeof(TValue); public override int valueSizeInBytes => UnsafeUtility.SizeOf(); public ref readonly TValue value { get { if (!InputSettings.readValueCachingFeatureEnabled || m_CachedValueIsStale || evaluateProcessorsEveryRead) { m_CachedValue = ProcessValue(unprocessedValue); m_CachedValueIsStale = false; } return ref m_CachedValue; } } internal unsafe ref readonly TValue unprocessedValue { get { if (!InputSettings.readValueCachingFeatureEnabled || m_UnprocessedCachedValueIsStale) { m_UnprocessedCachedValue = ReadUnprocessedValueFromState(base.currentStatePtr); m_UnprocessedCachedValueIsStale = false; } return ref m_UnprocessedCachedValue; } } internal InputProcessor[] processors => m_ProcessorStack.ToArray(); public TValue ReadValue() { return value; } public unsafe TValue ReadValueFromPreviousFrame() { return ReadValueFromState(base.previousFrameStatePtr); } public unsafe TValue ReadDefaultValue() { return ReadValueFromState(base.defaultStatePtr); } public unsafe TValue ReadValueFromState(void* statePtr) { if (statePtr == null) { throw new ArgumentNullException("statePtr"); } return ProcessValue(ReadUnprocessedValueFromState(statePtr)); } public unsafe TValue ReadValueFromStateWithCaching(void* statePtr) { if (statePtr != base.currentStatePtr) { return ReadValueFromState(statePtr); } return value; } public unsafe TValue ReadUnprocessedValueFromStateWithCaching(void* statePtr) { if (statePtr != base.currentStatePtr) { return ReadUnprocessedValueFromState(statePtr); } return unprocessedValue; } public TValue ReadUnprocessedValue() { return unprocessedValue; } public unsafe abstract TValue ReadUnprocessedValueFromState(void* statePtr); public unsafe override object ReadValueFromStateAsObject(void* statePtr) { return ReadValueFromState(statePtr); } public unsafe override void ReadValueFromStateIntoBuffer(void* statePtr, void* bufferPtr, int bufferSize) { if (statePtr == null) { throw new ArgumentNullException("statePtr"); } if (bufferPtr == null) { throw new ArgumentNullException("bufferPtr"); } int num = UnsafeUtility.SizeOf(); if (bufferSize < num) { throw new ArgumentException($"bufferSize={bufferSize} < sizeof(TValue)={num}", "bufferSize"); } TValue val = ReadValueFromState(statePtr); void* ptr = UnsafeUtility.AddressOf(ref val); UnsafeUtility.MemCpy(bufferPtr, ptr, (long)num); } public unsafe override void WriteValueFromBufferIntoState(void* bufferPtr, int bufferSize, void* statePtr) { if (bufferPtr == null) { throw new ArgumentNullException("bufferPtr"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } int num = UnsafeUtility.SizeOf(); if (bufferSize < num) { throw new ArgumentException($"bufferSize={bufferSize} < sizeof(TValue)={num}", "bufferSize"); } TValue val = default(TValue); UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref val), bufferPtr, (long)num); WriteValueIntoState(val, statePtr); } public unsafe override void WriteValueFromObjectIntoState(object value, void* statePtr) { if (statePtr == null) { throw new ArgumentNullException("statePtr"); } if (value == null) { throw new ArgumentNullException("value"); } if (!(value is TValue)) { value = Convert.ChangeType(value, typeof(TValue)); } TValue val = (TValue)value; WriteValueIntoState(val, statePtr); } public unsafe virtual void WriteValueIntoState(TValue value, void* statePtr) { throw new NotSupportedException($"Control '{this}' does not support writing"); } public unsafe override object ReadValueFromBufferAsObject(void* buffer, int bufferSize) { if (buffer == null) { throw new ArgumentNullException("buffer"); } int num = UnsafeUtility.SizeOf(); if (bufferSize < num) { throw new ArgumentException($"Expecting buffer of at least {num} bytes for value of type {typeof(TValue).Name} but got buffer of only {bufferSize} bytes instead", "bufferSize"); } TValue val = default(TValue); UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref val), buffer, (long)num); return val; } private unsafe static bool CompareValue(ref TValue firstValue, ref TValue secondValue) { void* intPtr = UnsafeUtility.AddressOf(ref firstValue); void* ptr = UnsafeUtility.AddressOf(ref secondValue); return UnsafeUtility.MemCmp(intPtr, ptr, (long)UnsafeUtility.SizeOf()) != 0; } public unsafe override bool CompareValue(void* firstStatePtr, void* secondStatePtr) { TValue firstValue = ReadValueFromState(firstStatePtr); TValue secondValue = ReadValueFromState(secondStatePtr); return CompareValue(ref firstValue, ref secondValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TValue ProcessValue(TValue value) { ProcessValue(ref value); return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ProcessValue(ref TValue value) { if (m_ProcessorStack.length <= 0) { return; } value = m_ProcessorStack.firstValue.Process(value, this); if (m_ProcessorStack.additionalValues != null) { for (int i = 0; i < m_ProcessorStack.length - 1; i++) { value = m_ProcessorStack.additionalValues[i].Process(value, this); } } } internal TProcessor TryGetProcessor() where TProcessor : InputProcessor { if (m_ProcessorStack.length > 0) { if (m_ProcessorStack.firstValue is TProcessor result) { return result; } if (m_ProcessorStack.additionalValues != null) { for (int i = 0; i < m_ProcessorStack.length - 1; i++) { if (m_ProcessorStack.additionalValues[i] is TProcessor result2) { return result2; } } } } return null; } internal override void AddProcessor(object processor) { if (!(processor is InputProcessor inputProcessor)) { throw new ArgumentException("Cannot add processor of type '" + processor.GetType().Name + "' to control of type '" + GetType().Name + "'", "processor"); } m_ProcessorStack.Append(inputProcessor); } protected override void FinishSetup() { foreach (InputProcessor item in m_ProcessorStack) { if (item.cachingPolicy == InputProcessor.CachingPolicy.EvaluateOnEveryRead) { evaluateProcessorsEveryRead = true; } } base.FinishSetup(); } } public static class InputControlExtensions { [Flags] public enum Enumerate { IgnoreControlsInDefaultState = 1, IgnoreControlsInCurrentState = 2, IncludeSyntheticControls = 4, IncludeNoisyControls = 8, IncludeNonLeafControls = 0x10 } public struct InputEventControlCollection : IEnumerable, IEnumerable { internal InputDevice m_Device; internal InputEventPtr m_EventPtr; internal Enumerate m_Flags; internal float m_MagnitudeThreshold; public InputEventPtr eventPtr => m_EventPtr; public InputEventControlEnumerator GetEnumerator() { return new InputEventControlEnumerator(m_EventPtr, m_Device, m_Flags, m_MagnitudeThreshold); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public struct InputEventControlEnumerator : IEnumerator, IDisposable, IEnumerator { private Enumerate m_Flags; private readonly InputDevice m_Device; private readonly uint[] m_StateOffsetToControlIndex; private readonly int m_StateOffsetToControlIndexLength; private readonly InputControl[] m_AllControls; private unsafe byte* m_DefaultState; private unsafe byte* m_CurrentState; private unsafe byte* m_NoiseMask; private InputEventPtr m_EventPtr; private InputControl m_CurrentControl; private int m_CurrentIndexInStateOffsetToControlIndexMap; private uint m_CurrentControlStateBitOffset; private unsafe byte* m_EventState; private uint m_CurrentBitOffset; private uint m_EndBitOffset; private float m_MagnitudeThreshold; public InputControl Current => m_CurrentControl; object IEnumerator.Current => Current; internal unsafe InputEventControlEnumerator(InputEventPtr eventPtr, InputDevice device, Enumerate flags, float magnitudeThreshold = 0f) { m_Device = device; m_StateOffsetToControlIndex = device.m_StateOffsetToControlMap; m_StateOffsetToControlIndexLength = m_StateOffsetToControlIndex.LengthSafe(); m_AllControls = device.m_ChildrenForEachControl; m_EventPtr = eventPtr; m_Flags = flags; m_CurrentControl = null; m_CurrentIndexInStateOffsetToControlIndexMap = 0; m_CurrentControlStateBitOffset = 0u; m_EventState = default(byte*); m_CurrentBitOffset = 0u; m_EndBitOffset = 0u; m_MagnitudeThreshold = magnitudeThreshold; if ((flags & Enumerate.IncludeNoisyControls) == 0) { m_NoiseMask = (byte*)device.noiseMaskPtr + device.m_StateBlock.byteOffset; } else { m_NoiseMask = default(byte*); } if ((flags & Enumerate.IgnoreControlsInDefaultState) != 0) { m_DefaultState = (byte*)device.defaultStatePtr + device.m_StateBlock.byteOffset; } else { m_DefaultState = default(byte*); } if ((flags & Enumerate.IgnoreControlsInCurrentState) != 0) { m_CurrentState = (byte*)device.currentStatePtr + device.m_StateBlock.byteOffset; } else { m_CurrentState = default(byte*); } Reset(); } private unsafe bool CheckDefault(uint numBits) { return MemoryHelpers.MemCmpBitRegion(m_EventState, m_DefaultState, m_CurrentBitOffset, numBits, m_NoiseMask); } private unsafe bool CheckCurrent(uint numBits) { return MemoryHelpers.MemCmpBitRegion(m_EventState, m_CurrentState, m_CurrentBitOffset, numBits, m_NoiseMask); } public unsafe bool MoveNext() { if (!m_EventPtr.valid) { throw new ObjectDisposedException("Enumerator has already been disposed"); } if (m_CurrentControl != null && (m_Flags & Enumerate.IncludeNonLeafControls) != 0) { InputControl parent = m_CurrentControl.parent; if (parent != m_Device) { m_CurrentControl = parent; return true; } } bool flag = m_DefaultState != null; bool flag2 = m_CurrentState != null; while (true) { m_CurrentControl = null; if (flag2 || flag) { if ((m_CurrentBitOffset & 7) != 0) { uint num = (m_CurrentBitOffset + 8) & 7; if ((flag2 && CheckCurrent(num)) || (flag && CheckDefault(num))) { m_CurrentBitOffset += num; } } while (m_CurrentBitOffset < m_EndBitOffset) { uint num2 = m_CurrentBitOffset >> 3; byte b = m_EventState[num2]; int num3 = ((m_NoiseMask != null) ? m_NoiseMask[num2] : byte.MaxValue); if (flag2 && (m_CurrentState[num2] & num3) == (b & num3)) { m_CurrentBitOffset += 8u; continue; } if (!flag || (m_DefaultState[num2] & num3) != (b & num3)) { break; } m_CurrentBitOffset += 8u; } } if (m_CurrentBitOffset >= m_EndBitOffset || m_CurrentIndexInStateOffsetToControlIndexMap >= m_StateOffsetToControlIndexLength) { return false; } for (; m_CurrentIndexInStateOffsetToControlIndexMap < m_StateOffsetToControlIndexLength; m_CurrentIndexInStateOffsetToControlIndexMap++) { InputDevice.DecodeStateOffsetToControlMapEntry(m_StateOffsetToControlIndex[m_CurrentIndexInStateOffsetToControlIndexMap], out var controlIndex, out var stateOffset, out var stateSize); if (stateOffset < m_CurrentControlStateBitOffset || m_CurrentBitOffset >= stateOffset + stateSize - m_CurrentControlStateBitOffset) { continue; } if (stateOffset - m_CurrentControlStateBitOffset >= m_CurrentBitOffset + 8) { m_CurrentBitOffset = stateOffset - m_CurrentControlStateBitOffset; break; } if (stateOffset + stateSize - m_CurrentControlStateBitOffset > m_EndBitOffset) { continue; } if ((stateOffset & 7) == 0 && (stateSize & 7) == 0) { m_CurrentControl = m_AllControls[controlIndex]; } else { if ((flag2 && MemoryHelpers.MemCmpBitRegion(m_EventState, m_CurrentState, stateOffset - m_CurrentControlStateBitOffset, stateSize, m_NoiseMask)) || (flag && MemoryHelpers.MemCmpBitRegion(m_EventState, m_DefaultState, stateOffset - m_CurrentControlStateBitOffset, stateSize, m_NoiseMask))) { continue; } m_CurrentControl = m_AllControls[controlIndex]; } if ((m_Flags & Enumerate.IncludeNoisyControls) == 0 && m_CurrentControl.noisy) { m_CurrentControl = null; continue; } if ((m_Flags & Enumerate.IncludeSyntheticControls) == 0 && (m_CurrentControl.m_ControlFlags & (InputControl.ControlFlags.IsSynthetic | InputControl.ControlFlags.UsesStateFromOtherControl)) != 0) { m_CurrentControl = null; continue; } m_CurrentIndexInStateOffsetToControlIndexMap++; break; } if (m_CurrentControl != null) { if (m_MagnitudeThreshold == 0f) { break; } byte* statePtr = m_EventState - (m_CurrentControlStateBitOffset >> 3) - m_Device.m_StateBlock.byteOffset; float num4 = m_CurrentControl.EvaluateMagnitude(statePtr); if (!(num4 >= 0f) || !(num4 < m_MagnitudeThreshold)) { break; } } } return true; } public unsafe void Reset() { if (!m_EventPtr.valid) { throw new ObjectDisposedException("Enumerator has already been disposed"); } FourCC type = m_EventPtr.type; FourCC stateFormat; if (type == 1398030676) { StateEvent* ptr = StateEvent.FromUnchecked(m_EventPtr); m_EventState = (byte*)ptr->state; m_EndBitOffset = ptr->stateSizeInBytes * 8; m_CurrentBitOffset = 0u; stateFormat = ptr->stateFormat; } else { if (!(type == 1145852993)) { throw new NotSupportedException($"Cannot iterate over controls in event of type '{type}'"); } DeltaStateEvent* ptr2 = DeltaStateEvent.FromUnchecked(m_EventPtr); m_EventState = (byte*)ptr2->deltaState - ptr2->stateOffset; m_CurrentBitOffset = ptr2->stateOffset * 8; m_EndBitOffset = m_CurrentBitOffset + ptr2->deltaStateSizeInBytes * 8; stateFormat = ptr2->stateFormat; } m_CurrentIndexInStateOffsetToControlIndexMap = 0; m_CurrentControlStateBitOffset = 0u; m_CurrentControl = null; if (!(stateFormat != m_Device.m_StateBlock.format)) { return; } uint offset = 0u; if (m_Device.hasStateCallbacks && ((IInputStateCallbackReceiver)m_Device).GetStateOffsetForEvent(null, m_EventPtr, ref offset)) { m_CurrentControlStateBitOffset = offset * 8; if (m_CurrentState != null) { m_CurrentState += offset; } if (m_DefaultState != null) { m_DefaultState += offset; } if (m_NoiseMask != null) { m_NoiseMask += offset; } } else if (!(m_Device is Touchscreen) || !m_EventPtr.IsA() || !(StateEvent.FromUnchecked(m_EventPtr)->stateFormat == TouchState.Format)) { throw new InvalidOperationException($"{type} event with state format {stateFormat} cannot be used with device '{m_Device}'"); } } public void Dispose() { m_EventPtr = default(InputEventPtr); } } public struct ControlBuilder { public InputControl control { get; internal set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder At(InputDevice device, int index) { device.m_ChildrenForEachControl[index] = control; control.m_Device = device; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithParent(InputControl parent) { control.m_Parent = parent; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithName(string name) { control.m_Name = new InternedString(name); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithDisplayName(string displayName) { control.m_DisplayNameFromLayout = new InternedString(displayName); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithShortDisplayName(string shortDisplayName) { control.m_ShortDisplayNameFromLayout = new InternedString(shortDisplayName); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithLayout(InternedString layout) { control.m_Layout = layout; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithUsages(int startIndex, int count) { control.m_UsageStartIndex = startIndex; control.m_UsageCount = count; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithAliases(int startIndex, int count) { control.m_AliasStartIndex = startIndex; control.m_AliasCount = count; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithChildren(int startIndex, int count) { control.m_ChildStartIndex = startIndex; control.m_ChildCount = count; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithStateBlock(InputStateBlock stateBlock) { control.m_StateBlock = stateBlock; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithDefaultState(PrimitiveValue value) { control.m_DefaultState = value; control.m_Device.hasControlsWithDefaultState = true; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithMinAndMax(PrimitiveValue min, PrimitiveValue max) { control.m_MinValue = min; control.m_MaxValue = max; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder WithProcessor(TProcessor processor) where TProcessor : InputProcessor where TValue : struct { ((InputControl)control).m_ProcessorStack.Append(processor); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder IsNoisy(bool value) { control.noisy = value; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder IsSynthetic(bool value) { control.synthetic = value; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder DontReset(bool value) { control.dontReset = value; if (value) { control.m_Device.hasDontResetControls = true; } return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ControlBuilder IsButton(bool value) { control.isButton = value; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Finish() { control.isSetupFinished = true; } } public struct DeviceBuilder { public InputDevice device { get; internal set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithName(string name) { device.m_Name = new InternedString(name); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithDisplayName(string displayName) { device.m_DisplayNameFromLayout = new InternedString(displayName); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithShortDisplayName(string shortDisplayName) { device.m_ShortDisplayNameFromLayout = new InternedString(shortDisplayName); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithLayout(InternedString layout) { device.m_Layout = layout; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithChildren(int startIndex, int count) { device.m_ChildStartIndex = startIndex; device.m_ChildCount = count; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithStateBlock(InputStateBlock stateBlock) { device.m_StateBlock = stateBlock; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder IsNoisy(bool value) { device.noisy = value; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithControlUsage(int controlIndex, InternedString usage, InputControl control) { device.m_UsagesForEachControl[controlIndex] = usage; device.m_UsageToControl[controlIndex] = control; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithControlAlias(int controlIndex, InternedString alias) { device.m_AliasesForEachControl[controlIndex] = alias; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public DeviceBuilder WithStateOffsetToControlIndexMap(uint[] map) { device.m_StateOffsetToControlMap = map; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe DeviceBuilder WithControlTree(byte[] controlTreeNodes, ushort[] controlTreeIndicies) { int num = UnsafeUtility.SizeOf(); int num2 = controlTreeNodes.Length / num; device.m_ControlTreeNodes = new InputDevice.ControlBitRangeNode[num2]; fixed (byte* ptr = controlTreeNodes) { for (int i = 0; i < num2; i++) { device.m_ControlTreeNodes[i] = *(InputDevice.ControlBitRangeNode*)(ptr + i * num); } } device.m_ControlTreeIndices = controlTreeIndicies; return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Finish() { device.isSetupFinished = true; } } public static TControl FindInParentChain(this InputControl control) where TControl : InputControl { if (control == null) { throw new ArgumentNullException("control"); } for (InputControl inputControl = control; inputControl != null; inputControl = inputControl.parent) { if (inputControl is TControl result) { return result; } } return null; } public static bool IsPressed(this InputControl control, float buttonPressPoint = 0f) { if (control == null) { throw new ArgumentNullException("control"); } if (Mathf.Approximately(0f, buttonPressPoint)) { buttonPressPoint = ((!(control is ButtonControl buttonControl)) ? ButtonControl.s_GlobalDefaultButtonPressPoint : buttonControl.pressPointOrDefault); } return control.IsActuated(buttonPressPoint); } public static bool IsActuated(this InputControl control, float threshold = 0f) { if (control.CheckStateIsAtDefault()) { return false; } float magnitude = control.magnitude; if (magnitude < 0f) { if (Mathf.Approximately(threshold, 0f)) { return true; } return false; } if (Mathf.Approximately(threshold, 0f)) { return magnitude > 0f; } return magnitude >= threshold; } public unsafe static object ReadValueAsObject(this InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } return control.ReadValueFromStateAsObject(control.currentStatePtr); } public unsafe static void ReadValueIntoBuffer(this InputControl control, void* buffer, int bufferSize) { if (control == null) { throw new ArgumentNullException("control"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } control.ReadValueFromStateIntoBuffer(control.currentStatePtr, buffer, bufferSize); } public unsafe static object ReadDefaultValueAsObject(this InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } return control.ReadValueFromStateAsObject(control.defaultStatePtr); } public static TValue ReadValueFromEvent(this InputControl control, InputEventPtr inputEvent) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } if (!control.ReadValueFromEvent(inputEvent, out var value)) { return default(TValue); } return value; } public unsafe static bool ReadValueFromEvent(this InputControl control, InputEventPtr inputEvent, out TValue value) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } void* statePtrFromStateEvent = control.GetStatePtrFromStateEvent(inputEvent); if (statePtrFromStateEvent == null) { value = control.ReadDefaultValue(); return false; } value = control.ReadValueFromState(statePtrFromStateEvent); return true; } public unsafe static object ReadValueFromEventAsObject(this InputControl control, InputEventPtr inputEvent) { if (control == null) { throw new ArgumentNullException("control"); } void* statePtrFromStateEvent = control.GetStatePtrFromStateEvent(inputEvent); if (statePtrFromStateEvent == null) { return control.ReadDefaultValueAsObject(); } return control.ReadValueFromStateAsObject(statePtrFromStateEvent); } public static TValue ReadUnprocessedValueFromEvent(this InputControl control, InputEventPtr eventPtr) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } TValue value = default(TValue); control.ReadUnprocessedValueFromEvent(eventPtr, out value); return value; } public unsafe static bool ReadUnprocessedValueFromEvent(this InputControl control, InputEventPtr inputEvent, out TValue value) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } void* statePtrFromStateEvent = control.GetStatePtrFromStateEvent(inputEvent); if (statePtrFromStateEvent == null) { value = control.ReadDefaultValue(); return false; } value = control.ReadUnprocessedValueFromState(statePtrFromStateEvent); return true; } public unsafe static void WriteValueFromObjectIntoEvent(this InputControl control, InputEventPtr eventPtr, object value) { if (control == null) { throw new ArgumentNullException("control"); } void* statePtrFromStateEvent = control.GetStatePtrFromStateEvent(eventPtr); if (statePtrFromStateEvent != null) { control.WriteValueFromObjectIntoState(value, statePtrFromStateEvent); } } public unsafe static void WriteValueIntoState(this InputControl control, void* statePtr) { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } int valueSizeInBytes = control.valueSizeInBytes; void* ptr = UnsafeUtility.Malloc((long)valueSizeInBytes, 8, (Allocator)2); try { control.ReadValueFromStateIntoBuffer(control.currentStatePtr, ptr, valueSizeInBytes); control.WriteValueFromBufferIntoState(ptr, valueSizeInBytes, statePtr); } finally { UnsafeUtility.Free(ptr, (Allocator)2); } } public unsafe static void WriteValueIntoState(this InputControl control, TValue value, void* statePtr) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } if (!(control is InputControl inputControl)) { throw new ArgumentException("Expecting control of type '" + typeof(TValue).Name + "' but got '" + control.GetType().Name + "'"); } inputControl.WriteValueIntoState(value, statePtr); } public unsafe static void WriteValueIntoState(this InputControl control, TValue value, void* statePtr) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } void* bufferPtr = UnsafeUtility.AddressOf(ref value); int bufferSize = UnsafeUtility.SizeOf(); control.WriteValueFromBufferIntoState(bufferPtr, bufferSize, statePtr); } public unsafe static void WriteValueIntoState(this InputControl control, void* statePtr) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } control.WriteValueIntoState(control.ReadValue(), statePtr); } public unsafe static void WriteValueIntoState(this InputControl control, TValue value, ref TState state) where TValue : struct where TState : struct, IInputStateTypeInfo { if (control == null) { throw new ArgumentNullException("control"); } int num = UnsafeUtility.SizeOf(); if (control.stateOffsetRelativeToDeviceRoot + control.m_StateBlock.alignedSizeInBytes >= num) { throw new ArgumentException($"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 {num}", "state"); } byte* statePtr = (byte*)UnsafeUtility.AddressOf(ref state); control.WriteValueIntoState(value, statePtr); } public static void WriteValueIntoEvent(this InputControl control, TValue value, InputEventPtr eventPtr) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } if (!(control is InputControl control2)) { throw new ArgumentException("Expecting control of type '" + typeof(TValue).Name + "' but got '" + control.GetType().Name + "'"); } control2.WriteValueIntoEvent(value, eventPtr); } public unsafe static void WriteValueIntoEvent(this InputControl control, TValue value, InputEventPtr eventPtr) where TValue : struct { if (control == null) { throw new ArgumentNullException("control"); } if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } void* statePtrFromStateEvent = control.GetStatePtrFromStateEvent(eventPtr); if (statePtrFromStateEvent != null) { control.WriteValueIntoState(value, statePtrFromStateEvent); } } public unsafe static void CopyState(this InputDevice device, void* buffer, int bufferSizeInBytes) { if (device == null) { throw new ArgumentNullException("device"); } if (bufferSizeInBytes <= 0) { throw new ArgumentException("bufferSizeInBytes must be positive", "bufferSizeInBytes"); } InputStateBlock stateBlock = device.m_StateBlock; long num = Math.Min(bufferSizeInBytes, stateBlock.alignedSizeInBytes); UnsafeUtility.MemCpy(buffer, (void*)((byte*)device.currentStatePtr + stateBlock.byteOffset), num); } public unsafe static void CopyState(this InputDevice device, out TState state) where TState : struct, IInputStateTypeInfo { if (device == null) { throw new ArgumentNullException("device"); } state = default(TState); if (device.stateBlock.format != state.format) { throw new ArgumentException($"Struct '{typeof(TState).Name}' has state format '{state.format}' which doesn't match device '{device}' with state format '{device.stateBlock.format}'", "TState"); } int bufferSizeInBytes = UnsafeUtility.SizeOf(); void* buffer = UnsafeUtility.AddressOf(ref state); device.CopyState(buffer, bufferSizeInBytes); } public unsafe static bool CheckStateIsAtDefault(this InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } return control.CheckStateIsAtDefault(control.currentStatePtr, null); } public unsafe static bool CheckStateIsAtDefault(this InputControl control, void* statePtr, void* maskPtr = null) { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } return control.CompareState(statePtr, control.defaultStatePtr, maskPtr); } public unsafe static bool CheckStateIsAtDefaultIgnoringNoise(this InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } return control.CheckStateIsAtDefaultIgnoringNoise(control.currentStatePtr); } public unsafe static bool CheckStateIsAtDefaultIgnoringNoise(this InputControl control, void* statePtr) { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } return control.CheckStateIsAtDefault(statePtr, InputStateBuffers.s_NoiseMaskBuffer); } public unsafe static bool CompareStateIgnoringNoise(this InputControl control, void* statePtr) { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } return control.CompareState(control.currentStatePtr, statePtr, control.noiseMaskPtr); } public unsafe static bool CompareState(this InputControl control, void* firstStatePtr, void* secondStatePtr, void* maskPtr = null) { byte* ptr = (byte*)firstStatePtr + (int)control.m_StateBlock.byteOffset; byte* ptr2 = (byte*)secondStatePtr + (int)control.m_StateBlock.byteOffset; byte* ptr3 = ((maskPtr != null) ? ((byte*)maskPtr + (int)control.m_StateBlock.byteOffset) : null); if (control.m_StateBlock.sizeInBits == 1) { if (ptr3 != null && MemoryHelpers.ReadSingleBit(ptr3, control.m_StateBlock.bitOffset)) { return true; } return MemoryHelpers.ReadSingleBit(ptr2, control.m_StateBlock.bitOffset) == MemoryHelpers.ReadSingleBit(ptr, control.m_StateBlock.bitOffset); } return MemoryHelpers.MemCmpBitRegion(ptr, ptr2, control.m_StateBlock.bitOffset, control.m_StateBlock.sizeInBits, ptr3); } public unsafe static bool CompareState(this InputControl control, void* statePtr, void* maskPtr = null) { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } return control.CompareState(control.currentStatePtr, statePtr, maskPtr); } public unsafe static bool HasValueChangeInState(this InputControl control, void* statePtr) { if (control == null) { throw new ArgumentNullException("control"); } if (statePtr == null) { throw new ArgumentNullException("statePtr"); } return control.CompareValue(control.currentStatePtr, statePtr); } public unsafe static bool HasValueChangeInEvent(this InputControl control, InputEventPtr eventPtr) { if (control == null) { throw new ArgumentNullException("control"); } if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } void* statePtrFromStateEvent = control.GetStatePtrFromStateEvent(eventPtr); if (statePtrFromStateEvent == null) { return false; } return control.CompareValue(control.currentStatePtr, statePtrFromStateEvent); } public unsafe static void* GetStatePtrFromStateEvent(this InputControl control, InputEventPtr eventPtr) { if (control == null) { throw new ArgumentNullException("control"); } if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } return control.GetStatePtrFromStateEventUnchecked(eventPtr, eventPtr.type); } internal unsafe static void* GetStatePtrFromStateEventUnchecked(this InputControl control, InputEventPtr eventPtr, FourCC eventType) { FourCC stateFormat; uint num; void* ptr; uint offset; if (eventType == 1398030676) { StateEvent* intPtr = StateEvent.FromUnchecked(eventPtr); offset = 0u; stateFormat = intPtr->stateFormat; num = intPtr->stateSizeInBytes; ptr = intPtr->state; } else { if (!(eventType == 1145852993)) { throw new ArgumentException($"Event must be a StateEvent or DeltaStateEvent but is a {eventType} instead", "eventPtr"); } DeltaStateEvent* intPtr2 = DeltaStateEvent.FromUnchecked(eventPtr); offset = intPtr2->stateOffset; stateFormat = intPtr2->stateFormat; num = intPtr2->deltaStateSizeInBytes; ptr = intPtr2->deltaState; } InputDevice device = control.device; if (stateFormat != device.m_StateBlock.format && (!device.hasStateCallbacks || !((IInputStateCallbackReceiver)device).GetStateOffsetForEvent(control, eventPtr, ref offset))) { return null; } offset += device.m_StateBlock.byteOffset; ref InputStateBlock stateBlock = ref control.m_StateBlock; long num2 = (int)stateBlock.effectiveByteOffset - offset; if (num2 < 0 || num2 + stateBlock.alignedSizeInBytes > num) { return null; } return (byte*)ptr - (int)offset; } public unsafe static bool ResetToDefaultStateInEvent(this InputControl control, InputEventPtr eventPtr) { if (control == null) { throw new ArgumentNullException("control"); } if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } FourCC type = eventPtr.type; if (type != 1398030676 && type != 1145852993) { throw new ArgumentException("Given event is not a StateEvent or a DeltaStateEvent", "eventPtr"); } byte* statePtrFromStateEvent = (byte*)control.GetStatePtrFromStateEvent(eventPtr); if (statePtrFromStateEvent == null) { return false; } byte* defaultStatePtr = (byte*)control.defaultStatePtr; ref InputStateBlock stateBlock = ref control.m_StateBlock; uint byteOffset = stateBlock.byteOffset; MemoryHelpers.MemCpyBitRegion(statePtrFromStateEvent + byteOffset, defaultStatePtr + byteOffset, stateBlock.bitOffset, stateBlock.sizeInBits); return true; } public static void QueueValueChange(this InputControl control, TValue value, double time = -1.0) where TValue : struct { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (control == null) { throw new ArgumentNullException("control"); } InputEventPtr eventPtr; NativeArray val = StateEvent.From(control.device, out eventPtr, (Allocator)2); try { if (time >= 0.0) { eventPtr.time = time; } control.WriteValueIntoEvent(value, eventPtr); InputSystem.QueueEvent(eventPtr); } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } public unsafe static void AccumulateValueInEvent(this InputControl control, void* currentStatePtr, InputEventPtr newState) { if (control == null) { throw new ArgumentNullException("control"); } if (control.ReadUnprocessedValueFromEvent(newState, out var value)) { float num = control.ReadUnprocessedValueFromState(currentStatePtr); control.WriteValueIntoEvent(num + value, newState); } } internal unsafe static void AccumulateValueInEvent(this InputControl control, void* currentStatePtr, InputEventPtr newState) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (control == null) { throw new ArgumentNullException("control"); } if (InputControlExtensions.ReadUnprocessedValueFromEvent(control, newState, out Vector2 value)) { Vector2 val = control.ReadUnprocessedValueFromState(currentStatePtr); InputControlExtensions.WriteValueIntoEvent(control, val + value, newState); } } public static void FindControlsRecursive(this InputControl parent, IList controls, Func predicate) where TControl : InputControl { if (parent == null) { throw new ArgumentNullException("parent"); } if (controls == null) { throw new ArgumentNullException("controls"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } if (parent is TControl val && predicate(val)) { controls.Add(val); } int count = parent.children.Count; for (int i = 0; i < count; i++) { parent.children[i].FindControlsRecursive(controls, predicate); } } internal static string BuildPath(this InputControl control, string deviceLayout, StringBuilder builder = null) { if (control == null) { throw new ArgumentNullException("control"); } if (string.IsNullOrEmpty(deviceLayout)) { throw new ArgumentNullException("deviceLayout"); } if (builder == null) { builder = new StringBuilder(); } InputDevice device = control.device; builder.Append('<'); builder.Append(deviceLayout.Escape("\\>", "\\>")); builder.Append('>'); ReadOnlyArray usages = device.usages; for (int i = 0; i < usages.Count; i++) { builder.Append('{'); builder.Append(usages[i].ToString().Escape("\\}", "\\}")); builder.Append('}'); } builder.Append('/'); string text = device.path.Replace("\\", "\\\\"); string text2 = control.path.Replace("\\", "\\\\"); builder.Append(text2, text.Length + 1, text2.Length - text.Length - 1); return builder.ToString(); } public static InputEventControlCollection EnumerateControls(this InputEventPtr eventPtr, Enumerate flags, InputDevice device = null, float magnitudeThreshold = 0f) { if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr", "Given event pointer must not be null"); } FourCC type = eventPtr.type; if (type != 1398030676 && type != 1145852993) { throw new ArgumentException($"Event must be a StateEvent or DeltaStateEvent but is a {type} instead", "eventPtr"); } if (device == null) { int deviceId = eventPtr.deviceId; device = InputSystem.GetDeviceById(deviceId); if (device == null) { throw new ArgumentException($"Cannot find device with ID {deviceId} referenced by event", "eventPtr"); } } return new InputEventControlCollection { m_Device = device, m_EventPtr = eventPtr, m_Flags = flags, m_MagnitudeThreshold = magnitudeThreshold }; } public static InputEventControlCollection EnumerateChangedControls(this InputEventPtr eventPtr, InputDevice device = null, float magnitudeThreshold = 0f) { return eventPtr.EnumerateControls(Enumerate.IgnoreControlsInCurrentState, device, magnitudeThreshold); } public static bool HasButtonPress(this InputEventPtr eventPtr, float magnitude = -1f, bool buttonControlsOnly = true) { return eventPtr.GetFirstButtonPressOrNull(magnitude, buttonControlsOnly) != null; } public static InputControl GetFirstButtonPressOrNull(this InputEventPtr eventPtr, float magnitude = -1f, bool buttonControlsOnly = true) { if (eventPtr.type != 1398030676 && eventPtr.type != 1145852993) { return null; } if (magnitude < 0f) { magnitude = InputSystem.settings.defaultButtonPressPoint; } foreach (InputControl item in eventPtr.EnumerateControls(Enumerate.IgnoreControlsInDefaultState, null, magnitude)) { if (!buttonControlsOnly || item.isButton) { return item; } } return null; } public static IEnumerable GetAllButtonPresses(this InputEventPtr eventPtr, float magnitude = -1f, bool buttonControlsOnly = true) { if (eventPtr.type != 1398030676 && eventPtr.type != 1145852993) { yield break; } if (magnitude < 0f) { magnitude = InputSystem.settings.defaultButtonPressPoint; } foreach (InputControl item in eventPtr.EnumerateControls(Enumerate.IgnoreControlsInDefaultState, null, magnitude)) { if (!buttonControlsOnly || item.isButton) { yield return item; } } } public static ControlBuilder Setup(this InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } if (control.isSetupFinished) { throw new InvalidOperationException($"The setup of {control} cannot be modified; control is already in use"); } return new ControlBuilder { control = control }; } public static DeviceBuilder Setup(this InputDevice device, int controlCount, int usageCount, int aliasCount) { if (device == null) { throw new ArgumentNullException("device"); } if (device.isSetupFinished) { throw new InvalidOperationException($"The setup of {device} cannot be modified; control is already in use"); } if (controlCount < 1) { throw new ArgumentOutOfRangeException("controlCount"); } if (usageCount < 0) { throw new ArgumentOutOfRangeException("usageCount"); } if (aliasCount < 0) { throw new ArgumentOutOfRangeException("aliasCount"); } device.m_Device = device; device.m_ChildrenForEachControl = new InputControl[controlCount]; if (usageCount > 0) { device.m_UsagesForEachControl = new InternedString[usageCount]; device.m_UsageToControl = new InputControl[usageCount]; } if (aliasCount > 0) { device.m_AliasesForEachControl = new InternedString[aliasCount]; } return new DeviceBuilder { device = device }; } } public enum InputControlLayoutChange { Added, Removed, Replaced } [DebuggerDisplay("Count = {Count}")] public struct InputControlList : IList, ICollection, IEnumerable, IEnumerable, IReadOnlyList, IReadOnlyCollection, IDisposable where TControl : InputControl { private struct Enumerator : IEnumerator, IDisposable, IEnumerator { private unsafe readonly ulong* m_Indices; private readonly int m_Count; private int m_Current; public unsafe TControl Current { get { if (m_Indices == null) { throw new InvalidOperationException("Enumerator is not valid"); } return InputControlList.FromIndex(m_Indices[m_Current]); } } object IEnumerator.Current => Current; public unsafe Enumerator(InputControlList list) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) m_Count = list.m_Count; m_Current = -1; m_Indices = (ulong*)((m_Count > 0) ? NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(list.m_Indices) : null); } public bool MoveNext() { if (m_Current >= m_Count) { return false; } m_Current++; return m_Current != m_Count; } public void Reset() { m_Current = -1; } public void Dispose() { } } private int m_Count; private NativeArray m_Indices; private readonly Allocator m_Allocator; private const ulong kInvalidIndex = ulong.MaxValue; public int Count => m_Count; public int Capacity { get { if (!m_Indices.IsCreated) { return 0; } return m_Indices.Length; } set { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (value < 0) { throw new ArgumentException("Capacity cannot be negative", "value"); } if (value == 0) { if (m_Count != 0) { m_Indices.Dispose(); } m_Count = 0; } else { Allocator allocator = (Allocator)(((int)m_Allocator == 0) ? 4 : ((int)m_Allocator)); ArrayHelpers.Resize(ref m_Indices, value, allocator); } } } public bool IsReadOnly => false; public TControl this[int index] { get { if (index < 0 || index >= m_Count) { throw new ArgumentOutOfRangeException("index", $"Index {index} is out of range in list with {m_Count} entries"); } return FromIndex(m_Indices[index]); } set { if (index < 0 || index >= m_Count) { throw new ArgumentOutOfRangeException("index", $"Index {index} is out of range in list with {m_Count} entries"); } m_Indices[index] = ToIndex(value); } } public InputControlList(Allocator allocator, int initialCapacity = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) m_Allocator = allocator; m_Indices = default(NativeArray); m_Count = 0; if (initialCapacity != 0) { Capacity = initialCapacity; } } public InputControlList(IEnumerable values, Allocator allocator = (Allocator)4) : this(allocator) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (values == null) { throw new ArgumentNullException("values"); } foreach (TControl value in values) { Add(value); } } public InputControlList(params TControl[] values) { this = default(InputControlList); if (values == null) { throw new ArgumentNullException("values"); } int num = values.Length; Capacity = Mathf.Max(num, 10); for (int i = 0; i < num; i++) { Add(values[i]); } } public unsafe void Resize(int size) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (size < 0) { throw new ArgumentOutOfRangeException("size", "Size cannot be negative"); } if (Capacity < size) { Capacity = size; } if (size > Count) { UnsafeUtility.MemSet((void*)((byte*)NativeArrayUnsafeUtility.GetUnsafePtr(m_Indices) + Count * 8), byte.MaxValue, (long)(size - Count)); } m_Count = size; } public void Add(TControl item) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) ulong value = ToIndex(item); Allocator allocator = (Allocator)(((int)m_Allocator == 0) ? 4 : ((int)m_Allocator)); ArrayHelpers.AppendWithCapacity(ref m_Indices, ref m_Count, value, 10, allocator); } public void AddSlice(TList list, int count = -1, int destinationIndex = -1, int sourceIndex = 0) where TList : IReadOnlyList { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) if (count < 0) { count = list.Count; } if (destinationIndex < 0) { destinationIndex = Count; } if (count != 0) { if (sourceIndex + count > list.Count) { throw new ArgumentOutOfRangeException("count", $"Count of {count} elements starting at index {sourceIndex} exceeds length of list of {list.Count}"); } if (Capacity < m_Count + count) { Capacity = Math.Max(m_Count + count, 10); } if (destinationIndex < Count) { NativeArray.Copy(m_Indices, destinationIndex, m_Indices, destinationIndex + count, Count - destinationIndex); } for (int i = 0; i < count; i++) { m_Indices[destinationIndex + i] = ToIndex(list[sourceIndex + i]); } m_Count += count; } } public void AddRange(IEnumerable list, int count = -1, int destinationIndex = -1) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (list == null) { throw new ArgumentNullException("list"); } if (count < 0) { count = list.Count(); } if (destinationIndex < 0) { destinationIndex = Count; } if (count == 0) { return; } if (Capacity < m_Count + count) { Capacity = Math.Max(m_Count + count, 10); } if (destinationIndex < Count) { NativeArray.Copy(m_Indices, destinationIndex, m_Indices, destinationIndex + count, Count - destinationIndex); } foreach (TControl item in list) { m_Indices[destinationIndex++] = ToIndex(item); m_Count++; count--; if (count == 0) { break; } } } public bool Remove(TControl item) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (m_Count == 0) { return false; } ulong num = ToIndex(item); for (int i = 0; i < m_Count; i++) { if (m_Indices[i] == num) { ArrayHelpers.EraseAtWithCapacity(m_Indices, ref m_Count, i); return true; } } return false; } public void RemoveAt(int index) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= m_Count) { throw new ArgumentOutOfRangeException("index", $"Index {index} is out of range in list with {m_Count} elements"); } ArrayHelpers.EraseAtWithCapacity(m_Indices, ref m_Count, index); } public void CopyTo(TControl[] array, int arrayIndex) { throw new NotImplementedException(); } public int IndexOf(TControl item) { return IndexOf(item, 0); } public unsafe int IndexOf(TControl item, int startIndex, int count = -1) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", "startIndex cannot be negative"); } if (m_Count == 0) { return -1; } if (count < 0) { count = Mathf.Max(m_Count - startIndex, 0); } if (startIndex + count > m_Count) { throw new ArgumentOutOfRangeException("count"); } ulong num = ToIndex(item); ulong* unsafeReadOnlyPtr = (ulong*)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(m_Indices); for (int i = 0; i < count; i++) { if (unsafeReadOnlyPtr[startIndex + i] == num) { return startIndex + i; } } return -1; } public void Insert(int index, TControl item) { throw new NotImplementedException(); } public void Clear() { m_Count = 0; } public bool Contains(TControl item) { return IndexOf(item) != -1; } public bool Contains(TControl item, int startIndex, int count = -1) { return IndexOf(item, startIndex, count) != -1; } public void SwapElements(int index1, int index2) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) if (index1 < 0 || index1 >= m_Count) { throw new ArgumentOutOfRangeException("index1"); } if (index2 < 0 || index2 >= m_Count) { throw new ArgumentOutOfRangeException("index2"); } if (index1 != index2) { m_Indices.SwapElements(index1, index2); } } public void Sort(int startIndex, int count, TCompare comparer) where TCompare : IComparer { if (startIndex < 0 || startIndex >= Count) { throw new ArgumentOutOfRangeException("startIndex"); } if (startIndex + count >= Count) { throw new ArgumentOutOfRangeException("count"); } for (int i = 1; i < count; i++) { int num = i; while (num > 0 && comparer.Compare(this[num - 1], this[num]) < 0) { SwapElements(num, num - 1); num--; } } } public TControl[] ToArray(bool dispose = false) { TControl[] array = new TControl[m_Count]; for (int i = 0; i < m_Count; i++) { array[i] = this[i]; } if (dispose) { Dispose(); } return array; } internal void AppendTo(ref TControl[] array, ref int count) { for (int i = 0; i < m_Count; i++) { ArrayHelpers.AppendWithCapacity(ref array, ref count, this[i]); } } public void Dispose() { if (m_Indices.IsCreated) { m_Indices.Dispose(); } } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override string ToString() { if (Count == 0) { return "()"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); for (int i = 0; i < Count; i++) { if (i != 0) { stringBuilder.Append(','); } stringBuilder.Append(this[i]); } stringBuilder.Append(')'); return stringBuilder.ToString(); } private static ulong ToIndex(TControl control) { if (control == null) { return ulong.MaxValue; } InputDevice device = control.device; int deviceId = device.m_DeviceId; int num = (((object)device != control) ? (device.m_ChildrenForEachControl.IndexOfReference((InputControl)control, -1) + 1) : 0); long num2 = (long)deviceId << 32; ulong num3 = (ulong)num; return (ulong)num2 | num3; } private static TControl FromIndex(ulong index) { if (index == ulong.MaxValue) { return null; } int deviceId = (int)(index >> 32); int num = (int)(index & 0xFFFFFFFFu); InputDevice deviceById = InputSystem.GetDeviceById(deviceId); if (deviceById == null) { return null; } if (num == 0) { return (TControl)(InputControl)deviceById; } return (TControl)deviceById.m_ChildrenForEachControl[num - 1]; } } public static class InputControlPath { [Flags] public enum HumanReadableStringOptions { None = 0, OmitDevice = 2, UseShortNames = 4 } private enum PathComponentType { Name, DisplayName, Usage, Layout } public struct ParsedPathComponent { internal Substring m_Layout; internal InlinedArray m_Usages; internal Substring m_Name; internal Substring m_DisplayName; public string layout => m_Layout.ToString(); public IEnumerable usages => m_Usages.Select((Substring x) => x.ToString()); public string name => m_Name.ToString(); public string displayName => m_DisplayName.ToString(); internal bool isWildcard => m_Name == "*"; internal bool isDoubleWildcard => m_Name == "**"; internal string ToHumanReadableString(string parentLayoutName, string parentControlPath, out string referencedLayoutName, out string controlPath, HumanReadableStringOptions options) { referencedLayoutName = null; controlPath = null; string text = string.Empty; if (isWildcard) { text += "Any"; } if (m_Usages.length > 0) { string text2 = string.Empty; for (int i = 0; i < m_Usages.length; i++) { if (!m_Usages[i].isEmpty) { text2 = ((!(text2 != string.Empty)) ? ToHumanReadableString(m_Usages[i]) : (text2 + " & " + ToHumanReadableString(m_Usages[i]))); } } if (text2 != string.Empty) { text = ((!(text != string.Empty)) ? (text + text2) : (text + " " + text2)); } } if (!m_Layout.isEmpty) { referencedLayoutName = m_Layout.ToString(); InputControlLayout inputControlLayout = InputControlLayout.cache.FindOrLoadLayout(referencedLayoutName, throwIfNotFound: false); string text3 = ((inputControlLayout == null || string.IsNullOrEmpty(inputControlLayout.m_DisplayName)) ? ToHumanReadableString(m_Layout) : inputControlLayout.m_DisplayName); text = (string.IsNullOrEmpty(text) ? (text + text3) : (text + " " + text3)); } if (!m_Name.isEmpty && !isWildcard) { string text4 = null; if (!string.IsNullOrEmpty(parentLayoutName)) { InputControlLayout inputControlLayout2 = InputControlLayout.cache.FindOrLoadLayout(new InternedString(parentLayoutName), throwIfNotFound: false); if (inputControlLayout2 != null) { InternedString internedString = new InternedString(m_Name.ToString()); int arrayIndex; InputControlLayout.ControlItem? controlItem = inputControlLayout2.FindControlIncludingArrayElements(internedString, out arrayIndex); if (controlItem.HasValue) { if (string.IsNullOrEmpty(parentControlPath)) { if (arrayIndex != -1) { controlPath = $"{controlItem.Value.name}{arrayIndex}"; } else { controlPath = controlItem.Value.name; } } else if (arrayIndex != -1) { controlPath = $"{parentControlPath}/{controlItem.Value.name}{arrayIndex}"; } else { controlPath = $"{parentControlPath}/{controlItem.Value.name}"; } string text5 = (((options & HumanReadableStringOptions.UseShortNames) != HumanReadableStringOptions.None) ? controlItem.Value.shortDisplayName : null); string text6 = ((!string.IsNullOrEmpty(text5)) ? text5 : controlItem.Value.displayName); if (!string.IsNullOrEmpty(text6)) { text4 = ((arrayIndex == -1) ? text6 : $"{text6} #{arrayIndex}"); } if (string.IsNullOrEmpty(referencedLayoutName)) { referencedLayoutName = controlItem.Value.layout; } } } } if (text4 == null) { text4 = ToHumanReadableString(m_Name); } text = (string.IsNullOrEmpty(text) ? (text + text4) : (text + " " + text4)); } if (!m_DisplayName.isEmpty) { string text7 = "\"" + ToHumanReadableString(m_DisplayName) + "\""; text = (string.IsNullOrEmpty(text) ? (text + text7) : (text + " " + text7)); } return text; } private static string ToHumanReadableString(Substring substring) { return substring.ToString().Unescape("/*{<", "/*{<"); } public bool Matches(InputControl control) { if (!m_Layout.isEmpty) { bool flag = ComparePathElementToString(m_Layout, control.layout); if (!flag) { InternedString value = control.m_Layout; while (InputControlLayout.s_Layouts.baseLayoutTable.TryGetValue(value, out value) && !flag) { flag = ComparePathElementToString(m_Layout, value.ToString()); } } if (!flag) { return false; } } if (m_Usages.length > 0) { for (int i = 0; i < m_Usages.length; i++) { if (m_Usages[i].isEmpty) { continue; } ReadOnlyArray readOnlyArray = control.usages; bool flag2 = false; for (int j = 0; j < readOnlyArray.Count; j++) { if (ComparePathElementToString(m_Usages[i], readOnlyArray[j])) { flag2 = true; break; } } if (!flag2) { return false; } } } if (!m_Name.isEmpty && !isWildcard && !ComparePathElementToString(m_Name, control.name)) { return false; } if (!m_DisplayName.isEmpty && !ComparePathElementToString(m_DisplayName, control.displayName)) { return false; } return true; } private static bool ComparePathElementToString(Substring pathElement, string element) { int length = pathElement.length; int length2 = element.Length; int num = 0; int num2 = 0; while (true) { bool flag = num == length; bool flag2 = num2 == length2; if (flag || flag2) { return flag == flag2; } char c = pathElement[num]; if (c == '\\' && num + 1 < length) { c = pathElement[++num]; } if (char.ToLowerInvariant(c) != char.ToLowerInvariant(element[num2])) { break; } num++; num2++; } return false; } } private struct PathParser { private string path; private int length; private int leftIndexInPath; private int rightIndexInPath; public ParsedPathComponent current; public bool isAtEnd => rightIndexInPath == length; public PathParser(string path) { this.path = path; length = path.Length; leftIndexInPath = 0; rightIndexInPath = 0; current = default(ParsedPathComponent); } public bool MoveToNextComponent() { if (rightIndexInPath == length) { return false; } leftIndexInPath = rightIndexInPath; if (path[leftIndexInPath] == '/') { leftIndexInPath++; rightIndexInPath = leftIndexInPath; if (leftIndexInPath == length) { return false; } } Substring layout = default(Substring); if (rightIndexInPath < length && path[rightIndexInPath] == '<') { layout = ParseComponentPart('>'); } InlinedArray usages = default(InlinedArray); while (rightIndexInPath < length && path[rightIndexInPath] == '{') { usages.AppendWithCapacity(ParseComponentPart('}')); } Substring displayName = default(Substring); if (rightIndexInPath < length - 1 && path[rightIndexInPath] == '#' && path[rightIndexInPath + 1] == '(') { rightIndexInPath++; displayName = ParseComponentPart(')'); } Substring name = default(Substring); if (rightIndexInPath < length && path[rightIndexInPath] != '/') { name = ParseComponentPart('/'); } current = new ParsedPathComponent { m_Layout = layout, m_Usages = usages, m_Name = name, m_DisplayName = displayName }; return leftIndexInPath != rightIndexInPath; } private Substring ParseComponentPart(char terminator) { if (terminator != '/') { rightIndexInPath++; } int num = rightIndexInPath; while (rightIndexInPath < length && path[rightIndexInPath] != terminator) { if (path[rightIndexInPath] == '\\' && rightIndexInPath + 1 < length) { rightIndexInPath++; } rightIndexInPath++; } int num2 = rightIndexInPath - num; if (rightIndexInPath < length && terminator != '/') { rightIndexInPath++; } return new Substring(path, num, num2); } } public const string Wildcard = "*"; public const string DoubleWildcard = "**"; public const char Separator = '/'; internal const char SeparatorReplacement = ' '; internal static string CleanSlashes(this string pathComponent) { return pathComponent.Replace('/', ' '); } public static string Combine(InputControl parent, string path) { if (parent == null) { if (string.IsNullOrEmpty(path)) { return string.Empty; } if (path[0] != '/') { return "/" + path; } return path; } if (string.IsNullOrEmpty(path)) { return parent.path; } return parent.path + "/" + path; } public static string ToHumanReadableString(string path, HumanReadableStringOptions options = HumanReadableStringOptions.None, InputControl control = null) { string deviceLayoutName; string controlPath; return ToHumanReadableString(path, out deviceLayoutName, out controlPath, options, control); } public static string ToHumanReadableString(string path, out string deviceLayoutName, out string controlPath, HumanReadableStringOptions options = HumanReadableStringOptions.None, InputControl control = null) { deviceLayoutName = null; controlPath = null; if (string.IsNullOrEmpty(path)) { return string.Empty; } if (control != null) { InputControl inputControl = TryFindControl(control, path) ?? (Matches(path, control) ? control : null); if (inputControl != null) { string text = (((options & HumanReadableStringOptions.UseShortNames) != HumanReadableStringOptions.None && !string.IsNullOrEmpty(inputControl.shortDisplayName)) ? inputControl.shortDisplayName : inputControl.displayName); if ((options & HumanReadableStringOptions.OmitDevice) == 0) { text = text + " [" + inputControl.device.displayName + "]"; } deviceLayoutName = inputControl.device.layout; if (!(inputControl is InputDevice)) { controlPath = inputControl.path.Substring(inputControl.device.path.Length + 1); } return text; } } StringBuilder stringBuilder = new StringBuilder(); PathParser pathParser = new PathParser(path); using (InputControlLayout.CacheRef()) { if (pathParser.MoveToNextComponent()) { string referencedLayoutName; string controlPath2; string value = pathParser.current.ToHumanReadableString(null, null, out referencedLayoutName, out controlPath2, options); deviceLayoutName = referencedLayoutName; bool flag = true; while (pathParser.MoveToNextComponent()) { if (!flag) { stringBuilder.Append('/'); } stringBuilder.Append(pathParser.current.ToHumanReadableString(referencedLayoutName, controlPath, out referencedLayoutName, out controlPath, options)); flag = false; } if ((options & HumanReadableStringOptions.OmitDevice) == 0 && !string.IsNullOrEmpty(value)) { stringBuilder.Append(" ["); stringBuilder.Append(value); stringBuilder.Append(']'); } } if (stringBuilder.Length == 0) { return path; } return stringBuilder.ToString(); } } public static string[] TryGetDeviceUsages(string path) { if (path == null) { throw new ArgumentNullException("path"); } PathParser pathParser = new PathParser(path); if (!pathParser.MoveToNextComponent()) { return null; } if (pathParser.current.m_Usages.length > 0) { return pathParser.current.m_Usages.ToArray((Substring x) => x.ToString()); } return null; } public static string TryGetDeviceLayout(string path) { if (path == null) { throw new ArgumentNullException("path"); } PathParser pathParser = new PathParser(path); if (!pathParser.MoveToNextComponent()) { return null; } if (pathParser.current.m_Layout.length > 0) { return pathParser.current.m_Layout.ToString().Unescape(); } if (pathParser.current.isWildcard) { return "*"; } return null; } public static string TryGetControlLayout(string path) { if (path == null) { throw new ArgumentNullException("path"); } int length = path.Length; int num = path.LastIndexOf('/'); if (num == -1 || num == 0) { return null; } if (length > num + 2 && path[num + 1] == '<' && path[length - 1] == '>') { int num2 = num + 2; int length2 = length - num2 - 1; return path.Substring(num2, length2); } PathParser parser = new PathParser(path); if (!parser.MoveToNextComponent()) { return null; } if (parser.current.isWildcard) { throw new NotImplementedException(); } if (parser.current.m_Layout.length == 0) { return null; } string str = parser.current.m_Layout.ToString(); if (!parser.MoveToNextComponent()) { return null; } if (parser.current.isWildcard) { return "*"; } return FindControlLayoutRecursive(ref parser, str.Unescape()); } private static string FindControlLayoutRecursive(ref PathParser parser, string layoutName) { using (InputControlLayout.CacheRef()) { InputControlLayout inputControlLayout = InputControlLayout.cache.FindOrLoadLayout(new InternedString(layoutName), throwIfNotFound: false); if (inputControlLayout == null) { return null; } return FindControlLayoutRecursive(ref parser, inputControlLayout); } } private static string FindControlLayoutRecursive(ref PathParser parser, InputControlLayout layout) { string text = null; int count = layout.controls.Count; for (int i = 0; i < count; i++) { if (!ControlLayoutMatchesPathComponent(ref layout.m_Controls[i], ref parser)) { continue; } InternedString layout2 = layout.m_Controls[i].layout; if (!parser.isAtEnd) { PathParser parser2 = parser; if (!parser2.MoveToNextComponent()) { continue; } string text2 = FindControlLayoutRecursive(ref parser2, layout2); if (text2 != null) { if (text != null && text2 != text) { return null; } text = text2; } } else { if (text != null && layout2 != text) { return null; } text = layout2.ToString(); } } return text; } private static bool ControlLayoutMatchesPathComponent(ref InputControlLayout.ControlItem controlItem, ref PathParser parser) { Substring layout = parser.current.m_Layout; if (layout.length > 0 && !StringMatches(layout, controlItem.layout)) { return false; } if (parser.current.m_Usages.length > 0) { for (int i = 0; i < parser.current.m_Usages.length; i++) { Substring str = parser.current.m_Usages[i]; if (str.length <= 0) { continue; } int count = controlItem.usages.Count; bool flag = false; for (int j = 0; j < count; j++) { if (StringMatches(str, controlItem.usages[j])) { flag = true; break; } } if (!flag) { return false; } } } Substring name = parser.current.m_Name; if (name.length > 0 && !StringMatches(name, controlItem.name)) { return false; } return true; } private static bool StringMatches(Substring str, InternedString matchTo) { int length = str.length; int length2 = matchTo.length; string text = matchTo.ToLower(); int i = 0; int j; for (j = 0; j < length; j++) { if (i >= length2) { break; } char c = str[j]; if (c == '\\' && j + 1 < length) { c = str[++j]; } if (c == '*') { if (j == length - 1) { return true; } j++; for (c = char.ToLower(str[j], CultureInfo.InvariantCulture); i < length2 && text[i] != c; i++) { } if (i == length2) { return false; } } else if (char.ToLower(c, CultureInfo.InvariantCulture) != text[i]) { return false; } i++; } if (i == length2) { return j == length; } return false; } public static InputControl TryFindControl(InputControl control, string path, int indexInPath = 0) { return TryFindControl(control, path, indexInPath); } public static InputControl[] TryFindControls(InputControl control, string path, int indexInPath = 0) { InputControlList matches = new InputControlList((Allocator)2); try { TryFindControls(control, path, indexInPath, ref matches); return matches.ToArray(); } finally { matches.Dispose(); } } public static int TryFindControls(InputControl control, string path, ref InputControlList matches, int indexInPath = 0) { return TryFindControls(control, path, indexInPath, ref matches); } public static TControl TryFindControl(InputControl control, string path, int indexInPath = 0) where TControl : InputControl { if (control == null) { throw new ArgumentNullException("control"); } if (string.IsNullOrEmpty(path)) { return null; } if (indexInPath == 0 && path[0] == '/') { indexInPath++; } InputControlList matches = default(InputControlList); return MatchControlsRecursive(control, path, indexInPath, ref matches, matchMultiple: false); } public static int TryFindControls(InputControl control, string path, int indexInPath, ref InputControlList matches) where TControl : InputControl { if (control == null) { throw new ArgumentNullException("control"); } if (path == null) { throw new ArgumentNullException("path"); } if (indexInPath == 0 && path[0] == '/') { indexInPath++; } int count = matches.Count; MatchControlsRecursive(control, path, indexInPath, ref matches, matchMultiple: true); return matches.Count - count; } public static InputControl TryFindChild(InputControl control, string path, int indexInPath = 0) { return TryFindChild(control, path, indexInPath); } public static TControl TryFindChild(InputControl control, string path, int indexInPath = 0) where TControl : InputControl { if (control == null) { throw new ArgumentNullException("control"); } if (path == null) { throw new ArgumentNullException("path"); } ReadOnlyArray children = control.children; int count = children.Count; for (int i = 0; i < count; i++) { TControl val = TryFindControl(children[i], path, indexInPath); if (val != null) { return val; } } return null; } public static bool Matches(string expected, InputControl control) { if (string.IsNullOrEmpty(expected)) { throw new ArgumentNullException("expected"); } if (control == null) { throw new ArgumentNullException("control"); } PathParser parser = new PathParser(expected); return MatchesRecursive(ref parser, control); } public static bool MatchesPrefix(string expected, InputControl control) { if (string.IsNullOrEmpty(expected)) { throw new ArgumentNullException("expected"); } if (control == null) { throw new ArgumentNullException("control"); } PathParser parser = new PathParser(expected); if (MatchesRecursive(ref parser, control, prefixOnly: true) && parser.isAtEnd) { return true; } return false; } private static bool MatchesRecursive(ref PathParser parser, InputControl currentControl, bool prefixOnly = false) { InputControl parent = currentControl.parent; if (parent != null && !MatchesRecursive(ref parser, parent, prefixOnly)) { return false; } if (!parser.MoveToNextComponent()) { return prefixOnly; } return parser.current.Matches(currentControl); } private static TControl MatchControlsRecursive(InputControl control, string path, int indexInPath, ref InputControlList matches, bool matchMultiple) where TControl : InputControl { int length = path.Length; bool flag = true; if (path[indexInPath] == '<') { indexInPath++; flag = MatchPathComponent(control.layout, path, ref indexInPath, PathComponentType.Layout); if (!flag) { InternedString value = control.m_Layout; while (InputControlLayout.s_Layouts.baseLayoutTable.TryGetValue(value, out value)) { flag = MatchPathComponent(value, path, ref indexInPath, PathComponentType.Layout); if (flag) { break; } } } } while (indexInPath < length && path[indexInPath] == '{' && flag) { indexInPath++; for (int i = 0; i < control.usages.Count; i++) { flag = MatchPathComponent(control.usages[i], path, ref indexInPath, PathComponentType.Usage); if (flag) { break; } } } if (indexInPath < length - 1 && flag && path[indexInPath] == '#' && path[indexInPath + 1] == '(') { indexInPath += 2; flag = MatchPathComponent(control.displayName, path, ref indexInPath, PathComponentType.DisplayName); } if (indexInPath < length && flag && path[indexInPath] != '/') { flag = MatchPathComponent(control.name, path, ref indexInPath, PathComponentType.Name); if (!flag) { for (int j = 0; j < control.aliases.Count; j++) { if (flag) { break; } flag = MatchPathComponent(control.aliases[j], path, ref indexInPath, PathComponentType.Name); } } } if (flag) { if (indexInPath < length && path[indexInPath] == '*') { indexInPath++; } if (indexInPath == length) { if (!(control is TControl val)) { return null; } if (matchMultiple) { matches.Add(val); } return val; } if (path[indexInPath] == '/') { indexInPath++; if (indexInPath == length) { if (!(control is TControl val2)) { return null; } if (matchMultiple) { matches.Add(val2); } return val2; } if (path[indexInPath] == '{') { return MatchByUsageAtDeviceRootRecursive(control.device, path, indexInPath, ref matches, matchMultiple); } return MatchChildrenRecursive(control, path, indexInPath, ref matches, matchMultiple); } } return null; } private static TControl MatchByUsageAtDeviceRootRecursive(InputDevice device, string path, int indexInPath, ref InputControlList matches, bool matchMultiple) where TControl : InputControl { InternedString[] usagesForEachControl = device.m_UsagesForEachControl; if (usagesForEachControl == null) { return null; } int num = device.m_UsageToControl.LengthSafe(); int num2 = indexInPath + 1; bool flag = PathComponentCanYieldMultipleMatches(path, indexInPath); int length = path.Length; indexInPath++; if (indexInPath == length) { throw new ArgumentException("Invalid path spec '" + path + "'; trailing '{'", "path"); } TControl val = null; for (int i = 0; i < num; i++) { if (!MatchPathComponent(usagesForEachControl[i], path, ref indexInPath, PathComponentType.Usage)) { indexInPath = num2; continue; } InputControl inputControl = device.m_UsageToControl[i]; if (indexInPath < length && path[indexInPath] == '/') { val = MatchChildrenRecursive(inputControl, path, indexInPath + 1, ref matches, matchMultiple); if ((val != null && !flag) || (val != null && !matchMultiple)) { break; } continue; } val = inputControl as TControl; if (val != null) { if (!matchMultiple) { break; } matches.Add(val); } } return val; } private static TControl MatchChildrenRecursive(InputControl control, string path, int indexInPath, ref InputControlList matches, bool matchMultiple) where TControl : InputControl { ReadOnlyArray children = control.children; int count = children.Count; TControl result = null; bool flag = PathComponentCanYieldMultipleMatches(path, indexInPath); for (int i = 0; i < count; i++) { TControl val = MatchControlsRecursive(children[i], path, indexInPath, ref matches, matchMultiple); if (val != null) { if (!flag) { return val; } if (!matchMultiple) { return val; } result = val; } } return result; } private static bool MatchPathComponent(string component, string path, ref int indexInPath, PathComponentType componentType, int startIndexInComponent = 0) { int length = component.Length; int length2 = path.Length; int num = indexInPath; int num2 = startIndexInComponent; while (indexInPath < length2) { char c = path[indexInPath]; if (c == '\\' && indexInPath + 1 < length2) { indexInPath++; c = path[indexInPath]; } else { if (c == '/' && componentType == PathComponentType.Name) { break; } if ((c == '>' && componentType == PathComponentType.Layout) || (c == '}' && componentType == PathComponentType.Usage) || (c == ')' && componentType == PathComponentType.DisplayName)) { indexInPath++; break; } if (c == '*') { int indexInPath2 = indexInPath + 1; if (indexInPath < length2 - 1 && num2 < length && MatchPathComponent(component, path, ref indexInPath2, componentType, num2)) { indexInPath = indexInPath2; return true; } if (num2 < length) { num2++; continue; } return true; } } if (num2 == length) { indexInPath = num; return false; } char c2 = component[num2]; if (c2 == c || char.ToLower(c2, CultureInfo.InvariantCulture) == char.ToLower(c, CultureInfo.InvariantCulture)) { num2++; indexInPath++; continue; } indexInPath = num; return false; } if (num2 == length) { return true; } indexInPath = num; return false; } private static bool PathComponentCanYieldMultipleMatches(string path, int indexInPath) { int num = path.IndexOf('/', indexInPath); if (num == -1) { if (path.IndexOf('*', indexInPath) == -1) { return path.IndexOf('<', indexInPath) != -1; } return true; } int count = num - indexInPath; if (path.IndexOf('*', indexInPath, count) == -1) { return path.IndexOf('<', indexInPath, count) != -1; } return true; } public static IEnumerable Parse(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } PathParser parser = new PathParser(path); while (parser.MoveToNextComponent()) { yield return parser.current; } } } public abstract class InputProcessor { public enum CachingPolicy { CacheResult, EvaluateOnEveryRead } internal static TypeTable s_Processors; public virtual CachingPolicy cachingPolicy => CachingPolicy.CacheResult; public abstract object ProcessAsObject(object value, InputControl control); public unsafe abstract void Process(void* buffer, int bufferSize, InputControl control); internal static Type GetValueTypeFromType(Type processorType) { if (processorType == null) { throw new ArgumentNullException("processorType"); } return TypeHelpers.GetGenericTypeArgumentFromHierarchy(processorType, typeof(InputProcessor<>), 0); } } public abstract class InputProcessor : InputProcessor where TValue : struct { public abstract TValue Process(TValue value, InputControl control); public override object ProcessAsObject(object value, InputControl control) { if (value == null) { throw new ArgumentNullException("value"); } if (!(value is TValue value2)) { throw new ArgumentException($"Expecting value of type '{typeof(TValue).Name}' but got value '{value}' of type '{value.GetType().Name}'", "value"); } return Process(value2, control); } public unsafe override void Process(void* buffer, int bufferSize, InputControl control) { if (buffer == null) { throw new ArgumentNullException("buffer"); } int num = UnsafeUtility.SizeOf(); if (bufferSize < num) { throw new ArgumentException($"Expected buffer of at least {num} bytes but got buffer with just {bufferSize} bytes", "bufferSize"); } TValue value = default(TValue); void* ptr = UnsafeUtility.AddressOf(ref value); UnsafeUtility.MemCpy(ptr, buffer, (long)num); value = Process(value, control); ptr = UnsafeUtility.AddressOf(ref value); UnsafeUtility.MemCpy(buffer, ptr, (long)num); } } [InputControlLayout(stateType = typeof(GamepadState), isGenericTypeOfDevice = true)] public class Gamepad : InputDevice, IDualMotorRumble, IHaptics { private DualMotorRumble m_Rumble; private static int s_GamepadCount; private static Gamepad[] s_Gamepads; public ButtonControl buttonWest { get; protected set; } public ButtonControl buttonNorth { get; protected set; } public ButtonControl buttonSouth { get; protected set; } public ButtonControl buttonEast { get; protected set; } public ButtonControl leftStickButton { get; protected set; } public ButtonControl rightStickButton { get; protected set; } public ButtonControl startButton { get; protected set; } public ButtonControl selectButton { get; protected set; } public DpadControl dpad { get; protected set; } public ButtonControl leftShoulder { get; protected set; } public ButtonControl rightShoulder { get; protected set; } public StickControl leftStick { get; protected set; } public StickControl rightStick { get; protected set; } public ButtonControl leftTrigger { get; protected set; } public ButtonControl rightTrigger { get; protected set; } public ButtonControl aButton => buttonSouth; public ButtonControl bButton => buttonEast; public ButtonControl xButton => buttonWest; public ButtonControl yButton => buttonNorth; public ButtonControl triangleButton => buttonNorth; public ButtonControl squareButton => buttonWest; public ButtonControl circleButton => buttonEast; public ButtonControl crossButton => buttonSouth; public ButtonControl this[GamepadButton button] => button switch { GamepadButton.North => buttonNorth, GamepadButton.South => buttonSouth, GamepadButton.East => buttonEast, GamepadButton.West => buttonWest, GamepadButton.Start => startButton, GamepadButton.Select => selectButton, GamepadButton.LeftShoulder => leftShoulder, GamepadButton.RightShoulder => rightShoulder, GamepadButton.LeftTrigger => leftTrigger, GamepadButton.RightTrigger => rightTrigger, GamepadButton.LeftStick => leftStickButton, GamepadButton.RightStick => rightStickButton, GamepadButton.DpadUp => dpad.up, GamepadButton.DpadDown => dpad.down, GamepadButton.DpadLeft => dpad.left, GamepadButton.DpadRight => dpad.right, _ => throw new InvalidEnumArgumentException("button", (int)button, typeof(GamepadButton)), }; public static Gamepad current { get; private set; } public new static ReadOnlyArray all => new ReadOnlyArray(s_Gamepads, 0, s_GamepadCount); protected override void FinishSetup() { buttonWest = GetChildControl("buttonWest"); buttonNorth = GetChildControl("buttonNorth"); buttonSouth = GetChildControl("buttonSouth"); buttonEast = GetChildControl("buttonEast"); startButton = GetChildControl("start"); selectButton = GetChildControl("select"); leftStickButton = GetChildControl("leftStickPress"); rightStickButton = GetChildControl("rightStickPress"); dpad = GetChildControl("dpad"); leftShoulder = GetChildControl("leftShoulder"); rightShoulder = GetChildControl("rightShoulder"); leftStick = GetChildControl("leftStick"); rightStick = GetChildControl("rightStick"); leftTrigger = GetChildControl("leftTrigger"); rightTrigger = GetChildControl("rightTrigger"); base.FinishSetup(); } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnAdded() { ArrayHelpers.AppendWithCapacity(ref s_Gamepads, ref s_GamepadCount, this); } protected override void OnRemoved() { if (current == this) { current = null; } int num = s_Gamepads.IndexOfReference(this, s_GamepadCount); if (num != -1) { s_Gamepads.EraseAtWithCapacity(ref s_GamepadCount, num); } } public virtual void PauseHaptics() { m_Rumble.PauseHaptics(this); } public virtual void ResumeHaptics() { m_Rumble.ResumeHaptics(this); } public virtual void ResetHaptics() { m_Rumble.ResetHaptics(this); } public virtual void SetMotorSpeeds(float lowFrequency, float highFrequency) { m_Rumble.SetMotorSpeeds(this, lowFrequency, highFrequency); } } public class InputDevice : InputControl { [Serializable] [Flags] internal enum DeviceFlags { UpdateBeforeRender = 1, HasStateCallbacks = 2, HasControlsWithDefaultState = 4, HasDontResetControls = 0x400, HasEventMerger = 0x2000, HasEventPreProcessor = 0x4000, Remote = 8, Native = 0x10, DisabledInFrontend = 0x20, DisabledInRuntime = 0x80, DisabledWhileInBackground = 0x100, DisabledStateHasBeenQueriedFromRuntime = 0x40, CanRunInBackground = 0x800, CanRunInBackgroundHasBeenQueried = 0x1000 } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ControlBitRangeNode { public ushort endBitOffset; public short leftChildIndex; public ushort controlStartIndex; public byte controlCount; public ControlBitRangeNode(ushort endOffset) { controlStartIndex = 0; controlCount = 0; endBitOffset = endOffset; leftChildIndex = -1; } } public const int InvalidDeviceId = 0; internal const int kLocalParticipantId = 0; internal const int kInvalidDeviceIndex = -1; internal DeviceFlags m_DeviceFlags; internal int m_DeviceId; internal int m_ParticipantId; internal int m_DeviceIndex; internal InputDeviceDescription m_Description; internal double m_LastUpdateTimeInternal; internal uint m_CurrentUpdateStepCount; internal InternedString[] m_AliasesForEachControl; internal InternedString[] m_UsagesForEachControl; internal InputControl[] m_UsageToControl; internal InputControl[] m_ChildrenForEachControl; internal uint[] m_StateOffsetToControlMap; internal ControlBitRangeNode[] m_ControlTreeNodes; internal ushort[] m_ControlTreeIndices; internal const int kControlIndexBits = 10; internal const int kStateOffsetBits = 13; internal const int kStateSizeBits = 9; public InputDeviceDescription description => m_Description; public bool enabled { get { if ((m_DeviceFlags & (DeviceFlags.DisabledInFrontend | DeviceFlags.DisabledWhileInBackground)) != 0) { return false; } return QueryEnabledStateFromRuntime(); } } public bool canRunInBackground { get { if ((m_DeviceFlags & DeviceFlags.CanRunInBackgroundHasBeenQueried) != 0) { return (m_DeviceFlags & DeviceFlags.CanRunInBackground) != 0; } QueryCanRunInBackground command = QueryCanRunInBackground.Create(); m_DeviceFlags |= DeviceFlags.CanRunInBackgroundHasBeenQueried; if (ExecuteCommand(ref command) >= 0 && command.canRunInBackground) { m_DeviceFlags |= DeviceFlags.CanRunInBackground; return true; } m_DeviceFlags &= ~DeviceFlags.CanRunInBackground; return false; } } public bool added => m_DeviceIndex != -1; public bool remote => (m_DeviceFlags & DeviceFlags.Remote) == DeviceFlags.Remote; public bool native => (m_DeviceFlags & DeviceFlags.Native) == DeviceFlags.Native; public bool updateBeforeRender => (m_DeviceFlags & DeviceFlags.UpdateBeforeRender) == DeviceFlags.UpdateBeforeRender; public int deviceId => m_DeviceId; public double lastUpdateTime => m_LastUpdateTimeInternal - InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup; public bool wasUpdatedThisFrame => m_CurrentUpdateStepCount == InputUpdate.s_UpdateStepCount; public ReadOnlyArray allControls => new ReadOnlyArray(m_ChildrenForEachControl); public override Type valueType => typeof(byte[]); public override int valueSizeInBytes => (int)m_StateBlock.alignedSizeInBytes; [Obsolete("Use 'InputSystem.devices' instead. (UnityUpgradable) -> InputSystem.devices", false)] public static ReadOnlyArray all => InputSystem.devices; internal bool disabledInFrontend { get { return (m_DeviceFlags & DeviceFlags.DisabledInFrontend) != 0; } set { if (value) { m_DeviceFlags |= DeviceFlags.DisabledInFrontend; } else { m_DeviceFlags &= ~DeviceFlags.DisabledInFrontend; } } } internal bool disabledInRuntime { get { return (m_DeviceFlags & DeviceFlags.DisabledInRuntime) != 0; } set { if (value) { m_DeviceFlags |= DeviceFlags.DisabledInRuntime; } else { m_DeviceFlags &= ~DeviceFlags.DisabledInRuntime; } } } internal bool disabledWhileInBackground { get { return (m_DeviceFlags & DeviceFlags.DisabledWhileInBackground) != 0; } set { if (value) { m_DeviceFlags |= DeviceFlags.DisabledWhileInBackground; } else { m_DeviceFlags &= ~DeviceFlags.DisabledWhileInBackground; } } } internal bool hasControlsWithDefaultState { get { return (m_DeviceFlags & DeviceFlags.HasControlsWithDefaultState) == DeviceFlags.HasControlsWithDefaultState; } set { if (value) { m_DeviceFlags |= DeviceFlags.HasControlsWithDefaultState; } else { m_DeviceFlags &= ~DeviceFlags.HasControlsWithDefaultState; } } } internal bool hasDontResetControls { get { return (m_DeviceFlags & DeviceFlags.HasDontResetControls) == DeviceFlags.HasDontResetControls; } set { if (value) { m_DeviceFlags |= DeviceFlags.HasDontResetControls; } else { m_DeviceFlags &= ~DeviceFlags.HasDontResetControls; } } } internal bool hasStateCallbacks { get { return (m_DeviceFlags & DeviceFlags.HasStateCallbacks) == DeviceFlags.HasStateCallbacks; } set { if (value) { m_DeviceFlags |= DeviceFlags.HasStateCallbacks; } else { m_DeviceFlags &= ~DeviceFlags.HasStateCallbacks; } } } internal bool hasEventMerger { get { return (m_DeviceFlags & DeviceFlags.HasEventMerger) == DeviceFlags.HasEventMerger; } set { if (value) { m_DeviceFlags |= DeviceFlags.HasEventMerger; } else { m_DeviceFlags &= ~DeviceFlags.HasEventMerger; } } } internal bool hasEventPreProcessor { get { return (m_DeviceFlags & DeviceFlags.HasEventPreProcessor) == DeviceFlags.HasEventPreProcessor; } set { if (value) { m_DeviceFlags |= DeviceFlags.HasEventPreProcessor; } else { m_DeviceFlags &= ~DeviceFlags.HasEventPreProcessor; } } } public InputDevice() { m_DeviceId = 0; m_ParticipantId = 0; m_DeviceIndex = -1; } public unsafe override object ReadValueFromBufferAsObject(void* buffer, int bufferSize) { throw new NotImplementedException(); } public unsafe override object ReadValueFromStateAsObject(void* statePtr) { if (m_DeviceIndex == -1) { return null; } uint alignedSizeInBytes = base.stateBlock.alignedSizeInBytes; byte[] array = new byte[alignedSizeInBytes]; fixed (byte* ptr = array) { byte* ptr2 = (byte*)statePtr + m_StateBlock.byteOffset; UnsafeUtility.MemCpy((void*)ptr, (void*)ptr2, (long)alignedSizeInBytes); } return array; } public unsafe override void ReadValueFromStateIntoBuffer(void* statePtr, void* bufferPtr, int bufferSize) { if (statePtr == null) { throw new ArgumentNullException("statePtr"); } if (bufferPtr == null) { throw new ArgumentNullException("bufferPtr"); } if (bufferSize < valueSizeInBytes) { throw new ArgumentException($"Buffer too small (expected: {valueSizeInBytes}, actual: {bufferSize}"); } byte* ptr = (byte*)statePtr + m_StateBlock.byteOffset; UnsafeUtility.MemCpy(bufferPtr, (void*)ptr, (long)m_StateBlock.alignedSizeInBytes); } public unsafe override bool CompareValue(void* firstStatePtr, void* secondStatePtr) { if (firstStatePtr == null) { throw new ArgumentNullException("firstStatePtr"); } if (secondStatePtr == null) { throw new ArgumentNullException("secondStatePtr"); } byte* num = (byte*)firstStatePtr + m_StateBlock.byteOffset; byte* ptr = (byte*)firstStatePtr + m_StateBlock.byteOffset; return UnsafeUtility.MemCmp((void*)num, (void*)ptr, (long)m_StateBlock.alignedSizeInBytes) == 0; } internal void NotifyConfigurationChanged() { base.isConfigUpToDate = false; for (int i = 0; i < m_ChildrenForEachControl.Length; i++) { m_ChildrenForEachControl[i].isConfigUpToDate = false; } m_DeviceFlags &= ~DeviceFlags.DisabledStateHasBeenQueriedFromRuntime; OnConfigurationChanged(); } public virtual void MakeCurrent() { } protected virtual void OnAdded() { } protected virtual void OnRemoved() { } protected virtual void OnConfigurationChanged() { } public unsafe long ExecuteCommand(ref TCommand command) where TCommand : struct, IInputDeviceCommandInfo { InputDeviceCommand* command2 = (InputDeviceCommand*)UnsafeUtility.AddressOf(ref command); InputManager s_Manager = InputSystem.s_Manager; s_Manager.m_DeviceCommandCallbacks.LockForChanges(); for (int i = 0; i < s_Manager.m_DeviceCommandCallbacks.length; i++) { try { long? num = s_Manager.m_DeviceCommandCallbacks[i](this, command2); if (num.HasValue) { return num.Value; } } catch (Exception ex) { Debug.LogError((object)(ex.GetType().Name + " while executing 'InputSystem.onDeviceCommand' callbacks")); Debug.LogException(ex); } } s_Manager.m_DeviceCommandCallbacks.UnlockForChanges(); return ExecuteCommand((InputDeviceCommand*)UnsafeUtility.AddressOf(ref command)); } protected unsafe virtual long ExecuteCommand(InputDeviceCommand* commandPtr) { return InputRuntime.s_Instance.DeviceCommand(deviceId, commandPtr); } internal bool QueryEnabledStateFromRuntime() { if ((m_DeviceFlags & DeviceFlags.DisabledStateHasBeenQueriedFromRuntime) == 0) { QueryEnabledStateCommand command = QueryEnabledStateCommand.Create(); if (ExecuteCommand(ref command) >= 0) { if (command.isEnabled) { m_DeviceFlags &= ~DeviceFlags.DisabledInRuntime; } else { m_DeviceFlags |= DeviceFlags.DisabledInRuntime; } } else { m_DeviceFlags &= ~DeviceFlags.DisabledInRuntime; } m_DeviceFlags |= DeviceFlags.DisabledStateHasBeenQueriedFromRuntime; } return (m_DeviceFlags & DeviceFlags.DisabledInRuntime) == 0; } internal static uint EncodeStateOffsetToControlMapEntry(uint controlIndex, uint stateOffsetInBits, uint stateSizeInBits) { return (stateOffsetInBits << 19) | (stateSizeInBits << 10) | controlIndex; } internal static void DecodeStateOffsetToControlMapEntry(uint entry, out uint controlIndex, out uint stateOffset, out uint stateSize) { controlIndex = entry & 0x3FF; stateOffset = entry >> 19; stateSize = (entry >> 10) & 0x1FF; } internal void AddDeviceUsage(InternedString usage) { int count = m_UsageToControl.LengthSafe() + m_UsageCount; if (m_UsageCount == 0) { m_UsageStartIndex = count; } ArrayHelpers.AppendWithCapacity(ref m_UsagesForEachControl, ref count, usage); m_UsageCount++; } internal void RemoveDeviceUsage(InternedString usage) { int count = m_UsageToControl.LengthSafe() + m_UsageCount; int num = m_UsagesForEachControl.IndexOfValue(usage, m_UsageStartIndex, count); if (num != -1) { m_UsagesForEachControl.EraseAtWithCapacity(ref count, num); m_UsageCount--; if (m_UsageCount == 0) { m_UsageStartIndex = 0; } } } internal void ClearDeviceUsages() { for (int i = m_UsageStartIndex; i < m_UsageCount; i++) { m_UsagesForEachControl[i] = default(InternedString); } m_UsageCount = 0; } internal bool RequestSync() { SetOptimizedControlDataTypeRecursively(); RequestSyncCommand command = RequestSyncCommand.Create(); return base.device.ExecuteCommand(ref command) >= 0; } internal bool RequestReset() { SetOptimizedControlDataTypeRecursively(); RequestResetCommand command = RequestResetCommand.Create(); return base.device.ExecuteCommand(ref command) >= 0; } internal bool ExecuteEnableCommand() { SetOptimizedControlDataTypeRecursively(); EnableDeviceCommand command = EnableDeviceCommand.Create(); return base.device.ExecuteCommand(ref command) >= 0; } internal bool ExecuteDisableCommand() { DisableDeviceCommand command = DisableDeviceCommand.Create(); return base.device.ExecuteCommand(ref command) >= 0; } internal void NotifyAdded() { OnAdded(); } internal void NotifyRemoved() { OnRemoved(); } internal static TDevice Build(string layoutName = null, string layoutVariants = null, InputDeviceDescription deviceDescription = default(InputDeviceDescription), bool noPrecompiledLayouts = false) where TDevice : InputDevice { InternedString key = new InternedString(layoutName); if (key.IsEmpty()) { key = InputControlLayout.s_Layouts.TryFindLayoutForType(typeof(TDevice)); if (key.IsEmpty()) { key = new InternedString(typeof(TDevice).Name); } } if (!noPrecompiledLayouts && string.IsNullOrEmpty(layoutVariants) && InputControlLayout.s_Layouts.precompiledLayouts.TryGetValue(key, out var value)) { return (TDevice)value.factoryMethod(); } using (InputDeviceBuilder.Ref()) { InputDeviceBuilder.instance.Setup(key, new InternedString(layoutVariants), deviceDescription); InputDevice inputDevice = InputDeviceBuilder.instance.Finish(); if (!(inputDevice is TDevice result)) { throw new ArgumentException("Expected device of type '" + typeof(TDevice).Name + "' but got device of type '" + inputDevice.GetType().Name + "' instead", "TDevice"); } return result; } } internal unsafe void WriteChangedControlStates(byte* deviceStateBuffer, void* statePtr, uint stateSizeInBytes, uint stateOffsetInDevice) { if (m_ControlTreeNodes.Length == 0) { return; } if (m_StateBlock.sizeInBits != stateSizeInBytes * 8) { if (m_ControlTreeNodes[0].leftChildIndex != -1) { WritePartialChangedControlStatesInternal(statePtr, stateSizeInBytes * 8, stateOffsetInDevice * 8, deviceStateBuffer, m_ControlTreeNodes[0], 0u); } } else if (m_ControlTreeNodes[0].leftChildIndex != -1) { WriteChangedControlStatesInternal(statePtr, stateSizeInBytes * 8, deviceStateBuffer, m_ControlTreeNodes[0], 0u); } } private unsafe void WritePartialChangedControlStatesInternal(void* statePtr, uint stateSizeInBits, uint stateOffsetInDeviceInBits, byte* deviceStatePtr, ControlBitRangeNode parentNode, uint startOffset) { ControlBitRangeNode parentNode2 = m_ControlTreeNodes[parentNode.leftChildIndex]; if (Math.Max(stateOffsetInDeviceInBits, startOffset) <= Math.Min(stateOffsetInDeviceInBits + stateSizeInBits, parentNode2.endBitOffset)) { int num = parentNode2.controlStartIndex + parentNode2.controlCount; for (int i = parentNode2.controlStartIndex; i < num; i++) { ushort num2 = m_ControlTreeIndices[i]; m_ChildrenForEachControl[num2].MarkAsStale(); } if (parentNode2.leftChildIndex != -1) { WritePartialChangedControlStatesInternal(statePtr, stateSizeInBits, stateOffsetInDeviceInBits, deviceStatePtr, parentNode2, startOffset); } } ControlBitRangeNode parentNode3 = m_ControlTreeNodes[parentNode.leftChildIndex + 1]; if (Math.Max(stateOffsetInDeviceInBits, parentNode2.endBitOffset) <= Math.Min(stateOffsetInDeviceInBits + stateSizeInBits, parentNode3.endBitOffset)) { int num3 = parentNode3.controlStartIndex + parentNode3.controlCount; for (int j = parentNode3.controlStartIndex; j < num3; j++) { ushort num4 = m_ControlTreeIndices[j]; m_ChildrenForEachControl[num4].MarkAsStale(); } if (parentNode3.leftChildIndex != -1) { WritePartialChangedControlStatesInternal(statePtr, stateSizeInBits, stateOffsetInDeviceInBits, deviceStatePtr, parentNode3, parentNode2.endBitOffset); } } } private void DumpControlBitRangeNode(int nodeIndex, ControlBitRangeNode node, uint startOffset, uint sizeInBits, List output) { List list = new List(); for (int i = 0; i < node.controlCount; i++) { ushort num = m_ControlTreeIndices[node.controlStartIndex + i]; InputControl inputControl = m_ChildrenForEachControl[num]; list.Add(inputControl.path); } string text = string.Join(", ", list); string text2 = ((node.leftChildIndex != -1) ? $" <{node.leftChildIndex}, {node.leftChildIndex + 1}>" : ""); output.Add($"{nodeIndex} [{startOffset}, {startOffset + sizeInBits}]{text2}->{text}"); } private void DumpControlTree(ControlBitRangeNode parentNode, uint startOffset, List output) { ControlBitRangeNode controlBitRangeNode = m_ControlTreeNodes[parentNode.leftChildIndex]; ControlBitRangeNode controlBitRangeNode2 = m_ControlTreeNodes[parentNode.leftChildIndex + 1]; DumpControlBitRangeNode(parentNode.leftChildIndex, controlBitRangeNode, startOffset, controlBitRangeNode.endBitOffset - startOffset, output); DumpControlBitRangeNode(parentNode.leftChildIndex + 1, controlBitRangeNode2, controlBitRangeNode.endBitOffset, (uint)(controlBitRangeNode2.endBitOffset - controlBitRangeNode.endBitOffset), output); if (controlBitRangeNode.leftChildIndex != -1) { DumpControlTree(controlBitRangeNode, startOffset, output); } if (controlBitRangeNode2.leftChildIndex != -1) { DumpControlTree(controlBitRangeNode2, controlBitRangeNode.endBitOffset, output); } } internal string DumpControlTree() { List list = new List(); DumpControlTree(m_ControlTreeNodes[0], 0u, list); return string.Join("\n", list); } private unsafe void WriteChangedControlStatesInternal(void* statePtr, uint stateSizeInBits, byte* deviceStatePtr, ControlBitRangeNode parentNode, uint startOffset) { ControlBitRangeNode parentNode2 = m_ControlTreeNodes[parentNode.leftChildIndex]; if (HasDataChangedInRange(deviceStatePtr, statePtr, startOffset, parentNode2.endBitOffset - startOffset + 1)) { int num = parentNode2.controlStartIndex + parentNode2.controlCount; for (int i = parentNode2.controlStartIndex; i < num; i++) { ushort num2 = m_ControlTreeIndices[i]; InputControl inputControl = m_ChildrenForEachControl[num2]; if (!inputControl.CompareState(deviceStatePtr - m_StateBlock.byteOffset, (byte*)statePtr - m_StateBlock.byteOffset, null)) { inputControl.MarkAsStale(); } } if (parentNode2.leftChildIndex != -1) { WriteChangedControlStatesInternal(statePtr, stateSizeInBits, deviceStatePtr, parentNode2, startOffset); } } ControlBitRangeNode parentNode3 = m_ControlTreeNodes[parentNode.leftChildIndex + 1]; if (!HasDataChangedInRange(deviceStatePtr, statePtr, parentNode2.endBitOffset, (uint)(parentNode3.endBitOffset - parentNode2.endBitOffset + 1))) { return; } int num3 = parentNode3.controlStartIndex + parentNode3.controlCount; for (int j = parentNode3.controlStartIndex; j < num3; j++) { ushort num4 = m_ControlTreeIndices[j]; InputControl inputControl2 = m_ChildrenForEachControl[num4]; if (!inputControl2.CompareState(deviceStatePtr - m_StateBlock.byteOffset, (byte*)statePtr - m_StateBlock.byteOffset, null)) { inputControl2.MarkAsStale(); } } if (parentNode3.leftChildIndex != -1) { WriteChangedControlStatesInternal(statePtr, stateSizeInBits, deviceStatePtr, parentNode3, parentNode2.endBitOffset); } } private unsafe static bool HasDataChangedInRange(byte* deviceStatePtr, void* statePtr, uint startOffset, uint sizeInBits) { if (sizeInBits == 1) { return MemoryHelpers.ReadSingleBit(deviceStatePtr, startOffset) != MemoryHelpers.ReadSingleBit(statePtr, startOffset); } return !MemoryHelpers.MemCmpBitRegion(deviceStatePtr, statePtr, startOffset, sizeInBits, null); } } public enum InputDeviceChange { Added, Removed, Disconnected, Reconnected, Enabled, Disabled, UsageChanged, ConfigurationChanged, SoftReset, HardReset, [Obsolete("Destroyed enum has been deprecated.")] Destroyed } [InputControlLayout(stateType = typeof(JoystickState), isGenericTypeOfDevice = true)] public class Joystick : InputDevice { private static int s_JoystickCount; private static Joystick[] s_Joysticks; public ButtonControl trigger { get; protected set; } public StickControl stick { get; protected set; } public AxisControl twist { get; protected set; } public Vector2Control hatswitch { get; protected set; } public static Joystick current { get; private set; } public new static ReadOnlyArray all => new ReadOnlyArray(s_Joysticks, 0, s_JoystickCount); protected override void FinishSetup() { trigger = GetChildControl("{PrimaryTrigger}"); stick = GetChildControl("{Primary2DMotion}"); twist = TryGetChildControl("{Twist}"); hatswitch = TryGetChildControl("{Hatswitch}"); base.FinishSetup(); } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnAdded() { ArrayHelpers.AppendWithCapacity(ref s_Joysticks, ref s_JoystickCount, this); } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } int num = s_Joysticks.IndexOfReference(this, s_JoystickCount); if (num != -1) { s_Joysticks.EraseAtWithCapacity(ref s_JoystickCount, num); } } } public enum Key { None = 0, Space = 1, Enter = 2, Tab = 3, Backquote = 4, Quote = 5, Semicolon = 6, Comma = 7, Period = 8, Slash = 9, Backslash = 10, LeftBracket = 11, RightBracket = 12, Minus = 13, Equals = 14, A = 15, B = 16, C = 17, D = 18, E = 19, F = 20, G = 21, H = 22, I = 23, J = 24, K = 25, L = 26, M = 27, N = 28, O = 29, P = 30, Q = 31, R = 32, S = 33, T = 34, U = 35, V = 36, W = 37, X = 38, Y = 39, Z = 40, Digit1 = 41, Digit2 = 42, Digit3 = 43, Digit4 = 44, Digit5 = 45, Digit6 = 46, Digit7 = 47, Digit8 = 48, Digit9 = 49, Digit0 = 50, LeftShift = 51, RightShift = 52, LeftAlt = 53, RightAlt = 54, AltGr = 54, LeftCtrl = 55, RightCtrl = 56, LeftMeta = 57, RightMeta = 58, LeftWindows = 57, RightWindows = 58, LeftApple = 57, RightApple = 58, LeftCommand = 57, RightCommand = 58, ContextMenu = 59, Escape = 60, LeftArrow = 61, RightArrow = 62, UpArrow = 63, DownArrow = 64, Backspace = 65, PageDown = 66, PageUp = 67, Home = 68, End = 69, Insert = 70, Delete = 71, CapsLock = 72, NumLock = 73, PrintScreen = 74, ScrollLock = 75, Pause = 76, NumpadEnter = 77, NumpadDivide = 78, NumpadMultiply = 79, NumpadPlus = 80, NumpadMinus = 81, NumpadPeriod = 82, NumpadEquals = 83, Numpad0 = 84, Numpad1 = 85, Numpad2 = 86, Numpad3 = 87, Numpad4 = 88, Numpad5 = 89, Numpad6 = 90, Numpad7 = 91, Numpad8 = 92, Numpad9 = 93, F1 = 94, F2 = 95, F3 = 96, F4 = 97, F5 = 98, F6 = 99, F7 = 100, F8 = 101, F9 = 102, F10 = 103, F11 = 104, F12 = 105, OEM1 = 106, OEM2 = 107, OEM3 = 108, OEM4 = 109, OEM5 = 110, IMESelected = 111 } [InputControlLayout(stateType = typeof(KeyboardState), isGenericTypeOfDevice = true)] public class Keyboard : InputDevice, ITextInputReceiver { public const int KeyCount = 110; private InlinedArray> m_TextInputListeners; private string m_KeyboardLayoutName; private KeyControl[] m_Keys; private InlinedArray> m_ImeCompositionListeners; public string keyboardLayout { get { RefreshConfigurationIfNeeded(); return m_KeyboardLayoutName; } protected set { m_KeyboardLayoutName = value; } } public AnyKeyControl anyKey { get; protected set; } public KeyControl spaceKey => this[Key.Space]; public KeyControl enterKey => this[Key.Enter]; public KeyControl tabKey => this[Key.Tab]; public KeyControl backquoteKey => this[Key.Backquote]; public KeyControl quoteKey => this[Key.Quote]; public KeyControl semicolonKey => this[Key.Semicolon]; public KeyControl commaKey => this[Key.Comma]; public KeyControl periodKey => this[Key.Period]; public KeyControl slashKey => this[Key.Slash]; public KeyControl backslashKey => this[Key.Backslash]; public KeyControl leftBracketKey => this[Key.LeftBracket]; public KeyControl rightBracketKey => this[Key.RightBracket]; public KeyControl minusKey => this[Key.Minus]; public KeyControl equalsKey => this[Key.Equals]; public KeyControl aKey => this[Key.A]; public KeyControl bKey => this[Key.B]; public KeyControl cKey => this[Key.C]; public KeyControl dKey => this[Key.D]; public KeyControl eKey => this[Key.E]; public KeyControl fKey => this[Key.F]; public KeyControl gKey => this[Key.G]; public KeyControl hKey => this[Key.H]; public KeyControl iKey => this[Key.I]; public KeyControl jKey => this[Key.J]; public KeyControl kKey => this[Key.K]; public KeyControl lKey => this[Key.L]; public KeyControl mKey => this[Key.M]; public KeyControl nKey => this[Key.N]; public KeyControl oKey => this[Key.O]; public KeyControl pKey => this[Key.P]; public KeyControl qKey => this[Key.Q]; public KeyControl rKey => this[Key.R]; public KeyControl sKey => this[Key.S]; public KeyControl tKey => this[Key.T]; public KeyControl uKey => this[Key.U]; public KeyControl vKey => this[Key.V]; public KeyControl wKey => this[Key.W]; public KeyControl xKey => this[Key.X]; public KeyControl yKey => this[Key.Y]; public KeyControl zKey => this[Key.Z]; public KeyControl digit1Key => this[Key.Digit1]; public KeyControl digit2Key => this[Key.Digit2]; public KeyControl digit3Key => this[Key.Digit3]; public KeyControl digit4Key => this[Key.Digit4]; public KeyControl digit5Key => this[Key.Digit5]; public KeyControl digit6Key => this[Key.Digit6]; public KeyControl digit7Key => this[Key.Digit7]; public KeyControl digit8Key => this[Key.Digit8]; public KeyControl digit9Key => this[Key.Digit9]; public KeyControl digit0Key => this[Key.Digit0]; public KeyControl leftShiftKey => this[Key.LeftShift]; public KeyControl rightShiftKey => this[Key.RightShift]; public KeyControl leftAltKey => this[Key.LeftAlt]; public KeyControl rightAltKey => this[Key.RightAlt]; public KeyControl leftCtrlKey => this[Key.LeftCtrl]; public KeyControl rightCtrlKey => this[Key.RightCtrl]; public KeyControl leftMetaKey => this[Key.LeftMeta]; public KeyControl rightMetaKey => this[Key.RightMeta]; public KeyControl leftWindowsKey => this[Key.LeftMeta]; public KeyControl rightWindowsKey => this[Key.RightMeta]; public KeyControl leftAppleKey => this[Key.LeftMeta]; public KeyControl rightAppleKey => this[Key.RightMeta]; public KeyControl leftCommandKey => this[Key.LeftMeta]; public KeyControl rightCommandKey => this[Key.RightMeta]; public KeyControl contextMenuKey => this[Key.ContextMenu]; public KeyControl escapeKey => this[Key.Escape]; public KeyControl leftArrowKey => this[Key.LeftArrow]; public KeyControl rightArrowKey => this[Key.RightArrow]; public KeyControl upArrowKey => this[Key.UpArrow]; public KeyControl downArrowKey => this[Key.DownArrow]; public KeyControl backspaceKey => this[Key.Backspace]; public KeyControl pageDownKey => this[Key.PageDown]; public KeyControl pageUpKey => this[Key.PageUp]; public KeyControl homeKey => this[Key.Home]; public KeyControl endKey => this[Key.End]; public KeyControl insertKey => this[Key.Insert]; public KeyControl deleteKey => this[Key.Delete]; public KeyControl capsLockKey => this[Key.CapsLock]; public KeyControl scrollLockKey => this[Key.ScrollLock]; public KeyControl numLockKey => this[Key.NumLock]; public KeyControl printScreenKey => this[Key.PrintScreen]; public KeyControl pauseKey => this[Key.Pause]; public KeyControl numpadEnterKey => this[Key.NumpadEnter]; public KeyControl numpadDivideKey => this[Key.NumpadDivide]; public KeyControl numpadMultiplyKey => this[Key.NumpadMultiply]; public KeyControl numpadMinusKey => this[Key.NumpadMinus]; public KeyControl numpadPlusKey => this[Key.NumpadPlus]; public KeyControl numpadPeriodKey => this[Key.NumpadPeriod]; public KeyControl numpadEqualsKey => this[Key.NumpadEquals]; public KeyControl numpad0Key => this[Key.Numpad0]; public KeyControl numpad1Key => this[Key.Numpad1]; public KeyControl numpad2Key => this[Key.Numpad2]; public KeyControl numpad3Key => this[Key.Numpad3]; public KeyControl numpad4Key => this[Key.Numpad4]; public KeyControl numpad5Key => this[Key.Numpad5]; public KeyControl numpad6Key => this[Key.Numpad6]; public KeyControl numpad7Key => this[Key.Numpad7]; public KeyControl numpad8Key => this[Key.Numpad8]; public KeyControl numpad9Key => this[Key.Numpad9]; public KeyControl f1Key => this[Key.F1]; public KeyControl f2Key => this[Key.F2]; public KeyControl f3Key => this[Key.F3]; public KeyControl f4Key => this[Key.F4]; public KeyControl f5Key => this[Key.F5]; public KeyControl f6Key => this[Key.F6]; public KeyControl f7Key => this[Key.F7]; public KeyControl f8Key => this[Key.F8]; public KeyControl f9Key => this[Key.F9]; public KeyControl f10Key => this[Key.F10]; public KeyControl f11Key => this[Key.F11]; public KeyControl f12Key => this[Key.F12]; public KeyControl oem1Key => this[Key.OEM1]; public KeyControl oem2Key => this[Key.OEM2]; public KeyControl oem3Key => this[Key.OEM3]; public KeyControl oem4Key => this[Key.OEM4]; public KeyControl oem5Key => this[Key.OEM5]; public ButtonControl shiftKey { get; protected set; } public ButtonControl ctrlKey { get; protected set; } public ButtonControl altKey { get; protected set; } public ButtonControl imeSelected { get; protected set; } public KeyControl this[Key key] { get { int num = (int)(key - 1); if (num < 0 || num >= m_Keys.Length) { throw new ArgumentOutOfRangeException("key"); } return m_Keys[num]; } } public ReadOnlyArray allKeys => new ReadOnlyArray(m_Keys); public static Keyboard current { get; private set; } protected KeyControl[] keys { get { return m_Keys; } set { m_Keys = value; } } public event Action onTextInput { add { if (value == null) { throw new ArgumentNullException("value"); } if (!m_TextInputListeners.Contains(value)) { m_TextInputListeners.Append(value); } } remove { m_TextInputListeners.Remove(value); } } public event Action onIMECompositionChange { add { if (value == null) { throw new ArgumentNullException("value"); } if (!m_ImeCompositionListeners.Contains(value)) { m_ImeCompositionListeners.Append(value); } } remove { m_ImeCompositionListeners.Remove(value); } } public void SetIMEEnabled(bool enabled) { EnableIMECompositionCommand command = EnableIMECompositionCommand.Create(enabled); ExecuteCommand(ref command); } public void SetIMECursorPosition(Vector2 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) SetIMECursorPositionCommand command = SetIMECursorPositionCommand.Create(position); ExecuteCommand(ref command); } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { string[] array = new string[110] { "space", "enter", "tab", "backquote", "quote", "semicolon", "comma", "period", "slash", "backslash", "leftbracket", "rightbracket", "minus", "equals", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "leftshift", "rightshift", "leftalt", "rightalt", "leftctrl", "rightctrl", "leftmeta", "rightmeta", "contextmenu", "escape", "leftarrow", "rightarrow", "uparrow", "downarrow", "backspace", "pagedown", "pageup", "home", "end", "insert", "delete", "capslock", "numlock", "printscreen", "scrolllock", "pause", "numpadenter", "numpaddivide", "numpadmultiply", "numpadplus", "numpadminus", "numpadperiod", "numpadequals", "numpad0", "numpad1", "numpad2", "numpad3", "numpad4", "numpad5", "numpad6", "numpad7", "numpad8", "numpad9", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "oem1", "oem2", "oem3", "oem4", "oem5" }; m_Keys = new KeyControl[array.Length]; for (int i = 0; i < array.Length; i++) { m_Keys[i] = GetChildControl(array[i]); m_Keys[i].keyCode = (Key)(i + 1); } anyKey = GetChildControl("anyKey"); shiftKey = GetChildControl("shift"); ctrlKey = GetChildControl("ctrl"); altKey = GetChildControl("alt"); imeSelected = GetChildControl("IMESelected"); base.FinishSetup(); } protected override void RefreshConfiguration() { keyboardLayout = null; QueryKeyboardLayoutCommand command = QueryKeyboardLayoutCommand.Create(); if (ExecuteCommand(ref command) >= 0) { keyboardLayout = command.ReadLayoutName(); } } public void OnTextInput(char character) { for (int i = 0; i < m_TextInputListeners.length; i++) { m_TextInputListeners[i](character); } } public KeyControl FindKeyOnCurrentKeyboardLayout(string displayName) { ReadOnlyArray readOnlyArray = allKeys; for (int i = 0; i < readOnlyArray.Count; i++) { if (string.Equals(readOnlyArray[i].displayName, displayName, StringComparison.CurrentCultureIgnoreCase)) { return readOnlyArray[i]; } } return null; } public void OnIMECompositionChanged(IMECompositionString compositionString) { if (m_ImeCompositionListeners.length > 0) { for (int i = 0; i < m_ImeCompositionListeners.length; i++) { m_ImeCompositionListeners[i](compositionString); } } } } [InputControlLayout(stateType = typeof(MouseState), isGenericTypeOfDevice = true)] public class Mouse : Pointer, IInputStateCallbackReceiver { internal static Mouse s_PlatformMouseDevice; public DeltaControl scroll { get; protected set; } public ButtonControl leftButton { get; protected set; } public ButtonControl middleButton { get; protected set; } public ButtonControl rightButton { get; protected set; } public ButtonControl backButton { get; protected set; } public ButtonControl forwardButton { get; protected set; } public IntegerControl clickCount { get; protected set; } public new static Mouse current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnAdded() { base.OnAdded(); if (base.native && s_PlatformMouseDevice == null) { s_PlatformMouseDevice = this; } } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } public void WarpCursorPosition(Vector2 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) WarpMousePositionCommand command = WarpMousePositionCommand.Create(position); ExecuteCommand(ref command); } protected override void FinishSetup() { scroll = GetChildControl("scroll"); leftButton = GetChildControl("leftButton"); middleButton = GetChildControl("middleButton"); rightButton = GetChildControl("rightButton"); forwardButton = GetChildControl("forwardButton"); backButton = GetChildControl("backButton"); base.displayIndex = GetChildControl("displayIndex"); clickCount = GetChildControl("clickCount"); base.FinishSetup(); } protected new void OnNextUpdate() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) base.OnNextUpdate(); InputState.Change((InputControl)scroll, Vector2.zero, InputUpdateType.None, default(InputEventPtr)); } protected new unsafe void OnStateEvent(InputEventPtr eventPtr) { scroll.AccumulateValueInEvent(base.currentStatePtr, eventPtr); base.OnStateEvent(eventPtr); } void IInputStateCallbackReceiver.OnNextUpdate() { OnNextUpdate(); } void IInputStateCallbackReceiver.OnStateEvent(InputEventPtr eventPtr) { OnStateEvent(eventPtr); } } public enum PenButton { Tip = 0, Eraser = 1, BarrelFirst = 2, BarrelSecond = 3, InRange = 4, BarrelThird = 5, BarrelFourth = 6, Barrel1 = 2, Barrel2 = 3, Barrel3 = 5, Barrel4 = 6 } [InputControlLayout(stateType = typeof(PenState), isGenericTypeOfDevice = true)] public class Pen : Pointer { public ButtonControl tip { get; protected set; } public ButtonControl eraser { get; protected set; } public ButtonControl firstBarrelButton { get; protected set; } public ButtonControl secondBarrelButton { get; protected set; } public ButtonControl thirdBarrelButton { get; protected set; } public ButtonControl fourthBarrelButton { get; protected set; } public ButtonControl inRange { get; protected set; } public Vector2Control tilt { get; protected set; } public AxisControl twist { get; protected set; } public new static Pen current { get; internal set; } public ButtonControl this[PenButton button] => button switch { PenButton.Tip => tip, PenButton.Eraser => eraser, PenButton.BarrelFirst => firstBarrelButton, PenButton.BarrelSecond => secondBarrelButton, PenButton.BarrelThird => thirdBarrelButton, PenButton.BarrelFourth => fourthBarrelButton, PenButton.InRange => inRange, _ => throw new InvalidEnumArgumentException("button", (int)button, typeof(PenButton)), }; public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { tip = GetChildControl("tip"); eraser = GetChildControl("eraser"); firstBarrelButton = GetChildControl("barrel1"); secondBarrelButton = GetChildControl("barrel2"); thirdBarrelButton = GetChildControl("barrel3"); fourthBarrelButton = GetChildControl("barrel4"); inRange = GetChildControl("inRange"); tilt = GetChildControl("tilt"); twist = GetChildControl("twist"); base.FinishSetup(); } } [InputControlLayout(stateType = typeof(PointerState), isGenericTypeOfDevice = true)] public class Pointer : InputDevice, IInputStateCallbackReceiver { public Vector2Control position { get; protected set; } public DeltaControl delta { get; protected set; } public Vector2Control radius { get; protected set; } public AxisControl pressure { get; protected set; } public ButtonControl press { get; protected set; } public IntegerControl displayIndex { get; protected set; } public static Pointer current { get; internal set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { position = GetChildControl("position"); delta = GetChildControl("delta"); radius = GetChildControl("radius"); pressure = GetChildControl("pressure"); press = GetChildControl("press"); displayIndex = GetChildControl("displayIndex"); base.FinishSetup(); } protected void OnNextUpdate() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) InputState.Change((InputControl)delta, Vector2.zero, InputUpdateType.None, default(InputEventPtr)); } protected unsafe void OnStateEvent(InputEventPtr eventPtr) { delta.AccumulateValueInEvent(base.currentStatePtr, eventPtr); InputState.Change(this, eventPtr); } void IInputStateCallbackReceiver.OnNextUpdate() { OnNextUpdate(); } void IInputStateCallbackReceiver.OnStateEvent(InputEventPtr eventPtr) { OnStateEvent(eventPtr); } bool IInputStateCallbackReceiver.GetStateOffsetForEvent(InputControl control, InputEventPtr eventPtr, ref uint offset) { return false; } } internal class FastKeyboard : Keyboard { public const string metadata = ";AnyKey;Button;Axis;Key;DiscreteButton;Keyboard"; public FastKeyboard() { InputControlExtensions.DeviceBuilder deviceBuilder = this.Setup(115, 15, 7).WithName("Keyboard").WithDisplayName("Keyboard") .WithChildren(0, 115) .WithLayout(new InternedString("Keyboard")) .WithStateBlock(new InputStateBlock { format = new FourCC(1262836051), sizeInBits = 112u }); InternedString kAnyKeyLayout = new InternedString("AnyKey"); InternedString kKeyLayout = new InternedString("Key"); InternedString kDiscreteButtonLayout = new InternedString("DiscreteButton"); InternedString kButtonLayout = new InternedString("Button"); AnyKeyControl anyKeyControl = Initialize_ctrlKeyboardanyKey(kAnyKeyLayout, this); KeyControl keyControl = Initialize_ctrlKeyboardescape(kKeyLayout, this); KeyControl keyControl2 = Initialize_ctrlKeyboardspace(kKeyLayout, this); KeyControl keyControl3 = Initialize_ctrlKeyboardenter(kKeyLayout, this); KeyControl keyControl4 = Initialize_ctrlKeyboardtab(kKeyLayout, this); KeyControl keyControl5 = Initialize_ctrlKeyboardbackquote(kKeyLayout, this); KeyControl keyControl6 = Initialize_ctrlKeyboardquote(kKeyLayout, this); KeyControl keyControl7 = Initialize_ctrlKeyboardsemicolon(kKeyLayout, this); KeyControl keyControl8 = Initialize_ctrlKeyboardcomma(kKeyLayout, this); KeyControl keyControl9 = Initialize_ctrlKeyboardperiod(kKeyLayout, this); KeyControl keyControl10 = Initialize_ctrlKeyboardslash(kKeyLayout, this); KeyControl keyControl11 = Initialize_ctrlKeyboardbackslash(kKeyLayout, this); KeyControl keyControl12 = Initialize_ctrlKeyboardleftBracket(kKeyLayout, this); KeyControl keyControl13 = Initialize_ctrlKeyboardrightBracket(kKeyLayout, this); KeyControl keyControl14 = Initialize_ctrlKeyboardminus(kKeyLayout, this); KeyControl keyControl15 = Initialize_ctrlKeyboardequals(kKeyLayout, this); KeyControl keyControl16 = Initialize_ctrlKeyboardupArrow(kKeyLayout, this); KeyControl keyControl17 = Initialize_ctrlKeyboarddownArrow(kKeyLayout, this); KeyControl keyControl18 = Initialize_ctrlKeyboardleftArrow(kKeyLayout, this); KeyControl keyControl19 = Initialize_ctrlKeyboardrightArrow(kKeyLayout, this); KeyControl keyControl20 = Initialize_ctrlKeyboarda(kKeyLayout, this); KeyControl keyControl21 = Initialize_ctrlKeyboardb(kKeyLayout, this); KeyControl keyControl22 = Initialize_ctrlKeyboardc(kKeyLayout, this); KeyControl keyControl23 = Initialize_ctrlKeyboardd(kKeyLayout, this); KeyControl keyControl24 = Initialize_ctrlKeyboarde(kKeyLayout, this); KeyControl keyControl25 = Initialize_ctrlKeyboardf(kKeyLayout, this); KeyControl keyControl26 = Initialize_ctrlKeyboardg(kKeyLayout, this); KeyControl keyControl27 = Initialize_ctrlKeyboardh(kKeyLayout, this); KeyControl keyControl28 = Initialize_ctrlKeyboardi(kKeyLayout, this); KeyControl keyControl29 = Initialize_ctrlKeyboardj(kKeyLayout, this); KeyControl keyControl30 = Initialize_ctrlKeyboardk(kKeyLayout, this); KeyControl keyControl31 = Initialize_ctrlKeyboardl(kKeyLayout, this); KeyControl keyControl32 = Initialize_ctrlKeyboardm(kKeyLayout, this); KeyControl keyControl33 = Initialize_ctrlKeyboardn(kKeyLayout, this); KeyControl keyControl34 = Initialize_ctrlKeyboardo(kKeyLayout, this); KeyControl keyControl35 = Initialize_ctrlKeyboardp(kKeyLayout, this); KeyControl keyControl36 = Initialize_ctrlKeyboardq(kKeyLayout, this); KeyControl keyControl37 = Initialize_ctrlKeyboardr(kKeyLayout, this); KeyControl keyControl38 = Initialize_ctrlKeyboards(kKeyLayout, this); KeyControl keyControl39 = Initialize_ctrlKeyboardt(kKeyLayout, this); KeyControl keyControl40 = Initialize_ctrlKeyboardu(kKeyLayout, this); KeyControl keyControl41 = Initialize_ctrlKeyboardv(kKeyLayout, this); KeyControl keyControl42 = Initialize_ctrlKeyboardw(kKeyLayout, this); KeyControl keyControl43 = Initialize_ctrlKeyboardx(kKeyLayout, this); KeyControl keyControl44 = Initialize_ctrlKeyboardy(kKeyLayout, this); KeyControl keyControl45 = Initialize_ctrlKeyboardz(kKeyLayout, this); KeyControl keyControl46 = Initialize_ctrlKeyboard1(kKeyLayout, this); KeyControl keyControl47 = Initialize_ctrlKeyboard2(kKeyLayout, this); KeyControl keyControl48 = Initialize_ctrlKeyboard3(kKeyLayout, this); KeyControl keyControl49 = Initialize_ctrlKeyboard4(kKeyLayout, this); KeyControl keyControl50 = Initialize_ctrlKeyboard5(kKeyLayout, this); KeyControl keyControl51 = Initialize_ctrlKeyboard6(kKeyLayout, this); KeyControl keyControl52 = Initialize_ctrlKeyboard7(kKeyLayout, this); KeyControl keyControl53 = Initialize_ctrlKeyboard8(kKeyLayout, this); KeyControl keyControl54 = Initialize_ctrlKeyboard9(kKeyLayout, this); KeyControl keyControl55 = Initialize_ctrlKeyboard0(kKeyLayout, this); KeyControl keyControl56 = Initialize_ctrlKeyboardleftShift(kKeyLayout, this); KeyControl keyControl57 = Initialize_ctrlKeyboardrightShift(kKeyLayout, this); DiscreteButtonControl control = Initialize_ctrlKeyboardshift(kDiscreteButtonLayout, this); KeyControl keyControl58 = Initialize_ctrlKeyboardleftAlt(kKeyLayout, this); KeyControl keyControl59 = Initialize_ctrlKeyboardrightAlt(kKeyLayout, this); DiscreteButtonControl control2 = Initialize_ctrlKeyboardalt(kDiscreteButtonLayout, this); KeyControl keyControl60 = Initialize_ctrlKeyboardleftCtrl(kKeyLayout, this); KeyControl keyControl61 = Initialize_ctrlKeyboardrightCtrl(kKeyLayout, this); DiscreteButtonControl control3 = Initialize_ctrlKeyboardctrl(kDiscreteButtonLayout, this); KeyControl keyControl62 = Initialize_ctrlKeyboardleftMeta(kKeyLayout, this); KeyControl keyControl63 = Initialize_ctrlKeyboardrightMeta(kKeyLayout, this); KeyControl keyControl64 = Initialize_ctrlKeyboardcontextMenu(kKeyLayout, this); KeyControl keyControl65 = Initialize_ctrlKeyboardbackspace(kKeyLayout, this); KeyControl keyControl66 = Initialize_ctrlKeyboardpageDown(kKeyLayout, this); KeyControl keyControl67 = Initialize_ctrlKeyboardpageUp(kKeyLayout, this); KeyControl keyControl68 = Initialize_ctrlKeyboardhome(kKeyLayout, this); KeyControl keyControl69 = Initialize_ctrlKeyboardend(kKeyLayout, this); KeyControl keyControl70 = Initialize_ctrlKeyboardinsert(kKeyLayout, this); KeyControl keyControl71 = Initialize_ctrlKeyboarddelete(kKeyLayout, this); KeyControl keyControl72 = Initialize_ctrlKeyboardcapsLock(kKeyLayout, this); KeyControl keyControl73 = Initialize_ctrlKeyboardnumLock(kKeyLayout, this); KeyControl keyControl74 = Initialize_ctrlKeyboardprintScreen(kKeyLayout, this); KeyControl keyControl75 = Initialize_ctrlKeyboardscrollLock(kKeyLayout, this); KeyControl keyControl76 = Initialize_ctrlKeyboardpause(kKeyLayout, this); KeyControl keyControl77 = Initialize_ctrlKeyboardnumpadEnter(kKeyLayout, this); KeyControl keyControl78 = Initialize_ctrlKeyboardnumpadDivide(kKeyLayout, this); KeyControl keyControl79 = Initialize_ctrlKeyboardnumpadMultiply(kKeyLayout, this); KeyControl keyControl80 = Initialize_ctrlKeyboardnumpadPlus(kKeyLayout, this); KeyControl keyControl81 = Initialize_ctrlKeyboardnumpadMinus(kKeyLayout, this); KeyControl keyControl82 = Initialize_ctrlKeyboardnumpadPeriod(kKeyLayout, this); KeyControl keyControl83 = Initialize_ctrlKeyboardnumpadEquals(kKeyLayout, this); KeyControl keyControl84 = Initialize_ctrlKeyboardnumpad1(kKeyLayout, this); KeyControl keyControl85 = Initialize_ctrlKeyboardnumpad2(kKeyLayout, this); KeyControl keyControl86 = Initialize_ctrlKeyboardnumpad3(kKeyLayout, this); KeyControl keyControl87 = Initialize_ctrlKeyboardnumpad4(kKeyLayout, this); KeyControl keyControl88 = Initialize_ctrlKeyboardnumpad5(kKeyLayout, this); KeyControl keyControl89 = Initialize_ctrlKeyboardnumpad6(kKeyLayout, this); KeyControl keyControl90 = Initialize_ctrlKeyboardnumpad7(kKeyLayout, this); KeyControl keyControl91 = Initialize_ctrlKeyboardnumpad8(kKeyLayout, this); KeyControl keyControl92 = Initialize_ctrlKeyboardnumpad9(kKeyLayout, this); KeyControl keyControl93 = Initialize_ctrlKeyboardnumpad0(kKeyLayout, this); KeyControl keyControl94 = Initialize_ctrlKeyboardf1(kKeyLayout, this); KeyControl keyControl95 = Initialize_ctrlKeyboardf2(kKeyLayout, this); KeyControl keyControl96 = Initialize_ctrlKeyboardf3(kKeyLayout, this); KeyControl keyControl97 = Initialize_ctrlKeyboardf4(kKeyLayout, this); KeyControl keyControl98 = Initialize_ctrlKeyboardf5(kKeyLayout, this); KeyControl keyControl99 = Initialize_ctrlKeyboardf6(kKeyLayout, this); KeyControl keyControl100 = Initialize_ctrlKeyboardf7(kKeyLayout, this); KeyControl keyControl101 = Initialize_ctrlKeyboardf8(kKeyLayout, this); KeyControl keyControl102 = Initialize_ctrlKeyboardf9(kKeyLayout, this); KeyControl keyControl103 = Initialize_ctrlKeyboardf10(kKeyLayout, this); KeyControl keyControl104 = Initialize_ctrlKeyboardf11(kKeyLayout, this); KeyControl keyControl105 = Initialize_ctrlKeyboardf12(kKeyLayout, this); KeyControl keyControl106 = Initialize_ctrlKeyboardOEM1(kKeyLayout, this); KeyControl keyControl107 = Initialize_ctrlKeyboardOEM2(kKeyLayout, this); KeyControl keyControl108 = Initialize_ctrlKeyboardOEM3(kKeyLayout, this); KeyControl keyControl109 = Initialize_ctrlKeyboardOEM4(kKeyLayout, this); KeyControl keyControl110 = Initialize_ctrlKeyboardOEM5(kKeyLayout, this); ButtonControl buttonControl = Initialize_ctrlKeyboardIMESelected(kButtonLayout, this); deviceBuilder.WithControlUsage(0, new InternedString("Back"), keyControl); deviceBuilder.WithControlUsage(1, new InternedString("Cancel"), keyControl); deviceBuilder.WithControlUsage(2, new InternedString("Submit"), keyControl3); deviceBuilder.WithControlUsage(3, new InternedString("Modifier"), keyControl56); deviceBuilder.WithControlUsage(4, new InternedString("Modifier"), keyControl57); deviceBuilder.WithControlUsage(5, new InternedString("Modifier"), control); deviceBuilder.WithControlUsage(6, new InternedString("Modifier"), keyControl58); deviceBuilder.WithControlUsage(7, new InternedString("Modifier"), keyControl59); deviceBuilder.WithControlUsage(8, new InternedString("Modifier"), control2); deviceBuilder.WithControlUsage(9, new InternedString("Modifier"), keyControl60); deviceBuilder.WithControlUsage(10, new InternedString("Modifier"), keyControl61); deviceBuilder.WithControlUsage(11, new InternedString("Modifier"), control3); deviceBuilder.WithControlUsage(12, new InternedString("Modifier"), keyControl62); deviceBuilder.WithControlUsage(13, new InternedString("Modifier"), keyControl63); deviceBuilder.WithControlUsage(14, new InternedString("Modifier"), keyControl64); deviceBuilder.WithControlAlias(0, new InternedString("AltGr")); deviceBuilder.WithControlAlias(1, new InternedString("LeftWindows")); deviceBuilder.WithControlAlias(2, new InternedString("LeftApple")); deviceBuilder.WithControlAlias(3, new InternedString("LeftCommand")); deviceBuilder.WithControlAlias(4, new InternedString("RightWindows")); deviceBuilder.WithControlAlias(5, new InternedString("RightApple")); deviceBuilder.WithControlAlias(6, new InternedString("RightCommand")); base.keys = new KeyControl[110]; base.keys[0] = keyControl2; base.keys[1] = keyControl3; base.keys[2] = keyControl4; base.keys[3] = keyControl5; base.keys[4] = keyControl6; base.keys[5] = keyControl7; base.keys[6] = keyControl8; base.keys[7] = keyControl9; base.keys[8] = keyControl10; base.keys[9] = keyControl11; base.keys[10] = keyControl12; base.keys[11] = keyControl13; base.keys[12] = keyControl14; base.keys[13] = keyControl15; base.keys[14] = keyControl20; base.keys[15] = keyControl21; base.keys[16] = keyControl22; base.keys[17] = keyControl23; base.keys[18] = keyControl24; base.keys[19] = keyControl25; base.keys[20] = keyControl26; base.keys[21] = keyControl27; base.keys[22] = keyControl28; base.keys[23] = keyControl29; base.keys[24] = keyControl30; base.keys[25] = keyControl31; base.keys[26] = keyControl32; base.keys[27] = keyControl33; base.keys[28] = keyControl34; base.keys[29] = keyControl35; base.keys[30] = keyControl36; base.keys[31] = keyControl37; base.keys[32] = keyControl38; base.keys[33] = keyControl39; base.keys[34] = keyControl40; base.keys[35] = keyControl41; base.keys[36] = keyControl42; base.keys[37] = keyControl43; base.keys[38] = keyControl44; base.keys[39] = keyControl45; base.keys[40] = keyControl46; base.keys[41] = keyControl47; base.keys[42] = keyControl48; base.keys[43] = keyControl49; base.keys[44] = keyControl50; base.keys[45] = keyControl51; base.keys[46] = keyControl52; base.keys[47] = keyControl53; base.keys[48] = keyControl54; base.keys[49] = keyControl55; base.keys[50] = keyControl56; base.keys[51] = keyControl57; base.keys[52] = keyControl58; base.keys[53] = keyControl59; base.keys[54] = keyControl60; base.keys[55] = keyControl61; base.keys[56] = keyControl62; base.keys[57] = keyControl63; base.keys[58] = keyControl64; base.keys[59] = keyControl; base.keys[60] = keyControl18; base.keys[61] = keyControl19; base.keys[62] = keyControl16; base.keys[63] = keyControl17; base.keys[64] = keyControl65; base.keys[65] = keyControl66; base.keys[66] = keyControl67; base.keys[67] = keyControl68; base.keys[68] = keyControl69; base.keys[69] = keyControl70; base.keys[70] = keyControl71; base.keys[71] = keyControl72; base.keys[72] = keyControl73; base.keys[73] = keyControl74; base.keys[74] = keyControl75; base.keys[75] = keyControl76; base.keys[76] = keyControl77; base.keys[77] = keyControl78; base.keys[78] = keyControl79; base.keys[79] = keyControl80; base.keys[80] = keyControl81; base.keys[81] = keyControl82; base.keys[82] = keyControl83; base.keys[83] = keyControl93; base.keys[84] = keyControl84; base.keys[85] = keyControl85; base.keys[86] = keyControl86; base.keys[87] = keyControl87; base.keys[88] = keyControl88; base.keys[89] = keyControl89; base.keys[90] = keyControl90; base.keys[91] = keyControl91; base.keys[92] = keyControl92; base.keys[93] = keyControl94; base.keys[94] = keyControl95; base.keys[95] = keyControl96; base.keys[96] = keyControl97; base.keys[97] = keyControl98; base.keys[98] = keyControl99; base.keys[99] = keyControl100; base.keys[100] = keyControl101; base.keys[101] = keyControl102; base.keys[102] = keyControl103; base.keys[103] = keyControl104; base.keys[104] = keyControl105; base.keys[105] = keyControl106; base.keys[106] = keyControl107; base.keys[107] = keyControl108; base.keys[108] = keyControl109; base.keys[109] = keyControl110; base.anyKey = anyKeyControl; base.shiftKey = control; base.ctrlKey = control3; base.altKey = control2; base.imeSelected = buttonControl; deviceBuilder.WithStateOffsetToControlIndexMap(new uint[115] { 111616u, 525314u, 1049603u, 1573892u, 2098181u, 2622470u, 3146759u, 3671048u, 4195337u, 4719626u, 5243915u, 5768204u, 6292493u, 6816782u, 7341071u, 7865364u, 8389653u, 8913942u, 9438231u, 9962520u, 10486809u, 11011098u, 11535387u, 12059676u, 12583965u, 13108254u, 13632543u, 14156832u, 14681121u, 15205410u, 15729699u, 16253988u, 16778277u, 17302566u, 17826855u, 18351144u, 18875433u, 19399722u, 19924011u, 20448300u, 20972589u, 21496878u, 22021167u, 22545456u, 23069745u, 23594034u, 24118323u, 24642612u, 25166901u, 25691190u, 26215479u, 26739768u, 26740794u, 27264057u, 27788347u, 27789373u, 28312636u, 28836926u, 28837952u, 29361215u, 29885505u, 30409794u, 30934083u, 31458305u, 31982610u, 32506899u, 33031184u, 33555473u, 34079812u, 34604101u, 35128390u, 35652679u, 36176968u, 36701257u, 37225546u, 37749835u, 38274124u, 38798413u, 39322702u, 39846991u, 40371280u, 40895569u, 41419858u, 41944147u, 42468436u, 42992725u, 43517014u, 44041312u, 44565591u, 45089880u, 45614169u, 46138458u, 46662747u, 47187036u, 47711325u, 48235614u, 48759903u, 49284193u, 49808482u, 50332771u, 50857060u, 51381349u, 51905638u, 52429927u, 52954216u, 53478505u, 54002794u, 54527083u, 55051372u, 55575661u, 56099950u, 56624239u, 57148528u, 57672817u, 58197106u }); deviceBuilder.WithControlTree(new byte[1575] { 111, 0, 1, 0, 0, 0, 0, 56, 0, 15, 0, 0, 0, 2, 111, 0, 3, 0, 2, 0, 2, 84, 0, 5, 0, 0, 0, 0, 111, 0, 169, 0, 0, 0, 0, 70, 0, 7, 0, 0, 0, 0, 84, 0, 143, 0, 0, 0, 0, 63, 0, 9, 0, 0, 0, 0, 70, 0, 53, 0, 0, 0, 0, 60, 0, 131, 0, 0, 0, 0, 63, 0, 11, 0, 0, 0, 0, 62, 0, 13, 0, 0, 0, 0, 63, 0, 255, 255, 22, 0, 1, 61, 0, 255, 255, 4, 0, 1, 62, 0, 255, 255, 21, 0, 1, 28, 0, 17, 0, 0, 0, 0, 56, 0, 77, 0, 0, 0, 0, 14, 0, 19, 0, 0, 0, 0, 28, 0, 45, 0, 0, 0, 0, 7, 0, 21, 0, 0, 0, 0, 14, 0, 33, 0, 0, 0, 0, 4, 0, 23, 0, 0, 0, 0, 7, 0, 29, 0, 0, 0, 0, 2, 0, 25, 0, 0, 0, 0, 4, 0, 27, 0, 0, 0, 0, 1, 0, 255, 255, 0, 0, 0, 2, 0, 255, 255, 5, 0, 1, 3, 0, 255, 255, 6, 0, 1, 4, 0, 255, 255, 7, 0, 1, 6, 0, 31, 0, 0, 0, 0, 7, 0, 255, 255, 10, 0, 1, 5, 0, 255, 255, 8, 0, 1, 6, 0, 255, 255, 9, 0, 1, 11, 0, 35, 0, 0, 0, 0, 14, 0, 41, 0, 0, 0, 0, 9, 0, 37, 0, 0, 0, 0, 11, 0, 39, 0, 0, 0, 0, 8, 0, 255, 255, 11, 0, 1, 9, 0, 255, 255, 12, 0, 1, 10, 0, 255, 255, 13, 0, 1, 11, 0, 255, 255, 14, 0, 1, 13, 0, 43, 0, 0, 0, 0, 14, 0, 255, 255, 17, 0, 1, 12, 0, 255, 255, 15, 0, 1, 13, 0, 255, 255, 16, 0, 1, 21, 0, 47, 0, 0, 0, 0, 28, 0, 65, 0, 0, 0, 0, 18, 0, 49, 0, 0, 0, 0, 21, 0, 61, 0, 0, 0, 0, 16, 0, 51, 0, 0, 0, 0, 18, 0, 59, 0, 0, 0, 0, 15, 0, 255, 255, 18, 0, 1, 16, 0, 255, 255, 23, 0, 1, 67, 0, 55, 0, 0, 0, 0, 70, 0, 139, 0, 0, 0, 0, 65, 0, 57, 0, 0, 0, 0, 67, 0, 137, 0, 0, 0, 0, 64, 0, 255, 255, 19, 0, 1, 65, 0, 255, 255, 20, 0, 1, 17, 0, 255, 255, 24, 0, 1, 18, 0, 255, 255, 25, 0, 1, 20, 0, 63, 0, 0, 0, 0, 21, 0, 255, 255, 28, 0, 1, 19, 0, 255, 255, 26, 0, 1, 20, 0, 255, 255, 27, 0, 1, 25, 0, 67, 0, 0, 0, 0, 28, 0, 73, 0, 0, 0, 0, 23, 0, 69, 0, 0, 0, 0, 25, 0, 71, 0, 0, 0, 0, 22, 0, 255, 255, 29, 0, 1, 23, 0, 255, 255, 30, 0, 1, 24, 0, 255, 255, 31, 0, 1, 25, 0, 255, 255, 32, 0, 1, 27, 0, 75, 0, 0, 0, 0, 28, 0, 255, 255, 35, 0, 1, 26, 0, 255, 255, 33, 0, 1, 27, 0, 255, 255, 34, 0, 1, 42, 0, 79, 0, 0, 0, 0, 56, 0, 105, 0, 0, 0, 0, 35, 0, 81, 0, 0, 0, 0, 42, 0, 93, 0, 0, 0, 0, 32, 0, 83, 0, 0, 0, 0, 35, 0, 89, 0, 0, 0, 0, 30, 0, 85, 0, 0, 0, 0, 32, 0, 87, 0, 0, 0, 0, 29, 0, 255, 255, 36, 0, 1, 30, 0, 255, 255, 37, 0, 1, 31, 0, 255, 255, 38, 0, 1, 32, 0, 255, 255, 39, 0, 1, 34, 0, 91, 0, 0, 0, 0, 35, 0, 255, 255, 42, 0, 1, 33, 0, 255, 255, 40, 0, 1, 34, 0, 255, 255, 41, 0, 1, 39, 0, 95, 0, 0, 0, 0, 42, 0, 101, 0, 0, 0, 0, 37, 0, 97, 0, 0, 0, 0, 39, 0, 99, 0, 0, 0, 0, 36, 0, 255, 255, 43, 0, 1, 37, 0, 255, 255, 44, 0, 1, 38, 0, 255, 255, 45, 0, 1, 39, 0, 255, 255, 46, 0, 1, 41, 0, 103, 0, 0, 0, 0, 42, 0, 255, 255, 49, 0, 1, 40, 0, 255, 255, 47, 0, 1, 41, 0, 255, 255, 48, 0, 1, 49, 0, 107, 0, 0, 0, 0, 56, 0, 119, 0, 0, 0, 0, 46, 0, 109, 0, 0, 0, 0, 49, 0, 115, 0, 0, 0, 0, 44, 0, 111, 0, 0, 0, 0, 46, 0, 113, 0, 0, 0, 0, 43, 0, 255, 255, 50, 0, 1, 44, 0, 255, 255, 51, 0, 1, 45, 0, 255, 255, 52, 0, 1, 46, 0, 255, 255, 53, 0, 1, 48, 0, 117, 0, 0, 0, 0, 49, 0, 255, 255, 56, 0, 1, 47, 0, 255, 255, 54, 0, 1, 48, 0, 255, 255, 55, 0, 1, 53, 0, 121, 0, 0, 0, 0, 56, 0, 127, 0, 0, 0, 0, 51, 0, 123, 0, 0, 0, 0, 53, 0, 125, 0, 61, 0, 1, 50, 0, 255, 255, 57, 0, 1, 51, 0, 255, 255, 58, 0, 1, 52, 0, 255, 255, 59, 0, 1, 53, 0, 255, 255, 60, 0, 1, 55, 0, 129, 0, 64, 0, 1, 56, 0, 255, 255, 65, 0, 1, 54, 0, 255, 255, 62, 0, 1, 55, 0, 255, 255, 63, 0, 1, 58, 0, 133, 0, 0, 0, 0, 60, 0, 135, 0, 0, 0, 0, 57, 0, 255, 255, 66, 0, 1, 58, 0, 255, 255, 67, 0, 1, 59, 0, 255, 255, 68, 0, 1, 60, 0, 255, 255, 69, 0, 1, 66, 0, 255, 255, 70, 0, 1, 67, 0, 255, 255, 71, 0, 1, 69, 0, 141, 0, 0, 0, 0, 70, 0, 255, 255, 74, 0, 1, 68, 0, 255, 255, 72, 0, 1, 69, 0, 255, 255, 73, 0, 1, 77, 0, 145, 0, 0, 0, 0, 84, 0, 157, 0, 0, 0, 0, 74, 0, 147, 0, 0, 0, 0, 77, 0, 153, 0, 0, 0, 0, 72, 0, 149, 0, 0, 0, 0, 74, 0, 151, 0, 0, 0, 0, 71, 0, 255, 255, 75, 0, 1, 72, 0, 255, 255, 76, 0, 1, 73, 0, 255, 255, 77, 0, 1, 74, 0, 255, 255, 78, 0, 1, 76, 0, 155, 0, 0, 0, 0, 77, 0, 255, 255, 81, 0, 1, 75, 0, 255, 255, 79, 0, 1, 76, 0, 255, 255, 80, 0, 1, 81, 0, 159, 0, 0, 0, 0, 84, 0, 165, 0, 0, 0, 0, 79, 0, 161, 0, 0, 0, 0, 81, 0, 163, 0, 0, 0, 0, 78, 0, 255, 255, 82, 0, 1, 79, 0, 255, 255, 83, 0, 1, 80, 0, 255, 255, 84, 0, 1, 81, 0, 255, 255, 85, 0, 1, 83, 0, 167, 0, 0, 0, 0, 84, 0, 255, 255, 88, 0, 1, 82, 0, 255, 255, 86, 0, 1, 83, 0, 255, 255, 87, 0, 1, 98, 0, 171, 0, 0, 0, 0, 111, 0, 197, 0, 0, 0, 0, 91, 0, 173, 0, 0, 0, 0, 98, 0, 185, 0, 0, 0, 0, 88, 0, 175, 0, 0, 0, 0, 91, 0, 181, 0, 0, 0, 0, 86, 0, 177, 0, 0, 0, 0, 88, 0, 179, 0, 0, 0, 0, 85, 0, 255, 255, 98, 0, 1, 86, 0, 255, 255, 89, 0, 1, 87, 0, 255, 255, 90, 0, 1, 88, 0, 255, 255, 91, 0, 1, 90, 0, 183, 0, 0, 0, 0, 91, 0, 255, 255, 94, 0, 1, 89, 0, 255, 255, 92, 0, 1, 90, 0, 255, 255, 93, 0, 1, 95, 0, 187, 0, 0, 0, 0, 98, 0, 193, 0, 0, 0, 0, 93, 0, 189, 0, 0, 0, 0, 95, 0, 191, 0, 0, 0, 0, 92, 0, 255, 255, 95, 0, 1, 93, 0, 255, 255, 96, 0, 1, 94, 0, 255, 255, 97, 0, 1, 95, 0, 255, 255, 99, 0, 1, 97, 0, 195, 0, 0, 0, 0, 98, 0, 255, 255, 102, 0, 1, 96, 0, 255, 255, 100, 0, 1, 97, 0, 255, 255, 101, 0, 1, 105, 0, 199, 0, 0, 0, 0, 111, 0, 211, 0, 0, 0, 0, 102, 0, 201, 0, 0, 0, 0, 105, 0, 207, 0, 0, 0, 0, 100, 0, 203, 0, 0, 0, 0, 102, 0, 205, 0, 0, 0, 0, 99, 0, 255, 255, 103, 0, 1, 100, 0, 255, 255, 104, 0, 1, 101, 0, 255, 255, 105, 0, 1, 102, 0, 255, 255, 106, 0, 1, 104, 0, 209, 0, 0, 0, 0, 105, 0, 255, 255, 109, 0, 1, 103, 0, 255, 255, 107, 0, 1, 104, 0, 255, 255, 108, 0, 1, 108, 0, 213, 0, 0, 0, 0, 111, 0, 217, 0, 0, 0, 0, 107, 0, 215, 0, 0, 0, 0, 108, 0, 255, 255, 112, 0, 1, 106, 0, 255, 255, 110, 0, 1, 107, 0, 255, 255, 111, 0, 1, 110, 0, 219, 0, 0, 0, 0, 111, 0, 221, 0, 115, 0, 1, 109, 0, 255, 255, 113, 0, 1, 110, 0, 255, 255, 114, 0, 1, 111, 0, 255, 255, 0, 0, 0, 111, 0, 223, 0, 0, 0, 0, 112, 0, 255, 255, 116, 0, 1, 111, 0, 255, 255, 0, 0, 0 }, new ushort[117] { 0, 64, 0, 64, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114 }); deviceBuilder.Finish(); } private AnyKeyControl Initialize_ctrlKeyboardanyKey(InternedString kAnyKeyLayout, InputControl parent) { AnyKeyControl anyKeyControl = new AnyKeyControl(); anyKeyControl.Setup().At(this, 0).WithParent(parent) .WithName("anyKey") .WithDisplayName("Any Key") .WithLayout(kAnyKeyLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 0u, sizeInBits = 109u }) .WithMinAndMax(0, 1) .Finish(); return anyKeyControl; } private KeyControl Initialize_ctrlKeyboardescape(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 1).WithParent(parent) .WithName("escape") .WithDisplayName("Escape") .WithLayout(kKeyLayout) .WithUsages(0, 2) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 60u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Escape; return keyControl; } private KeyControl Initialize_ctrlKeyboardspace(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 2).WithParent(parent) .WithName("space") .WithDisplayName("Space") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 1u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Space; return keyControl; } private KeyControl Initialize_ctrlKeyboardenter(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 3).WithParent(parent) .WithName("enter") .WithDisplayName("Enter") .WithLayout(kKeyLayout) .WithUsages(2, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 2u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Enter; return keyControl; } private KeyControl Initialize_ctrlKeyboardtab(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 4).WithParent(parent) .WithName("tab") .WithDisplayName("Tab") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 3u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Tab; return keyControl; } private KeyControl Initialize_ctrlKeyboardbackquote(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 5).WithParent(parent) .WithName("backquote") .WithDisplayName("`") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Backquote; return keyControl; } private KeyControl Initialize_ctrlKeyboardquote(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 6).WithParent(parent) .WithName("quote") .WithDisplayName("'") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 5u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Quote; return keyControl; } private KeyControl Initialize_ctrlKeyboardsemicolon(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 7).WithParent(parent) .WithName("semicolon") .WithDisplayName(";") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 6u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Semicolon; return keyControl; } private KeyControl Initialize_ctrlKeyboardcomma(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 8).WithParent(parent) .WithName("comma") .WithDisplayName(",") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 7u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Comma; return keyControl; } private KeyControl Initialize_ctrlKeyboardperiod(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 9).WithParent(parent) .WithName("period") .WithDisplayName(".") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 8u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Period; return keyControl; } private KeyControl Initialize_ctrlKeyboardslash(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 10).WithParent(parent) .WithName("slash") .WithDisplayName("/") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 9u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Slash; return keyControl; } private KeyControl Initialize_ctrlKeyboardbackslash(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 11).WithParent(parent) .WithName("backslash") .WithDisplayName("\\") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 10u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Backslash; return keyControl; } private KeyControl Initialize_ctrlKeyboardleftBracket(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 12).WithParent(parent) .WithName("leftBracket") .WithDisplayName("[") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 11u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.LeftBracket; return keyControl; } private KeyControl Initialize_ctrlKeyboardrightBracket(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 13).WithParent(parent) .WithName("rightBracket") .WithDisplayName("]") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 12u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.RightBracket; return keyControl; } private KeyControl Initialize_ctrlKeyboardminus(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 14).WithParent(parent) .WithName("minus") .WithDisplayName("-") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 13u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Minus; return keyControl; } private KeyControl Initialize_ctrlKeyboardequals(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 15).WithParent(parent) .WithName("equals") .WithDisplayName("=") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 14u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Equals; return keyControl; } private KeyControl Initialize_ctrlKeyboardupArrow(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 16).WithParent(parent) .WithName("upArrow") .WithDisplayName("Up Arrow") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 63u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.UpArrow; return keyControl; } private KeyControl Initialize_ctrlKeyboarddownArrow(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 17).WithParent(parent) .WithName("downArrow") .WithDisplayName("Down Arrow") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 64u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.DownArrow; return keyControl; } private KeyControl Initialize_ctrlKeyboardleftArrow(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 18).WithParent(parent) .WithName("leftArrow") .WithDisplayName("Left Arrow") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 61u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.LeftArrow; return keyControl; } private KeyControl Initialize_ctrlKeyboardrightArrow(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 19).WithParent(parent) .WithName("rightArrow") .WithDisplayName("Right Arrow") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 62u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.RightArrow; return keyControl; } private KeyControl Initialize_ctrlKeyboarda(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 20).WithParent(parent) .WithName("a") .WithDisplayName("A") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 15u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.A; return keyControl; } private KeyControl Initialize_ctrlKeyboardb(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 21).WithParent(parent) .WithName("b") .WithDisplayName("B") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 16u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.B; return keyControl; } private KeyControl Initialize_ctrlKeyboardc(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 22).WithParent(parent) .WithName("c") .WithDisplayName("C") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 17u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.C; return keyControl; } private KeyControl Initialize_ctrlKeyboardd(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 23).WithParent(parent) .WithName("d") .WithDisplayName("D") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 18u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.D; return keyControl; } private KeyControl Initialize_ctrlKeyboarde(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 24).WithParent(parent) .WithName("e") .WithDisplayName("E") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 19u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.E; return keyControl; } private KeyControl Initialize_ctrlKeyboardf(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 25).WithParent(parent) .WithName("f") .WithDisplayName("F") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 20u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F; return keyControl; } private KeyControl Initialize_ctrlKeyboardg(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 26).WithParent(parent) .WithName("g") .WithDisplayName("G") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 21u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.G; return keyControl; } private KeyControl Initialize_ctrlKeyboardh(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 27).WithParent(parent) .WithName("h") .WithDisplayName("H") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 22u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.H; return keyControl; } private KeyControl Initialize_ctrlKeyboardi(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 28).WithParent(parent) .WithName("i") .WithDisplayName("I") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 23u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.I; return keyControl; } private KeyControl Initialize_ctrlKeyboardj(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 29).WithParent(parent) .WithName("j") .WithDisplayName("J") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 24u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.J; return keyControl; } private KeyControl Initialize_ctrlKeyboardk(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 30).WithParent(parent) .WithName("k") .WithDisplayName("K") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 25u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.K; return keyControl; } private KeyControl Initialize_ctrlKeyboardl(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 31).WithParent(parent) .WithName("l") .WithDisplayName("L") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 26u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.L; return keyControl; } private KeyControl Initialize_ctrlKeyboardm(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 32).WithParent(parent) .WithName("m") .WithDisplayName("M") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 27u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.M; return keyControl; } private KeyControl Initialize_ctrlKeyboardn(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 33).WithParent(parent) .WithName("n") .WithDisplayName("N") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 28u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.N; return keyControl; } private KeyControl Initialize_ctrlKeyboardo(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 34).WithParent(parent) .WithName("o") .WithDisplayName("O") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 29u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.O; return keyControl; } private KeyControl Initialize_ctrlKeyboardp(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 35).WithParent(parent) .WithName("p") .WithDisplayName("P") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 30u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.P; return keyControl; } private KeyControl Initialize_ctrlKeyboardq(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 36).WithParent(parent) .WithName("q") .WithDisplayName("Q") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 31u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Q; return keyControl; } private KeyControl Initialize_ctrlKeyboardr(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 37).WithParent(parent) .WithName("r") .WithDisplayName("R") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 32u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.R; return keyControl; } private KeyControl Initialize_ctrlKeyboards(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 38).WithParent(parent) .WithName("s") .WithDisplayName("S") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 33u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.S; return keyControl; } private KeyControl Initialize_ctrlKeyboardt(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 39).WithParent(parent) .WithName("t") .WithDisplayName("T") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 34u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.T; return keyControl; } private KeyControl Initialize_ctrlKeyboardu(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 40).WithParent(parent) .WithName("u") .WithDisplayName("U") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 35u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.U; return keyControl; } private KeyControl Initialize_ctrlKeyboardv(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 41).WithParent(parent) .WithName("v") .WithDisplayName("V") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 36u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.V; return keyControl; } private KeyControl Initialize_ctrlKeyboardw(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 42).WithParent(parent) .WithName("w") .WithDisplayName("W") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 37u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.W; return keyControl; } private KeyControl Initialize_ctrlKeyboardx(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 43).WithParent(parent) .WithName("x") .WithDisplayName("X") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 38u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.X; return keyControl; } private KeyControl Initialize_ctrlKeyboardy(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 44).WithParent(parent) .WithName("y") .WithDisplayName("Y") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 39u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Y; return keyControl; } private KeyControl Initialize_ctrlKeyboardz(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 45).WithParent(parent) .WithName("z") .WithDisplayName("Z") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 40u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Z; return keyControl; } private KeyControl Initialize_ctrlKeyboard1(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 46).WithParent(parent) .WithName("1") .WithDisplayName("1") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 41u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit1; return keyControl; } private KeyControl Initialize_ctrlKeyboard2(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 47).WithParent(parent) .WithName("2") .WithDisplayName("2") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 42u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit2; return keyControl; } private KeyControl Initialize_ctrlKeyboard3(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 48).WithParent(parent) .WithName("3") .WithDisplayName("3") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 43u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit3; return keyControl; } private KeyControl Initialize_ctrlKeyboard4(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 49).WithParent(parent) .WithName("4") .WithDisplayName("4") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 44u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit4; return keyControl; } private KeyControl Initialize_ctrlKeyboard5(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 50).WithParent(parent) .WithName("5") .WithDisplayName("5") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 45u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit5; return keyControl; } private KeyControl Initialize_ctrlKeyboard6(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 51).WithParent(parent) .WithName("6") .WithDisplayName("6") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 46u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit6; return keyControl; } private KeyControl Initialize_ctrlKeyboard7(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 52).WithParent(parent) .WithName("7") .WithDisplayName("7") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 47u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit7; return keyControl; } private KeyControl Initialize_ctrlKeyboard8(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 53).WithParent(parent) .WithName("8") .WithDisplayName("8") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 48u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit8; return keyControl; } private KeyControl Initialize_ctrlKeyboard9(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 54).WithParent(parent) .WithName("9") .WithDisplayName("9") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 49u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit9; return keyControl; } private KeyControl Initialize_ctrlKeyboard0(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 55).WithParent(parent) .WithName("0") .WithDisplayName("0") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 50u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Digit0; return keyControl; } private KeyControl Initialize_ctrlKeyboardleftShift(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 56).WithParent(parent) .WithName("leftShift") .WithDisplayName("Left Shift") .WithLayout(kKeyLayout) .WithUsages(3, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 51u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.LeftShift; return keyControl; } private KeyControl Initialize_ctrlKeyboardrightShift(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 57).WithParent(parent) .WithName("rightShift") .WithDisplayName("Right Shift") .WithLayout(kKeyLayout) .WithUsages(4, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 52u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.RightShift; return keyControl; } private DiscreteButtonControl Initialize_ctrlKeyboardshift(InternedString kDiscreteButtonLayout, InputControl parent) { DiscreteButtonControl obj = new DiscreteButtonControl { minValue = 1, maxValue = 3, writeMode = DiscreteButtonControl.WriteMode.WriteNullAndMaxValue }; obj.Setup().At(this, 58).WithParent(parent) .WithName("shift") .WithDisplayName("Shift") .WithLayout(kDiscreteButtonLayout) .WithUsages(5, 1) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 51u, sizeInBits = 2u }) .WithMinAndMax(0, 1) .Finish(); return obj; } private KeyControl Initialize_ctrlKeyboardleftAlt(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 59).WithParent(parent) .WithName("leftAlt") .WithDisplayName("Left Alt") .WithLayout(kKeyLayout) .WithUsages(6, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 53u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.LeftAlt; return keyControl; } private KeyControl Initialize_ctrlKeyboardrightAlt(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 60).WithParent(parent) .WithName("rightAlt") .WithDisplayName("Right Alt") .WithLayout(kKeyLayout) .WithUsages(7, 1) .WithAliases(0, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 54u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.RightAlt; return keyControl; } private DiscreteButtonControl Initialize_ctrlKeyboardalt(InternedString kDiscreteButtonLayout, InputControl parent) { DiscreteButtonControl obj = new DiscreteButtonControl { minValue = 1, maxValue = 3, writeMode = DiscreteButtonControl.WriteMode.WriteNullAndMaxValue }; obj.Setup().At(this, 61).WithParent(parent) .WithName("alt") .WithDisplayName("Alt") .WithLayout(kDiscreteButtonLayout) .WithUsages(8, 1) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 53u, sizeInBits = 2u }) .WithMinAndMax(0, 1) .Finish(); return obj; } private KeyControl Initialize_ctrlKeyboardleftCtrl(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 62).WithParent(parent) .WithName("leftCtrl") .WithDisplayName("Left Control") .WithLayout(kKeyLayout) .WithUsages(9, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 55u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.LeftCtrl; return keyControl; } private KeyControl Initialize_ctrlKeyboardrightCtrl(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 63).WithParent(parent) .WithName("rightCtrl") .WithDisplayName("Right Control") .WithLayout(kKeyLayout) .WithUsages(10, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 56u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.RightCtrl; return keyControl; } private DiscreteButtonControl Initialize_ctrlKeyboardctrl(InternedString kDiscreteButtonLayout, InputControl parent) { DiscreteButtonControl obj = new DiscreteButtonControl { minValue = 1, maxValue = 3, writeMode = DiscreteButtonControl.WriteMode.WriteNullAndMaxValue }; obj.Setup().At(this, 64).WithParent(parent) .WithName("ctrl") .WithDisplayName("Control") .WithLayout(kDiscreteButtonLayout) .WithUsages(11, 1) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 55u, sizeInBits = 2u }) .WithMinAndMax(0, 1) .Finish(); return obj; } private KeyControl Initialize_ctrlKeyboardleftMeta(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 65).WithParent(parent) .WithName("leftMeta") .WithDisplayName("Left System") .WithLayout(kKeyLayout) .WithUsages(12, 1) .WithAliases(1, 3) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 57u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.LeftMeta; return keyControl; } private KeyControl Initialize_ctrlKeyboardrightMeta(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 66).WithParent(parent) .WithName("rightMeta") .WithDisplayName("Right System") .WithLayout(kKeyLayout) .WithUsages(13, 1) .WithAliases(4, 3) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 58u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.RightMeta; return keyControl; } private KeyControl Initialize_ctrlKeyboardcontextMenu(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 67).WithParent(parent) .WithName("contextMenu") .WithDisplayName("Context Menu") .WithLayout(kKeyLayout) .WithUsages(14, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 59u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.ContextMenu; return keyControl; } private KeyControl Initialize_ctrlKeyboardbackspace(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 68).WithParent(parent) .WithName("backspace") .WithDisplayName("Backspace") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 65u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Backspace; return keyControl; } private KeyControl Initialize_ctrlKeyboardpageDown(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 69).WithParent(parent) .WithName("pageDown") .WithDisplayName("Page Down") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 66u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.PageDown; return keyControl; } private KeyControl Initialize_ctrlKeyboardpageUp(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 70).WithParent(parent) .WithName("pageUp") .WithDisplayName("Page Up") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 67u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.PageUp; return keyControl; } private KeyControl Initialize_ctrlKeyboardhome(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 71).WithParent(parent) .WithName("home") .WithDisplayName("Home") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 68u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Home; return keyControl; } private KeyControl Initialize_ctrlKeyboardend(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 72).WithParent(parent) .WithName("end") .WithDisplayName("End") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 69u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.End; return keyControl; } private KeyControl Initialize_ctrlKeyboardinsert(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 73).WithParent(parent) .WithName("insert") .WithDisplayName("Insert") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 70u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Insert; return keyControl; } private KeyControl Initialize_ctrlKeyboarddelete(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 74).WithParent(parent) .WithName("delete") .WithDisplayName("Delete") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 71u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Delete; return keyControl; } private KeyControl Initialize_ctrlKeyboardcapsLock(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 75).WithParent(parent) .WithName("capsLock") .WithDisplayName("Caps Lock") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 72u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.CapsLock; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumLock(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 76).WithParent(parent) .WithName("numLock") .WithDisplayName("Num Lock") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 73u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumLock; return keyControl; } private KeyControl Initialize_ctrlKeyboardprintScreen(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 77).WithParent(parent) .WithName("printScreen") .WithDisplayName("Print Screen") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 74u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.PrintScreen; return keyControl; } private KeyControl Initialize_ctrlKeyboardscrollLock(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 78).WithParent(parent) .WithName("scrollLock") .WithDisplayName("Scroll Lock") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 75u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.ScrollLock; return keyControl; } private KeyControl Initialize_ctrlKeyboardpause(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 79).WithParent(parent) .WithName("pause") .WithDisplayName("Pause/Break") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 76u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Pause; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadEnter(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 80).WithParent(parent) .WithName("numpadEnter") .WithDisplayName("Numpad Enter") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 77u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadEnter; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadDivide(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 81).WithParent(parent) .WithName("numpadDivide") .WithDisplayName("Numpad /") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 78u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadDivide; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadMultiply(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 82).WithParent(parent) .WithName("numpadMultiply") .WithDisplayName("Numpad *") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 79u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadMultiply; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadPlus(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 83).WithParent(parent) .WithName("numpadPlus") .WithDisplayName("Numpad +") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 80u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadPlus; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadMinus(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 84).WithParent(parent) .WithName("numpadMinus") .WithDisplayName("Numpad -") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 81u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadMinus; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadPeriod(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 85).WithParent(parent) .WithName("numpadPeriod") .WithDisplayName("Numpad .") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 82u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadPeriod; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpadEquals(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 86).WithParent(parent) .WithName("numpadEquals") .WithDisplayName("Numpad =") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 83u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.NumpadEquals; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad1(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 87).WithParent(parent) .WithName("numpad1") .WithDisplayName("Numpad 1") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 85u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad1; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad2(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 88).WithParent(parent) .WithName("numpad2") .WithDisplayName("Numpad 2") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 86u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad2; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad3(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 89).WithParent(parent) .WithName("numpad3") .WithDisplayName("Numpad 3") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 87u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad3; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad4(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 90).WithParent(parent) .WithName("numpad4") .WithDisplayName("Numpad 4") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 88u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad4; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad5(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 91).WithParent(parent) .WithName("numpad5") .WithDisplayName("Numpad 5") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 89u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad5; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad6(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 92).WithParent(parent) .WithName("numpad6") .WithDisplayName("Numpad 6") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 90u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad6; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad7(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 93).WithParent(parent) .WithName("numpad7") .WithDisplayName("Numpad 7") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 91u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad7; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad8(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 94).WithParent(parent) .WithName("numpad8") .WithDisplayName("Numpad 8") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 92u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad8; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad9(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 95).WithParent(parent) .WithName("numpad9") .WithDisplayName("Numpad 9") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 93u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad9; return keyControl; } private KeyControl Initialize_ctrlKeyboardnumpad0(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 96).WithParent(parent) .WithName("numpad0") .WithDisplayName("Numpad 0") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 84u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.Numpad0; return keyControl; } private KeyControl Initialize_ctrlKeyboardf1(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 97).WithParent(parent) .WithName("f1") .WithDisplayName("F1") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 94u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F1; return keyControl; } private KeyControl Initialize_ctrlKeyboardf2(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 98).WithParent(parent) .WithName("f2") .WithDisplayName("F2") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 95u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F2; return keyControl; } private KeyControl Initialize_ctrlKeyboardf3(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 99).WithParent(parent) .WithName("f3") .WithDisplayName("F3") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 96u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F3; return keyControl; } private KeyControl Initialize_ctrlKeyboardf4(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 100).WithParent(parent) .WithName("f4") .WithDisplayName("F4") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 97u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F4; return keyControl; } private KeyControl Initialize_ctrlKeyboardf5(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 101).WithParent(parent) .WithName("f5") .WithDisplayName("F5") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 98u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F5; return keyControl; } private KeyControl Initialize_ctrlKeyboardf6(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 102).WithParent(parent) .WithName("f6") .WithDisplayName("F6") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 99u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F6; return keyControl; } private KeyControl Initialize_ctrlKeyboardf7(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 103).WithParent(parent) .WithName("f7") .WithDisplayName("F7") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 100u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F7; return keyControl; } private KeyControl Initialize_ctrlKeyboardf8(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 104).WithParent(parent) .WithName("f8") .WithDisplayName("F8") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 101u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F8; return keyControl; } private KeyControl Initialize_ctrlKeyboardf9(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 105).WithParent(parent) .WithName("f9") .WithDisplayName("F9") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 102u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F9; return keyControl; } private KeyControl Initialize_ctrlKeyboardf10(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 106).WithParent(parent) .WithName("f10") .WithDisplayName("F10") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 103u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F10; return keyControl; } private KeyControl Initialize_ctrlKeyboardf11(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 107).WithParent(parent) .WithName("f11") .WithDisplayName("F11") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 104u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F11; return keyControl; } private KeyControl Initialize_ctrlKeyboardf12(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 108).WithParent(parent) .WithName("f12") .WithDisplayName("F12") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 105u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.F12; return keyControl; } private KeyControl Initialize_ctrlKeyboardOEM1(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 109).WithParent(parent) .WithName("OEM1") .WithDisplayName("OEM1") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 106u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.OEM1; return keyControl; } private KeyControl Initialize_ctrlKeyboardOEM2(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 110).WithParent(parent) .WithName("OEM2") .WithDisplayName("OEM2") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 107u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.OEM2; return keyControl; } private KeyControl Initialize_ctrlKeyboardOEM3(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 111).WithParent(parent) .WithName("OEM3") .WithDisplayName("OEM3") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 108u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.OEM3; return keyControl; } private KeyControl Initialize_ctrlKeyboardOEM4(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 112).WithParent(parent) .WithName("OEM4") .WithDisplayName("OEM4") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 109u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.OEM4; return keyControl; } private KeyControl Initialize_ctrlKeyboardOEM5(InternedString kKeyLayout, InputControl parent) { KeyControl keyControl = new KeyControl(); keyControl.Setup().At(this, 113).WithParent(parent) .WithName("OEM5") .WithDisplayName("OEM5") .WithLayout(kKeyLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 110u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); keyControl.keyCode = Key.OEM5; return keyControl; } private ButtonControl Initialize_ctrlKeyboardIMESelected(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 114).WithParent(parent) .WithName("IMESelected") .WithDisplayName("IMESelected") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 0u, bitOffset = 111u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } } internal class FastMouse : Mouse, IInputStateCallbackReceiver, IEventMerger { public const string metadata = "AutoWindowSpace;Vector2;Delta;Button;Axis;Digital;Integer;Mouse;Pointer"; public FastMouse() { InputControlExtensions.DeviceBuilder deviceBuilder = this.Setup(30, 10, 2).WithName("Mouse").WithDisplayName("Mouse") .WithChildren(0, 14) .WithLayout(new InternedString("Mouse")) .WithStateBlock(new InputStateBlock { format = new FourCC(1297044819), sizeInBits = 392u }); InternedString kVector2Layout = new InternedString("Vector2"); InternedString kDeltaLayout = new InternedString("Delta"); InternedString kButtonLayout = new InternedString("Button"); InternedString kAxisLayout = new InternedString("Axis"); InternedString kDigitalLayout = new InternedString("Digital"); InternedString kIntegerLayout = new InternedString("Integer"); Vector2Control vector2Control = Initialize_ctrlMouseposition(kVector2Layout, this); DeltaControl deltaControl = Initialize_ctrlMousedelta(kDeltaLayout, this); DeltaControl deltaControl2 = Initialize_ctrlMousescroll(kDeltaLayout, this); ButtonControl buttonControl = Initialize_ctrlMousepress(kButtonLayout, this); ButtonControl control = Initialize_ctrlMouseleftButton(kButtonLayout, this); ButtonControl control2 = Initialize_ctrlMouserightButton(kButtonLayout, this); ButtonControl buttonControl2 = Initialize_ctrlMousemiddleButton(kButtonLayout, this); ButtonControl control3 = Initialize_ctrlMouseforwardButton(kButtonLayout, this); ButtonControl control4 = Initialize_ctrlMousebackButton(kButtonLayout, this); AxisControl control5 = Initialize_ctrlMousepressure(kAxisLayout, this); Vector2Control vector2Control2 = Initialize_ctrlMouseradius(kVector2Layout, this); Initialize_ctrlMousepointerId(kDigitalLayout, this); IntegerControl integerControl = Initialize_ctrlMousedisplayIndex(kIntegerLayout, this); IntegerControl integerControl2 = Initialize_ctrlMouseclickCount(kIntegerLayout, this); AxisControl x = Initialize_ctrlMousepositionx(kAxisLayout, vector2Control); AxisControl y = Initialize_ctrlMousepositiony(kAxisLayout, vector2Control); AxisControl up = Initialize_ctrlMousedeltaup(kAxisLayout, deltaControl); AxisControl down = Initialize_ctrlMousedeltadown(kAxisLayout, deltaControl); AxisControl left = Initialize_ctrlMousedeltaleft(kAxisLayout, deltaControl); AxisControl right = Initialize_ctrlMousedeltaright(kAxisLayout, deltaControl); AxisControl x2 = Initialize_ctrlMousedeltax(kAxisLayout, deltaControl); AxisControl y2 = Initialize_ctrlMousedeltay(kAxisLayout, deltaControl); AxisControl up2 = Initialize_ctrlMousescrollup(kAxisLayout, deltaControl2); AxisControl down2 = Initialize_ctrlMousescrolldown(kAxisLayout, deltaControl2); AxisControl left2 = Initialize_ctrlMousescrollleft(kAxisLayout, deltaControl2); AxisControl right2 = Initialize_ctrlMousescrollright(kAxisLayout, deltaControl2); AxisControl axisControl = Initialize_ctrlMousescrollx(kAxisLayout, deltaControl2); AxisControl axisControl2 = Initialize_ctrlMousescrolly(kAxisLayout, deltaControl2); AxisControl x3 = Initialize_ctrlMouseradiusx(kAxisLayout, vector2Control2); AxisControl y3 = Initialize_ctrlMouseradiusy(kAxisLayout, vector2Control2); deviceBuilder.WithControlUsage(0, new InternedString("Point"), vector2Control); deviceBuilder.WithControlUsage(1, new InternedString("Secondary2DMotion"), deltaControl); deviceBuilder.WithControlUsage(2, new InternedString("ScrollHorizontal"), axisControl); deviceBuilder.WithControlUsage(3, new InternedString("ScrollVertical"), axisControl2); deviceBuilder.WithControlUsage(4, new InternedString("PrimaryAction"), control); deviceBuilder.WithControlUsage(5, new InternedString("SecondaryAction"), control2); deviceBuilder.WithControlUsage(6, new InternedString("Forward"), control3); deviceBuilder.WithControlUsage(7, new InternedString("Back"), control4); deviceBuilder.WithControlUsage(8, new InternedString("Pressure"), control5); deviceBuilder.WithControlUsage(9, new InternedString("Radius"), vector2Control2); deviceBuilder.WithControlAlias(0, new InternedString("horizontal")); deviceBuilder.WithControlAlias(1, new InternedString("vertical")); base.scroll = deltaControl2; base.leftButton = control; base.middleButton = buttonControl2; base.rightButton = control2; base.backButton = control4; base.forwardButton = control3; base.clickCount = integerControl2; base.position = vector2Control; base.delta = deltaControl; base.radius = vector2Control2; base.pressure = control5; base.press = buttonControl; base.displayIndex = integerControl; vector2Control.x = x; vector2Control.y = y; deltaControl.up = up; deltaControl.down = down; deltaControl.left = left; deltaControl.right = right; deltaControl.x = x2; deltaControl.y = y2; deltaControl2.up = up2; deltaControl2.down = down2; deltaControl2.left = left2; deltaControl2.right = right2; deltaControl2.x = axisControl; deltaControl2.y = axisControl2; vector2Control2.x = x3; vector2Control2.y = y3; deviceBuilder.WithStateOffsetToControlIndexMap(new uint[26] { 32782u, 16809999u, 33587218u, 33587219u, 33587220u, 50364432u, 50364433u, 50364437u, 67141656u, 67141657u, 67141658u, 83918870u, 83918871u, 83918875u, 100664323u, 100664324u, 101188613u, 101712902u, 102237191u, 102761480u, 109068300u, 117456909u, 134250505u, 167804956u, 184582173u, 201327627u }); deviceBuilder.WithControlTree(new byte[371] { 135, 1, 1, 0, 0, 0, 0, 196, 0, 3, 0, 0, 0, 0, 135, 1, 23, 0, 0, 0, 0, 128, 0, 5, 0, 0, 0, 0, 196, 0, 11, 0, 0, 0, 0, 64, 0, 7, 0, 0, 0, 1, 128, 0, 9, 0, 3, 0, 1, 32, 0, 255, 255, 1, 0, 1, 64, 0, 255, 255, 2, 0, 1, 96, 0, 255, 255, 7, 0, 3, 128, 0, 255, 255, 4, 0, 3, 193, 0, 13, 0, 0, 0, 0, 196, 0, 19, 0, 0, 0, 0, 161, 0, 15, 0, 10, 0, 4, 193, 0, 17, 0, 14, 0, 4, 145, 0, 255, 255, 18, 0, 3, 161, 0, 255, 255, 21, 0, 3, 192, 0, 255, 255, 0, 0, 0, 193, 0, 255, 255, 24, 0, 2, 195, 0, 21, 0, 0, 0, 0, 196, 0, 255, 255, 28, 0, 1, 194, 0, 255, 255, 26, 0, 1, 195, 0, 255, 255, 27, 0, 1, 32, 1, 25, 0, 0, 0, 0, 135, 1, 41, 0, 0, 0, 0, 240, 0, 27, 0, 0, 0, 0, 32, 1, 39, 0, 0, 0, 0, 224, 0, 29, 0, 0, 0, 0, 240, 0, 255, 255, 41, 0, 1, 210, 0, 31, 0, 39, 0, 1, 224, 0, 255, 255, 40, 0, 1, 203, 0, 33, 0, 0, 0, 0, 210, 0, 255, 255, 0, 0, 0, 200, 0, 35, 0, 0, 0, 0, 203, 0, 255, 255, 0, 0, 0, 198, 0, 37, 0, 0, 0, 0, 200, 0, 255, 255, 0, 0, 0, 197, 0, 255, 255, 29, 0, 1, 198, 0, 255, 255, 0, 0, 0, 8, 1, 255, 255, 30, 0, 1, 32, 1, 255, 255, 31, 0, 1, 128, 1, 43, 0, 0, 0, 0, 135, 1, 47, 0, 0, 0, 0, 80, 1, 255, 255, 32, 0, 2, 128, 1, 45, 0, 34, 0, 2, 104, 1, 255, 255, 36, 0, 1, 128, 1, 255, 255, 37, 0, 1, 132, 1, 49, 0, 0, 0, 0, 135, 1, 255, 255, 0, 0, 0, 130, 1, 51, 0, 0, 0, 0, 132, 1, 255, 255, 0, 0, 0, 129, 1, 255, 255, 38, 0, 1, 130, 1, 255, 255, 0, 0, 0 }, new ushort[42] { 0, 14, 15, 1, 16, 17, 21, 18, 19, 20, 2, 22, 23, 27, 2, 22, 23, 27, 24, 25, 26, 24, 25, 26, 3, 4, 5, 6, 7, 8, 9, 9, 10, 28, 10, 28, 29, 29, 11, 12, 12, 13 }); deviceBuilder.Finish(); } private Vector2Control Initialize_ctrlMouseposition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 0).WithParent(parent) .WithChildren(14, 2) .WithName("position") .WithDisplayName("Position") .WithLayout(kVector2Layout) .WithUsages(0, 1) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 0u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlMousedelta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 1).WithParent(parent) .WithChildren(16, 6) .WithName("delta") .WithDisplayName("Delta") .WithLayout(kDeltaLayout) .WithUsages(1, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 8u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private DeltaControl Initialize_ctrlMousescroll(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 2).WithParent(parent) .WithChildren(22, 6) .WithName("scroll") .WithDisplayName("Scroll") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 16u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private ButtonControl Initialize_ctrlMousepress(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 3).WithParent(parent) .WithName("press") .WithDisplayName("Press") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 24u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlMouseleftButton(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 4).WithParent(parent) .WithName("leftButton") .WithDisplayName("Left Button") .WithShortDisplayName("LMB") .WithLayout(kButtonLayout) .WithUsages(4, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 24u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlMouserightButton(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 5).WithParent(parent) .WithName("rightButton") .WithDisplayName("Right Button") .WithShortDisplayName("RMB") .WithLayout(kButtonLayout) .WithUsages(5, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 24u, bitOffset = 1u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlMousemiddleButton(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 6).WithParent(parent) .WithName("middleButton") .WithDisplayName("Middle Button") .WithShortDisplayName("MMB") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 24u, bitOffset = 2u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlMouseforwardButton(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 7).WithParent(parent) .WithName("forwardButton") .WithDisplayName("Forward") .WithLayout(kButtonLayout) .WithUsages(6, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 24u, bitOffset = 3u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlMousebackButton(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 8).WithParent(parent) .WithName("backButton") .WithDisplayName("Back") .WithLayout(kButtonLayout) .WithUsages(7, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 24u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private AxisControl Initialize_ctrlMousepressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 9).WithParent(parent) .WithName("pressure") .WithDisplayName("Pressure") .WithLayout(kAxisLayout) .WithUsages(8, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 32u, bitOffset = 0u, sizeInBits = 32u }) .WithDefaultState(1) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlMouseradius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 10).WithParent(parent) .WithChildren(28, 2) .WithName("radius") .WithDisplayName("Radius") .WithLayout(kVector2Layout) .WithUsages(9, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 40u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private IntegerControl Initialize_ctrlMousepointerId(InternedString kDigitalLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 11).WithParent(parent) .WithName("pointerId") .WithDisplayName("pointerId") .WithLayout(kDigitalLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 48u, bitOffset = 0u, sizeInBits = 1u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlMousedisplayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 12).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1431521364), byteOffset = 26u, bitOffset = 0u, sizeInBits = 16u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlMouseclickCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 13).WithParent(parent) .WithName("clickCount") .WithDisplayName("Click Count") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1431521364), byteOffset = 28u, bitOffset = 0u, sizeInBits = 16u }) .Finish(); return integerControl; } private AxisControl Initialize_ctrlMousepositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 14).WithParent(parent) .WithName("x") .WithDisplayName("Position X") .WithShortDisplayName("Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 0u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMousepositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 15).WithParent(parent) .WithName("y") .WithDisplayName("Position Y") .WithShortDisplayName("Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 4u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMousedeltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 16).WithParent(parent) .WithName("up") .WithDisplayName("Delta Up") .WithShortDisplayName("Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousedeltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 17).WithParent(parent) .WithName("down") .WithDisplayName("Delta Down") .WithShortDisplayName("Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousedeltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 18).WithParent(parent) .WithName("left") .WithDisplayName("Delta Left") .WithShortDisplayName("Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 8u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousedeltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 19).WithParent(parent) .WithName("right") .WithDisplayName("Delta Right") .WithShortDisplayName("Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 8u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousedeltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 20).WithParent(parent) .WithName("x") .WithDisplayName("Delta X") .WithShortDisplayName("Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 8u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMousedeltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 21).WithParent(parent) .WithName("y") .WithDisplayName("Delta Y") .WithShortDisplayName("Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMousescrollup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 22).WithParent(parent) .WithName("up") .WithDisplayName("Scroll Up") .WithShortDisplayName("Scroll Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 20u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousescrolldown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 23).WithParent(parent) .WithName("down") .WithDisplayName("Scroll Down") .WithShortDisplayName("Scroll Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 20u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousescrollleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 24).WithParent(parent) .WithName("left") .WithDisplayName("Scroll Left") .WithShortDisplayName("Scroll Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousescrollright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 25).WithParent(parent) .WithName("right") .WithDisplayName("Scroll Right") .WithShortDisplayName("Scroll Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlMousescrollx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 26).WithParent(parent) .WithName("x") .WithDisplayName("Scroll Left/Right") .WithShortDisplayName("Scroll Left/Right") .WithLayout(kAxisLayout) .WithUsages(2, 1) .WithAliases(0, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMousescrolly(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 27).WithParent(parent) .WithName("y") .WithDisplayName("Scroll Up/Down") .WithShortDisplayName("Scroll Wheel") .WithLayout(kAxisLayout) .WithUsages(3, 1) .WithAliases(1, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 20u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMouseradiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 28).WithParent(parent) .WithName("x") .WithDisplayName("Radius X") .WithShortDisplayName("Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 40u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlMouseradiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 29).WithParent(parent) .WithName("y") .WithDisplayName("Radius Y") .WithShortDisplayName("Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 44u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } protected new void OnNextUpdate() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) InputState.Change((InputControl)base.delta, Vector2.zero, InputState.currentUpdateType, default(InputEventPtr)); InputState.Change((InputControl)base.scroll, Vector2.zero, InputState.currentUpdateType, default(InputEventPtr)); } protected new unsafe void OnStateEvent(InputEventPtr eventPtr) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) if (eventPtr.type != 1398030676) { base.OnStateEvent(eventPtr); return; } StateEvent* ptr = StateEvent.FromUnchecked(eventPtr); if (ptr->stateFormat != MouseState.Format) { base.OnStateEvent(eventPtr); return; } MouseState state = Unsafe.Read(ptr->state); MouseState* ptr2 = (MouseState*)((byte*)base.currentStatePtr + m_StateBlock.byteOffset); ref Vector2 reference = ref state.delta; reference += ptr2->delta; ref Vector2 reference2 = ref state.scroll; reference2 += ptr2->scroll; InputState.Change(this, ref state, InputState.currentUpdateType, eventPtr); } void IInputStateCallbackReceiver.OnNextUpdate() { OnNextUpdate(); } void IInputStateCallbackReceiver.OnStateEvent(InputEventPtr eventPtr) { OnStateEvent(eventPtr); } internal unsafe static bool MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) if (currentEventPtr.type != 1398030676 || nextEventPtr.type != 1398030676) { return false; } StateEvent* ptr = StateEvent.FromUnchecked(currentEventPtr); StateEvent* ptr2 = StateEvent.FromUnchecked(nextEventPtr); if (ptr->stateFormat != MouseState.Format || ptr2->stateFormat != MouseState.Format) { return false; } MouseState* state = (MouseState*)ptr->state; MouseState* state2 = (MouseState*)ptr2->state; if (state->buttons != state2->buttons || state->clickCount != state2->clickCount) { return false; } Vector2* intPtr = &state2->delta; Unsafe.Write(intPtr, *intPtr + state->delta); Vector2* intPtr2 = &state2->scroll; Unsafe.Write(intPtr2, *intPtr2 + state->scroll); return true; } bool IEventMerger.MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr) { return MergeForward(currentEventPtr, nextEventPtr); } } internal class FastTouchscreen : Touchscreen { public const string metadata = "AutoWindowSpace;Touch;Vector2;Delta;Analog;TouchPress;Button;Axis;Integer;TouchPhase;Double;Touchscreen;Pointer"; public FastTouchscreen() { InputControlExtensions.DeviceBuilder deviceBuilder = this.Setup(302, 5, 0).WithName("Touchscreen").WithDisplayName("Touchscreen") .WithChildren(0, 17) .WithLayout(new InternedString("Touchscreen")) .WithStateBlock(new InputStateBlock { format = new FourCC(1414742866), sizeInBits = 4928u }); InternedString kTouchLayout = new InternedString("Touch"); InternedString kVector2Layout = new InternedString("Vector2"); InternedString kDeltaLayout = new InternedString("Delta"); InternedString kAnalogLayout = new InternedString("Analog"); InternedString kTouchPressLayout = new InternedString("TouchPress"); InternedString kIntegerLayout = new InternedString("Integer"); InternedString kAxisLayout = new InternedString("Axis"); InternedString kTouchPhaseLayout = new InternedString("TouchPhase"); InternedString kButtonLayout = new InternedString("Button"); InternedString kDoubleLayout = new InternedString("Double"); TouchControl touchControl = Initialize_ctrlTouchscreenprimaryTouch(kTouchLayout, this); Vector2Control vector2Control = Initialize_ctrlTouchscreenposition(kVector2Layout, this); DeltaControl deltaControl = Initialize_ctrlTouchscreendelta(kDeltaLayout, this); AxisControl control = Initialize_ctrlTouchscreenpressure(kAnalogLayout, this); Vector2Control vector2Control2 = Initialize_ctrlTouchscreenradius(kVector2Layout, this); TouchPressControl touchPressControl = Initialize_ctrlTouchscreenpress(kTouchPressLayout, this); TouchControl touchControl2 = Initialize_ctrlTouchscreentouch0(kTouchLayout, this); TouchControl touchControl3 = Initialize_ctrlTouchscreentouch1(kTouchLayout, this); TouchControl touchControl4 = Initialize_ctrlTouchscreentouch2(kTouchLayout, this); TouchControl touchControl5 = Initialize_ctrlTouchscreentouch3(kTouchLayout, this); TouchControl touchControl6 = Initialize_ctrlTouchscreentouch4(kTouchLayout, this); TouchControl touchControl7 = Initialize_ctrlTouchscreentouch5(kTouchLayout, this); TouchControl touchControl8 = Initialize_ctrlTouchscreentouch6(kTouchLayout, this); TouchControl touchControl9 = Initialize_ctrlTouchscreentouch7(kTouchLayout, this); TouchControl touchControl10 = Initialize_ctrlTouchscreentouch8(kTouchLayout, this); TouchControl touchControl11 = Initialize_ctrlTouchscreentouch9(kTouchLayout, this); Initialize_ctrlTouchscreendisplayIndex(kIntegerLayout, this); IntegerControl touchId = Initialize_ctrlTouchscreenprimaryTouchtouchId(kIntegerLayout, touchControl); Vector2Control vector2Control3 = Initialize_ctrlTouchscreenprimaryTouchposition(kVector2Layout, touchControl); DeltaControl deltaControl2 = Initialize_ctrlTouchscreenprimaryTouchdelta(kDeltaLayout, touchControl); AxisControl axisControl = Initialize_ctrlTouchscreenprimaryTouchpressure(kAxisLayout, touchControl); Vector2Control vector2Control4 = Initialize_ctrlTouchscreenprimaryTouchradius(kVector2Layout, touchControl); TouchPhaseControl phase = Initialize_ctrlTouchscreenprimaryTouchphase(kTouchPhaseLayout, touchControl); TouchPressControl touchPressControl2 = Initialize_ctrlTouchscreenprimaryTouchpress(kTouchPressLayout, touchControl); IntegerControl tapCount = Initialize_ctrlTouchscreenprimaryTouchtapCount(kIntegerLayout, touchControl); IntegerControl integerControl = Initialize_ctrlTouchscreenprimaryTouchdisplayIndex(kIntegerLayout, touchControl); ButtonControl indirectTouch = Initialize_ctrlTouchscreenprimaryTouchindirectTouch(kButtonLayout, touchControl); ButtonControl buttonControl = Initialize_ctrlTouchscreenprimaryTouchtap(kButtonLayout, touchControl); DoubleControl startTime = Initialize_ctrlTouchscreenprimaryTouchstartTime(kDoubleLayout, touchControl); Vector2Control vector2Control5 = Initialize_ctrlTouchscreenprimaryTouchstartPosition(kVector2Layout, touchControl); AxisControl x = Initialize_ctrlTouchscreenprimaryTouchpositionx(kAxisLayout, vector2Control3); AxisControl y = Initialize_ctrlTouchscreenprimaryTouchpositiony(kAxisLayout, vector2Control3); AxisControl up = Initialize_ctrlTouchscreenprimaryTouchdeltaup(kAxisLayout, deltaControl2); AxisControl down = Initialize_ctrlTouchscreenprimaryTouchdeltadown(kAxisLayout, deltaControl2); AxisControl left = Initialize_ctrlTouchscreenprimaryTouchdeltaleft(kAxisLayout, deltaControl2); AxisControl right = Initialize_ctrlTouchscreenprimaryTouchdeltaright(kAxisLayout, deltaControl2); AxisControl x2 = Initialize_ctrlTouchscreenprimaryTouchdeltax(kAxisLayout, deltaControl2); AxisControl y2 = Initialize_ctrlTouchscreenprimaryTouchdeltay(kAxisLayout, deltaControl2); AxisControl x3 = Initialize_ctrlTouchscreenprimaryTouchradiusx(kAxisLayout, vector2Control4); AxisControl y3 = Initialize_ctrlTouchscreenprimaryTouchradiusy(kAxisLayout, vector2Control4); AxisControl x4 = Initialize_ctrlTouchscreenprimaryTouchstartPositionx(kAxisLayout, vector2Control5); AxisControl y4 = Initialize_ctrlTouchscreenprimaryTouchstartPositiony(kAxisLayout, vector2Control5); AxisControl x5 = Initialize_ctrlTouchscreenpositionx(kAxisLayout, vector2Control); AxisControl y5 = Initialize_ctrlTouchscreenpositiony(kAxisLayout, vector2Control); AxisControl up2 = Initialize_ctrlTouchscreendeltaup(kAxisLayout, deltaControl); AxisControl down2 = Initialize_ctrlTouchscreendeltadown(kAxisLayout, deltaControl); AxisControl left2 = Initialize_ctrlTouchscreendeltaleft(kAxisLayout, deltaControl); AxisControl right2 = Initialize_ctrlTouchscreendeltaright(kAxisLayout, deltaControl); AxisControl x6 = Initialize_ctrlTouchscreendeltax(kAxisLayout, deltaControl); AxisControl y6 = Initialize_ctrlTouchscreendeltay(kAxisLayout, deltaControl); AxisControl x7 = Initialize_ctrlTouchscreenradiusx(kAxisLayout, vector2Control2); AxisControl y7 = Initialize_ctrlTouchscreenradiusy(kAxisLayout, vector2Control2); IntegerControl touchId2 = Initialize_ctrlTouchscreentouch0touchId(kIntegerLayout, touchControl2); Vector2Control vector2Control6 = Initialize_ctrlTouchscreentouch0position(kVector2Layout, touchControl2); DeltaControl deltaControl3 = Initialize_ctrlTouchscreentouch0delta(kDeltaLayout, touchControl2); AxisControl axisControl2 = Initialize_ctrlTouchscreentouch0pressure(kAxisLayout, touchControl2); Vector2Control vector2Control7 = Initialize_ctrlTouchscreentouch0radius(kVector2Layout, touchControl2); TouchPhaseControl phase2 = Initialize_ctrlTouchscreentouch0phase(kTouchPhaseLayout, touchControl2); TouchPressControl touchPressControl3 = Initialize_ctrlTouchscreentouch0press(kTouchPressLayout, touchControl2); IntegerControl tapCount2 = Initialize_ctrlTouchscreentouch0tapCount(kIntegerLayout, touchControl2); IntegerControl integerControl2 = Initialize_ctrlTouchscreentouch0displayIndex(kIntegerLayout, touchControl2); ButtonControl indirectTouch2 = Initialize_ctrlTouchscreentouch0indirectTouch(kButtonLayout, touchControl2); ButtonControl tap = Initialize_ctrlTouchscreentouch0tap(kButtonLayout, touchControl2); DoubleControl startTime2 = Initialize_ctrlTouchscreentouch0startTime(kDoubleLayout, touchControl2); Vector2Control vector2Control8 = Initialize_ctrlTouchscreentouch0startPosition(kVector2Layout, touchControl2); AxisControl x8 = Initialize_ctrlTouchscreentouch0positionx(kAxisLayout, vector2Control6); AxisControl y8 = Initialize_ctrlTouchscreentouch0positiony(kAxisLayout, vector2Control6); AxisControl up3 = Initialize_ctrlTouchscreentouch0deltaup(kAxisLayout, deltaControl3); AxisControl down3 = Initialize_ctrlTouchscreentouch0deltadown(kAxisLayout, deltaControl3); AxisControl left3 = Initialize_ctrlTouchscreentouch0deltaleft(kAxisLayout, deltaControl3); AxisControl right3 = Initialize_ctrlTouchscreentouch0deltaright(kAxisLayout, deltaControl3); AxisControl x9 = Initialize_ctrlTouchscreentouch0deltax(kAxisLayout, deltaControl3); AxisControl y9 = Initialize_ctrlTouchscreentouch0deltay(kAxisLayout, deltaControl3); AxisControl x10 = Initialize_ctrlTouchscreentouch0radiusx(kAxisLayout, vector2Control7); AxisControl y10 = Initialize_ctrlTouchscreentouch0radiusy(kAxisLayout, vector2Control7); AxisControl x11 = Initialize_ctrlTouchscreentouch0startPositionx(kAxisLayout, vector2Control8); AxisControl y11 = Initialize_ctrlTouchscreentouch0startPositiony(kAxisLayout, vector2Control8); IntegerControl touchId3 = Initialize_ctrlTouchscreentouch1touchId(kIntegerLayout, touchControl3); Vector2Control vector2Control9 = Initialize_ctrlTouchscreentouch1position(kVector2Layout, touchControl3); DeltaControl deltaControl4 = Initialize_ctrlTouchscreentouch1delta(kDeltaLayout, touchControl3); AxisControl axisControl3 = Initialize_ctrlTouchscreentouch1pressure(kAxisLayout, touchControl3); Vector2Control vector2Control10 = Initialize_ctrlTouchscreentouch1radius(kVector2Layout, touchControl3); TouchPhaseControl phase3 = Initialize_ctrlTouchscreentouch1phase(kTouchPhaseLayout, touchControl3); TouchPressControl touchPressControl4 = Initialize_ctrlTouchscreentouch1press(kTouchPressLayout, touchControl3); IntegerControl tapCount3 = Initialize_ctrlTouchscreentouch1tapCount(kIntegerLayout, touchControl3); IntegerControl integerControl3 = Initialize_ctrlTouchscreentouch1displayIndex(kIntegerLayout, touchControl3); ButtonControl indirectTouch3 = Initialize_ctrlTouchscreentouch1indirectTouch(kButtonLayout, touchControl3); ButtonControl tap2 = Initialize_ctrlTouchscreentouch1tap(kButtonLayout, touchControl3); DoubleControl startTime3 = Initialize_ctrlTouchscreentouch1startTime(kDoubleLayout, touchControl3); Vector2Control vector2Control11 = Initialize_ctrlTouchscreentouch1startPosition(kVector2Layout, touchControl3); AxisControl x12 = Initialize_ctrlTouchscreentouch1positionx(kAxisLayout, vector2Control9); AxisControl y12 = Initialize_ctrlTouchscreentouch1positiony(kAxisLayout, vector2Control9); AxisControl up4 = Initialize_ctrlTouchscreentouch1deltaup(kAxisLayout, deltaControl4); AxisControl down4 = Initialize_ctrlTouchscreentouch1deltadown(kAxisLayout, deltaControl4); AxisControl left4 = Initialize_ctrlTouchscreentouch1deltaleft(kAxisLayout, deltaControl4); AxisControl right4 = Initialize_ctrlTouchscreentouch1deltaright(kAxisLayout, deltaControl4); AxisControl x13 = Initialize_ctrlTouchscreentouch1deltax(kAxisLayout, deltaControl4); AxisControl y13 = Initialize_ctrlTouchscreentouch1deltay(kAxisLayout, deltaControl4); AxisControl x14 = Initialize_ctrlTouchscreentouch1radiusx(kAxisLayout, vector2Control10); AxisControl y14 = Initialize_ctrlTouchscreentouch1radiusy(kAxisLayout, vector2Control10); AxisControl x15 = Initialize_ctrlTouchscreentouch1startPositionx(kAxisLayout, vector2Control11); AxisControl y15 = Initialize_ctrlTouchscreentouch1startPositiony(kAxisLayout, vector2Control11); IntegerControl touchId4 = Initialize_ctrlTouchscreentouch2touchId(kIntegerLayout, touchControl4); Vector2Control vector2Control12 = Initialize_ctrlTouchscreentouch2position(kVector2Layout, touchControl4); DeltaControl deltaControl5 = Initialize_ctrlTouchscreentouch2delta(kDeltaLayout, touchControl4); AxisControl axisControl4 = Initialize_ctrlTouchscreentouch2pressure(kAxisLayout, touchControl4); Vector2Control vector2Control13 = Initialize_ctrlTouchscreentouch2radius(kVector2Layout, touchControl4); TouchPhaseControl phase4 = Initialize_ctrlTouchscreentouch2phase(kTouchPhaseLayout, touchControl4); TouchPressControl touchPressControl5 = Initialize_ctrlTouchscreentouch2press(kTouchPressLayout, touchControl4); IntegerControl tapCount4 = Initialize_ctrlTouchscreentouch2tapCount(kIntegerLayout, touchControl4); IntegerControl integerControl4 = Initialize_ctrlTouchscreentouch2displayIndex(kIntegerLayout, touchControl4); ButtonControl indirectTouch4 = Initialize_ctrlTouchscreentouch2indirectTouch(kButtonLayout, touchControl4); ButtonControl tap3 = Initialize_ctrlTouchscreentouch2tap(kButtonLayout, touchControl4); DoubleControl startTime4 = Initialize_ctrlTouchscreentouch2startTime(kDoubleLayout, touchControl4); Vector2Control vector2Control14 = Initialize_ctrlTouchscreentouch2startPosition(kVector2Layout, touchControl4); AxisControl x16 = Initialize_ctrlTouchscreentouch2positionx(kAxisLayout, vector2Control12); AxisControl y16 = Initialize_ctrlTouchscreentouch2positiony(kAxisLayout, vector2Control12); AxisControl up5 = Initialize_ctrlTouchscreentouch2deltaup(kAxisLayout, deltaControl5); AxisControl down5 = Initialize_ctrlTouchscreentouch2deltadown(kAxisLayout, deltaControl5); AxisControl left5 = Initialize_ctrlTouchscreentouch2deltaleft(kAxisLayout, deltaControl5); AxisControl right5 = Initialize_ctrlTouchscreentouch2deltaright(kAxisLayout, deltaControl5); AxisControl x17 = Initialize_ctrlTouchscreentouch2deltax(kAxisLayout, deltaControl5); AxisControl y17 = Initialize_ctrlTouchscreentouch2deltay(kAxisLayout, deltaControl5); AxisControl x18 = Initialize_ctrlTouchscreentouch2radiusx(kAxisLayout, vector2Control13); AxisControl y18 = Initialize_ctrlTouchscreentouch2radiusy(kAxisLayout, vector2Control13); AxisControl x19 = Initialize_ctrlTouchscreentouch2startPositionx(kAxisLayout, vector2Control14); AxisControl y19 = Initialize_ctrlTouchscreentouch2startPositiony(kAxisLayout, vector2Control14); IntegerControl touchId5 = Initialize_ctrlTouchscreentouch3touchId(kIntegerLayout, touchControl5); Vector2Control vector2Control15 = Initialize_ctrlTouchscreentouch3position(kVector2Layout, touchControl5); DeltaControl deltaControl6 = Initialize_ctrlTouchscreentouch3delta(kDeltaLayout, touchControl5); AxisControl axisControl5 = Initialize_ctrlTouchscreentouch3pressure(kAxisLayout, touchControl5); Vector2Control vector2Control16 = Initialize_ctrlTouchscreentouch3radius(kVector2Layout, touchControl5); TouchPhaseControl phase5 = Initialize_ctrlTouchscreentouch3phase(kTouchPhaseLayout, touchControl5); TouchPressControl touchPressControl6 = Initialize_ctrlTouchscreentouch3press(kTouchPressLayout, touchControl5); IntegerControl tapCount5 = Initialize_ctrlTouchscreentouch3tapCount(kIntegerLayout, touchControl5); IntegerControl integerControl5 = Initialize_ctrlTouchscreentouch3displayIndex(kIntegerLayout, touchControl5); ButtonControl indirectTouch5 = Initialize_ctrlTouchscreentouch3indirectTouch(kButtonLayout, touchControl5); ButtonControl tap4 = Initialize_ctrlTouchscreentouch3tap(kButtonLayout, touchControl5); DoubleControl startTime5 = Initialize_ctrlTouchscreentouch3startTime(kDoubleLayout, touchControl5); Vector2Control vector2Control17 = Initialize_ctrlTouchscreentouch3startPosition(kVector2Layout, touchControl5); AxisControl x20 = Initialize_ctrlTouchscreentouch3positionx(kAxisLayout, vector2Control15); AxisControl y20 = Initialize_ctrlTouchscreentouch3positiony(kAxisLayout, vector2Control15); AxisControl up6 = Initialize_ctrlTouchscreentouch3deltaup(kAxisLayout, deltaControl6); AxisControl down6 = Initialize_ctrlTouchscreentouch3deltadown(kAxisLayout, deltaControl6); AxisControl left6 = Initialize_ctrlTouchscreentouch3deltaleft(kAxisLayout, deltaControl6); AxisControl right6 = Initialize_ctrlTouchscreentouch3deltaright(kAxisLayout, deltaControl6); AxisControl x21 = Initialize_ctrlTouchscreentouch3deltax(kAxisLayout, deltaControl6); AxisControl y21 = Initialize_ctrlTouchscreentouch3deltay(kAxisLayout, deltaControl6); AxisControl x22 = Initialize_ctrlTouchscreentouch3radiusx(kAxisLayout, vector2Control16); AxisControl y22 = Initialize_ctrlTouchscreentouch3radiusy(kAxisLayout, vector2Control16); AxisControl x23 = Initialize_ctrlTouchscreentouch3startPositionx(kAxisLayout, vector2Control17); AxisControl y23 = Initialize_ctrlTouchscreentouch3startPositiony(kAxisLayout, vector2Control17); IntegerControl touchId6 = Initialize_ctrlTouchscreentouch4touchId(kIntegerLayout, touchControl6); Vector2Control vector2Control18 = Initialize_ctrlTouchscreentouch4position(kVector2Layout, touchControl6); DeltaControl deltaControl7 = Initialize_ctrlTouchscreentouch4delta(kDeltaLayout, touchControl6); AxisControl axisControl6 = Initialize_ctrlTouchscreentouch4pressure(kAxisLayout, touchControl6); Vector2Control vector2Control19 = Initialize_ctrlTouchscreentouch4radius(kVector2Layout, touchControl6); TouchPhaseControl phase6 = Initialize_ctrlTouchscreentouch4phase(kTouchPhaseLayout, touchControl6); TouchPressControl touchPressControl7 = Initialize_ctrlTouchscreentouch4press(kTouchPressLayout, touchControl6); IntegerControl tapCount6 = Initialize_ctrlTouchscreentouch4tapCount(kIntegerLayout, touchControl6); IntegerControl integerControl6 = Initialize_ctrlTouchscreentouch4displayIndex(kIntegerLayout, touchControl6); ButtonControl indirectTouch6 = Initialize_ctrlTouchscreentouch4indirectTouch(kButtonLayout, touchControl6); ButtonControl tap5 = Initialize_ctrlTouchscreentouch4tap(kButtonLayout, touchControl6); DoubleControl startTime6 = Initialize_ctrlTouchscreentouch4startTime(kDoubleLayout, touchControl6); Vector2Control vector2Control20 = Initialize_ctrlTouchscreentouch4startPosition(kVector2Layout, touchControl6); AxisControl x24 = Initialize_ctrlTouchscreentouch4positionx(kAxisLayout, vector2Control18); AxisControl y24 = Initialize_ctrlTouchscreentouch4positiony(kAxisLayout, vector2Control18); AxisControl up7 = Initialize_ctrlTouchscreentouch4deltaup(kAxisLayout, deltaControl7); AxisControl down7 = Initialize_ctrlTouchscreentouch4deltadown(kAxisLayout, deltaControl7); AxisControl left7 = Initialize_ctrlTouchscreentouch4deltaleft(kAxisLayout, deltaControl7); AxisControl right7 = Initialize_ctrlTouchscreentouch4deltaright(kAxisLayout, deltaControl7); AxisControl x25 = Initialize_ctrlTouchscreentouch4deltax(kAxisLayout, deltaControl7); AxisControl y25 = Initialize_ctrlTouchscreentouch4deltay(kAxisLayout, deltaControl7); AxisControl x26 = Initialize_ctrlTouchscreentouch4radiusx(kAxisLayout, vector2Control19); AxisControl y26 = Initialize_ctrlTouchscreentouch4radiusy(kAxisLayout, vector2Control19); AxisControl x27 = Initialize_ctrlTouchscreentouch4startPositionx(kAxisLayout, vector2Control20); AxisControl y27 = Initialize_ctrlTouchscreentouch4startPositiony(kAxisLayout, vector2Control20); IntegerControl touchId7 = Initialize_ctrlTouchscreentouch5touchId(kIntegerLayout, touchControl7); Vector2Control vector2Control21 = Initialize_ctrlTouchscreentouch5position(kVector2Layout, touchControl7); DeltaControl deltaControl8 = Initialize_ctrlTouchscreentouch5delta(kDeltaLayout, touchControl7); AxisControl axisControl7 = Initialize_ctrlTouchscreentouch5pressure(kAxisLayout, touchControl7); Vector2Control vector2Control22 = Initialize_ctrlTouchscreentouch5radius(kVector2Layout, touchControl7); TouchPhaseControl phase7 = Initialize_ctrlTouchscreentouch5phase(kTouchPhaseLayout, touchControl7); TouchPressControl touchPressControl8 = Initialize_ctrlTouchscreentouch5press(kTouchPressLayout, touchControl7); IntegerControl tapCount7 = Initialize_ctrlTouchscreentouch5tapCount(kIntegerLayout, touchControl7); IntegerControl integerControl7 = Initialize_ctrlTouchscreentouch5displayIndex(kIntegerLayout, touchControl7); ButtonControl indirectTouch7 = Initialize_ctrlTouchscreentouch5indirectTouch(kButtonLayout, touchControl7); ButtonControl tap6 = Initialize_ctrlTouchscreentouch5tap(kButtonLayout, touchControl7); DoubleControl startTime7 = Initialize_ctrlTouchscreentouch5startTime(kDoubleLayout, touchControl7); Vector2Control vector2Control23 = Initialize_ctrlTouchscreentouch5startPosition(kVector2Layout, touchControl7); AxisControl x28 = Initialize_ctrlTouchscreentouch5positionx(kAxisLayout, vector2Control21); AxisControl y28 = Initialize_ctrlTouchscreentouch5positiony(kAxisLayout, vector2Control21); AxisControl up8 = Initialize_ctrlTouchscreentouch5deltaup(kAxisLayout, deltaControl8); AxisControl down8 = Initialize_ctrlTouchscreentouch5deltadown(kAxisLayout, deltaControl8); AxisControl left8 = Initialize_ctrlTouchscreentouch5deltaleft(kAxisLayout, deltaControl8); AxisControl right8 = Initialize_ctrlTouchscreentouch5deltaright(kAxisLayout, deltaControl8); AxisControl x29 = Initialize_ctrlTouchscreentouch5deltax(kAxisLayout, deltaControl8); AxisControl y29 = Initialize_ctrlTouchscreentouch5deltay(kAxisLayout, deltaControl8); AxisControl x30 = Initialize_ctrlTouchscreentouch5radiusx(kAxisLayout, vector2Control22); AxisControl y30 = Initialize_ctrlTouchscreentouch5radiusy(kAxisLayout, vector2Control22); AxisControl x31 = Initialize_ctrlTouchscreentouch5startPositionx(kAxisLayout, vector2Control23); AxisControl y31 = Initialize_ctrlTouchscreentouch5startPositiony(kAxisLayout, vector2Control23); IntegerControl touchId8 = Initialize_ctrlTouchscreentouch6touchId(kIntegerLayout, touchControl8); Vector2Control vector2Control24 = Initialize_ctrlTouchscreentouch6position(kVector2Layout, touchControl8); DeltaControl deltaControl9 = Initialize_ctrlTouchscreentouch6delta(kDeltaLayout, touchControl8); AxisControl axisControl8 = Initialize_ctrlTouchscreentouch6pressure(kAxisLayout, touchControl8); Vector2Control vector2Control25 = Initialize_ctrlTouchscreentouch6radius(kVector2Layout, touchControl8); TouchPhaseControl phase8 = Initialize_ctrlTouchscreentouch6phase(kTouchPhaseLayout, touchControl8); TouchPressControl touchPressControl9 = Initialize_ctrlTouchscreentouch6press(kTouchPressLayout, touchControl8); IntegerControl tapCount8 = Initialize_ctrlTouchscreentouch6tapCount(kIntegerLayout, touchControl8); IntegerControl integerControl8 = Initialize_ctrlTouchscreentouch6displayIndex(kIntegerLayout, touchControl8); ButtonControl indirectTouch8 = Initialize_ctrlTouchscreentouch6indirectTouch(kButtonLayout, touchControl8); ButtonControl tap7 = Initialize_ctrlTouchscreentouch6tap(kButtonLayout, touchControl8); DoubleControl startTime8 = Initialize_ctrlTouchscreentouch6startTime(kDoubleLayout, touchControl8); Vector2Control vector2Control26 = Initialize_ctrlTouchscreentouch6startPosition(kVector2Layout, touchControl8); AxisControl x32 = Initialize_ctrlTouchscreentouch6positionx(kAxisLayout, vector2Control24); AxisControl y32 = Initialize_ctrlTouchscreentouch6positiony(kAxisLayout, vector2Control24); AxisControl up9 = Initialize_ctrlTouchscreentouch6deltaup(kAxisLayout, deltaControl9); AxisControl down9 = Initialize_ctrlTouchscreentouch6deltadown(kAxisLayout, deltaControl9); AxisControl left9 = Initialize_ctrlTouchscreentouch6deltaleft(kAxisLayout, deltaControl9); AxisControl right9 = Initialize_ctrlTouchscreentouch6deltaright(kAxisLayout, deltaControl9); AxisControl x33 = Initialize_ctrlTouchscreentouch6deltax(kAxisLayout, deltaControl9); AxisControl y33 = Initialize_ctrlTouchscreentouch6deltay(kAxisLayout, deltaControl9); AxisControl x34 = Initialize_ctrlTouchscreentouch6radiusx(kAxisLayout, vector2Control25); AxisControl y34 = Initialize_ctrlTouchscreentouch6radiusy(kAxisLayout, vector2Control25); AxisControl x35 = Initialize_ctrlTouchscreentouch6startPositionx(kAxisLayout, vector2Control26); AxisControl y35 = Initialize_ctrlTouchscreentouch6startPositiony(kAxisLayout, vector2Control26); IntegerControl touchId9 = Initialize_ctrlTouchscreentouch7touchId(kIntegerLayout, touchControl9); Vector2Control vector2Control27 = Initialize_ctrlTouchscreentouch7position(kVector2Layout, touchControl9); DeltaControl deltaControl10 = Initialize_ctrlTouchscreentouch7delta(kDeltaLayout, touchControl9); AxisControl axisControl9 = Initialize_ctrlTouchscreentouch7pressure(kAxisLayout, touchControl9); Vector2Control vector2Control28 = Initialize_ctrlTouchscreentouch7radius(kVector2Layout, touchControl9); TouchPhaseControl phase9 = Initialize_ctrlTouchscreentouch7phase(kTouchPhaseLayout, touchControl9); TouchPressControl touchPressControl10 = Initialize_ctrlTouchscreentouch7press(kTouchPressLayout, touchControl9); IntegerControl tapCount9 = Initialize_ctrlTouchscreentouch7tapCount(kIntegerLayout, touchControl9); IntegerControl integerControl9 = Initialize_ctrlTouchscreentouch7displayIndex(kIntegerLayout, touchControl9); ButtonControl indirectTouch9 = Initialize_ctrlTouchscreentouch7indirectTouch(kButtonLayout, touchControl9); ButtonControl tap8 = Initialize_ctrlTouchscreentouch7tap(kButtonLayout, touchControl9); DoubleControl startTime9 = Initialize_ctrlTouchscreentouch7startTime(kDoubleLayout, touchControl9); Vector2Control vector2Control29 = Initialize_ctrlTouchscreentouch7startPosition(kVector2Layout, touchControl9); AxisControl x36 = Initialize_ctrlTouchscreentouch7positionx(kAxisLayout, vector2Control27); AxisControl y36 = Initialize_ctrlTouchscreentouch7positiony(kAxisLayout, vector2Control27); AxisControl up10 = Initialize_ctrlTouchscreentouch7deltaup(kAxisLayout, deltaControl10); AxisControl down10 = Initialize_ctrlTouchscreentouch7deltadown(kAxisLayout, deltaControl10); AxisControl left10 = Initialize_ctrlTouchscreentouch7deltaleft(kAxisLayout, deltaControl10); AxisControl right10 = Initialize_ctrlTouchscreentouch7deltaright(kAxisLayout, deltaControl10); AxisControl x37 = Initialize_ctrlTouchscreentouch7deltax(kAxisLayout, deltaControl10); AxisControl y37 = Initialize_ctrlTouchscreentouch7deltay(kAxisLayout, deltaControl10); AxisControl x38 = Initialize_ctrlTouchscreentouch7radiusx(kAxisLayout, vector2Control28); AxisControl y38 = Initialize_ctrlTouchscreentouch7radiusy(kAxisLayout, vector2Control28); AxisControl x39 = Initialize_ctrlTouchscreentouch7startPositionx(kAxisLayout, vector2Control29); AxisControl y39 = Initialize_ctrlTouchscreentouch7startPositiony(kAxisLayout, vector2Control29); IntegerControl touchId10 = Initialize_ctrlTouchscreentouch8touchId(kIntegerLayout, touchControl10); Vector2Control vector2Control30 = Initialize_ctrlTouchscreentouch8position(kVector2Layout, touchControl10); DeltaControl deltaControl11 = Initialize_ctrlTouchscreentouch8delta(kDeltaLayout, touchControl10); AxisControl axisControl10 = Initialize_ctrlTouchscreentouch8pressure(kAxisLayout, touchControl10); Vector2Control vector2Control31 = Initialize_ctrlTouchscreentouch8radius(kVector2Layout, touchControl10); TouchPhaseControl phase10 = Initialize_ctrlTouchscreentouch8phase(kTouchPhaseLayout, touchControl10); TouchPressControl touchPressControl11 = Initialize_ctrlTouchscreentouch8press(kTouchPressLayout, touchControl10); IntegerControl tapCount10 = Initialize_ctrlTouchscreentouch8tapCount(kIntegerLayout, touchControl10); IntegerControl integerControl10 = Initialize_ctrlTouchscreentouch8displayIndex(kIntegerLayout, touchControl10); ButtonControl indirectTouch10 = Initialize_ctrlTouchscreentouch8indirectTouch(kButtonLayout, touchControl10); ButtonControl tap9 = Initialize_ctrlTouchscreentouch8tap(kButtonLayout, touchControl10); DoubleControl startTime10 = Initialize_ctrlTouchscreentouch8startTime(kDoubleLayout, touchControl10); Vector2Control vector2Control32 = Initialize_ctrlTouchscreentouch8startPosition(kVector2Layout, touchControl10); AxisControl x40 = Initialize_ctrlTouchscreentouch8positionx(kAxisLayout, vector2Control30); AxisControl y40 = Initialize_ctrlTouchscreentouch8positiony(kAxisLayout, vector2Control30); AxisControl up11 = Initialize_ctrlTouchscreentouch8deltaup(kAxisLayout, deltaControl11); AxisControl down11 = Initialize_ctrlTouchscreentouch8deltadown(kAxisLayout, deltaControl11); AxisControl left11 = Initialize_ctrlTouchscreentouch8deltaleft(kAxisLayout, deltaControl11); AxisControl right11 = Initialize_ctrlTouchscreentouch8deltaright(kAxisLayout, deltaControl11); AxisControl x41 = Initialize_ctrlTouchscreentouch8deltax(kAxisLayout, deltaControl11); AxisControl y41 = Initialize_ctrlTouchscreentouch8deltay(kAxisLayout, deltaControl11); AxisControl x42 = Initialize_ctrlTouchscreentouch8radiusx(kAxisLayout, vector2Control31); AxisControl y42 = Initialize_ctrlTouchscreentouch8radiusy(kAxisLayout, vector2Control31); AxisControl x43 = Initialize_ctrlTouchscreentouch8startPositionx(kAxisLayout, vector2Control32); AxisControl y43 = Initialize_ctrlTouchscreentouch8startPositiony(kAxisLayout, vector2Control32); IntegerControl touchId11 = Initialize_ctrlTouchscreentouch9touchId(kIntegerLayout, touchControl11); Vector2Control vector2Control33 = Initialize_ctrlTouchscreentouch9position(kVector2Layout, touchControl11); DeltaControl deltaControl12 = Initialize_ctrlTouchscreentouch9delta(kDeltaLayout, touchControl11); AxisControl axisControl11 = Initialize_ctrlTouchscreentouch9pressure(kAxisLayout, touchControl11); Vector2Control vector2Control34 = Initialize_ctrlTouchscreentouch9radius(kVector2Layout, touchControl11); TouchPhaseControl phase11 = Initialize_ctrlTouchscreentouch9phase(kTouchPhaseLayout, touchControl11); TouchPressControl touchPressControl12 = Initialize_ctrlTouchscreentouch9press(kTouchPressLayout, touchControl11); IntegerControl tapCount11 = Initialize_ctrlTouchscreentouch9tapCount(kIntegerLayout, touchControl11); IntegerControl integerControl11 = Initialize_ctrlTouchscreentouch9displayIndex(kIntegerLayout, touchControl11); ButtonControl indirectTouch11 = Initialize_ctrlTouchscreentouch9indirectTouch(kButtonLayout, touchControl11); ButtonControl tap10 = Initialize_ctrlTouchscreentouch9tap(kButtonLayout, touchControl11); DoubleControl startTime11 = Initialize_ctrlTouchscreentouch9startTime(kDoubleLayout, touchControl11); Vector2Control vector2Control35 = Initialize_ctrlTouchscreentouch9startPosition(kVector2Layout, touchControl11); AxisControl x44 = Initialize_ctrlTouchscreentouch9positionx(kAxisLayout, vector2Control33); AxisControl y44 = Initialize_ctrlTouchscreentouch9positiony(kAxisLayout, vector2Control33); AxisControl up12 = Initialize_ctrlTouchscreentouch9deltaup(kAxisLayout, deltaControl12); AxisControl down12 = Initialize_ctrlTouchscreentouch9deltadown(kAxisLayout, deltaControl12); AxisControl left12 = Initialize_ctrlTouchscreentouch9deltaleft(kAxisLayout, deltaControl12); AxisControl right12 = Initialize_ctrlTouchscreentouch9deltaright(kAxisLayout, deltaControl12); AxisControl x45 = Initialize_ctrlTouchscreentouch9deltax(kAxisLayout, deltaControl12); AxisControl y45 = Initialize_ctrlTouchscreentouch9deltay(kAxisLayout, deltaControl12); AxisControl x46 = Initialize_ctrlTouchscreentouch9radiusx(kAxisLayout, vector2Control34); AxisControl y46 = Initialize_ctrlTouchscreentouch9radiusy(kAxisLayout, vector2Control34); AxisControl x47 = Initialize_ctrlTouchscreentouch9startPositionx(kAxisLayout, vector2Control35); AxisControl y47 = Initialize_ctrlTouchscreentouch9startPositiony(kAxisLayout, vector2Control35); deviceBuilder.WithControlUsage(0, new InternedString("PrimaryAction"), buttonControl); deviceBuilder.WithControlUsage(1, new InternedString("Point"), vector2Control); deviceBuilder.WithControlUsage(2, new InternedString("Secondary2DMotion"), deltaControl); deviceBuilder.WithControlUsage(3, new InternedString("Pressure"), control); deviceBuilder.WithControlUsage(4, new InternedString("Radius"), vector2Control2); base.touchControlArray = new TouchControl[10]; base.touchControlArray[0] = touchControl2; base.touchControlArray[1] = touchControl3; base.touchControlArray[2] = touchControl4; base.touchControlArray[3] = touchControl5; base.touchControlArray[4] = touchControl6; base.touchControlArray[5] = touchControl7; base.touchControlArray[6] = touchControl8; base.touchControlArray[7] = touchControl9; base.touchControlArray[8] = touchControl10; base.touchControlArray[9] = touchControl11; base.primaryTouch = touchControl; base.position = vector2Control; base.delta = deltaControl; base.radius = vector2Control2; base.pressure = control; base.press = touchPressControl; base.displayIndex = integerControl; touchControl.press = touchPressControl2; touchControl.displayIndex = integerControl; touchControl.touchId = touchId; touchControl.position = vector2Control3; touchControl.delta = deltaControl2; touchControl.pressure = axisControl; touchControl.radius = vector2Control4; touchControl.phase = phase; touchControl.indirectTouch = indirectTouch; touchControl.tap = buttonControl; touchControl.tapCount = tapCount; touchControl.startTime = startTime; touchControl.startPosition = vector2Control5; vector2Control.x = x5; vector2Control.y = y5; deltaControl.up = up2; deltaControl.down = down2; deltaControl.left = left2; deltaControl.right = right2; deltaControl.x = x6; deltaControl.y = y6; vector2Control2.x = x7; vector2Control2.y = y7; touchControl2.press = touchPressControl3; touchControl2.displayIndex = integerControl2; touchControl2.touchId = touchId2; touchControl2.position = vector2Control6; touchControl2.delta = deltaControl3; touchControl2.pressure = axisControl2; touchControl2.radius = vector2Control7; touchControl2.phase = phase2; touchControl2.indirectTouch = indirectTouch2; touchControl2.tap = tap; touchControl2.tapCount = tapCount2; touchControl2.startTime = startTime2; touchControl2.startPosition = vector2Control8; touchControl3.press = touchPressControl4; touchControl3.displayIndex = integerControl3; touchControl3.touchId = touchId3; touchControl3.position = vector2Control9; touchControl3.delta = deltaControl4; touchControl3.pressure = axisControl3; touchControl3.radius = vector2Control10; touchControl3.phase = phase3; touchControl3.indirectTouch = indirectTouch3; touchControl3.tap = tap2; touchControl3.tapCount = tapCount3; touchControl3.startTime = startTime3; touchControl3.startPosition = vector2Control11; touchControl4.press = touchPressControl5; touchControl4.displayIndex = integerControl4; touchControl4.touchId = touchId4; touchControl4.position = vector2Control12; touchControl4.delta = deltaControl5; touchControl4.pressure = axisControl4; touchControl4.radius = vector2Control13; touchControl4.phase = phase4; touchControl4.indirectTouch = indirectTouch4; touchControl4.tap = tap3; touchControl4.tapCount = tapCount4; touchControl4.startTime = startTime4; touchControl4.startPosition = vector2Control14; touchControl5.press = touchPressControl6; touchControl5.displayIndex = integerControl5; touchControl5.touchId = touchId5; touchControl5.position = vector2Control15; touchControl5.delta = deltaControl6; touchControl5.pressure = axisControl5; touchControl5.radius = vector2Control16; touchControl5.phase = phase5; touchControl5.indirectTouch = indirectTouch5; touchControl5.tap = tap4; touchControl5.tapCount = tapCount5; touchControl5.startTime = startTime5; touchControl5.startPosition = vector2Control17; touchControl6.press = touchPressControl7; touchControl6.displayIndex = integerControl6; touchControl6.touchId = touchId6; touchControl6.position = vector2Control18; touchControl6.delta = deltaControl7; touchControl6.pressure = axisControl6; touchControl6.radius = vector2Control19; touchControl6.phase = phase6; touchControl6.indirectTouch = indirectTouch6; touchControl6.tap = tap5; touchControl6.tapCount = tapCount6; touchControl6.startTime = startTime6; touchControl6.startPosition = vector2Control20; touchControl7.press = touchPressControl8; touchControl7.displayIndex = integerControl7; touchControl7.touchId = touchId7; touchControl7.position = vector2Control21; touchControl7.delta = deltaControl8; touchControl7.pressure = axisControl7; touchControl7.radius = vector2Control22; touchControl7.phase = phase7; touchControl7.indirectTouch = indirectTouch7; touchControl7.tap = tap6; touchControl7.tapCount = tapCount7; touchControl7.startTime = startTime7; touchControl7.startPosition = vector2Control23; touchControl8.press = touchPressControl9; touchControl8.displayIndex = integerControl8; touchControl8.touchId = touchId8; touchControl8.position = vector2Control24; touchControl8.delta = deltaControl9; touchControl8.pressure = axisControl8; touchControl8.radius = vector2Control25; touchControl8.phase = phase8; touchControl8.indirectTouch = indirectTouch8; touchControl8.tap = tap7; touchControl8.tapCount = tapCount8; touchControl8.startTime = startTime8; touchControl8.startPosition = vector2Control26; touchControl9.press = touchPressControl10; touchControl9.displayIndex = integerControl9; touchControl9.touchId = touchId9; touchControl9.position = vector2Control27; touchControl9.delta = deltaControl10; touchControl9.pressure = axisControl9; touchControl9.radius = vector2Control28; touchControl9.phase = phase9; touchControl9.indirectTouch = indirectTouch9; touchControl9.tap = tap8; touchControl9.tapCount = tapCount9; touchControl9.startTime = startTime9; touchControl9.startPosition = vector2Control29; touchControl10.press = touchPressControl11; touchControl10.displayIndex = integerControl10; touchControl10.touchId = touchId10; touchControl10.position = vector2Control30; touchControl10.delta = deltaControl11; touchControl10.pressure = axisControl10; touchControl10.radius = vector2Control31; touchControl10.phase = phase10; touchControl10.indirectTouch = indirectTouch10; touchControl10.tap = tap9; touchControl10.tapCount = tapCount10; touchControl10.startTime = startTime10; touchControl10.startPosition = vector2Control32; touchControl11.press = touchPressControl12; touchControl11.displayIndex = integerControl11; touchControl11.touchId = touchId11; touchControl11.position = vector2Control33; touchControl11.delta = deltaControl12; touchControl11.pressure = axisControl11; touchControl11.radius = vector2Control34; touchControl11.phase = phase11; touchControl11.indirectTouch = indirectTouch11; touchControl11.tap = tap10; touchControl11.tapCount = tapCount11; touchControl11.startTime = startTime11; touchControl11.startPosition = vector2Control35; vector2Control3.x = x; vector2Control3.y = y; deltaControl2.up = up; deltaControl2.down = down; deltaControl2.left = left; deltaControl2.right = right; deltaControl2.x = x2; deltaControl2.y = y2; vector2Control4.x = x3; vector2Control4.y = y3; vector2Control5.x = x4; vector2Control5.y = y4; vector2Control6.x = x8; vector2Control6.y = y8; deltaControl3.up = up3; deltaControl3.down = down3; deltaControl3.left = left3; deltaControl3.right = right3; deltaControl3.x = x9; deltaControl3.y = y9; vector2Control7.x = x10; vector2Control7.y = y10; vector2Control8.x = x11; vector2Control8.y = y11; vector2Control9.x = x12; vector2Control9.y = y12; deltaControl4.up = up4; deltaControl4.down = down4; deltaControl4.left = left4; deltaControl4.right = right4; deltaControl4.x = x13; deltaControl4.y = y13; vector2Control10.x = x14; vector2Control10.y = y14; vector2Control11.x = x15; vector2Control11.y = y15; vector2Control12.x = x16; vector2Control12.y = y16; deltaControl5.up = up5; deltaControl5.down = down5; deltaControl5.left = left5; deltaControl5.right = right5; deltaControl5.x = x17; deltaControl5.y = y17; vector2Control13.x = x18; vector2Control13.y = y18; vector2Control14.x = x19; vector2Control14.y = y19; vector2Control15.x = x20; vector2Control15.y = y20; deltaControl6.up = up6; deltaControl6.down = down6; deltaControl6.left = left6; deltaControl6.right = right6; deltaControl6.x = x21; deltaControl6.y = y21; vector2Control16.x = x22; vector2Control16.y = y22; vector2Control17.x = x23; vector2Control17.y = y23; vector2Control18.x = x24; vector2Control18.y = y24; deltaControl7.up = up7; deltaControl7.down = down7; deltaControl7.left = left7; deltaControl7.right = right7; deltaControl7.x = x25; deltaControl7.y = y25; vector2Control19.x = x26; vector2Control19.y = y26; vector2Control20.x = x27; vector2Control20.y = y27; vector2Control21.x = x28; vector2Control21.y = y28; deltaControl8.up = up8; deltaControl8.down = down8; deltaControl8.left = left8; deltaControl8.right = right8; deltaControl8.x = x29; deltaControl8.y = y29; vector2Control22.x = x30; vector2Control22.y = y30; vector2Control23.x = x31; vector2Control23.y = y31; vector2Control24.x = x32; vector2Control24.y = y32; deltaControl9.up = up9; deltaControl9.down = down9; deltaControl9.left = left9; deltaControl9.right = right9; deltaControl9.x = x33; deltaControl9.y = y33; vector2Control25.x = x34; vector2Control25.y = y34; vector2Control26.x = x35; vector2Control26.y = y35; vector2Control27.x = x36; vector2Control27.y = y36; deltaControl10.up = up10; deltaControl10.down = down10; deltaControl10.left = left10; deltaControl10.right = right10; deltaControl10.x = x37; deltaControl10.y = y37; vector2Control28.x = x38; vector2Control28.y = y38; vector2Control29.x = x39; vector2Control29.y = y39; vector2Control30.x = x40; vector2Control30.y = y40; deltaControl11.up = up11; deltaControl11.down = down11; deltaControl11.left = left11; deltaControl11.right = right11; deltaControl11.x = x41; deltaControl11.y = y41; vector2Control31.x = x42; vector2Control31.y = y42; vector2Control32.x = x43; vector2Control32.y = y43; vector2Control33.x = x44; vector2Control33.y = y44; deltaControl12.up = up12; deltaControl12.down = down12; deltaControl12.left = left12; deltaControl12.right = right12; deltaControl12.x = x45; deltaControl12.y = y45; vector2Control34.x = x46; vector2Control34.y = y46; vector2Control35.x = x47; vector2Control35.y = y47; deviceBuilder.WithStateOffsetToControlIndexMap(new uint[244] { 32785u, 16810014u, 16810026u, 33587231u, 33587243u, 50364450u, 50364451u, 50364452u, 50364462u, 50364463u, 50364464u, 67141664u, 67141665u, 67141669u, 67141676u, 67141677u, 67141681u, 83918851u, 83918868u, 100696102u, 100696114u, 117473319u, 117473331u, 134225925u, 134225942u, 134225943u, 138420248u, 142614553u, 142622736u, 146801690u, 148898843u, 167837724u, 201359400u, 218136617u, 234913844u, 251691073u, 268468290u, 285245509u, 285245510u, 285245511u, 302022723u, 302022724u, 302022728u, 318799927u, 335577161u, 352354378u, 369107001u, 369107002u, 373301307u, 377495612u, 381682749u, 383779902u, 402718783u, 436240459u, 453017676u, 469794893u, 486572122u, 503349339u, 520126558u, 520126559u, 520126560u, 536903772u, 536903773u, 536903777u, 553680976u, 570458210u, 587235427u, 603988050u, 603988051u, 608182356u, 612376661u, 616563798u, 618660951u, 637599832u, 671121508u, 687898725u, 704675942u, 721453171u, 738230388u, 755007607u, 755007608u, 755007609u, 771784821u, 771784822u, 771784826u, 788562025u, 805339259u, 822116476u, 838869099u, 838869100u, 843063405u, 847257710u, 851444847u, 853542000u, 872480881u, 906002557u, 922779774u, 939556991u, 956334220u, 973111437u, 989888656u, 989888657u, 989888658u, 1006665870u, 1006665871u, 1006665875u, 1023443074u, 1040220308u, 1056997525u, 1073750148u, 1073750149u, 1077944454u, 1082138759u, 1086325896u, 1088423049u, 1107361930u, 1140883606u, 1157660823u, 1174438040u, 1191215269u, 1207992486u, 1224769705u, 1224769706u, 1224769707u, 1241546919u, 1241546920u, 1241546924u, 1258324123u, 1275101357u, 1291878574u, 1308631197u, 1308631198u, 1312825503u, 1317019808u, 1321206945u, 1323304098u, 1342242979u, 1375764655u, 1392541872u, 1409319089u, 1426096318u, 1442873535u, 1459650754u, 1459650755u, 1459650756u, 1476427968u, 1476427969u, 1476427973u, 1493205172u, 1509982406u, 1526759623u, 1543512246u, 1543512247u, 1547706552u, 1551900857u, 1556087994u, 1558185147u, 1577124028u, 1610645704u, 1627422921u, 1644200138u, 1660977367u, 1677754584u, 1694531803u, 1694531804u, 1694531805u, 1711309017u, 1711309018u, 1711309022u, 1728086221u, 1744863455u, 1761640672u, 1778393295u, 1778393296u, 1782587601u, 1786781906u, 1790969043u, 1793066196u, 1812005077u, 1845526753u, 1862303970u, 1879081187u, 1895858416u, 1912635633u, 1929412852u, 1929412853u, 1929412854u, 1946190066u, 1946190067u, 1946190071u, 1962967270u, 1979744504u, 1996521721u, 2013274344u, 2013274345u, 2017468650u, 2021662955u, 2025850092u, 2027947245u, 2046886126u, 2080407802u, 2097185019u, 2113962236u, 2130739465u, 2147516682u, 2164293901u, 2164293902u, 2164293903u, 2181071115u, 2181071116u, 2181071120u, 2197848319u, 2214625553u, 2231402770u, 2248155393u, 2248155394u, 2252349699u, 2256544004u, 2260731141u, 2262828294u, 2281767175u, 2315288851u, 2332066068u, 2348843285u, 2365620514u, 2382397731u, 2399174950u, 2399174951u, 2399174952u, 2415952164u, 2415952165u, 2415952169u, 2432729368u, 2449506602u, 2466283819u, 2483036442u, 2483036443u, 2487230748u, 2491425053u, 2495612190u, 2497709343u, 2516648224u, 2550169900u, 2566947117u }); deviceBuilder.WithControlTree(new byte[4011] { 63, 19, 1, 0, 0, 0, 0, 192, 8, 3, 0, 0, 0, 0, 63, 19, 5, 1, 0, 0, 0, 128, 3, 5, 0, 0, 0, 0, 192, 8, 107, 0, 0, 0, 0, 192, 1, 7, 0, 0, 0, 1, 128, 3, 57, 0, 68, 0, 1, 192, 0, 9, 0, 0, 0, 0, 192, 1, 21, 0, 0, 0, 0, 96, 0, 11, 0, 0, 0, 0, 192, 0, 15, 0, 0, 0, 0, 32, 0, 255, 255, 1, 0, 1, 96, 0, 13, 0, 2, 0, 2, 64, 0, 255, 255, 4, 0, 2, 96, 0, 255, 255, 6, 0, 2, 144, 0, 17, 0, 8, 0, 8, 192, 0, 19, 0, 16, 0, 8, 120, 0, 255, 255, 24, 0, 6, 144, 0, 255, 255, 30, 0, 6, 168, 0, 255, 255, 36, 0, 2, 192, 0, 255, 255, 38, 0, 2, 32, 1, 23, 0, 0, 0, 0, 192, 1, 51, 0, 0, 0, 0, 8, 1, 25, 0, 0, 0, 0, 32, 1, 35, 0, 0, 0, 0, 228, 0, 27, 0, 40, 0, 4, 8, 1, 29, 0, 44, 0, 4, 210, 0, 255, 255, 48, 0, 2, 228, 0, 255, 255, 50, 0, 2, 246, 0, 255, 255, 0, 0, 0, 8, 1, 31, 0, 0, 0, 0, 255, 0, 255, 255, 0, 0, 0, 8, 1, 33, 0, 0, 0, 0, 4, 1, 255, 255, 52, 0, 3, 8, 1, 255, 255, 55, 0, 3, 16, 1, 255, 255, 58, 0, 1, 32, 1, 37, 0, 6, 2, 1, 25, 1, 39, 0, 0, 0, 0, 32, 1, 45, 0, 0, 0, 0, 21, 1, 255, 255, 59, 0, 1, 25, 1, 41, 0, 60, 0, 1, 23, 1, 255, 255, 0, 0, 0, 25, 1, 43, 0, 0, 0, 0, 24, 1, 255, 255, 0, 0, 0, 25, 1, 255, 255, 61, 0, 1, 29, 1, 47, 0, 0, 0, 0, 32, 1, 255, 255, 0, 0, 0, 27, 1, 255, 255, 0, 0, 0, 29, 1, 49, 0, 0, 0, 0, 28, 1, 255, 255, 0, 0, 0, 29, 1, 255, 255, 62, 0, 1, 128, 1, 53, 0, 0, 0, 0, 192, 1, 55, 0, 65, 0, 1, 80, 1, 255, 255, 63, 0, 1, 128, 1, 255, 255, 64, 0, 1, 160, 1, 255, 255, 66, 0, 1, 192, 1, 255, 255, 67, 0, 1, 160, 2, 59, 0, 92, 0, 1, 128, 3, 75, 0, 93, 0, 1, 48, 2, 61, 0, 77, 0, 4, 160, 2, 69, 0, 81, 0, 4, 248, 1, 63, 0, 71, 0, 2, 48, 2, 65, 0, 73, 0, 2, 220, 1, 255, 255, 69, 0, 1, 248, 1, 255, 255, 70, 0, 1, 32, 2, 67, 0, 0, 0, 0, 48, 2, 255, 255, 0, 0, 0, 12, 2, 255, 255, 75, 0, 1, 32, 2, 255, 255, 76, 0, 1, 96, 2, 71, 0, 0, 0, 0, 160, 2, 73, 0, 0, 0, 0, 72, 2, 255, 255, 85, 0, 3, 96, 2, 255, 255, 88, 0, 3, 128, 2, 255, 255, 91, 0, 1, 160, 2, 255, 255, 94, 0, 1, 16, 3, 77, 0, 105, 0, 1, 128, 3, 103, 0, 106, 0, 1, 216, 2, 79, 0, 0, 0, 0, 16, 3, 87, 0, 0, 0, 0, 188, 2, 255, 255, 95, 0, 1, 216, 2, 81, 0, 96, 0, 1, 200, 2, 83, 0, 0, 0, 0, 216, 2, 85, 0, 0, 0, 0, 194, 2, 255, 255, 97, 0, 2, 200, 2, 255, 255, 99, 0, 2, 208, 2, 255, 255, 101, 0, 1, 216, 2, 255, 255, 102, 0, 1, 244, 2, 89, 0, 0, 0, 0, 16, 3, 255, 255, 0, 0, 0, 230, 2, 91, 0, 0, 0, 0, 244, 2, 255, 255, 0, 0, 0, 223, 2, 93, 0, 0, 0, 0, 230, 2, 255, 255, 0, 0, 0, 220, 2, 95, 0, 0, 0, 0, 223, 2, 99, 0, 0, 0, 0, 218, 2, 97, 0, 0, 0, 0, 220, 2, 255, 255, 0, 0, 0, 217, 2, 255, 255, 103, 0, 1, 218, 2, 255, 255, 0, 0, 0, 222, 2, 101, 0, 0, 0, 0, 223, 2, 255, 255, 0, 0, 0, 221, 2, 255, 255, 104, 0, 1, 222, 2, 255, 255, 0, 0, 0, 72, 3, 255, 255, 107, 0, 2, 128, 3, 105, 0, 109, 0, 2, 100, 3, 255, 255, 111, 0, 1, 128, 3, 255, 255, 112, 0, 1, 0, 7, 109, 0, 0, 0, 0, 192, 8, 211, 0, 203, 0, 1, 64, 5, 111, 0, 113, 0, 1, 0, 7, 161, 0, 158, 0, 1, 96, 4, 113, 0, 137, 0, 1, 64, 5, 129, 0, 138, 0, 1, 240, 3, 115, 0, 122, 0, 4, 96, 4, 123, 0, 126, 0, 4, 184, 3, 117, 0, 116, 0, 2, 240, 3, 119, 0, 118, 0, 2, 156, 3, 255, 255, 114, 0, 1, 184, 3, 255, 255, 115, 0, 1, 224, 3, 121, 0, 0, 0, 0, 240, 3, 255, 255, 0, 0, 0, 204, 3, 255, 255, 120, 0, 1, 224, 3, 255, 255, 121, 0, 1, 32, 4, 125, 0, 0, 0, 0, 96, 4, 127, 0, 0, 0, 0, 8, 4, 255, 255, 130, 0, 3, 32, 4, 255, 255, 133, 0, 3, 64, 4, 255, 255, 136, 0, 1, 96, 4, 255, 255, 139, 0, 1, 208, 4, 131, 0, 150, 0, 1, 64, 5, 157, 0, 151, 0, 1, 152, 4, 133, 0, 0, 0, 0, 208, 4, 141, 0, 0, 0, 0, 124, 4, 255, 255, 140, 0, 1, 152, 4, 135, 0, 141, 0, 1, 136, 4, 137, 0, 0, 0, 0, 152, 4, 139, 0, 0, 0, 0, 130, 4, 255, 255, 142, 0, 2, 136, 4, 255, 255, 144, 0, 2, 144, 4, 255, 255, 146, 0, 1, 152, 4, 255, 255, 147, 0, 1, 180, 4, 143, 0, 0, 0, 0, 208, 4, 255, 255, 0, 0, 0, 166, 4, 145, 0, 0, 0, 0, 180, 4, 255, 255, 0, 0, 0, 159, 4, 147, 0, 0, 0, 0, 166, 4, 255, 255, 0, 0, 0, 156, 4, 149, 0, 0, 0, 0, 159, 4, 153, 0, 0, 0, 0, 154, 4, 151, 0, 0, 0, 0, 156, 4, 255, 255, 0, 0, 0, 153, 4, 255, 255, 148, 0, 1, 154, 4, 255, 255, 0, 0, 0, 158, 4, 155, 0, 0, 0, 0, 159, 4, 255, 255, 0, 0, 0, 157, 4, 255, 255, 149, 0, 1, 158, 4, 255, 255, 0, 0, 0, 8, 5, 255, 255, 152, 0, 2, 64, 5, 159, 0, 154, 0, 2, 36, 5, 255, 255, 156, 0, 1, 64, 5, 255, 255, 157, 0, 1, 32, 6, 163, 0, 182, 0, 1, 0, 7, 179, 0, 183, 0, 1, 176, 5, 165, 0, 167, 0, 4, 32, 6, 173, 0, 171, 0, 4, 120, 5, 167, 0, 161, 0, 2, 176, 5, 169, 0, 163, 0, 2, 92, 5, 255, 255, 159, 0, 1, 120, 5, 255, 255, 160, 0, 1, 160, 5, 171, 0, 0, 0, 0, 176, 5, 255, 255, 0, 0, 0, 140, 5, 255, 255, 165, 0, 1, 160, 5, 255, 255, 166, 0, 1, 224, 5, 175, 0, 0, 0, 0, 32, 6, 177, 0, 0, 0, 0, 200, 5, 255, 255, 175, 0, 3, 224, 5, 255, 255, 178, 0, 3, 0, 6, 255, 255, 181, 0, 1, 32, 6, 255, 255, 184, 0, 1, 144, 6, 181, 0, 195, 0, 1, 0, 7, 207, 0, 196, 0, 1, 88, 6, 183, 0, 0, 0, 0, 144, 6, 191, 0, 0, 0, 0, 60, 6, 255, 255, 185, 0, 1, 88, 6, 185, 0, 186, 0, 1, 72, 6, 187, 0, 0, 0, 0, 88, 6, 189, 0, 0, 0, 0, 66, 6, 255, 255, 187, 0, 2, 72, 6, 255, 255, 189, 0, 2, 80, 6, 255, 255, 191, 0, 1, 88, 6, 255, 255, 192, 0, 1, 116, 6, 193, 0, 0, 0, 0, 144, 6, 255, 255, 0, 0, 0, 102, 6, 195, 0, 0, 0, 0, 116, 6, 255, 255, 0, 0, 0, 95, 6, 197, 0, 0, 0, 0, 102, 6, 255, 255, 0, 0, 0, 92, 6, 199, 0, 0, 0, 0, 95, 6, 203, 0, 0, 0, 0, 90, 6, 201, 0, 0, 0, 0, 92, 6, 255, 255, 0, 0, 0, 89, 6, 255, 255, 193, 0, 1, 90, 6, 255, 255, 0, 0, 0, 94, 6, 205, 0, 0, 0, 0, 95, 6, 255, 255, 0, 0, 0, 93, 6, 255, 255, 194, 0, 1, 94, 6, 255, 255, 0, 0, 0, 200, 6, 255, 255, 197, 0, 2, 0, 7, 209, 0, 199, 0, 2, 228, 6, 255, 255, 201, 0, 1, 0, 7, 255, 255, 202, 0, 1, 224, 7, 213, 0, 227, 0, 1, 192, 8, 229, 0, 228, 0, 1, 112, 7, 215, 0, 212, 0, 4, 224, 7, 223, 0, 216, 0, 4, 56, 7, 217, 0, 206, 0, 2, 112, 7, 219, 0, 208, 0, 2, 28, 7, 255, 255, 204, 0, 1, 56, 7, 255, 255, 205, 0, 1, 96, 7, 221, 0, 0, 0, 0, 112, 7, 255, 255, 0, 0, 0, 76, 7, 255, 255, 210, 0, 1, 96, 7, 255, 255, 211, 0, 1, 160, 7, 225, 0, 0, 0, 0, 224, 7, 227, 0, 0, 0, 0, 136, 7, 255, 255, 220, 0, 3, 160, 7, 255, 255, 223, 0, 3, 192, 7, 255, 255, 226, 0, 1, 224, 7, 255, 255, 229, 0, 1, 80, 8, 231, 0, 240, 0, 1, 192, 8, 1, 1, 241, 0, 1, 24, 8, 233, 0, 0, 0, 0, 80, 8, 241, 0, 0, 0, 0, 252, 7, 255, 255, 230, 0, 1, 24, 8, 235, 0, 231, 0, 1, 8, 8, 237, 0, 0, 0, 0, 24, 8, 239, 0, 0, 0, 0, 2, 8, 255, 255, 232, 0, 2, 8, 8, 255, 255, 234, 0, 2, 16, 8, 255, 255, 236, 0, 1, 24, 8, 255, 255, 237, 0, 1, 52, 8, 243, 0, 0, 0, 0, 80, 8, 255, 255, 0, 0, 0, 38, 8, 245, 0, 0, 0, 0, 52, 8, 255, 255, 0, 0, 0, 31, 8, 247, 0, 0, 0, 0, 38, 8, 255, 255, 0, 0, 0, 28, 8, 249, 0, 0, 0, 0, 31, 8, 253, 0, 0, 0, 0, 26, 8, 251, 0, 0, 0, 0, 28, 8, 255, 255, 0, 0, 0, 25, 8, 255, 255, 238, 0, 1, 26, 8, 255, 255, 0, 0, 0, 30, 8, 255, 0, 0, 0, 0, 31, 8, 255, 255, 0, 0, 0, 29, 8, 255, 255, 239, 0, 1, 30, 8, 255, 255, 0, 0, 0, 136, 8, 255, 255, 242, 0, 2, 192, 8, 3, 1, 244, 0, 2, 164, 8, 255, 255, 246, 0, 1, 192, 8, 255, 255, 247, 0, 1, 0, 14, 7, 1, 0, 0, 0, 63, 19, 161, 1, 0, 0, 0, 64, 12, 9, 1, 0, 0, 0, 0, 14, 111, 1, 82, 1, 1, 128, 10, 11, 1, 248, 0, 1, 64, 12, 61, 1, 37, 1, 1, 160, 9, 13, 1, 16, 1, 1, 128, 10, 29, 1, 17, 1, 1, 48, 9, 15, 1, 1, 1, 4, 160, 9, 23, 1, 5, 1, 4, 248, 8, 17, 1, 251, 0, 2, 48, 9, 19, 1, 253, 0, 2, 220, 8, 255, 255, 249, 0, 1, 248, 8, 255, 255, 250, 0, 1, 32, 9, 21, 1, 0, 0, 0, 48, 9, 255, 255, 0, 0, 0, 12, 9, 255, 255, 255, 0, 1, 32, 9, 255, 255, 0, 1, 1, 96, 9, 25, 1, 0, 0, 0, 160, 9, 27, 1, 0, 0, 0, 72, 9, 255, 255, 9, 1, 3, 96, 9, 255, 255, 12, 1, 3, 128, 9, 255, 255, 15, 1, 1, 160, 9, 255, 255, 18, 1, 1, 16, 10, 31, 1, 29, 1, 1, 128, 10, 57, 1, 30, 1, 1, 216, 9, 33, 1, 0, 0, 0, 16, 10, 41, 1, 0, 0, 0, 188, 9, 255, 255, 19, 1, 1, 216, 9, 35, 1, 20, 1, 1, 200, 9, 37, 1, 0, 0, 0, 216, 9, 39, 1, 0, 0, 0, 194, 9, 255, 255, 21, 1, 2, 200, 9, 255, 255, 23, 1, 2, 208, 9, 255, 255, 25, 1, 1, 216, 9, 255, 255, 26, 1, 1, 244, 9, 43, 1, 0, 0, 0, 16, 10, 255, 255, 0, 0, 0, 230, 9, 45, 1, 0, 0, 0, 244, 9, 255, 255, 0, 0, 0, 223, 9, 47, 1, 0, 0, 0, 230, 9, 255, 255, 0, 0, 0, 220, 9, 49, 1, 0, 0, 0, 223, 9, 53, 1, 0, 0, 0, 218, 9, 51, 1, 0, 0, 0, 220, 9, 255, 255, 0, 0, 0, 217, 9, 255, 255, 27, 1, 1, 218, 9, 255, 255, 0, 0, 0, 222, 9, 55, 1, 0, 0, 0, 223, 9, 255, 255, 0, 0, 0, 221, 9, 255, 255, 28, 1, 1, 222, 9, 255, 255, 0, 0, 0, 72, 10, 255, 255, 31, 1, 2, 128, 10, 59, 1, 33, 1, 2, 100, 10, 255, 255, 35, 1, 1, 128, 10, 255, 255, 36, 1, 1, 96, 11, 63, 1, 61, 1, 1, 64, 12, 79, 1, 62, 1, 1, 240, 10, 65, 1, 46, 1, 4, 96, 11, 73, 1, 50, 1, 4, 184, 10, 67, 1, 40, 1, 2, 240, 10, 69, 1, 42, 1, 2, 156, 10, 255, 255, 38, 1, 1, 184, 10, 255, 255, 39, 1, 1, 224, 10, 71, 1, 0, 0, 0, 240, 10, 255, 255, 0, 0, 0, 204, 10, 255, 255, 44, 1, 1, 224, 10, 255, 255, 45, 1, 1, 32, 11, 75, 1, 0, 0, 0, 96, 11, 77, 1, 0, 0, 0, 8, 11, 255, 255, 54, 1, 3, 32, 11, 255, 255, 57, 1, 3, 64, 11, 255, 255, 60, 1, 1, 96, 11, 255, 255, 63, 1, 1, 208, 11, 81, 1, 74, 1, 1, 64, 12, 107, 1, 75, 1, 1, 152, 11, 83, 1, 0, 0, 0, 208, 11, 91, 1, 0, 0, 0, 124, 11, 255, 255, 64, 1, 1, 152, 11, 85, 1, 65, 1, 1, 136, 11, 87, 1, 0, 0, 0, 152, 11, 89, 1, 0, 0, 0, 130, 11, 255, 255, 66, 1, 2, 136, 11, 255, 255, 68, 1, 2, 144, 11, 255, 255, 70, 1, 1, 152, 11, 255, 255, 71, 1, 1, 180, 11, 93, 1, 0, 0, 0, 208, 11, 255, 255, 0, 0, 0, 166, 11, 95, 1, 0, 0, 0, 180, 11, 255, 255, 0, 0, 0, 159, 11, 97, 1, 0, 0, 0, 166, 11, 255, 255, 0, 0, 0, 156, 11, 99, 1, 0, 0, 0, 159, 11, 103, 1, 0, 0, 0, 154, 11, 101, 1, 0, 0, 0, 156, 11, 255, 255, 0, 0, 0, 153, 11, 255, 255, 72, 1, 1, 154, 11, 255, 255, 0, 0, 0, 158, 11, 105, 1, 0, 0, 0, 159, 11, 255, 255, 0, 0, 0, 157, 11, 255, 255, 73, 1, 1, 158, 11, 255, 255, 0, 0, 0, 8, 12, 255, 255, 76, 1, 2, 64, 12, 109, 1, 78, 1, 2, 36, 12, 255, 255, 80, 1, 1, 64, 12, 255, 255, 81, 1, 1, 32, 13, 113, 1, 106, 1, 1, 0, 14, 129, 1, 107, 1, 1, 176, 12, 115, 1, 91, 1, 4, 32, 13, 123, 1, 95, 1, 4, 120, 12, 117, 1, 85, 1, 2, 176, 12, 119, 1, 87, 1, 2, 92, 12, 255, 255, 83, 1, 1, 120, 12, 255, 255, 84, 1, 1, 160, 12, 121, 1, 0, 0, 0, 176, 12, 255, 255, 0, 0, 0, 140, 12, 255, 255, 89, 1, 1, 160, 12, 255, 255, 90, 1, 1, 224, 12, 125, 1, 0, 0, 0, 32, 13, 127, 1, 0, 0, 0, 200, 12, 255, 255, 99, 1, 3, 224, 12, 255, 255, 102, 1, 3, 0, 13, 255, 255, 105, 1, 1, 32, 13, 255, 255, 108, 1, 1, 144, 13, 131, 1, 119, 1, 1, 0, 14, 157, 1, 120, 1, 1, 88, 13, 133, 1, 0, 0, 0, 144, 13, 141, 1, 0, 0, 0, 60, 13, 255, 255, 109, 1, 1, 88, 13, 135, 1, 110, 1, 1, 72, 13, 137, 1, 0, 0, 0, 88, 13, 139, 1, 0, 0, 0, 66, 13, 255, 255, 111, 1, 2, 72, 13, 255, 255, 113, 1, 2, 80, 13, 255, 255, 115, 1, 1, 88, 13, 255, 255, 116, 1, 1, 116, 13, 143, 1, 0, 0, 0, 144, 13, 255, 255, 0, 0, 0, 102, 13, 145, 1, 0, 0, 0, 116, 13, 255, 255, 0, 0, 0, 95, 13, 147, 1, 0, 0, 0, 102, 13, 255, 255, 0, 0, 0, 92, 13, 149, 1, 0, 0, 0, 95, 13, 153, 1, 0, 0, 0, 90, 13, 151, 1, 0, 0, 0, 92, 13, 255, 255, 0, 0, 0, 89, 13, 255, 255, 117, 1, 1, 90, 13, 255, 255, 0, 0, 0, 94, 13, 155, 1, 0, 0, 0, 95, 13, 255, 255, 0, 0, 0, 93, 13, 255, 255, 118, 1, 1, 94, 13, 255, 255, 0, 0, 0, 200, 13, 255, 255, 121, 1, 2, 0, 14, 159, 1, 123, 1, 2, 228, 13, 255, 255, 125, 1, 1, 0, 14, 255, 255, 126, 1, 1, 128, 17, 163, 1, 0, 0, 0, 63, 19, 9, 2, 0, 0, 0, 192, 15, 165, 1, 127, 1, 1, 128, 17, 215, 1, 172, 1, 1, 224, 14, 167, 1, 151, 1, 1, 192, 15, 183, 1, 152, 1, 1, 112, 14, 169, 1, 136, 1, 4, 224, 14, 177, 1, 140, 1, 4, 56, 14, 171, 1, 130, 1, 2, 112, 14, 173, 1, 132, 1, 2, 28, 14, 255, 255, 128, 1, 1, 56, 14, 255, 255, 129, 1, 1, 96, 14, 175, 1, 0, 0, 0, 112, 14, 255, 255, 0, 0, 0, 76, 14, 255, 255, 134, 1, 1, 96, 14, 255, 255, 135, 1, 1, 160, 14, 179, 1, 0, 0, 0, 224, 14, 181, 1, 0, 0, 0, 136, 14, 255, 255, 144, 1, 3, 160, 14, 255, 255, 147, 1, 3, 192, 14, 255, 255, 150, 1, 1, 224, 14, 255, 255, 153, 1, 1, 80, 15, 185, 1, 164, 1, 1, 192, 15, 211, 1, 165, 1, 1, 24, 15, 187, 1, 0, 0, 0, 80, 15, 195, 1, 0, 0, 0, 252, 14, 255, 255, 154, 1, 1, 24, 15, 189, 1, 155, 1, 1, 8, 15, 191, 1, 0, 0, 0, 24, 15, 193, 1, 0, 0, 0, 2, 15, 255, 255, 156, 1, 2, 8, 15, 255, 255, 158, 1, 2, 16, 15, 255, 255, 160, 1, 1, 24, 15, 255, 255, 161, 1, 1, 52, 15, 197, 1, 0, 0, 0, 80, 15, 255, 255, 0, 0, 0, 38, 15, 199, 1, 0, 0, 0, 52, 15, 255, 255, 0, 0, 0, 31, 15, 201, 1, 0, 0, 0, 38, 15, 255, 255, 0, 0, 0, 28, 15, 203, 1, 0, 0, 0, 31, 15, 207, 1, 0, 0, 0, 26, 15, 205, 1, 0, 0, 0, 28, 15, 255, 255, 0, 0, 0, 25, 15, 255, 255, 162, 1, 1, 26, 15, 255, 255, 0, 0, 0, 30, 15, 209, 1, 0, 0, 0, 31, 15, 255, 255, 0, 0, 0, 29, 15, 255, 255, 163, 1, 1, 30, 15, 255, 255, 0, 0, 0, 136, 15, 255, 255, 166, 1, 2, 192, 15, 213, 1, 168, 1, 2, 164, 15, 255, 255, 170, 1, 1, 192, 15, 255, 255, 171, 1, 1, 160, 16, 217, 1, 196, 1, 1, 128, 17, 233, 1, 197, 1, 1, 48, 16, 219, 1, 181, 1, 4, 160, 16, 227, 1, 185, 1, 4, 248, 15, 221, 1, 175, 1, 2, 48, 16, 223, 1, 177, 1, 2, 220, 15, 255, 255, 173, 1, 1, 248, 15, 255, 255, 174, 1, 1, 32, 16, 225, 1, 0, 0, 0, 48, 16, 255, 255, 0, 0, 0, 12, 16, 255, 255, 179, 1, 1, 32, 16, 255, 255, 180, 1, 1, 96, 16, 229, 1, 0, 0, 0, 160, 16, 231, 1, 0, 0, 0, 72, 16, 255, 255, 189, 1, 3, 96, 16, 255, 255, 192, 1, 3, 128, 16, 255, 255, 195, 1, 1, 160, 16, 255, 255, 198, 1, 1, 16, 17, 235, 1, 209, 1, 1, 128, 17, 5, 2, 210, 1, 1, 216, 16, 237, 1, 0, 0, 0, 16, 17, 245, 1, 0, 0, 0, 188, 16, 255, 255, 199, 1, 1, 216, 16, 239, 1, 200, 1, 1, 200, 16, 241, 1, 0, 0, 0, 216, 16, 243, 1, 0, 0, 0, 194, 16, 255, 255, 201, 1, 2, 200, 16, 255, 255, 203, 1, 2, 208, 16, 255, 255, 205, 1, 1, 216, 16, 255, 255, 206, 1, 1, 244, 16, 247, 1, 0, 0, 0, 16, 17, 255, 255, 0, 0, 0, 230, 16, 249, 1, 0, 0, 0, 244, 16, 255, 255, 0, 0, 0, 223, 16, 251, 1, 0, 0, 0, 230, 16, 255, 255, 0, 0, 0, 220, 16, 253, 1, 0, 0, 0, 223, 16, 1, 2, 0, 0, 0, 218, 16, 255, 1, 0, 0, 0, 220, 16, 255, 255, 0, 0, 0, 217, 16, 255, 255, 207, 1, 1, 218, 16, 255, 255, 0, 0, 0, 222, 16, 3, 2, 0, 0, 0, 223, 16, 255, 255, 0, 0, 0, 221, 16, 255, 255, 208, 1, 1, 222, 16, 255, 255, 0, 0, 0, 72, 17, 255, 255, 211, 1, 2, 128, 17, 7, 2, 213, 1, 2, 100, 17, 255, 255, 215, 1, 1, 128, 17, 255, 255, 216, 1, 1, 96, 18, 11, 2, 217, 1, 2, 63, 19, 27, 2, 219, 1, 2, 240, 17, 13, 2, 229, 1, 4, 96, 18, 21, 2, 233, 1, 4, 184, 17, 15, 2, 223, 1, 2, 240, 17, 17, 2, 225, 1, 2, 156, 17, 255, 255, 221, 1, 1, 184, 17, 255, 255, 222, 1, 1, 224, 17, 19, 2, 0, 0, 0, 240, 17, 255, 255, 0, 0, 0, 204, 17, 255, 255, 227, 1, 1, 224, 17, 255, 255, 228, 1, 1, 32, 18, 23, 2, 0, 0, 0, 96, 18, 25, 2, 0, 0, 0, 8, 18, 255, 255, 237, 1, 3, 32, 18, 255, 255, 240, 1, 3, 64, 18, 255, 255, 243, 1, 1, 96, 18, 255, 255, 244, 1, 1, 208, 18, 29, 2, 255, 1, 1, 63, 19, 55, 2, 0, 2, 1, 152, 18, 31, 2, 0, 0, 0, 208, 18, 39, 2, 0, 0, 0, 124, 18, 255, 255, 245, 1, 1, 152, 18, 33, 2, 246, 1, 1, 136, 18, 35, 2, 0, 0, 0, 152, 18, 37, 2, 0, 0, 0, 130, 18, 255, 255, 247, 1, 2, 136, 18, 255, 255, 249, 1, 2, 144, 18, 255, 255, 251, 1, 1, 152, 18, 255, 255, 252, 1, 1, 180, 18, 41, 2, 0, 0, 0, 208, 18, 255, 255, 0, 0, 0, 166, 18, 43, 2, 0, 0, 0, 180, 18, 255, 255, 0, 0, 0, 159, 18, 45, 2, 0, 0, 0, 166, 18, 255, 255, 0, 0, 0, 156, 18, 47, 2, 0, 0, 0, 159, 18, 51, 2, 0, 0, 0, 154, 18, 49, 2, 0, 0, 0, 156, 18, 255, 255, 0, 0, 0, 153, 18, 255, 255, 253, 1, 1, 154, 18, 255, 255, 0, 0, 0, 158, 18, 53, 2, 0, 0, 0, 159, 18, 255, 255, 0, 0, 0, 157, 18, 255, 255, 254, 1, 1, 158, 18, 255, 255, 0, 0, 0, 0, 19, 255, 255, 0, 0, 0, 63, 19, 57, 2, 0, 0, 0, 32, 19, 255, 255, 1, 2, 2, 63, 19, 59, 2, 3, 2, 1, 48, 19, 255, 255, 4, 2, 1, 63, 19, 255, 255, 5, 2, 1 }, new ushort[519] { 0, 17, 18, 1, 30, 42, 31, 43, 19, 32, 33, 37, 2, 44, 45, 49, 19, 32, 33, 37, 2, 44, 45, 49, 34, 35, 36, 46, 47, 48, 34, 35, 36, 46, 47, 48, 20, 3, 20, 3, 21, 39, 4, 51, 21, 39, 4, 51, 38, 50, 38, 50, 22, 23, 5, 22, 23, 5, 24, 25, 25, 26, 27, 28, 28, 29, 40, 41, 6, 52, 52, 53, 65, 53, 65, 66, 66, 54, 69, 70, 71, 54, 69, 70, 71, 67, 68, 72, 67, 68, 72, 55, 56, 56, 73, 74, 74, 57, 58, 57, 58, 59, 60, 61, 62, 63, 63, 64, 75, 64, 75, 76, 76, 7, 77, 77, 78, 90, 78, 90, 91, 91, 79, 94, 95, 96, 79, 94, 95, 96, 92, 93, 97, 92, 93, 97, 80, 81, 81, 98, 99, 99, 82, 83, 82, 83, 84, 85, 86, 87, 88, 88, 89, 100, 89, 100, 101, 101, 8, 102, 102, 103, 115, 103, 115, 116, 116, 104, 119, 120, 121, 104, 119, 120, 121, 117, 118, 122, 117, 118, 122, 105, 106, 106, 123, 124, 124, 107, 108, 107, 108, 109, 110, 111, 112, 113, 113, 114, 125, 114, 125, 126, 126, 9, 127, 127, 128, 140, 128, 140, 141, 141, 129, 144, 145, 146, 129, 144, 145, 146, 142, 143, 147, 142, 143, 147, 130, 131, 131, 148, 149, 149, 132, 133, 132, 133, 134, 135, 136, 137, 138, 138, 139, 150, 139, 150, 151, 151, 10, 152, 152, 153, 165, 153, 165, 166, 166, 154, 169, 170, 171, 154, 169, 170, 171, 167, 168, 172, 167, 168, 172, 155, 156, 156, 173, 174, 174, 157, 158, 157, 158, 159, 160, 161, 162, 163, 163, 164, 175, 164, 175, 176, 176, 11, 177, 177, 178, 190, 178, 190, 191, 191, 179, 194, 195, 196, 179, 194, 195, 196, 192, 193, 197, 192, 193, 197, 180, 181, 181, 198, 199, 199, 182, 183, 182, 183, 184, 185, 186, 187, 188, 188, 189, 200, 189, 200, 201, 201, 12, 202, 202, 203, 215, 203, 215, 216, 216, 204, 219, 220, 221, 204, 219, 220, 221, 217, 218, 222, 217, 218, 222, 205, 206, 206, 223, 224, 224, 207, 208, 207, 208, 209, 210, 211, 212, 213, 213, 214, 225, 214, 225, 226, 226, 13, 227, 227, 228, 240, 228, 240, 241, 241, 229, 244, 245, 246, 229, 244, 245, 246, 242, 243, 247, 242, 243, 247, 230, 231, 231, 248, 249, 249, 232, 233, 232, 233, 234, 235, 236, 237, 238, 238, 239, 250, 239, 250, 251, 251, 14, 252, 252, 253, 265, 253, 265, 266, 266, 254, 269, 270, 271, 254, 269, 270, 271, 267, 268, 272, 267, 268, 272, 255, 256, 256, 273, 274, 274, 257, 258, 257, 258, 259, 260, 261, 262, 263, 263, 264, 275, 264, 275, 276, 276, 15, 281, 15, 281, 277, 277, 278, 290, 278, 290, 291, 291, 279, 294, 295, 296, 279, 294, 295, 296, 292, 293, 297, 292, 293, 297, 280, 298, 299, 299, 282, 283, 282, 283, 284, 285, 286, 287, 288, 288, 289, 300, 289, 301, 301, 16 }); deviceBuilder.Finish(); } private TouchControl Initialize_ctrlTouchscreenprimaryTouch(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 0).WithParent(parent) .WithChildren(17, 13) .WithName("primaryTouch") .WithDisplayName("Primary Touch") .WithLayout(kTouchLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 0u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private Vector2Control Initialize_ctrlTouchscreenposition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 1).WithParent(parent) .WithChildren(42, 2) .WithName("position") .WithDisplayName("Position") .WithLayout(kVector2Layout) .WithUsages(1, 1) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 4u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreendelta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 2).WithParent(parent) .WithChildren(44, 6) .WithName("delta") .WithDisplayName("Delta") .WithLayout(kDeltaLayout) .WithUsages(2, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 12u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreenpressure(InternedString kAnalogLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 3).WithParent(parent) .WithName("pressure") .WithDisplayName("Pressure") .WithLayout(kAnalogLayout) .WithUsages(3, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 20u, bitOffset = 0u, sizeInBits = 32u }) .WithDefaultState(1) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreenradius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 4).WithParent(parent) .WithChildren(50, 2) .WithName("radius") .WithDisplayName("Radius") .WithLayout(kVector2Layout) .WithUsages(4, 1) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 24u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPressControl Initialize_ctrlTouchscreenpress(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 5).WithParent(parent) .WithName("press") .WithDisplayName("Press") .WithLayout(kTouchPressLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 32u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private TouchControl Initialize_ctrlTouchscreentouch0(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 6).WithParent(parent) .WithChildren(52, 13) .WithName("touch0") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 56u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch1(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 7).WithParent(parent) .WithChildren(77, 13) .WithName("touch1") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 112u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch2(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 8).WithParent(parent) .WithChildren(102, 13) .WithName("touch2") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 168u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch3(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 9).WithParent(parent) .WithChildren(127, 13) .WithName("touch3") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 224u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch4(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 10).WithParent(parent) .WithChildren(152, 13) .WithName("touch4") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 280u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch5(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 11).WithParent(parent) .WithChildren(177, 13) .WithName("touch5") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 336u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch6(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 12).WithParent(parent) .WithChildren(202, 13) .WithName("touch6") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 392u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch7(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 13).WithParent(parent) .WithChildren(227, 13) .WithName("touch7") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 448u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch8(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 14).WithParent(parent) .WithChildren(252, 13) .WithName("touch8") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 504u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private TouchControl Initialize_ctrlTouchscreentouch9(InternedString kTouchLayout, InputControl parent) { TouchControl touchControl = new TouchControl(); touchControl.Setup().At(this, 15).WithParent(parent) .WithChildren(277, 13) .WithName("touch9") .WithDisplayName("Touch") .WithLayout(kTouchLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1414485315), byteOffset = 560u, bitOffset = 0u, sizeInBits = 448u }) .Finish(); return touchControl; } private IntegerControl Initialize_ctrlTouchscreendisplayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 16).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1431521364), byteOffset = 34u, bitOffset = 0u, sizeInBits = 16u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreenprimaryTouchtouchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 17).WithParent(parent) .WithName("touchId") .WithDisplayName("Primary Touch Touch ID") .WithShortDisplayName("Primary Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 0u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreenprimaryTouchposition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 18).WithParent(parent) .WithChildren(30, 2) .WithName("position") .WithDisplayName("Primary Touch Position") .WithShortDisplayName("Primary Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 4u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreenprimaryTouchdelta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 19).WithParent(parent) .WithChildren(32, 6) .WithName("delta") .WithDisplayName("Primary Touch Delta") .WithShortDisplayName("Primary Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 12u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchpressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 20).WithParent(parent) .WithName("pressure") .WithDisplayName("Primary Touch Pressure") .WithShortDisplayName("Primary Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 20u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreenprimaryTouchradius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 21).WithParent(parent) .WithChildren(38, 2) .WithName("radius") .WithDisplayName("Primary Touch Radius") .WithShortDisplayName("Primary Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 24u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreenprimaryTouchphase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 22).WithParent(parent) .WithName("phase") .WithDisplayName("Primary Touch Touch Phase") .WithShortDisplayName("Primary Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 32u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreenprimaryTouchpress(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 23).WithParent(parent) .WithName("press") .WithDisplayName("Primary Touch Touch Contact?") .WithShortDisplayName("Primary Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 32u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreenprimaryTouchtapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 24).WithParent(parent) .WithName("tapCount") .WithDisplayName("Primary Touch Tap Count") .WithShortDisplayName("Primary Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 33u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreenprimaryTouchdisplayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 25).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Primary Touch Display Index") .WithShortDisplayName("Primary Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 34u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreenprimaryTouchindirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 26).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Primary Touch Indirect Touch?") .WithShortDisplayName("Primary Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 35u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreenprimaryTouchtap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 27).WithParent(parent) .WithName("tap") .WithDisplayName("Primary Touch Tap") .WithShortDisplayName("Primary Touch Tap") .WithLayout(kButtonLayout) .WithUsages(0, 1) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 35u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreenprimaryTouchstartTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 28).WithParent(parent) .WithName("startTime") .WithDisplayName("Primary Touch Start Time") .WithShortDisplayName("Primary Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 40u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreenprimaryTouchstartPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 29).WithParent(parent) .WithChildren(40, 2) .WithName("startPosition") .WithDisplayName("Primary Touch Start Position") .WithShortDisplayName("Primary Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 48u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchpositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 30).WithParent(parent) .WithName("x") .WithDisplayName("Primary Touch Primary Touch Position X") .WithShortDisplayName("Primary Touch Primary Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 4u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchpositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 31).WithParent(parent) .WithName("y") .WithDisplayName("Primary Touch Primary Touch Position Y") .WithShortDisplayName("Primary Touch Primary Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 8u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchdeltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 32).WithParent(parent) .WithName("up") .WithDisplayName("Primary Touch Primary Touch Delta Up") .WithShortDisplayName("Primary Touch Primary Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchdeltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 33).WithParent(parent) .WithName("down") .WithDisplayName("Primary Touch Primary Touch Delta Down") .WithShortDisplayName("Primary Touch Primary Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchdeltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 34).WithParent(parent) .WithName("left") .WithDisplayName("Primary Touch Primary Touch Delta Left") .WithShortDisplayName("Primary Touch Primary Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchdeltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 35).WithParent(parent) .WithName("right") .WithDisplayName("Primary Touch Primary Touch Delta Right") .WithShortDisplayName("Primary Touch Primary Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchdeltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 36).WithParent(parent) .WithName("x") .WithDisplayName("Primary Touch Primary Touch Delta X") .WithShortDisplayName("Primary Touch Primary Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchdeltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 37).WithParent(parent) .WithName("y") .WithDisplayName("Primary Touch Primary Touch Delta Y") .WithShortDisplayName("Primary Touch Primary Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchradiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 38).WithParent(parent) .WithName("x") .WithDisplayName("Primary Touch Primary Touch Radius X") .WithShortDisplayName("Primary Touch Primary Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 24u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchradiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 39).WithParent(parent) .WithName("y") .WithDisplayName("Primary Touch Primary Touch Radius Y") .WithShortDisplayName("Primary Touch Primary Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 28u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchstartPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 40).WithParent(parent) .WithName("x") .WithDisplayName("Primary Touch Primary Touch Start Position X") .WithShortDisplayName("Primary Touch Primary Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 48u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenprimaryTouchstartPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 41).WithParent(parent) .WithName("y") .WithDisplayName("Primary Touch Primary Touch Start Position Y") .WithShortDisplayName("Primary Touch Primary Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 52u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenpositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 42).WithParent(parent) .WithName("x") .WithDisplayName("Position X") .WithShortDisplayName("Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 4u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenpositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 43).WithParent(parent) .WithName("y") .WithDisplayName("Position Y") .WithShortDisplayName("Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 8u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreendeltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 44).WithParent(parent) .WithName("up") .WithDisplayName("Delta Up") .WithShortDisplayName("Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreendeltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 45).WithParent(parent) .WithName("down") .WithDisplayName("Delta Down") .WithShortDisplayName("Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreendeltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 46).WithParent(parent) .WithName("left") .WithDisplayName("Delta Left") .WithShortDisplayName("Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreendeltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 47).WithParent(parent) .WithName("right") .WithDisplayName("Delta Right") .WithShortDisplayName("Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreendeltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 48).WithParent(parent) .WithName("x") .WithDisplayName("Delta X") .WithShortDisplayName("Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 12u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreendeltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 49).WithParent(parent) .WithName("y") .WithDisplayName("Delta Y") .WithShortDisplayName("Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 16u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenradiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 50).WithParent(parent) .WithName("x") .WithDisplayName("Radius X") .WithShortDisplayName("Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 24u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreenradiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 51).WithParent(parent) .WithName("y") .WithDisplayName("Radius Y") .WithShortDisplayName("Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 28u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch0touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 52).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 56u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch0position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 53).WithParent(parent) .WithChildren(65, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 60u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch0delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 54).WithParent(parent) .WithChildren(67, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 68u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch0pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 55).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 76u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch0radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 56).WithParent(parent) .WithChildren(73, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 80u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch0phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 57).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 88u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch0press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 58).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 88u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch0tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 59).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 89u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch0displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 60).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 90u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch0indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 61).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 91u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch0tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 62).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 91u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch0startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 63).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 96u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch0startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 64).WithParent(parent) .WithChildren(75, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 104u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch0positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 65).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 60u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 66).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 64u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 67).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 72u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch0deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 68).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 72u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch0deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 69).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 68u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch0deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 70).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 68u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch0deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 71).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 68u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 72).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 72u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 73).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 80u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 74).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 84u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 75).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 104u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch0startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 76).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 108u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch1touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 77).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 112u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch1position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 78).WithParent(parent) .WithChildren(90, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 116u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch1delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 79).WithParent(parent) .WithChildren(92, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 124u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch1pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 80).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 132u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch1radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 81).WithParent(parent) .WithChildren(98, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 136u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch1phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 82).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 144u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch1press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 83).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 144u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch1tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 84).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 145u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch1displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 85).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 146u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch1indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 86).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 147u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch1tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 87).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 147u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch1startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 88).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 152u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch1startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 89).WithParent(parent) .WithChildren(100, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 160u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch1positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 90).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 116u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 91).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 120u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 92).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 128u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch1deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 93).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 128u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch1deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 94).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 124u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch1deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 95).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 124u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch1deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 96).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 124u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 97).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 128u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 98).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 136u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 99).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 140u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 100).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 160u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch1startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 101).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 164u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch2touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 102).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 168u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch2position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 103).WithParent(parent) .WithChildren(115, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 172u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch2delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 104).WithParent(parent) .WithChildren(117, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 180u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch2pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 105).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 188u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch2radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 106).WithParent(parent) .WithChildren(123, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 192u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch2phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 107).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 200u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch2press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 108).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 200u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch2tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 109).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 201u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch2displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 110).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 202u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch2indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 111).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 203u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch2tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 112).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 203u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch2startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 113).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 208u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch2startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 114).WithParent(parent) .WithChildren(125, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 216u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch2positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 115).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 172u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 116).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 176u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 117).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 184u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch2deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 118).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 184u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch2deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 119).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 180u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch2deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 120).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 180u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch2deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 121).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 180u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 122).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 184u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 123).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 192u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 124).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 196u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 125).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 216u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch2startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 126).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 220u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch3touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 127).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 224u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch3position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 128).WithParent(parent) .WithChildren(140, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 228u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch3delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 129).WithParent(parent) .WithChildren(142, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 236u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch3pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 130).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 244u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch3radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 131).WithParent(parent) .WithChildren(148, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 248u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch3phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 132).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 256u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch3press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 133).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 256u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch3tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 134).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 257u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch3displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 135).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 258u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch3indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 136).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 259u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch3tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 137).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 259u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch3startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 138).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 264u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch3startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 139).WithParent(parent) .WithChildren(150, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 272u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch3positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 140).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 228u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 141).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 232u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 142).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 240u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch3deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 143).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 240u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch3deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 144).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 236u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch3deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 145).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 236u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch3deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 146).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 236u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 147).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 240u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 148).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 248u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 149).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 252u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 150).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 272u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch3startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 151).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 276u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch4touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 152).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 280u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch4position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 153).WithParent(parent) .WithChildren(165, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 284u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch4delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 154).WithParent(parent) .WithChildren(167, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 292u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch4pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 155).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 300u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch4radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 156).WithParent(parent) .WithChildren(173, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 304u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch4phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 157).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 312u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch4press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 158).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 312u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch4tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 159).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 313u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch4displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 160).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 314u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch4indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 161).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 315u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch4tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 162).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 315u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch4startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 163).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 320u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch4startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 164).WithParent(parent) .WithChildren(175, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 328u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch4positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 165).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 284u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 166).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 288u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 167).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 296u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch4deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 168).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 296u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch4deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 169).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 292u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch4deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 170).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 292u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch4deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 171).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 292u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 172).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 296u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 173).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 304u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 174).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 308u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 175).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 328u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch4startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 176).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 332u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch5touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 177).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 336u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch5position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 178).WithParent(parent) .WithChildren(190, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 340u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch5delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 179).WithParent(parent) .WithChildren(192, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 348u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch5pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 180).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 356u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch5radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 181).WithParent(parent) .WithChildren(198, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 360u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch5phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 182).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 368u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch5press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 183).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 368u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch5tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 184).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 369u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch5displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 185).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 370u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch5indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 186).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 371u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch5tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 187).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 371u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch5startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 188).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 376u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch5startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 189).WithParent(parent) .WithChildren(200, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 384u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch5positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 190).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 340u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 191).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 344u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 192).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 352u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch5deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 193).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 352u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch5deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 194).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 348u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch5deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 195).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 348u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch5deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 196).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 348u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 197).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 352u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 198).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 360u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 199).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 364u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 200).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 384u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch5startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 201).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 388u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch6touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 202).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 392u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch6position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 203).WithParent(parent) .WithChildren(215, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 396u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch6delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 204).WithParent(parent) .WithChildren(217, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 404u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch6pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 205).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 412u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch6radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 206).WithParent(parent) .WithChildren(223, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 416u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch6phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 207).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 424u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch6press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 208).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 424u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch6tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 209).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 425u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch6displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 210).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 426u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch6indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 211).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 427u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch6tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 212).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 427u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch6startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 213).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 432u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch6startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 214).WithParent(parent) .WithChildren(225, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 440u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch6positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 215).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 396u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 216).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 400u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 217).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 408u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch6deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 218).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 408u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch6deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 219).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 404u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch6deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 220).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 404u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch6deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 221).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 404u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 222).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 408u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 223).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 416u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 224).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 420u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 225).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 440u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch6startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 226).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 444u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch7touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 227).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 448u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch7position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 228).WithParent(parent) .WithChildren(240, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 452u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch7delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 229).WithParent(parent) .WithChildren(242, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 460u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch7pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 230).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 468u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch7radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 231).WithParent(parent) .WithChildren(248, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 472u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch7phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 232).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 480u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch7press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 233).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 480u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch7tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 234).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 481u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch7displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 235).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 482u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch7indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 236).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 483u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch7tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 237).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 483u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch7startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 238).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 488u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch7startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 239).WithParent(parent) .WithChildren(250, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 496u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch7positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 240).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 452u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 241).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 456u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 242).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 464u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch7deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 243).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 464u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch7deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 244).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 460u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch7deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 245).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 460u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch7deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 246).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 460u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 247).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 464u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 248).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 472u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 249).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 476u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 250).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 496u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch7startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 251).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 500u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch8touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 252).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 504u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch8position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 253).WithParent(parent) .WithChildren(265, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 508u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch8delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 254).WithParent(parent) .WithChildren(267, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 516u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch8pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 255).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 524u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch8radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 256).WithParent(parent) .WithChildren(273, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 528u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch8phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 257).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 536u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch8press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 258).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 536u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch8tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 259).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 537u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch8displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 260).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 538u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch8indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 261).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 539u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch8tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 262).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 539u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch8startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 263).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 544u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch8startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 264).WithParent(parent) .WithChildren(275, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 552u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch8positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 265).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 508u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 266).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 512u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 267).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 520u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch8deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 268).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 520u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch8deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 269).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 516u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch8deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 270).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 516u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch8deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 271).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 516u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 272).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 520u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 273).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 528u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 274).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 532u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 275).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 552u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch8startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 276).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 556u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private IntegerControl Initialize_ctrlTouchscreentouch9touchId(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 277).WithParent(parent) .WithName("touchId") .WithDisplayName("Touch Touch ID") .WithShortDisplayName("Touch Touch ID") .WithLayout(kIntegerLayout) .IsSynthetic(value: true) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1229870112), byteOffset = 560u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return integerControl; } private Vector2Control Initialize_ctrlTouchscreentouch9position(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 278).WithParent(parent) .WithChildren(290, 2) .WithName("position") .WithDisplayName("Touch Position") .WithShortDisplayName("Touch Position") .WithLayout(kVector2Layout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 564u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private DeltaControl Initialize_ctrlTouchscreentouch9delta(InternedString kDeltaLayout, InputControl parent) { DeltaControl deltaControl = new DeltaControl(); deltaControl.Setup().At(this, 279).WithParent(parent) .WithChildren(292, 6) .WithName("delta") .WithDisplayName("Touch Delta") .WithShortDisplayName("Touch Delta") .WithLayout(kDeltaLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 572u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return deltaControl; } private AxisControl Initialize_ctrlTouchscreentouch9pressure(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 280).WithParent(parent) .WithName("pressure") .WithDisplayName("Touch Pressure") .WithShortDisplayName("Touch Pressure") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 580u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private Vector2Control Initialize_ctrlTouchscreentouch9radius(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 281).WithParent(parent) .WithChildren(298, 2) .WithName("radius") .WithDisplayName("Touch Radius") .WithShortDisplayName("Touch Radius") .WithLayout(kVector2Layout) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 584u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private TouchPhaseControl Initialize_ctrlTouchscreentouch9phase(InternedString kTouchPhaseLayout, InputControl parent) { TouchPhaseControl touchPhaseControl = new TouchPhaseControl(); touchPhaseControl.Setup().At(this, 282).WithParent(parent) .WithName("phase") .WithDisplayName("Touch Touch Phase") .WithShortDisplayName("Touch Touch Phase") .WithLayout(kTouchPhaseLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 592u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return touchPhaseControl; } private TouchPressControl Initialize_ctrlTouchscreentouch9press(InternedString kTouchPressLayout, InputControl parent) { TouchPressControl touchPressControl = new TouchPressControl(); touchPressControl.Setup().At(this, 283).WithParent(parent) .WithName("press") .WithDisplayName("Touch Touch Contact?") .WithShortDisplayName("Touch Touch Contact?") .WithLayout(kTouchPressLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 592u, bitOffset = 0u, sizeInBits = 8u }) .WithMinAndMax(0, 1) .Finish(); return touchPressControl; } private IntegerControl Initialize_ctrlTouchscreentouch9tapCount(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 284).WithParent(parent) .WithName("tapCount") .WithDisplayName("Touch Tap Count") .WithShortDisplayName("Touch Tap Count") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 593u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private IntegerControl Initialize_ctrlTouchscreentouch9displayIndex(InternedString kIntegerLayout, InputControl parent) { IntegerControl integerControl = new IntegerControl(); integerControl.Setup().At(this, 285).WithParent(parent) .WithName("displayIndex") .WithDisplayName("Touch Display Index") .WithShortDisplayName("Touch Display Index") .WithLayout(kIntegerLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1113150533), byteOffset = 594u, bitOffset = 0u, sizeInBits = 8u }) .Finish(); return integerControl; } private ButtonControl Initialize_ctrlTouchscreentouch9indirectTouch(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 286).WithParent(parent) .WithName("indirectTouch") .WithDisplayName("Touch Indirect Touch?") .WithShortDisplayName("Touch Indirect Touch?") .WithLayout(kButtonLayout) .IsSynthetic(value: true) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 595u, bitOffset = 0u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private ButtonControl Initialize_ctrlTouchscreentouch9tap(InternedString kButtonLayout, InputControl parent) { ButtonControl buttonControl = new ButtonControl(); buttonControl.Setup().At(this, 287).WithParent(parent) .WithName("tap") .WithDisplayName("Touch Tap") .WithShortDisplayName("Touch Tap") .WithLayout(kButtonLayout) .IsButton(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1112101920), byteOffset = 595u, bitOffset = 4u, sizeInBits = 1u }) .WithMinAndMax(0, 1) .Finish(); return buttonControl; } private DoubleControl Initialize_ctrlTouchscreentouch9startTime(InternedString kDoubleLayout, InputControl parent) { DoubleControl doubleControl = new DoubleControl(); doubleControl.Setup().At(this, 288).WithParent(parent) .WithName("startTime") .WithDisplayName("Touch Start Time") .WithShortDisplayName("Touch Start Time") .WithLayout(kDoubleLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1145195552), byteOffset = 600u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return doubleControl; } private Vector2Control Initialize_ctrlTouchscreentouch9startPosition(InternedString kVector2Layout, InputControl parent) { Vector2Control vector2Control = new Vector2Control(); vector2Control.Setup().At(this, 289).WithParent(parent) .WithChildren(300, 2) .WithName("startPosition") .WithDisplayName("Touch Start Position") .WithShortDisplayName("Touch Start Position") .WithLayout(kVector2Layout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1447379762), byteOffset = 608u, bitOffset = 0u, sizeInBits = 64u }) .Finish(); return vector2Control; } private AxisControl Initialize_ctrlTouchscreentouch9positionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 290).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Position X") .WithShortDisplayName("Touch Touch Position X") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 564u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9positiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 291).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Position Y") .WithShortDisplayName("Touch Touch Position Y") .WithLayout(kAxisLayout) .DontReset(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 568u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9deltaup(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 292).WithParent(parent) .WithName("up") .WithDisplayName("Touch Touch Delta Up") .WithShortDisplayName("Touch Touch Delta Up") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 576u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch9deltadown(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 293).WithParent(parent) .WithName("down") .WithDisplayName("Touch Touch Delta Down") .WithShortDisplayName("Touch Touch Delta Down") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 576u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch9deltaleft(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMin = -3.402823E+38f, invert = true }; obj.Setup().At(this, 294).WithParent(parent) .WithName("left") .WithDisplayName("Touch Touch Delta Left") .WithShortDisplayName("Touch Touch Delta Left") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 572u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch9deltaright(InternedString kAxisLayout, InputControl parent) { AxisControl obj = new AxisControl { clamp = AxisControl.Clamp.BeforeNormalize, clampMax = 3.402823E+38f }; obj.Setup().At(this, 295).WithParent(parent) .WithName("right") .WithDisplayName("Touch Touch Delta Right") .WithShortDisplayName("Touch Touch Delta Right") .WithLayout(kAxisLayout) .IsSynthetic(value: true) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 572u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return obj; } private AxisControl Initialize_ctrlTouchscreentouch9deltax(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 296).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Delta X") .WithShortDisplayName("Touch Touch Delta X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 572u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9deltay(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 297).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Delta Y") .WithShortDisplayName("Touch Touch Delta Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 576u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9radiusx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 298).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Radius X") .WithShortDisplayName("Touch Touch Radius X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 584u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9radiusy(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 299).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Radius Y") .WithShortDisplayName("Touch Touch Radius Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 588u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9startPositionx(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 300).WithParent(parent) .WithName("x") .WithDisplayName("Touch Touch Start Position X") .WithShortDisplayName("Touch Touch Start Position X") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 608u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } private AxisControl Initialize_ctrlTouchscreentouch9startPositiony(InternedString kAxisLayout, InputControl parent) { AxisControl axisControl = new AxisControl(); axisControl.Setup().At(this, 301).WithParent(parent) .WithName("y") .WithDisplayName("Touch Touch Start Position Y") .WithShortDisplayName("Touch Touch Start Position Y") .WithLayout(kAxisLayout) .WithStateBlock(new InputStateBlock { format = new FourCC(1179407392), byteOffset = 612u, bitOffset = 0u, sizeInBits = 32u }) .Finish(); return axisControl; } } public sealed class InputRemoting : IObservable, IObserver { public enum MessageType { Connect, Disconnect, NewLayout, NewDevice, NewEvents, RemoveDevice, RemoveLayout, ChangeUsages, StartSending, StopSending } public struct Message { public int participantId; public MessageType type; public byte[] data; } [Flags] private enum Flags { Sending = 1, StartSendingOnConnect = 2 } [Serializable] internal struct RemoteSender { public int senderId; public InternedString[] layouts; public RemoteInputDevice[] devices; } [Serializable] internal struct RemoteInputDevice { public int remoteId; public int localId; public InputDeviceDescription description; } internal class Subscriber : IDisposable { public InputRemoting owner; public IObserver observer; public void Dispose() { ArrayHelpers.Erase(ref owner.m_Subscribers, this); } } private static class ConnectMsg { public static void Process(InputRemoting receiver) { if (receiver.sending) { receiver.SendInitialMessages(); } else if ((receiver.m_Flags & Flags.StartSendingOnConnect) == Flags.StartSendingOnConnect) { receiver.StartSending(); } } } private static class StartSendingMsg { public static void Process(InputRemoting receiver) { receiver.StartSending(); } } private static class StopSendingMsg { public static void Process(InputRemoting receiver) { receiver.StopSending(); } } private static class DisconnectMsg { public static void Process(InputRemoting receiver, Message msg) { Debug.Log((object)"DisconnectMsg.Process"); receiver.RemoveRemoteDevices(msg.participantId); receiver.StopSending(); } } private static class NewLayoutMsg { [Serializable] public struct Data { public string name; public string layoutJson; public bool isOverride; } public static Message? Create(InputRemoting sender, string layoutName) { InputControlLayout inputControlLayout; try { inputControlLayout = sender.m_LocalManager.TryLoadControlLayout(new InternedString(layoutName)); if (inputControlLayout == null) { Debug.Log((object)$"Could not find layout '{layoutName}' meant to be sent through remote connection; this should not happen"); return null; } } catch (Exception arg) { Debug.Log((object)$"Could not load layout '{layoutName}'; not sending to remote listeners (exception: {arg})"); return null; } Data data = new Data { name = layoutName, layoutJson = inputControlLayout.ToJson(), isOverride = inputControlLayout.isOverride }; return new Message { type = MessageType.NewLayout, data = SerializeData(data) }; } public static void Process(InputRemoting receiver, Message msg) { Data data = DeserializeData(msg.data); int num = receiver.FindOrCreateSenderRecord(msg.participantId); InternedString value = new InternedString(data.name); receiver.m_LocalManager.RegisterControlLayout(data.layoutJson, data.name, data.isOverride); ArrayHelpers.Append(ref receiver.m_Senders[num].layouts, value); } } private static class NewDeviceMsg { [Serializable] public struct Data { public string name; public string layout; public int deviceId; public string[] usages; public InputDeviceDescription description; } public static Message Create(InputDevice device) { Data data = new Data { name = device.name, layout = device.layout, deviceId = device.deviceId, description = device.description, usages = device.usages.Select((InternedString x) => x.ToString()).ToArray() }; return new Message { type = MessageType.NewDevice, data = SerializeData(data) }; } public static void Process(InputRemoting receiver, Message msg) { int num = receiver.FindOrCreateSenderRecord(msg.participantId); Data data = DeserializeData(msg.data); RemoteInputDevice[] devices = receiver.m_Senders[num].devices; if (devices != null) { RemoteInputDevice[] array = devices; for (int i = 0; i < array.Length; i++) { if (array[i].remoteId == data.deviceId) { Debug.LogError((object)string.Format("Already received device with id {0} (layout '{1}', description '{3}) from remote {2}", data.deviceId, data.layout, msg.participantId, data.description)); return; } } } InputDevice inputDevice; try { InternedString internedString = new InternedString(data.layout); inputDevice = receiver.m_LocalManager.AddDevice(internedString, data.name); inputDevice.m_ParticipantId = msg.participantId; } catch (Exception arg) { Debug.LogError((object)$"Could not create remote device '{data.description}' with layout '{data.layout}' locally (exception: {arg})"); return; } inputDevice.m_Description = data.description; inputDevice.m_DeviceFlags |= InputDevice.DeviceFlags.Remote; string[] usages = data.usages; foreach (string text in usages) { receiver.m_LocalManager.AddDeviceUsage(inputDevice, new InternedString(text)); } RemoteInputDevice value = new RemoteInputDevice { remoteId = data.deviceId, localId = inputDevice.deviceId, description = data.description }; ArrayHelpers.Append(ref receiver.m_Senders[num].devices, value); } } private static class NewEventsMsg { public unsafe static Message CreateResetEvent(InputDevice device, bool isHardReset) { DeviceResetEvent deviceResetEvent = DeviceResetEvent.Create(device.deviceId, isHardReset); return Create((InputEvent*)UnsafeUtility.AddressOf(ref deviceResetEvent), 1); } public unsafe static Message CreateStateEvent(InputDevice device) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) InputEventPtr eventPtr; NativeArray val = StateEvent.From(device, out eventPtr, (Allocator)2); try { return Create(eventPtr.data, 1); } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } public unsafe static Message Create(InputEvent* events, int eventCount) { uint num = 0u; InputEventPtr inputEventPtr = new InputEventPtr(events); int num2 = 0; while (num2 < eventCount) { num = num.AlignToMultipleOf(4u) + inputEventPtr.sizeInBytes; num2++; inputEventPtr = inputEventPtr.Next(); } byte[] array = new byte[num]; fixed (byte* ptr = array) { UnsafeUtility.MemCpy((void*)ptr, (void*)events, (long)num); } return new Message { type = MessageType.NewEvents, data = array }; } public unsafe static void Process(InputRemoting receiver, Message msg) { InputManager localManager = receiver.m_LocalManager; fixed (byte* data = msg.data) { IntPtr intPtr = new IntPtr(data + msg.data.Length); int num = 0; InputEventPtr ptr = new InputEventPtr((InputEvent*)data); int senderIndex = receiver.FindOrCreateSenderRecord(msg.participantId); while (ptr.data < intPtr.ToPointer()) { int deviceId = ptr.deviceId; if ((ptr.deviceId = receiver.FindLocalDeviceId(deviceId, senderIndex)) != 0) { localManager.QueueEvent(ptr); } num++; ptr = ptr.Next(); } } } } private static class ChangeUsageMsg { [Serializable] public struct Data { public int deviceId; public string[] usages; } public static Message Create(InputDevice device) { Data data = new Data { deviceId = device.deviceId, usages = device.usages.Select((InternedString x) => x.ToString()).ToArray() }; return new Message { type = MessageType.ChangeUsages, data = SerializeData(data) }; } public static void Process(InputRemoting receiver, Message msg) { int senderIndex = receiver.FindOrCreateSenderRecord(msg.participantId); Data data = DeserializeData(msg.data); InputDevice inputDevice = receiver.TryGetDeviceByRemoteId(data.deviceId, senderIndex); if (inputDevice == null) { return; } foreach (InternedString usage in inputDevice.usages) { if (!data.usages.Contains(usage)) { receiver.m_LocalManager.RemoveDeviceUsage(inputDevice, new InternedString(usage)); } } string[] usages = data.usages; foreach (string text in usages) { if (!ReadOnlyArrayExtensions.Contains(value: new InternedString(text), array: inputDevice.usages)) { receiver.m_LocalManager.AddDeviceUsage(inputDevice, new InternedString(text)); } } } } private static class RemoveDeviceMsg { public static Message Create(InputDevice device) { return new Message { type = MessageType.RemoveDevice, data = BitConverter.GetBytes(device.deviceId) }; } public static void Process(InputRemoting receiver, Message msg) { int senderIndex = receiver.FindOrCreateSenderRecord(msg.participantId); int remoteDeviceId = BitConverter.ToInt32(msg.data, 0); InputDevice inputDevice = receiver.TryGetDeviceByRemoteId(remoteDeviceId, senderIndex); if (inputDevice != null) { receiver.m_LocalManager.RemoveDevice(inputDevice); } } } private Flags m_Flags; private InputManager m_LocalManager; private Subscriber[] m_Subscribers; private RemoteSender[] m_Senders; public bool sending { get { return (m_Flags & Flags.Sending) == Flags.Sending; } private set { if (value) { m_Flags |= Flags.Sending; } else { m_Flags &= ~Flags.Sending; } } } internal InputManager manager => m_LocalManager; internal InputRemoting(InputManager manager, bool startSendingOnConnect = false) { if (manager == null) { throw new ArgumentNullException("manager"); } m_LocalManager = manager; if (startSendingOnConnect) { m_Flags |= Flags.StartSendingOnConnect; } } public void StartSending() { if (!sending) { m_LocalManager.onEvent += SendEvent; m_LocalManager.onDeviceChange += SendDeviceChange; m_LocalManager.onLayoutChange += SendLayoutChange; sending = true; SendInitialMessages(); } } public void StopSending() { if (sending) { m_LocalManager.onEvent -= SendEvent; m_LocalManager.onDeviceChange -= SendDeviceChange; m_LocalManager.onLayoutChange -= SendLayoutChange; sending = false; } } void IObserver.OnNext(Message msg) { switch (msg.type) { case MessageType.Connect: ConnectMsg.Process(this); break; case MessageType.Disconnect: DisconnectMsg.Process(this, msg); break; case MessageType.NewLayout: NewLayoutMsg.Process(this, msg); break; case MessageType.NewDevice: NewDeviceMsg.Process(this, msg); break; case MessageType.NewEvents: NewEventsMsg.Process(this, msg); break; case MessageType.ChangeUsages: ChangeUsageMsg.Process(this, msg); break; case MessageType.RemoveDevice: RemoveDeviceMsg.Process(this, msg); break; case MessageType.StartSending: StartSendingMsg.Process(this); break; case MessageType.StopSending: StopSendingMsg.Process(this); break; case MessageType.RemoveLayout: break; } } void IObserver.OnError(Exception error) { } void IObserver.OnCompleted() { } public IDisposable Subscribe(IObserver observer) { if (observer == null) { throw new ArgumentNullException("observer"); } Subscriber subscriber = new Subscriber { owner = this, observer = observer }; ArrayHelpers.Append(ref m_Subscribers, subscriber); return subscriber; } private void SendInitialMessages() { SendAllGeneratedLayouts(); SendAllDevices(); } private void SendAllGeneratedLayouts() { foreach (KeyValuePair> layoutBuilder in m_LocalManager.m_Layouts.layoutBuilders) { SendLayout(layoutBuilder.Key); } } private void SendLayout(string layoutName) { if (m_Subscribers != null) { Message? message = NewLayoutMsg.Create(this, layoutName); if (message.HasValue) { Send(message.Value); } } } private void SendAllDevices() { foreach (InputDevice device in m_LocalManager.devices) { SendDevice(device); } } private void SendDevice(InputDevice device) { if (m_Subscribers != null && !device.remote) { Message msg = NewDeviceMsg.Create(device); Send(msg); Message msg2 = NewEventsMsg.CreateStateEvent(device); Send(msg2); } } private unsafe void SendEvent(InputEventPtr eventPtr, InputDevice device) { if (m_Subscribers != null && (device == null || !device.remote)) { Message msg = NewEventsMsg.Create(eventPtr.data, 1); Send(msg); } } private void SendDeviceChange(InputDevice device, InputDeviceChange change) { if (m_Subscribers != null && !device.remote) { Message msg; switch (change) { case InputDeviceChange.Added: msg = NewDeviceMsg.Create(device); break; case InputDeviceChange.Removed: msg = RemoveDeviceMsg.Create(device); break; case InputDeviceChange.UsageChanged: msg = ChangeUsageMsg.Create(device); break; case InputDeviceChange.SoftReset: msg = NewEventsMsg.CreateResetEvent(device, isHardReset: false); break; case InputDeviceChange.HardReset: msg = NewEventsMsg.CreateResetEvent(device, isHardReset: true); break; default: return; } Send(msg); } } private void SendLayoutChange(string layout, InputControlLayoutChange change) { if (m_Subscribers != null && m_LocalManager.m_Layouts.IsGeneratedLayout(new InternedString(layout)) && (change == InputControlLayoutChange.Added || change == InputControlLayoutChange.Replaced)) { Message? message = NewLayoutMsg.Create(this, layout); if (message.HasValue) { Send(message.Value); } } } private void Send(Message msg) { Subscriber[] subscribers = m_Subscribers; for (int i = 0; i < subscribers.Length; i++) { subscribers[i].observer.OnNext(msg); } } private int FindOrCreateSenderRecord(int senderId) { if (m_Senders != null) { int num = m_Senders.Length; for (int i = 0; i < num; i++) { if (m_Senders[i].senderId == senderId) { return i; } } } RemoteSender value = new RemoteSender { senderId = senderId }; return ArrayHelpers.Append(ref m_Senders, value); } private static InternedString BuildLayoutNamespace(int senderId) { return new InternedString($"Remote::{senderId}"); } private int FindLocalDeviceId(int remoteDeviceId, int senderIndex) { RemoteInputDevice[] devices = m_Senders[senderIndex].devices; if (devices != null) { int num = devices.Length; for (int i = 0; i < num; i++) { if (devices[i].remoteId == remoteDeviceId) { return devices[i].localId; } } } return 0; } private InputDevice TryGetDeviceByRemoteId(int remoteDeviceId, int senderIndex) { int id = FindLocalDeviceId(remoteDeviceId, senderIndex); return m_LocalManager.TryGetDeviceById(id); } public void RemoveRemoteDevices(int participantId) { int num = FindOrCreateSenderRecord(participantId); RemoteInputDevice[] devices = m_Senders[num].devices; if (devices != null) { RemoteInputDevice[] array = devices; for (int i = 0; i < array.Length; i++) { RemoteInputDevice remoteInputDevice = array[i]; InputDevice inputDevice = m_LocalManager.TryGetDeviceById(remoteInputDevice.localId); if (inputDevice != null) { m_LocalManager.RemoveDevice(inputDevice); } } } ArrayHelpers.EraseAt(ref m_Senders, num); } private static byte[] SerializeData(TData data) { string s = JsonUtility.ToJson((object)data); return Encoding.UTF8.GetBytes(s); } private static TData DeserializeData(byte[] data) { return JsonUtility.FromJson(Encoding.UTF8.GetString(data)); } } [Serializable] internal class RemoteInputPlayerConnection : ScriptableObject, IObserver, IObservable { private class Subscriber : IDisposable { public RemoteInputPlayerConnection owner; public IObserver observer; public void Dispose() { ArrayHelpers.Erase(ref owner.m_Subscribers, this); } } public static readonly Guid kNewDeviceMsg = new Guid("fcd9651ded40425995dfa6aeb78f1f1c"); public static readonly Guid kNewLayoutMsg = new Guid("fccfec2b7369466d88502a9dd38505f4"); public static readonly Guid kNewEventsMsg = new Guid("53546641df1347bc8aa315278a603586"); public static readonly Guid kRemoveDeviceMsg = new Guid("e5e299b2d9e44255b8990bb71af8922d"); public static readonly Guid kChangeUsagesMsg = new Guid("b9fe706dfc854d7ca109a5e38d7db730"); public static readonly Guid kStartSendingMsg = new Guid("0d58e99045904672b3ef34b8797d23cb"); public static readonly Guid kStopSendingMsg = new Guid("548716b2534a45369ab0c9323fc8b4a8"); [SerializeField] private IEditorPlayerConnection m_Connection; [NonSerialized] private Subscriber[] m_Subscribers; [SerializeField] private int[] m_ConnectedIds; public void Bind(IEditorPlayerConnection connection, bool isConnected) { if (m_Connection != null) { if (m_Connection != connection) { throw new InvalidOperationException("Already bound to an IEditorPlayerConnection"); } return; } connection.RegisterConnection((UnityAction)OnConnected); connection.RegisterDisconnection((UnityAction)OnDisconnected); connection.Register(kNewDeviceMsg, (UnityAction)OnNewDevice); connection.Register(kNewLayoutMsg, (UnityAction)OnNewLayout); connection.Register(kNewEventsMsg, (UnityAction)OnNewEvents); connection.Register(kRemoveDeviceMsg, (UnityAction)OnRemoveDevice); connection.Register(kChangeUsagesMsg, (UnityAction)OnChangeUsages); connection.Register(kStartSendingMsg, (UnityAction)OnStartSending); connection.Register(kStopSendingMsg, (UnityAction)OnStopSending); m_Connection = connection; if (isConnected) { OnConnected(0); } } public IDisposable Subscribe(IObserver observer) { if (observer == null) { throw new ArgumentNullException("observer"); } Subscriber subscriber = new Subscriber { owner = this, observer = observer }; ArrayHelpers.Append(ref m_Subscribers, subscriber); if (m_ConnectedIds != null) { int[] connectedIds = m_ConnectedIds; foreach (int participantId in connectedIds) { observer.OnNext(new InputRemoting.Message { type = InputRemoting.MessageType.Connect, participantId = participantId }); } } return subscriber; } private void OnConnected(int id) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown if (m_ConnectedIds == null || !ArrayHelpers.Contains(m_ConnectedIds, id)) { ArrayHelpers.Append(ref m_ConnectedIds, id); SendToSubscribers(InputRemoting.MessageType.Connect, new MessageEventArgs { playerId = id }); } } private void OnDisconnected(int id) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown if (m_ConnectedIds != null && ArrayHelpers.Contains(m_ConnectedIds, id)) { ArrayHelpers.Erase(ref m_ConnectedIds, id); SendToSubscribers(InputRemoting.MessageType.Disconnect, new MessageEventArgs { playerId = id }); } } private void OnNewDevice(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.NewDevice, args); } private void OnNewLayout(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.NewLayout, args); } private void OnNewEvents(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.NewEvents, args); } private void OnRemoveDevice(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.RemoveDevice, args); } private void OnChangeUsages(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.ChangeUsages, args); } private void OnStartSending(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.StartSending, args); } private void OnStopSending(MessageEventArgs args) { SendToSubscribers(InputRemoting.MessageType.StopSending, args); } private void SendToSubscribers(InputRemoting.MessageType type, MessageEventArgs args) { if (m_Subscribers != null) { InputRemoting.Message value = new InputRemoting.Message { participantId = args.playerId, type = type, data = args.data }; for (int i = 0; i < m_Subscribers.Length; i++) { m_Subscribers[i].observer.OnNext(value); } } } void IObserver.OnNext(InputRemoting.Message msg) { if (m_Connection != null) { switch (msg.type) { case InputRemoting.MessageType.NewDevice: m_Connection.Send(kNewDeviceMsg, msg.data); break; case InputRemoting.MessageType.NewLayout: m_Connection.Send(kNewLayoutMsg, msg.data); break; case InputRemoting.MessageType.NewEvents: m_Connection.Send(kNewEventsMsg, msg.data); break; case InputRemoting.MessageType.ChangeUsages: m_Connection.Send(kChangeUsagesMsg, msg.data); break; case InputRemoting.MessageType.RemoveDevice: m_Connection.Send(kRemoveDeviceMsg, msg.data); break; case InputRemoting.MessageType.RemoveLayout: break; } } } void IObserver.OnError(Exception error) { } void IObserver.OnCompleted() { } } [InputControlLayout(isGenericTypeOfDevice = true)] public class Sensor : InputDevice { public float samplingFrequency { get { QuerySamplingFrequencyCommand command = QuerySamplingFrequencyCommand.Create(); if (ExecuteCommand(ref command) >= 0) { return command.frequency; } throw new NotSupportedException($"Device '{this}' does not support querying sampling frequency"); } set { SetSamplingFrequencyCommand command = SetSamplingFrequencyCommand.Create(value); ExecuteCommand(ref command); } } } [InputControlLayout(stateType = typeof(AccelerometerState))] public class Accelerometer : Sensor { public Vector3Control acceleration { get; private set; } public static Accelerometer current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { acceleration = GetChildControl("acceleration"); base.FinishSetup(); } } [InputControlLayout(stateType = typeof(GyroscopeState))] public class Gyroscope : Sensor { public Vector3Control angularVelocity { get; private set; } public static Gyroscope current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { angularVelocity = GetChildControl("angularVelocity"); base.FinishSetup(); } } [InputControlLayout(stateType = typeof(GravityState), displayName = "Gravity")] public class GravitySensor : Sensor { public Vector3Control gravity { get; private set; } public static GravitySensor current { get; private set; } protected override void FinishSetup() { gravity = GetChildControl("gravity"); base.FinishSetup(); } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } } [InputControlLayout(stateType = typeof(AttitudeState), displayName = "Attitude")] public class AttitudeSensor : Sensor { public QuaternionControl attitude { get; private set; } public static AttitudeSensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { attitude = GetChildControl("attitude"); base.FinishSetup(); } } [InputControlLayout(stateType = typeof(LinearAccelerationState), displayName = "Linear Acceleration")] public class LinearAccelerationSensor : Sensor { public Vector3Control acceleration { get; private set; } public static LinearAccelerationSensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { acceleration = GetChildControl("acceleration"); base.FinishSetup(); } } [InputControlLayout(displayName = "Magnetic Field")] public class MagneticFieldSensor : Sensor { [InputControl(displayName = "Magnetic Field", noisy = true)] public Vector3Control magneticField { get; private set; } public static MagneticFieldSensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { magneticField = GetChildControl("magneticField"); base.FinishSetup(); } } [InputControlLayout(displayName = "Light")] public class LightSensor : Sensor { [InputControl(displayName = "Light Level", noisy = true)] public AxisControl lightLevel { get; private set; } public static LightSensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { lightLevel = GetChildControl("lightLevel"); base.FinishSetup(); } } [InputControlLayout(displayName = "Pressure")] public class PressureSensor : Sensor { [InputControl(displayName = "Atmospheric Pressure", noisy = true)] public AxisControl atmosphericPressure { get; private set; } public static PressureSensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { atmosphericPressure = GetChildControl("atmosphericPressure"); base.FinishSetup(); } } [InputControlLayout(displayName = "Proximity")] public class ProximitySensor : Sensor { [InputControl(displayName = "Distance", noisy = true)] public AxisControl distance { get; private set; } public static ProximitySensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { distance = GetChildControl("distance"); base.FinishSetup(); } } [InputControlLayout(displayName = "Humidity")] public class HumiditySensor : Sensor { [InputControl(displayName = "Relative Humidity", noisy = true)] public AxisControl relativeHumidity { get; private set; } public static HumiditySensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { relativeHumidity = GetChildControl("relativeHumidity"); base.FinishSetup(); } } [InputControlLayout(displayName = "Ambient Temperature")] public class AmbientTemperatureSensor : Sensor { [InputControl(displayName = "Ambient Temperature", noisy = true)] public AxisControl ambientTemperature { get; private set; } public static AmbientTemperatureSensor current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { ambientTemperature = GetChildControl("ambientTemperature"); base.FinishSetup(); } } [InputControlLayout(displayName = "Step Counter")] public class StepCounter : Sensor { [InputControl(displayName = "Step Counter", noisy = true)] public IntegerControl stepCounter { get; private set; } public static StepCounter current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { stepCounter = GetChildControl("stepCounter"); base.FinishSetup(); } } public enum TouchPhase { None, Began, Moved, Ended, Canceled, Stationary } [InputControlLayout(stateType = typeof(TouchscreenState), isGenericTypeOfDevice = true)] public class Touchscreen : Pointer, IInputStateCallbackReceiver, IEventMerger, ICustomDeviceReset { internal static float s_TapTime; internal static float s_TapDelayTime; internal static float s_TapRadiusSquared; public TouchControl primaryTouch { get; protected set; } public ReadOnlyArray touches { get; protected set; } protected TouchControl[] touchControlArray { get { return touches.m_Array; } set { touches = new ReadOnlyArray(value); } } public new static Touchscreen current { get; internal set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { base.FinishSetup(); primaryTouch = GetChildControl("primaryTouch"); base.displayIndex = primaryTouch.displayIndex; int num = 0; foreach (InputControl child in base.children) { if (child is TouchControl) { num++; } } if (num >= 1) { num--; } TouchControl[] array = new TouchControl[num]; int num2 = 0; foreach (InputControl child2 in base.children) { if (child2 != primaryTouch && child2 is TouchControl touchControl) { array[num2++] = touchControl; } } touches = new ReadOnlyArray(array); } protected new unsafe void OnNextUpdate() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) void* ptr = base.currentStatePtr; TouchState* ptr2 = (TouchState*)((byte*)ptr + base.stateBlock.byteOffset + 56); int num = 0; while (num < touches.Count) { if (ptr2->delta != default(Vector2)) { InputState.Change((InputControl)touches[num].delta, Vector2.zero, InputUpdateType.None, default(InputEventPtr)); } if (ptr2->tapCount > 0 && InputState.currentTime >= ptr2->startTime + (double)s_TapTime + (double)s_TapDelayTime) { InputState.Change((InputControl)touches[num].tapCount, (byte)0, InputUpdateType.None, default(InputEventPtr)); } num++; ptr2++; } TouchState* ptr3 = (TouchState*)((byte*)ptr + base.stateBlock.byteOffset); if (ptr3->delta != default(Vector2)) { InputState.Change((InputControl)primaryTouch.delta, Vector2.zero, InputUpdateType.None, default(InputEventPtr)); } if (ptr3->tapCount > 0 && InputState.currentTime >= ptr3->startTime + (double)s_TapTime + (double)s_TapDelayTime) { InputState.Change((InputControl)primaryTouch.tapCount, (byte)0, InputUpdateType.None, default(InputEventPtr)); } } protected new unsafe void OnStateEvent(InputEventPtr eventPtr) { //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_03ce: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) if (eventPtr.type == 1145852993) { return; } StateEvent* ptr = StateEvent.FromUnchecked(eventPtr); if (ptr->stateFormat != TouchState.Format) { InputState.Change(this, eventPtr); return; } void* num = base.currentStatePtr; TouchState* ptr2 = (TouchState*)((byte*)num + touches[0].stateBlock.byteOffset); TouchState* ptr3 = (TouchState*)((byte*)num + primaryTouch.stateBlock.byteOffset); int count = touches.Count; TouchState state; if (ptr->stateSizeInBytes == 56) { state = Unsafe.Read(ptr->state); } else { state = default(TouchState); UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref state), ptr->state, (long)ptr->stateSizeInBytes); } state.tapCount = 0; state.isTapPress = false; state.isTapRelease = false; state.updateStepCount = InputUpdate.s_UpdateStepCount; if (state.phase != TouchPhase.Began) { int touchId = state.touchId; for (int i = 0; i < count; i++) { if (ptr2[i].touchId != touchId) { continue; } bool flag = (state.isPrimaryTouch = ptr2[i].isPrimaryTouch); Vector2 val = state.delta; Vector2 val2 = default(Vector2); if (val == val2) { state.delta = state.position - ptr2[i].position; } ref Vector2 reference = ref state.delta; reference += ptr2[i].delta; state.startTime = ptr2[i].startTime; state.startPosition = ptr2[i].startPosition; int num2; if (state.isNoneEndedOrCanceled && eventPtr.time - state.startTime <= (double)s_TapTime) { val2 = state.position - state.startPosition; num2 = ((((Vector2)(ref val2)).sqrMagnitude <= s_TapRadiusSquared) ? 1 : 0); } else { num2 = 0; } bool flag2 = (byte)num2 != 0; if (flag2) { state.tapCount = (byte)(ptr2[i].tapCount + 1); } else { state.tapCount = ptr2[i].tapCount; } if (flag) { if (state.isNoneEndedOrCanceled) { state.isPrimaryTouch = false; bool flag3 = false; for (int j = 0; j < count; j++) { if (j != i && ptr2[j].isInProgress) { flag3 = true; break; } } if (!flag3) { if (flag2) { TriggerTap(primaryTouch, ref state, eventPtr); } else { InputState.Change(primaryTouch, ref state, InputUpdateType.None, eventPtr); } } else { TouchState state2 = state; state2.phase = TouchPhase.Moved; state2.isOrphanedPrimaryTouch = true; InputState.Change(primaryTouch, ref state2, InputUpdateType.None, eventPtr); } } else { InputState.Change(primaryTouch, ref state, InputUpdateType.None, eventPtr); } } else if (state.isNoneEndedOrCanceled && ptr3->isOrphanedPrimaryTouch) { bool flag4 = false; for (int k = 0; k < count; k++) { if (k != i && ptr2[k].isInProgress) { flag4 = true; break; } } if (!flag4) { ptr3->isOrphanedPrimaryTouch = false; InputState.Change((InputControl)primaryTouch.phase, (byte)3, InputUpdateType.None, default(InputEventPtr)); } } if (flag2) { TriggerTap(touches[i], ref state, eventPtr); } else { InputState.Change(touches[i], ref state, InputUpdateType.None, eventPtr); } break; } return; } int num3 = 0; while (num3 < count) { if (ptr2->isNoneEndedOrCanceled) { state.delta = Vector2.zero; state.startTime = eventPtr.time; state.startPosition = state.position; state.isPrimaryTouch = false; state.isOrphanedPrimaryTouch = false; state.isTap = false; state.tapCount = ptr2->tapCount; if (ptr3->isNoneEndedOrCanceled) { state.isPrimaryTouch = true; InputState.Change(primaryTouch, ref state, InputUpdateType.None, eventPtr); } InputState.Change(touches[num3], ref state, InputUpdateType.None, eventPtr); break; } num3++; ptr2++; } } void IInputStateCallbackReceiver.OnNextUpdate() { OnNextUpdate(); } void IInputStateCallbackReceiver.OnStateEvent(InputEventPtr eventPtr) { OnStateEvent(eventPtr); } unsafe bool IInputStateCallbackReceiver.GetStateOffsetForEvent(InputControl control, InputEventPtr eventPtr, ref uint offset) { if (!eventPtr.IsA()) { return false; } StateEvent* ptr = StateEvent.FromUnchecked(eventPtr); if (ptr->stateFormat != TouchState.Format) { return false; } if (control == null) { TouchState* ptr2 = (TouchState*)((byte*)base.currentStatePtr + touches[0].stateBlock.byteOffset); TouchState* state = (TouchState*)ptr->state; int touchId = state->touchId; TouchPhase phase = state->phase; int count = touches.Count; for (int i = 0; i < count; i++) { TouchState* ptr3 = ptr2 + i; if (ptr3->touchId == touchId || (!ptr3->isInProgress && phase.IsActive())) { offset = primaryTouch.m_StateBlock.byteOffset + primaryTouch.m_StateBlock.alignedSizeInBytes - m_StateBlock.byteOffset + (uint)(i * UnsafeUtility.SizeOf()); return true; } } return false; } TouchControl touchControl = control.FindInParentChain(); if (touchControl == null || touchControl.parent != this) { return false; } if (touchControl != primaryTouch) { return false; } offset = touchControl.stateBlock.byteOffset - m_StateBlock.byteOffset; return true; } unsafe void ICustomDeviceReset.Reset() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) void* ptr = base.currentStatePtr; NativeArray val = default(NativeArray); val..ctor(StateEvent.GetEventSizeWithPayload(), (Allocator)2, (NativeArrayOptions)1); try { StateEvent* unsafePtr = (StateEvent*)NativeArrayUnsafeUtility.GetUnsafePtr(val); Unsafe.Write(&unsafePtr->baseEvent, new InputEvent(1398030676, val.Length, base.deviceId)); TouchState* ptr2 = (TouchState*)((byte*)ptr + primaryTouch.stateBlock.byteOffset); if (ptr2->phase.IsActive()) { UnsafeUtility.MemCpy(unsafePtr->state, (void*)ptr2, (long)UnsafeUtility.SizeOf()); ((TouchState*)unsafePtr->state)->phase = TouchPhase.Canceled; InputState.Change(primaryTouch.phase, TouchPhase.Canceled, InputUpdateType.None, new InputEventPtr((InputEvent*)unsafePtr)); } TouchState* ptr3 = (TouchState*)((byte*)ptr + touches[0].stateBlock.byteOffset); int count = touches.Count; for (int i = 0; i < count; i++) { if (ptr3[i].phase.IsActive()) { UnsafeUtility.MemCpy(unsafePtr->state, (void*)(ptr3 + i), (long)UnsafeUtility.SizeOf()); ((TouchState*)unsafePtr->state)->phase = TouchPhase.Canceled; InputState.Change(touches[i].phase, TouchPhase.Canceled, InputUpdateType.None, new InputEventPtr((InputEvent*)unsafePtr)); } } } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } internal unsafe static bool MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) if (currentEventPtr.type != 1398030676 || nextEventPtr.type != 1398030676) { return false; } StateEvent* ptr = StateEvent.FromUnchecked(currentEventPtr); StateEvent* ptr2 = StateEvent.FromUnchecked(nextEventPtr); if (ptr->stateFormat != TouchState.Format || ptr2->stateFormat != TouchState.Format) { return false; } TouchState* state = (TouchState*)ptr->state; TouchState* state2 = (TouchState*)ptr2->state; if (state->touchId != state2->touchId || state->phaseId != state2->phaseId || state->flags != state2->flags) { return false; } Vector2* intPtr = &state2->delta; Unsafe.Write(intPtr, *intPtr + state->delta); return true; } bool IEventMerger.MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr) { return MergeForward(currentEventPtr, nextEventPtr); } private static void TriggerTap(TouchControl control, ref TouchState state, InputEventPtr eventPtr) { state.isTapPress = true; state.isTapRelease = false; InputState.Change(control, ref state, InputUpdateType.None, eventPtr); state.isTapPress = false; state.isTapRelease = true; InputState.Change(control, ref state, InputUpdateType.None, eventPtr); state.isTapRelease = false; } } [InputControlLayout(displayName = "Tracked Device", isGenericTypeOfDevice = true)] public class TrackedDevice : InputDevice { [InputControl(synthetic = true)] public IntegerControl trackingState { get; private set; } [InputControl(synthetic = true)] public ButtonControl isTracked { get; private set; } [InputControl(noisy = true, dontReset = true)] public Vector3Control devicePosition { get; private set; } [InputControl(noisy = true, dontReset = true)] public QuaternionControl deviceRotation { get; private set; } protected override void FinishSetup() { base.FinishSetup(); trackingState = GetChildControl("trackingState"); isTracked = GetChildControl("isTracked"); devicePosition = GetChildControl("devicePosition"); deviceRotation = GetChildControl("deviceRotation"); } } internal static class InputAnalytics { [Serializable] public struct StartupEventData { [Serializable] public struct DeviceInfo { public string layout; public string @interface; public string product; public bool native; public static DeviceInfo FromDescription(InputDeviceDescription description, bool native = false, string layout = null) { string text = ((!string.IsNullOrEmpty(description.product) && !string.IsNullOrEmpty(description.manufacturer)) ? (description.manufacturer + " " + description.product) : (string.IsNullOrEmpty(description.product) ? description.manufacturer : description.product)); if (string.IsNullOrEmpty(layout)) { layout = description.deviceClass; } return new DeviceInfo { layout = layout, @interface = description.interfaceName, product = text, native = native }; } } public string version; public DeviceInfo[] devices; public DeviceInfo[] unrecognized_devices; } [Serializable] [StructLayout(LayoutKind.Sequential, Size = 1)] public struct FirstUserInteractionEventData { } [Serializable] public struct ShutdownEventData { public int max_num_devices; public int max_state_size_in_bytes; public int total_event_bytes; public int total_event_count; public int total_frame_count; public float total_event_processing_time; } public const string kEventStartup = "input_startup"; public const string kEventShutdown = "input_shutdown"; public static void Initialize(InputManager manager) { } public static void OnStartup(InputManager manager) { StartupEventData startupEventData = new StartupEventData { version = InputSystem.version.ToString() }; ReadOnlyArray devices = manager.devices; List list = new List(); for (int i = 0; i < devices.Count; i++) { InputDevice inputDevice = devices[i]; list.Add(StartupEventData.DeviceInfo.FromDescription(inputDevice.description, inputDevice.native, inputDevice.layout)); } startupEventData.devices = list.ToArray(); list.Clear(); InputManager.AvailableDevice[] availableDevices = manager.m_AvailableDevices; int availableDeviceCount = manager.m_AvailableDeviceCount; for (int j = 0; j < availableDeviceCount; j++) { int deviceId = availableDevices[j].deviceId; if (manager.TryGetDeviceById(deviceId) == null) { list.Add(StartupEventData.DeviceInfo.FromDescription(availableDevices[j].description, availableDevices[j].isNative)); } } startupEventData.unrecognized_devices = list.ToArray(); manager.m_Runtime.RegisterAnalyticsEvent("input_startup", 10, 100); manager.m_Runtime.SendAnalyticsEvent("input_startup", startupEventData); } public static void OnShutdown(InputManager manager) { InputMetrics metrics = manager.metrics; ShutdownEventData shutdownEventData = new ShutdownEventData { max_num_devices = metrics.maxNumDevices, max_state_size_in_bytes = metrics.maxStateSizeInBytes, total_event_bytes = metrics.totalEventBytes, total_event_count = metrics.totalEventCount, total_frame_count = metrics.totalUpdateCount, total_event_processing_time = (float)metrics.totalEventProcessingTime }; manager.m_Runtime.RegisterAnalyticsEvent("input_shutdown", 10, 100); manager.m_Runtime.SendAnalyticsEvent("input_shutdown", shutdownEventData); } } public static class InputExtensions { public static bool IsInProgress(this InputActionPhase phase) { if (phase != InputActionPhase.Started) { return phase == InputActionPhase.Performed; } return true; } public static bool IsEndedOrCanceled(this TouchPhase phase) { if (phase != TouchPhase.Canceled) { return phase == TouchPhase.Ended; } return true; } public static bool IsActive(this TouchPhase phase) { if ((uint)(phase - 1) <= 1u || phase == TouchPhase.Stationary) { return true; } return false; } public static bool IsModifierKey(this Key key) { if ((uint)(key - 51) <= 7u) { return true; } return false; } public static bool IsTextInputKey(this Key key) { if ((uint)key <= 3u || (uint)(key - 51) <= 26u || (uint)(key - 94) <= 17u) { return false; } return true; } } internal static class InputFeatureNames { public const string kRunPlayerUpdatesInEditMode = "RUN_PLAYER_UPDATES_IN_EDIT_MODE"; public const string kDisableUnityRemoteSupport = "DISABLE_UNITY_REMOTE_SUPPORT"; public const string kUseWindowsGamingInputBackend = "USE_WINDOWS_GAMING_INPUT_BACKEND"; public const string kUseOptimizedControls = "USE_OPTIMIZED_CONTROLS"; public const string kUseReadValueCaching = "USE_READ_VALUE_CACHING"; public const string kParanoidReadValueCachingChecks = "PARANOID_READ_VALUE_CACHING_CHECKS"; } internal class InputManager { internal enum DeviceDisableScope { Everywhere, InFrontendOnly, TemporaryWhilePlayerIsInBackground } [Serializable] internal struct AvailableDevice { public InputDeviceDescription description; public int deviceId; public bool isNative; public bool isRemoved; } private struct StateChangeMonitorTimeout { public InputControl control; public double time; public IInputStateChangeMonitor monitor; public long monitorIndex; public int timerIndex; } internal struct StateChangeMonitorListener { public InputControl control; public IInputStateChangeMonitor monitor; public long monitorIndex; public uint groupIndex; } internal struct StateChangeMonitorsForDevice { public MemoryHelpers.BitRegion[] memoryRegions; public StateChangeMonitorListener[] listeners; public DynamicBitfield signalled; public bool needToUpdateOrderingOfMonitors; public bool needToCompactArrays; public int count => signalled.length; public void Add(InputControl control, IInputStateChangeMonitor monitor, long monitorIndex, uint groupIndex) { int length = signalled.length; ArrayHelpers.AppendWithCapacity(ref listeners, ref length, new StateChangeMonitorListener { monitor = monitor, monitorIndex = monitorIndex, groupIndex = groupIndex, control = control }); ref InputStateBlock stateBlock = ref control.m_StateBlock; int length2 = signalled.length; ArrayHelpers.AppendWithCapacity(ref memoryRegions, ref length2, new MemoryHelpers.BitRegion(stateBlock.byteOffset - control.device.stateBlock.byteOffset, stateBlock.bitOffset, stateBlock.sizeInBits)); signalled.SetLength(signalled.length + 1); needToUpdateOrderingOfMonitors = true; } public void Remove(IInputStateChangeMonitor monitor, long monitorIndex, bool deferRemoval) { if (listeners == null) { return; } for (int i = 0; i < signalled.length; i++) { if (listeners[i].monitor == monitor && listeners[i].monitorIndex == monitorIndex) { if (deferRemoval) { listeners[i] = default(StateChangeMonitorListener); memoryRegions[i] = default(MemoryHelpers.BitRegion); signalled.ClearBit(i); needToCompactArrays = true; } else { RemoveAt(i); } break; } } } public void Clear() { listeners.Clear(count); signalled.SetLength(0); needToCompactArrays = false; } public void CompactArrays() { for (int num = count - 1; num >= 0; num--) { if (memoryRegions[num].sizeInBits == 0) { RemoveAt(num); } } needToCompactArrays = false; } private void RemoveAt(int i) { int num = count; int num2 = count; listeners.EraseAtWithCapacity(ref num, i); memoryRegions.EraseAtWithCapacity(ref num2, i); signalled.SetLength(count - 1); } public void SortMonitorsByIndex() { for (int i = 1; i < signalled.length; i++) { for (int num = i; num > 0; num--) { int complexityFromMonitorIndex = InputActionState.GetComplexityFromMonitorIndex(listeners[num - 1].monitorIndex); int complexityFromMonitorIndex2 = InputActionState.GetComplexityFromMonitorIndex(listeners[num].monitorIndex); if (complexityFromMonitorIndex >= complexityFromMonitorIndex2) { break; } listeners.SwapElements(num, num - 1); memoryRegions.SwapElements(num, num - 1); } } needToUpdateOrderingOfMonitors = false; } } internal int m_LayoutRegistrationVersion; private float m_PollingFrequency; internal InputControlLayout.Collection m_Layouts; private TypeTable m_Processors; private TypeTable m_Interactions; private TypeTable m_Composites; private int m_DevicesCount; private InputDevice[] m_Devices; private Dictionary m_DevicesById; internal int m_AvailableDeviceCount; internal AvailableDevice[] m_AvailableDevices; internal int m_DisconnectedDevicesCount; internal InputDevice[] m_DisconnectedDevices; internal InputUpdateType m_UpdateMask; private InputUpdateType m_CurrentUpdate; internal InputStateBuffers m_StateBuffers; private CallbackArray> m_DeviceChangeListeners; private CallbackArray> m_DeviceStateChangeListeners; private CallbackArray m_DeviceFindLayoutCallbacks; internal CallbackArray m_DeviceCommandCallbacks; private CallbackArray> m_LayoutChangeListeners; private CallbackArray> m_EventListeners; private CallbackArray m_BeforeUpdateListeners; private CallbackArray m_AfterUpdateListeners; private CallbackArray m_SettingsChangedListeners; private bool m_NativeBeforeUpdateHooked; private bool m_HaveDevicesWithStateCallbackReceivers; private bool m_HasFocus; private InputEventStream m_InputEventStream; private InputDeviceExecuteCommandDelegate m_DeviceFindExecuteCommandDelegate; private int m_DeviceFindExecuteCommandDeviceId; private bool m_HaveSentStartupAnalytics; internal IInputRuntime m_Runtime; internal InputMetrics m_Metrics; internal InputSettings m_Settings; private bool m_ShouldMakeCurrentlyUpdatingDeviceCurrent; internal StateChangeMonitorsForDevice[] m_StateChangeMonitors; private InlinedArray m_StateChangeMonitorTimeouts; public ReadOnlyArray devices => new ReadOnlyArray(m_Devices, 0, m_DevicesCount); public TypeTable processors => m_Processors; public TypeTable interactions => m_Interactions; public TypeTable composites => m_Composites; public InputMetrics metrics { get { InputMetrics result = m_Metrics; result.currentNumDevices = m_DevicesCount; result.currentStateSizeInBytes = (int)m_StateBuffers.totalSize; result.currentControlCount = m_DevicesCount; for (int i = 0; i < m_DevicesCount; i++) { result.currentControlCount += m_Devices[i].allControls.Count; } result.currentLayoutCount = m_Layouts.layoutTypes.Count; result.currentLayoutCount += m_Layouts.layoutStrings.Count; result.currentLayoutCount += m_Layouts.layoutBuilders.Count; result.currentLayoutCount += m_Layouts.layoutOverrides.Count; return result; } } public InputSettings settings { get { return m_Settings; } set { if ((Object)(object)value == (Object)null) { throw new ArgumentNullException("value"); } if (!((Object)(object)m_Settings == (Object)(object)value)) { m_Settings = value; ApplySettings(); } } } public InputUpdateType updateMask { get { return m_UpdateMask; } set { if (m_UpdateMask != value) { m_UpdateMask = value; if (m_DevicesCount > 0) { ReallocateStateBuffers(); } } } } public InputUpdateType defaultUpdateType { get { if (m_CurrentUpdate != InputUpdateType.None) { return m_CurrentUpdate; } return m_UpdateMask.GetUpdateTypeForPlayer(); } } public float pollingFrequency { get { return m_PollingFrequency; } set { if (value <= 0f) { throw new ArgumentException("Polling frequency must be greater than zero", "value"); } m_PollingFrequency = value; if (m_Runtime != null) { m_Runtime.pollingFrequency = value; } } } public bool isProcessingEvents => m_InputEventStream.isOpen; private bool gameIsPlaying => true; private bool gameHasFocus { get { if (!m_HasFocus) { return gameShouldGetInputRegardlessOfFocus; } return true; } } private bool gameShouldGetInputRegardlessOfFocus => m_Settings.backgroundBehavior == InputSettings.BackgroundBehavior.IgnoreFocus; public event Action onDeviceChange { add { m_DeviceChangeListeners.AddCallback(value); } remove { m_DeviceChangeListeners.RemoveCallback(value); } } public event Action onDeviceStateChange { add { m_DeviceStateChangeListeners.AddCallback(value); } remove { m_DeviceStateChangeListeners.RemoveCallback(value); } } public event InputDeviceCommandDelegate onDeviceCommand { add { m_DeviceCommandCallbacks.AddCallback(value); } remove { m_DeviceCommandCallbacks.RemoveCallback(value); } } public event InputDeviceFindControlLayoutDelegate onFindControlLayoutForDevice { add { m_DeviceFindLayoutCallbacks.AddCallback(value); AddAvailableDevicesThatAreNowRecognized(); } remove { m_DeviceFindLayoutCallbacks.RemoveCallback(value); } } public event Action onLayoutChange { add { m_LayoutChangeListeners.AddCallback(value); } remove { m_LayoutChangeListeners.RemoveCallback(value); } } public event Action onEvent { add { m_EventListeners.AddCallback(value); } remove { m_EventListeners.RemoveCallback(value); } } public event Action onBeforeUpdate { add { InstallBeforeUpdateHookIfNecessary(); m_BeforeUpdateListeners.AddCallback(value); } remove { m_BeforeUpdateListeners.RemoveCallback(value); } } public event Action onAfterUpdate { add { m_AfterUpdateListeners.AddCallback(value); } remove { m_AfterUpdateListeners.RemoveCallback(value); } } public event Action onSettingsChange { add { m_SettingsChangedListeners.AddCallback(value); } remove { m_SettingsChangedListeners.RemoveCallback(value); } } public void RegisterControlLayout(string name, Type type) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (type == null) { throw new ArgumentNullException("type"); } bool flag = typeof(InputDevice).IsAssignableFrom(type); bool flag2 = typeof(InputControl).IsAssignableFrom(type); if (!flag && !flag2) { throw new ArgumentException("Types used as layouts have to be InputControls or InputDevices; '" + type.Name + "' is a '" + type.BaseType.Name + "'", "type"); } InternedString internedString = new InternedString(name); bool isReplacement = m_Layouts.HasLayout(internedString); m_Layouts.layoutTypes[internedString] = type; string text = null; Type baseType = type.BaseType; while (text == null && baseType != typeof(InputControl)) { foreach (KeyValuePair layoutType in m_Layouts.layoutTypes) { if (layoutType.Value == baseType) { text = layoutType.Key; break; } } baseType = baseType.BaseType; } PerformLayoutPostRegistration(internedString, new InlinedArray(new InternedString(text)), isReplacement, flag); } public void RegisterControlLayout(string json, string name = null, bool isOverride = false) { if (string.IsNullOrEmpty(json)) { throw new ArgumentNullException("json"); } InputControlLayout.ParseHeaderFieldsFromJson(json, out var name2, out var baseLayouts, out var deviceMatcher); InternedString internedString = new InternedString(name); if (internedString.IsEmpty()) { internedString = name2; if (internedString.IsEmpty()) { throw new ArgumentException("Layout name has not been given and is not set in JSON layout", "name"); } } if (isOverride && baseLayouts.length == 0) { throw new ArgumentException($"Layout override '{internedString}' must have 'extend' property mentioning layout to which to apply the overrides", "json"); } bool flag = m_Layouts.HasLayout(internedString); if (flag && isOverride && !m_Layouts.layoutOverrideNames.Contains(internedString)) { throw new ArgumentException($"Failed to register layout override '{internedString}'" + $"since a layout named '{internedString}' already exist. Layout overrides must " + "have unique names with respect to existing layouts."); } m_Layouts.layoutStrings[internedString] = json; if (isOverride) { m_Layouts.layoutOverrideNames.Add(internedString); for (int i = 0; i < baseLayouts.length; i++) { InternedString key = baseLayouts[i]; m_Layouts.layoutOverrides.TryGetValue(key, out var value); if (!flag) { ArrayHelpers.Append(ref value, internedString); } m_Layouts.layoutOverrides[key] = value; } } PerformLayoutPostRegistration(internedString, baseLayouts, flag, isKnownToBeDeviceLayout: false, isOverride); if (!deviceMatcher.empty) { RegisterControlLayoutMatcher(internedString, deviceMatcher); } } public void RegisterControlLayoutBuilder(Func method, string name, string baseLayout = null) { if (method == null) { throw new ArgumentNullException("method"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } InternedString internedString = new InternedString(name); InternedString value = new InternedString(baseLayout); bool isReplacement = m_Layouts.HasLayout(internedString); m_Layouts.layoutBuilders[internedString] = method; PerformLayoutPostRegistration(internedString, new InlinedArray(value), isReplacement); } private void PerformLayoutPostRegistration(InternedString layoutName, InlinedArray baseLayouts, bool isReplacement, bool isKnownToBeDeviceLayout = false, bool isOverride = false) { m_LayoutRegistrationVersion++; InputControlLayout.s_CacheInstance.Clear(); if (!isOverride && baseLayouts.length > 0) { if (baseLayouts.length > 1) { throw new NotSupportedException($"Layout '{layoutName}' has multiple base layouts; this is only supported on layout overrides"); } InternedString value = baseLayouts[0]; if (!value.IsEmpty()) { m_Layouts.baseLayoutTable[layoutName] = value; } } m_Layouts.precompiledLayouts.Remove(layoutName); if (m_Layouts.precompiledLayouts.Count > 0) { InternedString[] array = m_Layouts.precompiledLayouts.Keys.ToArray(); foreach (InternedString internedString in array) { string metadata = m_Layouts.precompiledLayouts[internedString].metadata; if (isOverride) { for (int j = 0; j < baseLayouts.length; j++) { if (internedString == baseLayouts[j] || StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(metadata, baseLayouts[j], ';')) { m_Layouts.precompiledLayouts.Remove(internedString); } } } else if (StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(metadata, layoutName, ';')) { m_Layouts.precompiledLayouts.Remove(internedString); } } } if (isOverride) { for (int k = 0; k < baseLayouts.length; k++) { RecreateDevicesUsingLayout(baseLayouts[k], isKnownToBeDeviceLayout); } } else { RecreateDevicesUsingLayout(layoutName, isKnownToBeDeviceLayout); } InputControlLayoutChange argument = (isReplacement ? InputControlLayoutChange.Replaced : InputControlLayoutChange.Added); DelegateHelpers.InvokeCallbacksSafe(ref m_LayoutChangeListeners, layoutName.ToString(), argument, "InputSystem.onLayoutChange"); } public void RegisterPrecompiledLayout(string metadata) where TDevice : InputDevice, new() { if (metadata == null) { throw new ArgumentNullException("metadata"); } Type baseType = typeof(TDevice).BaseType; InternedString key = FindOrRegisterDeviceLayoutForType(baseType); m_Layouts.precompiledLayouts[key] = new InputControlLayout.Collection.PrecompiledLayout { factoryMethod = () => new TDevice(), metadata = metadata }; } private void RecreateDevicesUsingLayout(InternedString layout, bool isKnownToBeDeviceLayout = false) { if (m_DevicesCount == 0) { return; } List list = null; for (int i = 0; i < m_DevicesCount; i++) { InputDevice inputDevice = m_Devices[i]; if ((!isKnownToBeDeviceLayout) ? IsControlOrChildUsingLayoutRecursive(inputDevice, layout) : IsControlUsingLayout(inputDevice, layout)) { if (list == null) { list = new List(); } list.Add(inputDevice); } } if (list == null) { return; } using (InputDeviceBuilder.Ref()) { for (int j = 0; j < list.Count; j++) { InputDevice inputDevice2 = list[j]; RecreateDevice(inputDevice2, inputDevice2.m_Layout); } } } private bool IsControlOrChildUsingLayoutRecursive(InputControl control, InternedString layout) { if (IsControlUsingLayout(control, layout)) { return true; } ReadOnlyArray children = control.children; for (int i = 0; i < children.Count; i++) { if (IsControlOrChildUsingLayoutRecursive(children[i], layout)) { return true; } } return false; } private bool IsControlUsingLayout(InputControl control, InternedString layout) { if (control.layout == layout) { return true; } InternedString value = control.m_Layout; while (m_Layouts.baseLayoutTable.TryGetValue(value, out value)) { if (value == layout) { return true; } } return false; } public void RegisterControlLayoutMatcher(string layoutName, InputDeviceMatcher matcher) { if (string.IsNullOrEmpty(layoutName)) { throw new ArgumentNullException("layoutName"); } if (matcher.empty) { throw new ArgumentException("Matcher cannot be empty", "matcher"); } InternedString layout = new InternedString(layoutName); m_Layouts.AddMatcher(layout, matcher); RecreateDevicesUsingLayoutWithInferiorMatch(matcher); AddAvailableDevicesMatchingDescription(matcher, layout); } public void RegisterControlLayoutMatcher(Type type, InputDeviceMatcher matcher) { if (type == null) { throw new ArgumentNullException("type"); } if (matcher.empty) { throw new ArgumentException("Matcher cannot be empty", "matcher"); } InternedString internedString = m_Layouts.TryFindLayoutForType(type); if (internedString.IsEmpty()) { throw new ArgumentException("Type '" + type.Name + "' has not been registered as a control layout", "type"); } RegisterControlLayoutMatcher(internedString, matcher); } private void RecreateDevicesUsingLayoutWithInferiorMatch(InputDeviceMatcher deviceMatcher) { if (m_DevicesCount == 0) { return; } using (InputDeviceBuilder.Ref()) { int num = m_DevicesCount; for (int i = 0; i < num; i++) { InputDevice inputDevice = m_Devices[i]; InputDeviceDescription deviceDescription = inputDevice.description; if (!deviceDescription.empty && deviceMatcher.MatchPercentage(deviceDescription) > 0f) { InternedString internedString = TryFindMatchingControlLayout(ref deviceDescription, inputDevice.deviceId); if (internedString != inputDevice.m_Layout) { inputDevice.m_Description = deviceDescription; RecreateDevice(inputDevice, internedString); i--; num--; } } } } } private void RecreateDevice(InputDevice oldDevice, InternedString newLayout) { RemoveDevice(oldDevice, keepOnListOfAvailableDevices: true); InputDevice inputDevice = InputDevice.Build(newLayout, oldDevice.m_Variants, oldDevice.m_Description); inputDevice.m_DeviceId = oldDevice.m_DeviceId; inputDevice.m_Description = oldDevice.m_Description; if (oldDevice.native) { inputDevice.m_DeviceFlags |= InputDevice.DeviceFlags.Native; } if (oldDevice.remote) { inputDevice.m_DeviceFlags |= InputDevice.DeviceFlags.Remote; } if (!oldDevice.enabled) { inputDevice.m_DeviceFlags |= InputDevice.DeviceFlags.DisabledStateHasBeenQueriedFromRuntime; inputDevice.m_DeviceFlags |= InputDevice.DeviceFlags.DisabledInFrontend; } AddDevice(inputDevice); } private void AddAvailableDevicesMatchingDescription(InputDeviceMatcher matcher, InternedString layout) { for (int i = 0; i < m_AvailableDeviceCount; i++) { if (m_AvailableDevices[i].isRemoved) { continue; } int deviceId = m_AvailableDevices[i].deviceId; if (TryGetDeviceById(deviceId) == null && matcher.MatchPercentage(m_AvailableDevices[i].description) > 0f) { try { AddDevice(layout, deviceId, null, m_AvailableDevices[i].description, m_AvailableDevices[i].isNative ? InputDevice.DeviceFlags.Native : ((InputDevice.DeviceFlags)0)); } catch (Exception ex) { Debug.LogError((object)$"Layout '{layout}' matches existing device '{m_AvailableDevices[i].description}' but failed to instantiate: {ex}"); Debug.LogException(ex); continue; } EnableDeviceCommand command = EnableDeviceCommand.Create(); m_Runtime.DeviceCommand(deviceId, ref command); } } } public void RemoveControlLayout(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } InternedString internedString = new InternedString(name); int num = 0; while (num < m_DevicesCount) { InputDevice inputDevice = m_Devices[num]; if (IsControlOrChildUsingLayoutRecursive(inputDevice, internedString)) { RemoveDevice(inputDevice, keepOnListOfAvailableDevices: true); } else { num++; } } m_Layouts.layoutTypes.Remove(internedString); m_Layouts.layoutStrings.Remove(internedString); m_Layouts.layoutBuilders.Remove(internedString); m_Layouts.baseLayoutTable.Remove(internedString); m_LayoutRegistrationVersion++; DelegateHelpers.InvokeCallbacksSafe(ref m_LayoutChangeListeners, name, InputControlLayoutChange.Removed, "InputSystem.onLayoutChange"); } public InputControlLayout TryLoadControlLayout(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!typeof(InputControl).IsAssignableFrom(type)) { throw new ArgumentException("Type '" + type.Name + "' is not an InputControl", "type"); } InternedString name = m_Layouts.TryFindLayoutForType(type); if (name.IsEmpty()) { throw new ArgumentException("Type '" + type.Name + "' has not been registered as a control layout", "type"); } return m_Layouts.TryLoadLayout(name); } public InputControlLayout TryLoadControlLayout(InternedString name) { return m_Layouts.TryLoadLayout(name); } public InternedString TryFindMatchingControlLayout(ref InputDeviceDescription deviceDescription, int deviceId = 0) { InternedString internedString = m_Layouts.TryFindMatchingLayout(deviceDescription); if (internedString.IsEmpty() && !string.IsNullOrEmpty(deviceDescription.deviceClass)) { InternedString layoutName = new InternedString(deviceDescription.deviceClass); Type controlTypeForLayout = m_Layouts.GetControlTypeForLayout(layoutName); if (controlTypeForLayout != null && typeof(InputDevice).IsAssignableFrom(controlTypeForLayout)) { internedString = new InternedString(deviceDescription.deviceClass); } } if (m_DeviceFindLayoutCallbacks.length > 0) { if (m_DeviceFindExecuteCommandDelegate == null) { m_DeviceFindExecuteCommandDelegate = delegate(ref InputDeviceCommand commandRef) { return (m_DeviceFindExecuteCommandDeviceId == 0) ? (-1) : m_Runtime.DeviceCommand(m_DeviceFindExecuteCommandDeviceId, ref commandRef); }; } m_DeviceFindExecuteCommandDeviceId = deviceId; bool flag = false; m_DeviceFindLayoutCallbacks.LockForChanges(); for (int num = 0; num < m_DeviceFindLayoutCallbacks.length; num++) { try { string text = m_DeviceFindLayoutCallbacks[num](ref deviceDescription, internedString, m_DeviceFindExecuteCommandDelegate); if (!string.IsNullOrEmpty(text) && !flag) { internedString = new InternedString(text); flag = true; } } catch (Exception ex) { Debug.LogError((object)(ex.GetType().Name + " while executing 'InputSystem.onFindLayoutForDevice' callbacks")); Debug.LogException(ex); } } m_DeviceFindLayoutCallbacks.UnlockForChanges(); } return internedString; } private InternedString FindOrRegisterDeviceLayoutForType(Type type) { InternedString result = m_Layouts.TryFindLayoutForType(type); if (result.IsEmpty() && result.IsEmpty()) { result = new InternedString(type.Name); RegisterControlLayout(type.Name, type); } return result; } private bool IsDeviceLayoutMarkedAsSupportedInSettings(InternedString layoutName) { ReadOnlyArray supportedDevices = m_Settings.supportedDevices; if (supportedDevices.Count == 0) { return true; } for (int i = 0; i < supportedDevices.Count; i++) { InternedString internedString = new InternedString(supportedDevices[i]); if (layoutName == internedString || m_Layouts.IsBasedOn(internedString, layoutName)) { return true; } } return false; } public IEnumerable ListControlLayouts(string basedOn = null) { if (!string.IsNullOrEmpty(basedOn)) { InternedString internedBasedOn = new InternedString(basedOn); foreach (KeyValuePair layoutType in m_Layouts.layoutTypes) { if (m_Layouts.IsBasedOn(internedBasedOn, layoutType.Key)) { yield return layoutType.Key; } } foreach (KeyValuePair layoutString in m_Layouts.layoutStrings) { if (m_Layouts.IsBasedOn(internedBasedOn, layoutString.Key)) { yield return layoutString.Key; } } foreach (KeyValuePair> layoutBuilder in m_Layouts.layoutBuilders) { if (m_Layouts.IsBasedOn(internedBasedOn, layoutBuilder.Key)) { yield return layoutBuilder.Key; } } yield break; } foreach (KeyValuePair layoutType2 in m_Layouts.layoutTypes) { yield return layoutType2.Key; } foreach (KeyValuePair layoutString2 in m_Layouts.layoutStrings) { yield return layoutString2.Key; } foreach (KeyValuePair> layoutBuilder2 in m_Layouts.layoutBuilders) { yield return layoutBuilder2.Key; } } public int GetControls(string path, ref InputControlList controls) where TControl : InputControl { if (string.IsNullOrEmpty(path)) { return 0; } if (m_DevicesCount == 0) { return 0; } int devicesCount = m_DevicesCount; int num = 0; for (int i = 0; i < devicesCount; i++) { InputDevice control = m_Devices[i]; num += InputControlPath.TryFindControls(control, path, 0, ref controls); } return num; } public void SetDeviceUsage(InputDevice device, InternedString usage) { if (device == null) { throw new ArgumentNullException("device"); } if ((device.usages.Count != 1 || !(device.usages[0] == usage)) && (device.usages.Count != 0 || !usage.IsEmpty())) { device.ClearDeviceUsages(); if (!usage.IsEmpty()) { device.AddDeviceUsage(usage); } NotifyUsageChanged(device); } } public void AddDeviceUsage(InputDevice device, InternedString usage) { if (device == null) { throw new ArgumentNullException("device"); } if (usage.IsEmpty()) { throw new ArgumentException("Usage string cannot be empty", "usage"); } if (!device.usages.Contains(usage)) { device.AddDeviceUsage(usage); NotifyUsageChanged(device); } } public void RemoveDeviceUsage(InputDevice device, InternedString usage) { if (device == null) { throw new ArgumentNullException("device"); } if (usage.IsEmpty()) { throw new ArgumentException("Usage string cannot be empty", "usage"); } if (device.usages.Contains(usage)) { device.RemoveDeviceUsage(usage); NotifyUsageChanged(device); } } private void NotifyUsageChanged(InputDevice device) { InputActionState.OnDeviceChange(device, InputDeviceChange.UsageChanged); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, device, InputDeviceChange.UsageChanged, "InputSystem.onDeviceChange"); device.MakeCurrent(); } public InputDevice AddDevice(Type type, string name = null) { if (type == null) { throw new ArgumentNullException("type"); } InternedString internedString = FindOrRegisterDeviceLayoutForType(type); return AddDevice(internedString, name); } public InputDevice AddDevice(string layout, string name = null, InternedString variants = default(InternedString)) { if (string.IsNullOrEmpty(layout)) { throw new ArgumentNullException("layout"); } InputDevice inputDevice = InputDevice.Build(layout, variants); if (!string.IsNullOrEmpty(name)) { inputDevice.m_Name = new InternedString(name); } AddDevice(inputDevice); return inputDevice; } private InputDevice AddDevice(InternedString layout, int deviceId, string deviceName = null, InputDeviceDescription deviceDescription = default(InputDeviceDescription), InputDevice.DeviceFlags deviceFlags = (InputDevice.DeviceFlags)0, InternedString variants = default(InternedString)) { InputDevice inputDevice = InputDevice.Build(new InternedString(layout), deviceDescription: deviceDescription, layoutVariants: variants); inputDevice.m_DeviceId = deviceId; inputDevice.m_Description = deviceDescription; inputDevice.m_DeviceFlags |= deviceFlags; if (!string.IsNullOrEmpty(deviceName)) { inputDevice.m_Name = new InternedString(deviceName); } if (!string.IsNullOrEmpty(deviceDescription.product)) { inputDevice.m_DisplayName = deviceDescription.product; } AddDevice(inputDevice); return inputDevice; } public void AddDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (string.IsNullOrEmpty(device.layout)) { throw new InvalidOperationException("Device has no associated layout"); } if (ArrayHelpers.Contains(m_Devices, device)) { return; } MakeDeviceNameUnique(device); AssignUniqueDeviceId(device); device.m_DeviceIndex = ArrayHelpers.AppendWithCapacity(ref m_Devices, ref m_DevicesCount, device); m_DevicesById[device.deviceId] = device; device.m_StateBlock.byteOffset = uint.MaxValue; ReallocateStateBuffers(); InitializeDeviceState(device); m_Metrics.maxNumDevices = Mathf.Max(m_DevicesCount, m_Metrics.maxNumDevices); m_Metrics.maxStateSizeInBytes = Mathf.Max((int)m_StateBuffers.totalSize, m_Metrics.maxStateSizeInBytes); for (int i = 0; i < m_AvailableDeviceCount; i++) { if (m_AvailableDevices[i].deviceId == device.deviceId) { m_AvailableDevices[i].isRemoved = false; } } if (true && !gameHasFocus && m_Settings.backgroundBehavior != InputSettings.BackgroundBehavior.IgnoreFocus && m_Runtime.runInBackground && device.QueryEnabledStateFromRuntime() && !ShouldRunDeviceInBackground(device)) { EnableOrDisableDevice(device, enable: false, DeviceDisableScope.TemporaryWhilePlayerIsInBackground); } InputActionState.OnDeviceChange(device, InputDeviceChange.Added); if (device is IInputUpdateCallbackReceiver inputUpdateCallbackReceiver) { onBeforeUpdate += inputUpdateCallbackReceiver.OnUpdate; } if (device is IInputStateCallbackReceiver) { InstallBeforeUpdateHookIfNecessary(); device.m_DeviceFlags |= InputDevice.DeviceFlags.HasStateCallbacks; m_HaveDevicesWithStateCallbackReceivers = true; } if (device is IEventMerger) { device.hasEventMerger = true; } if (device is IEventPreProcessor) { device.hasEventPreProcessor = true; } if (device.updateBeforeRender) { updateMask |= InputUpdateType.BeforeRender; } device.NotifyAdded(); device.MakeCurrent(); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, device, InputDeviceChange.Added, "InputSystem.onDeviceChange"); if (device.enabled) { device.RequestSync(); } device.SetOptimizedControlDataTypeRecursively(); } public InputDevice AddDevice(InputDeviceDescription description) { return AddDevice(description, throwIfNoLayoutFound: true); } public InputDevice AddDevice(InputDeviceDescription description, bool throwIfNoLayoutFound, string deviceName = null, int deviceId = 0, InputDevice.DeviceFlags deviceFlags = (InputDevice.DeviceFlags)0) { InternedString layout = TryFindMatchingControlLayout(ref description, deviceId); if (layout.IsEmpty()) { if (throwIfNoLayoutFound) { throw new ArgumentException($"Cannot find layout matching device description '{description}'", "description"); } if (deviceId != 0) { DisableDeviceCommand command = DisableDeviceCommand.Create(); m_Runtime.DeviceCommand(deviceId, ref command); } return null; } InputDevice inputDevice = AddDevice(layout, deviceId, deviceName, description, deviceFlags); inputDevice.m_Description = description; return inputDevice; } public InputDevice AddDevice(InputDeviceDescription description, InternedString layout, string deviceName = null, int deviceId = 0, InputDevice.DeviceFlags deviceFlags = (InputDevice.DeviceFlags)0) { try { InputDevice inputDevice = AddDevice(layout, deviceId, deviceName, description, deviceFlags); inputDevice.m_Description = description; return inputDevice; } finally { } } public void RemoveDevice(InputDevice device, bool keepOnListOfAvailableDevices = false) { if (device == null) { throw new ArgumentNullException("device"); } if (device.m_DeviceIndex == -1) { return; } RemoveStateChangeMonitors(device); int deviceIndex = device.m_DeviceIndex; int deviceId = device.deviceId; if (deviceIndex < m_StateChangeMonitors.LengthSafe()) { int count = m_StateChangeMonitors.Length; m_StateChangeMonitors.EraseAtWithCapacity(ref count, deviceIndex); } m_Devices.EraseAtWithCapacity(ref m_DevicesCount, deviceIndex); m_DevicesById.Remove(deviceId); if (m_Devices != null) { ReallocateStateBuffers(); } else { m_StateBuffers.FreeAll(); } for (int i = deviceIndex; i < m_DevicesCount; i++) { m_Devices[i].m_DeviceIndex--; } device.m_DeviceIndex = -1; for (int j = 0; j < m_AvailableDeviceCount; j++) { if (m_AvailableDevices[j].deviceId == deviceId) { if (keepOnListOfAvailableDevices) { m_AvailableDevices[j].isRemoved = true; } else { m_AvailableDevices.EraseAtWithCapacity(ref m_AvailableDeviceCount, j); } break; } } device.BakeOffsetIntoStateBlockRecursive((uint)(0uL - (ulong)device.m_StateBlock.byteOffset)); InputActionState.OnDeviceChange(device, InputDeviceChange.Removed); if (device is IInputUpdateCallbackReceiver inputUpdateCallbackReceiver) { onBeforeUpdate -= inputUpdateCallbackReceiver.OnUpdate; } if (device.updateBeforeRender) { bool flag = false; for (int k = 0; k < m_DevicesCount; k++) { if (m_Devices[k].updateBeforeRender) { flag = true; break; } } if (!flag) { updateMask &= ~InputUpdateType.BeforeRender; } } device.NotifyRemoved(); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, device, InputDeviceChange.Removed, "InputSystem.onDeviceChange"); InputSystem.GetDevice(device.GetType())?.MakeCurrent(); } public void FlushDisconnectedDevices() { m_DisconnectedDevices.Clear(m_DisconnectedDevicesCount); m_DisconnectedDevicesCount = 0; } public unsafe void ResetDevice(InputDevice device, bool alsoResetDontResetControls = false, bool? issueResetCommand = null) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) if (device == null) { throw new ArgumentNullException("device"); } if (!device.added) { throw new InvalidOperationException($"Device '{device}' has not been added to the system"); } bool flag = alsoResetDontResetControls || !device.hasDontResetControls; InputDeviceChange inputDeviceChange = (flag ? InputDeviceChange.HardReset : InputDeviceChange.SoftReset); InputActionState.OnDeviceChange(device, inputDeviceChange); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, device, inputDeviceChange, "onDeviceChange"); if (!alsoResetDontResetControls && device is ICustomDeviceReset customDeviceReset) { customDeviceReset.Reset(); } else { void* defaultStatePtr = device.defaultStatePtr; uint alignedSizeInBytes = device.stateBlock.alignedSizeInBytes; NativeArray val = default(NativeArray); val..ctor((int)(24 + alignedSizeInBytes), (Allocator)2, (NativeArrayOptions)1); try { StateEvent* unsafePtr = (StateEvent*)NativeArrayUnsafeUtility.GetUnsafePtr(val); void* state = unsafePtr->state; double currentTime = m_Runtime.currentTime; ref InputStateBlock stateBlock = ref device.m_StateBlock; unsafePtr->baseEvent.type = 1398030676; unsafePtr->baseEvent.sizeInBytes = 24 + alignedSizeInBytes; unsafePtr->baseEvent.time = currentTime; unsafePtr->baseEvent.deviceId = device.deviceId; unsafePtr->baseEvent.eventId = -1; unsafePtr->stateFormat = device.m_StateBlock.format; if (flag) { UnsafeUtility.MemCpy(state, (void*)((byte*)defaultStatePtr + stateBlock.byteOffset), (long)alignedSizeInBytes); } else { void* currentStatePtr = device.currentStatePtr; void* resetMaskBuffer = m_StateBuffers.resetMaskBuffer; UnsafeUtility.MemCpy(state, (void*)((byte*)currentStatePtr + stateBlock.byteOffset), (long)alignedSizeInBytes); MemoryHelpers.MemCpyMasked(state, (byte*)defaultStatePtr + stateBlock.byteOffset, (int)alignedSizeInBytes, (byte*)resetMaskBuffer + stateBlock.byteOffset); } UpdateState(device, defaultUpdateType, state, 0u, alignedSizeInBytes, currentTime, new InputEventPtr((InputEvent*)unsafePtr)); } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } bool flag2 = flag; if (issueResetCommand.HasValue) { flag2 = issueResetCommand.Value; } if (flag2) { device.RequestReset(); } } public InputDevice TryGetDevice(string nameOrLayout) { if (string.IsNullOrEmpty(nameOrLayout)) { throw new ArgumentException("Name is null or empty.", "nameOrLayout"); } if (m_DevicesCount == 0) { return null; } string text = nameOrLayout.ToLower(); for (int i = 0; i < m_DevicesCount; i++) { InputDevice inputDevice = m_Devices[i]; if (inputDevice.m_Name.ToLower() == text || inputDevice.m_Layout.ToLower() == text) { return inputDevice; } } return null; } public InputDevice GetDevice(string nameOrLayout) { return TryGetDevice(nameOrLayout) ?? throw new ArgumentException("Cannot find device with name or layout '" + nameOrLayout + "'", "nameOrLayout"); } public InputDevice TryGetDevice(Type layoutType) { InternedString internedString = m_Layouts.TryFindLayoutForType(layoutType); if (internedString.IsEmpty()) { return null; } return TryGetDevice(internedString); } public InputDevice TryGetDeviceById(int id) { if (m_DevicesById.TryGetValue(id, out var value)) { return value; } return null; } public int GetUnsupportedDevices(List descriptions) { if (descriptions == null) { throw new ArgumentNullException("descriptions"); } int num = 0; for (int i = 0; i < m_AvailableDeviceCount; i++) { if (TryGetDeviceById(m_AvailableDevices[i].deviceId) == null) { descriptions.Add(m_AvailableDevices[i].description); num++; } } return num; } public void EnableOrDisableDevice(InputDevice device, bool enable, DeviceDisableScope scope = DeviceDisableScope.Everywhere) { if (device == null) { throw new ArgumentNullException("device"); } if (enable) { switch (scope) { case DeviceDisableScope.Everywhere: device.disabledWhileInBackground = false; if (!device.disabledInFrontend && !device.disabledInRuntime) { return; } if (device.disabledInRuntime) { device.ExecuteEnableCommand(); device.disabledInRuntime = false; } if (device.disabledInFrontend) { if (!device.RequestSync()) { ResetDevice(device); } device.disabledInFrontend = false; } break; case DeviceDisableScope.InFrontendOnly: device.disabledWhileInBackground = false; if (!device.disabledInFrontend && device.disabledInRuntime) { return; } if (!device.disabledInRuntime) { device.ExecuteDisableCommand(); device.disabledInRuntime = true; } if (device.disabledInFrontend) { if (!device.RequestSync()) { ResetDevice(device); } device.disabledInFrontend = false; } break; case DeviceDisableScope.TemporaryWhilePlayerIsInBackground: if (device.disabledWhileInBackground) { if (device.disabledInRuntime) { device.ExecuteEnableCommand(); device.disabledInRuntime = false; } if (!device.RequestSync()) { ResetDevice(device); } device.disabledWhileInBackground = false; } break; } } else { switch (scope) { case DeviceDisableScope.Everywhere: device.disabledWhileInBackground = false; if (device.disabledInFrontend && device.disabledInRuntime) { return; } if (!device.disabledInRuntime) { device.ExecuteDisableCommand(); device.disabledInRuntime = true; } if (!device.disabledInFrontend) { ResetDevice(device, alsoResetDontResetControls: false, false); device.disabledInFrontend = true; } break; case DeviceDisableScope.InFrontendOnly: device.disabledWhileInBackground = false; if (!device.disabledInRuntime && device.disabledInFrontend) { return; } if (device.disabledInRuntime) { device.ExecuteEnableCommand(); device.disabledInRuntime = false; } if (!device.disabledInFrontend) { ResetDevice(device, alsoResetDontResetControls: false, false); device.disabledInFrontend = true; } break; case DeviceDisableScope.TemporaryWhilePlayerIsInBackground: if (device.disabledInFrontend || device.disabledWhileInBackground) { return; } device.disabledWhileInBackground = true; ResetDevice(device, alsoResetDontResetControls: false, false); device.ExecuteDisableCommand(); device.disabledInRuntime = true; break; } } InputDeviceChange argument = (enable ? InputDeviceChange.Enabled : InputDeviceChange.Disabled); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, device, argument, "InputSystem.onDeviceChange"); } private unsafe void QueueEvent(InputEvent* eventPtr) { if (m_InputEventStream.isOpen) { m_InputEventStream.Write(eventPtr); } else { m_Runtime.QueueEvent(eventPtr); } } public unsafe void QueueEvent(InputEventPtr ptr) { QueueEvent(ptr.data); } public unsafe void QueueEvent(ref TEvent inputEvent) where TEvent : struct, IInputEventTypeInfo { QueueEvent((InputEvent*)UnsafeUtility.AddressOf(ref inputEvent)); } public void Update() { Update(defaultUpdateType); } public void Update(InputUpdateType updateType) { m_Runtime.Update(updateType); } internal void Initialize(IInputRuntime runtime, InputSettings settings) { m_Settings = settings; InitializeData(); InstallRuntime(runtime); InstallGlobals(); ApplySettings(); } internal void Destroy() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Invalid comparison between Unknown and I4 for (int i = 0; i < m_DevicesCount; i++) { m_Devices[i].NotifyRemoved(); } m_StateBuffers.FreeAll(); UninstallGlobals(); if ((Object)(object)m_Settings != (Object)null && (int)((Object)m_Settings).hideFlags == 61) { Object.DestroyImmediate((Object)(object)m_Settings); } } internal void InitializeData() { m_Layouts.Allocate(); m_Processors.Initialize(); m_Interactions.Initialize(); m_Composites.Initialize(); m_DevicesById = new Dictionary(); m_UpdateMask = InputUpdateType.Dynamic | InputUpdateType.Fixed; m_HasFocus = Application.isFocused; m_PollingFrequency = 60f; RegisterControlLayout("Axis", typeof(AxisControl)); RegisterControlLayout("Button", typeof(ButtonControl)); RegisterControlLayout("DiscreteButton", typeof(DiscreteButtonControl)); RegisterControlLayout("Key", typeof(KeyControl)); RegisterControlLayout("Analog", typeof(AxisControl)); RegisterControlLayout("Integer", typeof(IntegerControl)); RegisterControlLayout("Digital", typeof(IntegerControl)); RegisterControlLayout("Double", typeof(DoubleControl)); RegisterControlLayout("Vector2", typeof(Vector2Control)); RegisterControlLayout("Vector3", typeof(Vector3Control)); RegisterControlLayout("Delta", typeof(DeltaControl)); RegisterControlLayout("Quaternion", typeof(QuaternionControl)); RegisterControlLayout("Stick", typeof(StickControl)); RegisterControlLayout("Dpad", typeof(DpadControl)); RegisterControlLayout("DpadAxis", typeof(DpadControl.DpadAxisControl)); RegisterControlLayout("AnyKey", typeof(AnyKeyControl)); RegisterControlLayout("Touch", typeof(TouchControl)); RegisterControlLayout("TouchPhase", typeof(TouchPhaseControl)); RegisterControlLayout("TouchPress", typeof(TouchPressControl)); RegisterControlLayout("Gamepad", typeof(Gamepad)); RegisterControlLayout("Joystick", typeof(Joystick)); RegisterControlLayout("Keyboard", typeof(Keyboard)); RegisterControlLayout("Pointer", typeof(Pointer)); RegisterControlLayout("Mouse", typeof(Mouse)); RegisterControlLayout("Pen", typeof(Pen)); RegisterControlLayout("Touchscreen", typeof(Touchscreen)); RegisterControlLayout("Sensor", typeof(Sensor)); RegisterControlLayout("Accelerometer", typeof(Accelerometer)); RegisterControlLayout("Gyroscope", typeof(Gyroscope)); RegisterControlLayout("GravitySensor", typeof(GravitySensor)); RegisterControlLayout("AttitudeSensor", typeof(AttitudeSensor)); RegisterControlLayout("LinearAccelerationSensor", typeof(LinearAccelerationSensor)); RegisterControlLayout("MagneticFieldSensor", typeof(MagneticFieldSensor)); RegisterControlLayout("LightSensor", typeof(LightSensor)); RegisterControlLayout("PressureSensor", typeof(PressureSensor)); RegisterControlLayout("HumiditySensor", typeof(HumiditySensor)); RegisterControlLayout("AmbientTemperatureSensor", typeof(AmbientTemperatureSensor)); RegisterControlLayout("StepCounter", typeof(StepCounter)); RegisterControlLayout("TrackedDevice", typeof(TrackedDevice)); RegisterPrecompiledLayout(";AnyKey;Button;Axis;Key;DiscreteButton;Keyboard"); RegisterPrecompiledLayout("AutoWindowSpace;Touch;Vector2;Delta;Analog;TouchPress;Button;Axis;Integer;TouchPhase;Double;Touchscreen;Pointer"); RegisterPrecompiledLayout("AutoWindowSpace;Vector2;Delta;Button;Axis;Digital;Integer;Mouse;Pointer"); processors.AddTypeRegistration("Invert", typeof(InvertProcessor)); processors.AddTypeRegistration("InvertVector2", typeof(InvertVector2Processor)); processors.AddTypeRegistration("InvertVector3", typeof(InvertVector3Processor)); processors.AddTypeRegistration("Clamp", typeof(ClampProcessor)); processors.AddTypeRegistration("Normalize", typeof(NormalizeProcessor)); processors.AddTypeRegistration("NormalizeVector2", typeof(NormalizeVector2Processor)); processors.AddTypeRegistration("NormalizeVector3", typeof(NormalizeVector3Processor)); processors.AddTypeRegistration("Scale", typeof(ScaleProcessor)); processors.AddTypeRegistration("ScaleVector2", typeof(ScaleVector2Processor)); processors.AddTypeRegistration("ScaleVector3", typeof(ScaleVector3Processor)); processors.AddTypeRegistration("StickDeadzone", typeof(StickDeadzoneProcessor)); processors.AddTypeRegistration("AxisDeadzone", typeof(AxisDeadzoneProcessor)); processors.AddTypeRegistration("CompensateDirection", typeof(CompensateDirectionProcessor)); processors.AddTypeRegistration("CompensateRotation", typeof(CompensateRotationProcessor)); interactions.AddTypeRegistration("Hold", typeof(HoldInteraction)); interactions.AddTypeRegistration("Tap", typeof(TapInteraction)); interactions.AddTypeRegistration("SlowTap", typeof(SlowTapInteraction)); interactions.AddTypeRegistration("MultiTap", typeof(MultiTapInteraction)); interactions.AddTypeRegistration("Press", typeof(PressInteraction)); composites.AddTypeRegistration("1DAxis", typeof(AxisComposite)); composites.AddTypeRegistration("2DVector", typeof(Vector2Composite)); composites.AddTypeRegistration("3DVector", typeof(Vector3Composite)); composites.AddTypeRegistration("Axis", typeof(AxisComposite)); composites.AddTypeRegistration("Dpad", typeof(Vector2Composite)); composites.AddTypeRegistration("ButtonWithOneModifier", typeof(ButtonWithOneModifier)); composites.AddTypeRegistration("ButtonWithTwoModifiers", typeof(ButtonWithTwoModifiers)); composites.AddTypeRegistration("OneModifier", typeof(OneModifierComposite)); composites.AddTypeRegistration("TwoModifiers", typeof(TwoModifiersComposite)); } internal void InstallRuntime(IInputRuntime runtime) { if (m_Runtime != null) { m_Runtime.onUpdate = null; m_Runtime.onBeforeUpdate = null; m_Runtime.onDeviceDiscovered = null; m_Runtime.onPlayerFocusChanged = null; m_Runtime.onShouldRunUpdate = null; } m_Runtime = runtime; m_Runtime.onUpdate = OnUpdate; m_Runtime.onDeviceDiscovered = OnNativeDeviceDiscovered; m_Runtime.onPlayerFocusChanged = OnFocusChanged; m_Runtime.onShouldRunUpdate = ShouldRunUpdate; m_Runtime.pollingFrequency = pollingFrequency; m_HasFocus = m_Runtime.isPlayerFocused; if (m_BeforeUpdateListeners.length > 0 || m_HaveDevicesWithStateCallbackReceivers) { m_Runtime.onBeforeUpdate = OnBeforeUpdate; m_NativeBeforeUpdateHooked = true; } InputAnalytics.Initialize(this); m_Runtime.onShutdown = delegate { InputAnalytics.OnShutdown(this); }; } internal unsafe void InstallGlobals() { InputControlLayout.s_Layouts = m_Layouts; InputProcessor.s_Processors = m_Processors; InputInteraction.s_Interactions = m_Interactions; InputBindingComposite.s_Composites = m_Composites; InputRuntime.s_Instance = m_Runtime; InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup = m_Runtime.currentTimeOffsetToRealtimeSinceStartup; InputUpdate.Restore(default(InputUpdate.SerializedState)); InputStateBuffers.SwitchTo(m_StateBuffers, InputUpdateType.Dynamic); InputStateBuffers.s_DefaultStateBuffer = m_StateBuffers.defaultStateBuffer; InputStateBuffers.s_NoiseMaskBuffer = m_StateBuffers.noiseMaskBuffer; InputStateBuffers.s_ResetMaskBuffer = m_StateBuffers.resetMaskBuffer; } internal void UninstallGlobals() { if (InputControlLayout.s_Layouts.baseLayoutTable == m_Layouts.baseLayoutTable) { InputControlLayout.s_Layouts = default(InputControlLayout.Collection); } if (InputProcessor.s_Processors.table == m_Processors.table) { InputProcessor.s_Processors = default(TypeTable); } if (InputInteraction.s_Interactions.table == m_Interactions.table) { InputInteraction.s_Interactions = default(TypeTable); } if (InputBindingComposite.s_Composites.table == m_Composites.table) { InputBindingComposite.s_Composites = default(TypeTable); } InputControlLayout.s_CacheInstance = default(InputControlLayout.Cache); InputControlLayout.s_CacheInstanceRef = 0; if (m_Runtime != null) { m_Runtime.onUpdate = null; m_Runtime.onDeviceDiscovered = null; m_Runtime.onBeforeUpdate = null; m_Runtime.onPlayerFocusChanged = null; m_Runtime.onShouldRunUpdate = null; if (InputRuntime.s_Instance == m_Runtime) { InputRuntime.s_Instance = null; } } } private void MakeDeviceNameUnique(InputDevice device) { if (m_DevicesCount != 0) { string text = StringHelpers.MakeUniqueName(device.name, m_Devices, (InputDevice x) => (x == null) ? string.Empty : x.name); if (text != device.name) { ResetControlPathsRecursive(device); device.m_Name = new InternedString(text); } } } private static void ResetControlPathsRecursive(InputControl control) { control.m_Path = null; ReadOnlyArray children = control.children; int count = children.Count; for (int i = 0; i < count; i++) { ResetControlPathsRecursive(children[i]); } } private void AssignUniqueDeviceId(InputDevice device) { if (device.deviceId != 0) { InputDevice inputDevice = TryGetDeviceById(device.deviceId); if (inputDevice != null) { throw new InvalidOperationException($"Duplicate device ID {device.deviceId} detected for devices '{device.name}' and '{inputDevice.name}'"); } } else { device.m_DeviceId = m_Runtime.AllocateDeviceId(); } } private unsafe void ReallocateStateBuffers() { InputStateBuffers stateBuffers = m_StateBuffers; InputStateBuffers stateBuffers2 = default(InputStateBuffers); stateBuffers2.AllocateAll(m_Devices, m_DevicesCount); stateBuffers2.MigrateAll(m_Devices, m_DevicesCount, stateBuffers); stateBuffers.FreeAll(); m_StateBuffers = stateBuffers2; InputStateBuffers.s_DefaultStateBuffer = stateBuffers2.defaultStateBuffer; InputStateBuffers.s_NoiseMaskBuffer = stateBuffers2.noiseMaskBuffer; InputStateBuffers.s_ResetMaskBuffer = stateBuffers2.resetMaskBuffer; InputStateBuffers.SwitchTo(m_StateBuffers, (InputUpdate.s_LatestUpdateType != InputUpdateType.None) ? InputUpdate.s_LatestUpdateType : defaultUpdateType); } private unsafe void InitializeDefaultState(InputDevice device) { if (!device.hasControlsWithDefaultState) { return; } ReadOnlyArray allControls = device.allControls; int count = allControls.Count; void* defaultStateBuffer = m_StateBuffers.defaultStateBuffer; for (int i = 0; i < count; i++) { InputControl inputControl = allControls[i]; if (inputControl.hasDefaultState) { inputControl.m_StateBlock.Write(defaultStateBuffer, inputControl.m_DefaultState); } } InputStateBlock stateBlock = device.m_StateBlock; int deviceIndex = device.m_DeviceIndex; if (m_StateBuffers.m_PlayerStateBuffers.valid) { stateBlock.CopyToFrom(m_StateBuffers.m_PlayerStateBuffers.GetFrontBuffer(deviceIndex), defaultStateBuffer); stateBlock.CopyToFrom(m_StateBuffers.m_PlayerStateBuffers.GetBackBuffer(deviceIndex), defaultStateBuffer); } } private unsafe void InitializeDeviceState(InputDevice device) { ReadOnlyArray allControls = device.allControls; int count = allControls.Count; void* resetMaskBuffer = m_StateBuffers.resetMaskBuffer; bool hasControlsWithDefaultState = device.hasControlsWithDefaultState; void* noiseMaskBuffer = m_StateBuffers.noiseMaskBuffer; MemoryHelpers.SetBitsInBuffer(noiseMaskBuffer, (int)device.stateBlock.byteOffset, 0, (int)device.stateBlock.sizeInBits, value: false); MemoryHelpers.SetBitsInBuffer(resetMaskBuffer, (int)device.stateBlock.byteOffset, 0, (int)device.stateBlock.sizeInBits, value: true); void* defaultStateBuffer = m_StateBuffers.defaultStateBuffer; for (int i = 0; i < count; i++) { InputControl inputControl = allControls[i]; if (inputControl.usesStateFromOtherControl) { continue; } if (!inputControl.noisy || inputControl.dontReset) { ref InputStateBlock stateBlock = ref inputControl.m_StateBlock; if (!inputControl.noisy) { MemoryHelpers.SetBitsInBuffer(noiseMaskBuffer, (int)stateBlock.byteOffset, (int)stateBlock.bitOffset, (int)stateBlock.sizeInBits, value: true); } if (inputControl.dontReset) { MemoryHelpers.SetBitsInBuffer(resetMaskBuffer, (int)stateBlock.byteOffset, (int)stateBlock.bitOffset, (int)stateBlock.sizeInBits, value: false); } } if (hasControlsWithDefaultState && inputControl.hasDefaultState) { inputControl.m_StateBlock.Write(defaultStateBuffer, inputControl.m_DefaultState); } } if (hasControlsWithDefaultState) { ref InputStateBlock stateBlock2 = ref device.m_StateBlock; int deviceIndex = device.m_DeviceIndex; if (m_StateBuffers.m_PlayerStateBuffers.valid) { stateBlock2.CopyToFrom(m_StateBuffers.m_PlayerStateBuffers.GetFrontBuffer(deviceIndex), defaultStateBuffer); stateBlock2.CopyToFrom(m_StateBuffers.m_PlayerStateBuffers.GetBackBuffer(deviceIndex), defaultStateBuffer); } } } private void OnNativeDeviceDiscovered(int deviceId, string deviceDescriptor) { RestoreDevicesAfterDomainReloadIfNecessary(); InputDevice inputDevice = TryMatchDisconnectedDevice(deviceDescriptor); InputDeviceDescription deviceDescription = inputDevice?.description ?? InputDeviceDescription.FromJson(deviceDescriptor); bool isRemoved = false; try { if (m_Settings.supportedDevices.Count > 0) { InternedString layoutName = inputDevice?.m_Layout ?? TryFindMatchingControlLayout(ref deviceDescription, deviceId); if (!IsDeviceLayoutMarkedAsSupportedInSettings(layoutName)) { isRemoved = true; return; } } if (inputDevice != null) { inputDevice.m_DeviceId = deviceId; inputDevice.m_DeviceFlags |= InputDevice.DeviceFlags.Native; inputDevice.m_DeviceFlags &= ~InputDevice.DeviceFlags.DisabledInFrontend; inputDevice.m_DeviceFlags &= ~InputDevice.DeviceFlags.DisabledWhileInBackground; inputDevice.m_DeviceFlags &= ~InputDevice.DeviceFlags.DisabledStateHasBeenQueriedFromRuntime; AddDevice(inputDevice); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, inputDevice, InputDeviceChange.Reconnected, "InputSystem.onDeviceChange"); } else { AddDevice(deviceDescription, throwIfNoLayoutFound: false, null, deviceId, InputDevice.DeviceFlags.Native); } } catch (Exception arg) { Debug.LogError((object)$"Could not create a device for '{deviceDescription}' (exception: {arg})"); } finally { ArrayHelpers.AppendWithCapacity(ref m_AvailableDevices, ref m_AvailableDeviceCount, new AvailableDevice { description = deviceDescription, deviceId = deviceId, isNative = true, isRemoved = isRemoved }); } } private InputDevice TryMatchDisconnectedDevice(string deviceDescriptor) { for (int i = 0; i < m_DisconnectedDevicesCount; i++) { InputDevice inputDevice = m_DisconnectedDevices[i]; InputDeviceDescription description = inputDevice.description; if (InputDeviceDescription.ComparePropertyToDeviceDescriptor("interface", description.interfaceName, deviceDescriptor) && InputDeviceDescription.ComparePropertyToDeviceDescriptor("product", description.product, deviceDescriptor) && InputDeviceDescription.ComparePropertyToDeviceDescriptor("manufacturer", description.manufacturer, deviceDescriptor) && InputDeviceDescription.ComparePropertyToDeviceDescriptor("type", description.deviceClass, deviceDescriptor) && InputDeviceDescription.ComparePropertyToDeviceDescriptor("capabilities", description.capabilities, deviceDescriptor) && InputDeviceDescription.ComparePropertyToDeviceDescriptor("serial", description.serial, deviceDescriptor)) { m_DisconnectedDevices.EraseAtWithCapacity(ref m_DisconnectedDevicesCount, i); return inputDevice; } } return null; } private void InstallBeforeUpdateHookIfNecessary() { if (!m_NativeBeforeUpdateHooked && m_Runtime != null) { m_Runtime.onBeforeUpdate = OnBeforeUpdate; m_NativeBeforeUpdateHooked = true; } } private void RestoreDevicesAfterDomainReloadIfNecessary() { } private void WarnAboutDevicesFailingToRecreateAfterDomainReload() { } private void OnBeforeUpdate(InputUpdateType updateType) { RestoreDevicesAfterDomainReloadIfNecessary(); if ((updateType & m_UpdateMask) == 0) { return; } InputStateBuffers.SwitchTo(m_StateBuffers, updateType); InputUpdate.OnBeforeUpdate(updateType); if (m_HaveDevicesWithStateCallbackReceivers && updateType != InputUpdateType.BeforeRender) { for (int i = 0; i < m_DevicesCount; i++) { InputDevice inputDevice = m_Devices[i]; if (inputDevice.hasStateCallbacks) { ((IInputStateCallbackReceiver)inputDevice).OnNextUpdate(); } } } DelegateHelpers.InvokeCallbacksSafe(ref m_BeforeUpdateListeners, "onBeforeUpdate"); } internal void ApplySettings() { InputUpdateType inputUpdateType = InputUpdateType.Editor; if ((m_UpdateMask & InputUpdateType.BeforeRender) != InputUpdateType.None) { inputUpdateType |= InputUpdateType.BeforeRender; } if (m_Settings.updateMode == (InputSettings.UpdateMode)0) { m_Settings.updateMode = InputSettings.UpdateMode.ProcessEventsInDynamicUpdate; } updateMask = m_Settings.updateMode switch { InputSettings.UpdateMode.ProcessEventsInDynamicUpdate => inputUpdateType | InputUpdateType.Dynamic, InputSettings.UpdateMode.ProcessEventsInFixedUpdate => inputUpdateType | InputUpdateType.Fixed, InputSettings.UpdateMode.ProcessEventsManually => inputUpdateType | InputUpdateType.Manual, _ => throw new NotSupportedException("Invalid input update mode: " + m_Settings.updateMode), }; AddAvailableDevicesThatAreNowRecognized(); if (settings.supportedDevices.Count > 0) { for (int i = 0; i < m_DevicesCount; i++) { InputDevice inputDevice = m_Devices[i]; InternedString layout = inputDevice.m_Layout; bool flag = false; for (int j = 0; j < m_AvailableDeviceCount; j++) { if (m_AvailableDevices[j].deviceId == inputDevice.deviceId) { flag = true; break; } } if (flag && !IsDeviceLayoutMarkedAsSupportedInSettings(layout)) { RemoveDevice(inputDevice, keepOnListOfAvailableDevices: true); i--; } } } if (m_Settings.m_FeatureFlags != null && m_Settings.IsFeatureEnabled("USE_WINDOWS_GAMING_INPUT_BACKEND")) { UseWindowsGamingInputCommand command = UseWindowsGamingInputCommand.Create(enable: true); if (ExecuteGlobalCommand(ref command) < 0) { Debug.LogError((object)"Could not enable Windows.Gaming.Input"); } } Touchscreen.s_TapTime = settings.defaultTapTime; Touchscreen.s_TapDelayTime = settings.multiTapDelayTime; Touchscreen.s_TapRadiusSquared = settings.tapRadius * settings.tapRadius; ButtonControl.s_GlobalDefaultButtonPressPoint = Mathf.Clamp(settings.defaultButtonPressPoint, 0.0001f, float.MaxValue); ButtonControl.s_GlobalDefaultButtonReleaseThreshold = settings.buttonReleaseThreshold; foreach (InputDevice device in devices) { device.SetOptimizedControlDataTypeRecursively(); } foreach (InputDevice device2 in devices) { device2.MarkAsStaleRecursively(); } DelegateHelpers.InvokeCallbacksSafe(ref m_SettingsChangedListeners, "InputSystem.onSettingsChange"); } internal unsafe long ExecuteGlobalCommand(ref TCommand command) where TCommand : struct, IInputDeviceCommandInfo { InputDeviceCommand* commandPtr = (InputDeviceCommand*)UnsafeUtility.AddressOf(ref command); return InputRuntime.s_Instance.DeviceCommand(0, commandPtr); } internal void AddAvailableDevicesThatAreNowRecognized() { for (int i = 0; i < m_AvailableDeviceCount; i++) { int deviceId = m_AvailableDevices[i].deviceId; if (TryGetDeviceById(deviceId) != null) { continue; } InternedString internedString = TryFindMatchingControlLayout(ref m_AvailableDevices[i].description, deviceId); if (!IsDeviceLayoutMarkedAsSupportedInSettings(internedString)) { continue; } if (internedString.IsEmpty()) { if (deviceId != 0) { DisableDeviceCommand command = DisableDeviceCommand.Create(); m_Runtime.DeviceCommand(deviceId, ref command); } } else { try { AddDevice(m_AvailableDevices[i].description, internedString, null, deviceId, m_AvailableDevices[i].isNative ? InputDevice.DeviceFlags.Native : ((InputDevice.DeviceFlags)0)); } catch (Exception) { } } } } private bool ShouldRunDeviceInBackground(InputDevice device) { if (m_Settings.backgroundBehavior != InputSettings.BackgroundBehavior.ResetAndDisableAllDevices) { return device.canRunInBackground; } return false; } internal void OnFocusChanged(bool focus) { bool runInBackground = m_Runtime.runInBackground; if (m_Settings.backgroundBehavior == InputSettings.BackgroundBehavior.IgnoreFocus && runInBackground) { m_HasFocus = focus; return; } if (!focus) { if (runInBackground) { for (int i = 0; i < m_DevicesCount; i++) { InputDevice inputDevice = m_Devices[i]; if (inputDevice.enabled && !ShouldRunDeviceInBackground(inputDevice)) { EnableOrDisableDevice(inputDevice, enable: false, DeviceDisableScope.TemporaryWhilePlayerIsInBackground); int num = m_Devices.IndexOfReference(inputDevice, m_DevicesCount); i = ((num != -1) ? num : (i - 1)); } } } } else { for (int j = 0; j < m_DevicesCount; j++) { InputDevice inputDevice2 = m_Devices[j]; if (inputDevice2.disabledWhileInBackground) { EnableOrDisableDevice(inputDevice2, enable: true, DeviceDisableScope.TemporaryWhilePlayerIsInBackground); } else if (inputDevice2.enabled && !runInBackground && !inputDevice2.RequestSync()) { ResetDevice(inputDevice2); } } } m_HasFocus = focus; } internal bool ShouldRunUpdate(InputUpdateType updateType) { if (updateType == InputUpdateType.None) { return true; } InputUpdateType inputUpdateType = m_UpdateMask; return (updateType & inputUpdateType) != 0; } private unsafe void OnUpdate(InputUpdateType updateType, ref InputEventBuffer eventBuffer) { if (m_InputEventStream.isOpen) { throw new InvalidOperationException("Already have an event buffer set! Was OnUpdate() called recursively?"); } RestoreDevicesAfterDomainReloadIfNecessary(); if ((updateType & m_UpdateMask) == 0) { return; } WarnAboutDevicesFailingToRecreateAfterDomainReload(); if (!m_HaveSentStartupAnalytics) { InputAnalytics.OnStartup(this); m_HaveSentStartupAnalytics = true; } ref InputMetrics reference = ref m_Metrics; int totalUpdateCount = reference.totalUpdateCount + 1; reference.totalUpdateCount = totalUpdateCount; InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup = m_Runtime.currentTimeOffsetToRealtimeSinceStartup; InputStateBuffers.SwitchTo(m_StateBuffers, updateType); m_CurrentUpdate = updateType; InputUpdate.OnUpdate(updateType); foreach (InputDevice device in devices) { _ = device; } bool flag = updateType.IsPlayerUpdate() && gameIsPlaying; double num = ((updateType == InputUpdateType.Fixed) ? m_Runtime.currentTimeForFixedUpdate : m_Runtime.currentTime); bool flag2 = (updateType == InputUpdateType.Fixed || updateType == InputUpdateType.BeforeRender) && InputSystem.settings.updateMode == InputSettings.UpdateMode.ProcessEventsInFixedUpdate; bool flag3 = !gameHasFocus && !m_Runtime.runInBackground; if (eventBuffer.eventCount == 0 || flag3 || ((!gameHasFocus || gameShouldGetInputRegardlessOfFocus) && m_Settings.backgroundBehavior == InputSettings.BackgroundBehavior.ResetAndDisableAllDevices && updateType != InputUpdateType.Editor)) { if (flag) { ProcessStateChangeMonitorTimeouts(); } InvokeAfterUpdateCallback(updateType); if (flag3) { eventBuffer.Reset(); } m_CurrentUpdate = InputUpdateType.None; return; } long timestamp = Stopwatch.GetTimestamp(); double num2 = 0.0; try { m_InputEventStream = new InputEventStream(ref eventBuffer, m_Settings.maxQueuedEventsPerUpdate); uint num3 = 0u; InputEvent* ptr = null; while (m_InputEventStream.remainingEventCount > 0) { if (m_Settings.maxEventBytesPerUpdate > 0 && num3 >= m_Settings.maxEventBytesPerUpdate) { Debug.LogError((object)"Exceeded budget for maximum input event throughput per InputSystem.Update(). Discarding remaining events. Increase InputSystem.settings.maxEventBytesPerUpdate or set it to 0 to remove the limit."); break; } InputDevice inputDevice = null; InputEvent* ptr2 = m_InputEventStream.currentEventPtr; if (updateType == InputUpdateType.BeforeRender) { while (m_InputEventStream.remainingEventCount > 0) { inputDevice = TryGetDeviceById(ptr2->deviceId); if (inputDevice != null && inputDevice.updateBeforeRender && (ptr2->type == 1398030676 || ptr2->type == 1145852993)) { break; } ptr2 = m_InputEventStream.Advance(leaveEventInBuffer: true); } } if (m_InputEventStream.remainingEventCount == 0) { break; } double internalTime = ptr2->internalTime; FourCC type = ptr2->type; if (flag2 && internalTime >= num) { m_InputEventStream.Advance(leaveEventInBuffer: true); continue; } if (inputDevice == null) { inputDevice = TryGetDeviceById(ptr2->deviceId); } if (inputDevice == null) { m_InputEventStream.Advance(leaveEventInBuffer: false); continue; } if (!inputDevice.enabled && type != 1146242381 && type != 1145259591 && (inputDevice.m_DeviceFlags & (InputDevice.DeviceFlags.DisabledInRuntime | InputDevice.DeviceFlags.DisabledWhileInBackground)) != 0) { m_InputEventStream.Advance(leaveEventInBuffer: false); continue; } if (!settings.disableRedundantEventsMerging && inputDevice.hasEventMerger && ptr2 != ptr) { InputEvent* ptr3 = m_InputEventStream.Peek(); if (ptr3 != null && ptr2->deviceId == ptr3->deviceId && (!flag2 || ptr3->internalTime < num)) { if (((IEventMerger)inputDevice).MergeForward(ptr2, ptr3)) { m_InputEventStream.Advance(leaveEventInBuffer: false); continue; } ptr = ptr3; } } if (inputDevice.hasEventPreProcessor && !((IEventPreProcessor)inputDevice).PreProcessEvent(ptr2)) { m_InputEventStream.Advance(leaveEventInBuffer: false); continue; } if (m_EventListeners.length > 0) { DelegateHelpers.InvokeCallbacksSafe(ref m_EventListeners, new InputEventPtr(ptr2), inputDevice, "InputSystem.onEvent"); if (ptr2->handled) { m_InputEventStream.Advance(leaveEventInBuffer: false); continue; } } if (internalTime <= num) { num2 += num - internalTime; } ref InputMetrics reference2 = ref m_Metrics; totalUpdateCount = reference2.totalEventCount + 1; reference2.totalEventCount = totalUpdateCount; m_Metrics.totalEventBytes += (int)ptr2->sizeInBytes; switch (type) { case 1145852993: case 1398030676: { InputEventPtr inputEventPtr = new InputEventPtr(ptr2); bool hasStateCallbacks = inputDevice.hasStateCallbacks; if (internalTime < inputDevice.m_LastUpdateTimeInternal && (!hasStateCallbacks || !(inputDevice.stateBlock.format != inputEventPtr.stateFormat))) { break; } bool flag4 = true; if (hasStateCallbacks) { m_ShouldMakeCurrentlyUpdatingDeviceCurrent = true; ((IInputStateCallbackReceiver)inputDevice).OnStateEvent(inputEventPtr); flag4 = m_ShouldMakeCurrentlyUpdatingDeviceCurrent; } else { if (inputDevice.stateBlock.format != inputEventPtr.stateFormat) { break; } flag4 = UpdateState(inputDevice, inputEventPtr, updateType); } num3 += inputEventPtr.sizeInBytes; if (inputDevice.m_LastUpdateTimeInternal <= inputEventPtr.internalTime) { inputDevice.m_LastUpdateTimeInternal = inputEventPtr.internalTime; } if (flag4) { inputDevice.MakeCurrent(); } break; } case 1413830740: { TextEvent* ptr4 = (TextEvent*)ptr2; if (inputDevice is ITextInputReceiver textInputReceiver) { int character = ptr4->character; if (character >= 65536) { character -= 65536; int num4 = 55296 + ((character >> 10) & 0x3FF); int num5 = 56320 + (character & 0x3FF); textInputReceiver.OnTextInput((char)num4); textInputReceiver.OnTextInput((char)num5); } else { textInputReceiver.OnTextInput((char)character); } } break; } case 1229800787: { IMECompositionEvent* ptr5 = (IMECompositionEvent*)ptr2; (inputDevice as ITextInputReceiver)?.OnIMECompositionChanged(ptr5->compositionString); break; } case 1146242381: RemoveDevice(inputDevice); if (inputDevice.native && !inputDevice.description.empty) { ArrayHelpers.AppendWithCapacity(ref m_DisconnectedDevices, ref m_DisconnectedDevicesCount, inputDevice); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, inputDevice, InputDeviceChange.Disconnected, "InputSystem.onDeviceChange"); } break; case 1145259591: inputDevice.NotifyConfigurationChanged(); InputActionState.OnDeviceChange(inputDevice, InputDeviceChange.ConfigurationChanged); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceChangeListeners, inputDevice, InputDeviceChange.ConfigurationChanged, "InputSystem.onDeviceChange"); break; case 1146245972: ResetDevice(inputDevice, ((DeviceResetEvent*)ptr2)->hardReset); break; } m_InputEventStream.Advance(leaveEventInBuffer: false); } m_Metrics.totalEventProcessingTime += (double)(Stopwatch.GetTimestamp() - timestamp) / (double)Stopwatch.Frequency; m_Metrics.totalEventLagTime += num2; m_InputEventStream.Close(ref eventBuffer); } catch (Exception) { m_InputEventStream.CleanUpAfterException(); throw; } if (flag) { ProcessStateChangeMonitorTimeouts(); } InvokeAfterUpdateCallback(updateType); m_CurrentUpdate = InputUpdateType.None; } private void InvokeAfterUpdateCallback(InputUpdateType updateType) { if (updateType != InputUpdateType.Editor || !gameIsPlaying) { DelegateHelpers.InvokeCallbacksSafe(ref m_AfterUpdateListeners, "InputSystem.onAfterUpdate"); } } internal void DontMakeCurrentlyUpdatingDeviceCurrent() { m_ShouldMakeCurrentlyUpdatingDeviceCurrent = false; } internal unsafe bool UpdateState(InputDevice device, InputEvent* eventPtr, InputUpdateType updateType) { InputStateBlock stateBlock = device.m_StateBlock; uint num = stateBlock.sizeInBits / 8; uint num2 = 0u; byte* statePtr; uint num3; if (eventPtr->type == 1398030676) { Unsafe.Read(eventPtr); uint stateSizeInBytes = ((StateEvent*)eventPtr)->stateSizeInBytes; statePtr = (byte*)((StateEvent*)eventPtr)->state; num3 = stateSizeInBytes; if (num3 > num) { num3 = num; } } else { Unsafe.Read(eventPtr); uint deltaStateSizeInBytes = ((DeltaStateEvent*)eventPtr)->deltaStateSizeInBytes; statePtr = (byte*)((DeltaStateEvent*)eventPtr)->deltaState; num2 = ((DeltaStateEvent*)eventPtr)->stateOffset; num3 = deltaStateSizeInBytes; if (num2 + num3 > num) { if (num2 >= num) { return false; } num3 = num - num2; } } return UpdateState(device, updateType, statePtr, num2, num3, eventPtr->internalTime, eventPtr); } internal unsafe bool UpdateState(InputDevice device, InputUpdateType updateType, void* statePtr, uint stateOffsetInDevice, uint stateSize, double internalTime, InputEventPtr eventPtr = default(InputEventPtr)) { int deviceIndex = device.m_DeviceIndex; ref InputStateBlock stateBlock = ref device.m_StateBlock; byte* frontBufferForDevice = (byte*)InputStateBuffers.GetFrontBufferForDevice(deviceIndex); SortStateChangeMonitorsIfNecessary(deviceIndex); bool flag = ProcessStateChangeMonitors(deviceIndex, statePtr, frontBufferForDevice + stateBlock.byteOffset, stateSize, stateOffsetInDevice); uint num = device.m_StateBlock.byteOffset + stateOffsetInDevice; byte* ptr = frontBufferForDevice + num; byte* mask = (device.noisy ? ((byte*)InputStateBuffers.s_NoiseMaskBuffer + num) : null); bool result = !MemoryHelpers.MemCmpBitRegion(ptr, statePtr, 0u, stateSize * 8, mask); WriteStateChange(flippedBuffers: FlipBuffersForDeviceIfNecessary(device, updateType), buffers: m_StateBuffers.m_PlayerStateBuffers, deviceIndex: deviceIndex, deviceStateBlock: ref stateBlock, stateOffsetInDevice: stateOffsetInDevice, statePtr: statePtr, stateSizeInBytes: stateSize); DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceStateChangeListeners, device, eventPtr, "InputSystem.onDeviceStateChange"); if (flag) { FireStateChangeNotifications(deviceIndex, internalTime, eventPtr); } return result; } private unsafe void WriteStateChange(InputStateBuffers.DoubleBuffers buffers, int deviceIndex, ref InputStateBlock deviceStateBlock, uint stateOffsetInDevice, void* statePtr, uint stateSizeInBytes, bool flippedBuffers) { void* frontBuffer = buffers.GetFrontBuffer(deviceIndex); uint num = deviceStateBlock.sizeInBits / 8; if (flippedBuffers && num != stateSizeInBytes) { void* backBuffer = buffers.GetBackBuffer(deviceIndex); UnsafeUtility.MemCpy((void*)((byte*)frontBuffer + deviceStateBlock.byteOffset), (void*)((byte*)backBuffer + deviceStateBlock.byteOffset), (long)num); } if (InputSettings.readValueCachingFeatureEnabled) { byte* ptr = (byte*)frontBuffer; if (flippedBuffers && num == stateSizeInBytes) { ptr = (byte*)buffers.GetBackBuffer(deviceIndex); } m_Devices[deviceIndex].WriteChangedControlStates(ptr + deviceStateBlock.byteOffset, statePtr, stateSizeInBytes, stateOffsetInDevice); } UnsafeUtility.MemCpy((void*)((byte*)frontBuffer + deviceStateBlock.byteOffset + stateOffsetInDevice), statePtr, (long)stateSizeInBytes); } private bool FlipBuffersForDeviceIfNecessary(InputDevice device, InputUpdateType updateType) { if (updateType == InputUpdateType.BeforeRender) { return false; } if (device.m_CurrentUpdateStepCount != InputUpdate.s_UpdateStepCount) { m_StateBuffers.m_PlayerStateBuffers.SwapBuffers(device.m_DeviceIndex); device.m_CurrentUpdateStepCount = InputUpdate.s_UpdateStepCount; return true; } return false; } public void AddStateChangeMonitor(InputControl control, IInputStateChangeMonitor monitor, long monitorIndex, uint groupIndex) { int deviceIndex = control.device.m_DeviceIndex; if (m_StateChangeMonitors == null) { m_StateChangeMonitors = new StateChangeMonitorsForDevice[m_DevicesCount]; } else if (m_StateChangeMonitors.Length <= deviceIndex) { Array.Resize(ref m_StateChangeMonitors, m_DevicesCount); } if (!isProcessingEvents && m_StateChangeMonitors[deviceIndex].needToCompactArrays) { m_StateChangeMonitors[deviceIndex].CompactArrays(); } m_StateChangeMonitors[deviceIndex].Add(control, monitor, monitorIndex, groupIndex); } private void RemoveStateChangeMonitors(InputDevice device) { if (m_StateChangeMonitors == null) { return; } int deviceIndex = device.m_DeviceIndex; if (deviceIndex >= m_StateChangeMonitors.Length) { return; } m_StateChangeMonitors[deviceIndex].Clear(); for (int i = 0; i < m_StateChangeMonitorTimeouts.length; i++) { if (m_StateChangeMonitorTimeouts[i].control?.device == device) { m_StateChangeMonitorTimeouts[i] = default(StateChangeMonitorTimeout); } } } public void RemoveStateChangeMonitor(InputControl control, IInputStateChangeMonitor monitor, long monitorIndex) { if (m_StateChangeMonitors == null) { return; } int deviceIndex = control.device.m_DeviceIndex; if (deviceIndex == -1 || deviceIndex >= m_StateChangeMonitors.Length) { return; } m_StateChangeMonitors[deviceIndex].Remove(monitor, monitorIndex, isProcessingEvents); for (int i = 0; i < m_StateChangeMonitorTimeouts.length; i++) { if (m_StateChangeMonitorTimeouts[i].monitor == monitor && m_StateChangeMonitorTimeouts[i].monitorIndex == monitorIndex) { m_StateChangeMonitorTimeouts[i] = default(StateChangeMonitorTimeout); } } } public void AddStateChangeMonitorTimeout(InputControl control, IInputStateChangeMonitor monitor, double time, long monitorIndex, int timerIndex) { m_StateChangeMonitorTimeouts.Append(new StateChangeMonitorTimeout { control = control, time = time, monitor = monitor, monitorIndex = monitorIndex, timerIndex = timerIndex }); } public void RemoveStateChangeMonitorTimeout(IInputStateChangeMonitor monitor, long monitorIndex, int timerIndex) { int length = m_StateChangeMonitorTimeouts.length; for (int i = 0; i < length; i++) { if (m_StateChangeMonitorTimeouts[i].monitor == monitor && m_StateChangeMonitorTimeouts[i].monitorIndex == monitorIndex && m_StateChangeMonitorTimeouts[i].timerIndex == timerIndex) { m_StateChangeMonitorTimeouts[i] = default(StateChangeMonitorTimeout); break; } } } private void SortStateChangeMonitorsIfNecessary(int deviceIndex) { if (m_StateChangeMonitors != null && deviceIndex < m_StateChangeMonitors.Length && m_StateChangeMonitors[deviceIndex].needToUpdateOrderingOfMonitors) { m_StateChangeMonitors[deviceIndex].SortMonitorsByIndex(); } } public void SignalStateChangeMonitor(InputControl control, IInputStateChangeMonitor monitor) { int deviceIndex = control.device.m_DeviceIndex; ref StateChangeMonitorsForDevice reference = ref m_StateChangeMonitors[deviceIndex]; for (int i = 0; i < reference.signalled.length; i++) { SortStateChangeMonitorsIfNecessary(i); ref StateChangeMonitorListener reference2 = ref reference.listeners[i]; if (reference2.control == control && reference2.monitor == monitor) { reference.signalled.SetBit(i); } } } public unsafe void FireStateChangeNotifications() { double currentTime = m_Runtime.currentTime; int num = Math.Min(m_StateChangeMonitors.LengthSafe(), m_DevicesCount); for (int i = 0; i < num; i++) { FireStateChangeNotifications(i, currentTime, null); } } private unsafe bool ProcessStateChangeMonitors(int deviceIndex, void* newStateFromEvent, void* oldStateOfDevice, uint newStateSizeInBytes, uint newStateOffsetInBytes) { if (m_StateChangeMonitors == null) { return false; } if (deviceIndex >= m_StateChangeMonitors.Length) { return false; } MemoryHelpers.BitRegion[] memoryRegions = m_StateChangeMonitors[deviceIndex].memoryRegions; if (memoryRegions == null) { return false; } int num = m_StateChangeMonitors[deviceIndex].count; bool result = false; DynamicBitfield signalled = m_StateChangeMonitors[deviceIndex].signalled; bool flag = false; MemoryHelpers.BitRegion bitRegion = new MemoryHelpers.BitRegion(newStateOffsetInBytes, 0u, newStateSizeInBytes * 8); for (int i = 0; i < num; i++) { MemoryHelpers.BitRegion other = memoryRegions[i]; if (other.sizeInBits == 0) { int count = num; int count2 = num; m_StateChangeMonitors[deviceIndex].listeners.EraseAtWithCapacity(ref count, i); memoryRegions.EraseAtWithCapacity(ref count2, i); signalled.SetLength(num - 1); flag = true; num--; i--; } else { MemoryHelpers.BitRegion region = bitRegion.Overlap(other); if (!region.isEmpty && !MemoryHelpers.Compare(oldStateOfDevice, (byte*)newStateFromEvent - newStateOffsetInBytes, region)) { signalled.SetBit(i); flag = true; result = true; } } } if (flag) { m_StateChangeMonitors[deviceIndex].signalled = signalled; } m_StateChangeMonitors[deviceIndex].needToCompactArrays = false; return result; } internal unsafe void FireStateChangeNotifications(int deviceIndex, double internalTime, InputEvent* eventPtr) { ref DynamicBitfield signalled = ref m_StateChangeMonitors[deviceIndex].signalled; ref StateChangeMonitorListener[] listeners = ref m_StateChangeMonitors[deviceIndex].listeners; double time = internalTime - InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup; InputEvent inputEvent = new InputEvent(new FourCC('F', 'A', 'K', 'E'), 20, -1, internalTime); if (eventPtr == null) { eventPtr = (InputEvent*)UnsafeUtility.AddressOf(ref inputEvent); } eventPtr->handled = false; for (int i = 0; i < signalled.length; i++) { if (!signalled.TestBit(i)) { continue; } StateChangeMonitorListener stateChangeMonitorListener = listeners[i]; try { stateChangeMonitorListener.monitor.NotifyControlStateChanged(stateChangeMonitorListener.control, time, eventPtr, stateChangeMonitorListener.monitorIndex); } catch (Exception ex) { Debug.LogError((object)$"Exception '{ex.GetType().Name}' thrown from state change monitor '{stateChangeMonitorListener.monitor.GetType().Name}' on '{stateChangeMonitorListener.control}'"); Debug.LogException(ex); } if (eventPtr->handled) { uint groupIndex = listeners[i].groupIndex; for (int j = i + 1; j < signalled.length; j++) { if (listeners[j].groupIndex == groupIndex && listeners[j].monitor == stateChangeMonitorListener.monitor) { signalled.ClearBit(j); } } eventPtr->handled = false; } signalled.ClearBit(i); } } private void ProcessStateChangeMonitorTimeouts() { if (m_StateChangeMonitorTimeouts.length == 0) { return; } double num = m_Runtime.currentTime - InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup; int num2 = 0; for (int i = 0; i < m_StateChangeMonitorTimeouts.length; i++) { if (m_StateChangeMonitorTimeouts[i].control == null) { continue; } if (m_StateChangeMonitorTimeouts[i].time <= num) { StateChangeMonitorTimeout stateChangeMonitorTimeout = m_StateChangeMonitorTimeouts[i]; stateChangeMonitorTimeout.monitor.NotifyTimerExpired(stateChangeMonitorTimeout.control, num, stateChangeMonitorTimeout.monitorIndex, stateChangeMonitorTimeout.timerIndex); continue; } if (i != num2) { m_StateChangeMonitorTimeouts[num2] = m_StateChangeMonitorTimeouts[i]; } num2++; } m_StateChangeMonitorTimeouts.SetLength(num2); } } public class InputSettings : ScriptableObject { public enum UpdateMode { ProcessEventsInDynamicUpdate = 1, ProcessEventsInFixedUpdate, ProcessEventsManually } public enum BackgroundBehavior { ResetAndDisableNonBackgroundDevices, ResetAndDisableAllDevices, IgnoreFocus } public enum EditorInputBehaviorInPlayMode { PointersAndKeyboardsRespectGameViewFocus, AllDevicesRespectGameViewFocus, AllDeviceInputAlwaysGoesToGameView } [Tooltip("Determine which type of devices are used by the application. By default, this is empty meaning that all devices recognized by Unity will be used. Restricting the set of supported devices will make only those devices appear in the input system.")] [SerializeField] private string[] m_SupportedDevices; [Tooltip("Determine when Unity processes events. By default, accumulated input events are flushed out before each fixed update and before each dynamic update. This setting can be used to restrict event processing to only where the application needs it.")] [SerializeField] private UpdateMode m_UpdateMode = UpdateMode.ProcessEventsInDynamicUpdate; [SerializeField] private int m_MaxEventBytesPerUpdate = 5242880; [SerializeField] private int m_MaxQueuedEventsPerUpdate = 1000; [SerializeField] private bool m_CompensateForScreenOrientation = true; [SerializeField] private BackgroundBehavior m_BackgroundBehavior; [SerializeField] private EditorInputBehaviorInPlayMode m_EditorInputBehaviorInPlayMode; [SerializeField] private float m_DefaultDeadzoneMin = 0.125f; [SerializeField] private float m_DefaultDeadzoneMax = 0.925f; [Min(0.0001f)] [SerializeField] private float m_DefaultButtonPressPoint = 0.5f; [SerializeField] private float m_ButtonReleaseThreshold = 0.75f; [SerializeField] private float m_DefaultTapTime = 0.2f; [SerializeField] private float m_DefaultSlowTapTime = 0.5f; [SerializeField] private float m_DefaultHoldTime = 0.4f; [SerializeField] private float m_TapRadius = 5f; [SerializeField] private float m_MultiTapDelayTime = 0.75f; [SerializeField] private bool m_DisableRedundantEventsMerging; [SerializeField] private bool m_ShortcutKeysConsumeInputs; [NonSerialized] internal HashSet m_FeatureFlags; internal static bool optimizedControlsFeatureEnabled; internal static bool readValueCachingFeatureEnabled; internal static bool paranoidReadValueCachingChecksEnabled; internal const int s_OldUnsupportedFixedAndDynamicUpdateSetting = 0; public UpdateMode updateMode { get { return m_UpdateMode; } set { if (m_UpdateMode != value) { m_UpdateMode = value; OnChange(); } } } public bool compensateForScreenOrientation { get { return m_CompensateForScreenOrientation; } set { if (m_CompensateForScreenOrientation != value) { m_CompensateForScreenOrientation = value; OnChange(); } } } [Obsolete("filterNoiseOnCurrent is deprecated, filtering of noise is always enabled now.", false)] public bool filterNoiseOnCurrent { get { return false; } set { } } public float defaultDeadzoneMin { get { return m_DefaultDeadzoneMin; } set { if (m_DefaultDeadzoneMin != value) { m_DefaultDeadzoneMin = value; OnChange(); } } } public float defaultDeadzoneMax { get { return m_DefaultDeadzoneMax; } set { if (m_DefaultDeadzoneMax != value) { m_DefaultDeadzoneMax = value; OnChange(); } } } public float defaultButtonPressPoint { get { return m_DefaultButtonPressPoint; } set { if (m_DefaultButtonPressPoint != value) { m_DefaultButtonPressPoint = Mathf.Clamp(value, 0.0001f, float.MaxValue); OnChange(); } } } public float buttonReleaseThreshold { get { return m_ButtonReleaseThreshold; } set { if (m_ButtonReleaseThreshold != value) { m_ButtonReleaseThreshold = value; OnChange(); } } } public float defaultTapTime { get { return m_DefaultTapTime; } set { if (m_DefaultTapTime != value) { m_DefaultTapTime = value; OnChange(); } } } public float defaultSlowTapTime { get { return m_DefaultSlowTapTime; } set { if (m_DefaultSlowTapTime != value) { m_DefaultSlowTapTime = value; OnChange(); } } } public float defaultHoldTime { get { return m_DefaultHoldTime; } set { if (m_DefaultHoldTime != value) { m_DefaultHoldTime = value; OnChange(); } } } public float tapRadius { get { return m_TapRadius; } set { if (m_TapRadius != value) { m_TapRadius = value; OnChange(); } } } public float multiTapDelayTime { get { return m_MultiTapDelayTime; } set { if (m_MultiTapDelayTime != value) { m_MultiTapDelayTime = value; OnChange(); } } } public BackgroundBehavior backgroundBehavior { get { return m_BackgroundBehavior; } set { if (m_BackgroundBehavior != value) { m_BackgroundBehavior = value; OnChange(); } } } public EditorInputBehaviorInPlayMode editorInputBehaviorInPlayMode { get { return m_EditorInputBehaviorInPlayMode; } set { if (m_EditorInputBehaviorInPlayMode != value) { m_EditorInputBehaviorInPlayMode = value; OnChange(); } } } public int maxEventBytesPerUpdate { get { return m_MaxEventBytesPerUpdate; } set { if (m_MaxEventBytesPerUpdate != value) { m_MaxEventBytesPerUpdate = value; OnChange(); } } } public int maxQueuedEventsPerUpdate { get { return m_MaxQueuedEventsPerUpdate; } set { if (m_MaxQueuedEventsPerUpdate != value) { m_MaxQueuedEventsPerUpdate = value; OnChange(); } } } public ReadOnlyArray supportedDevices { get { return new ReadOnlyArray(m_SupportedDevices); } set { if (supportedDevices.Count == value.Count) { bool flag = false; for (int i = 0; i < supportedDevices.Count; i++) { if (m_SupportedDevices[i] != value[i]) { flag = true; break; } } if (!flag) { return; } } m_SupportedDevices = value.ToArray(); OnChange(); } } public bool disableRedundantEventsMerging { get { return m_DisableRedundantEventsMerging; } set { if (m_DisableRedundantEventsMerging != value) { m_DisableRedundantEventsMerging = value; OnChange(); } } } public bool shortcutKeysConsumeInput { get { return m_ShortcutKeysConsumeInputs; } set { if (m_ShortcutKeysConsumeInputs != value) { m_ShortcutKeysConsumeInputs = value; OnChange(); } } } public void SetInternalFeatureFlag(string featureName, bool enabled) { if (string.IsNullOrEmpty(featureName)) { throw new ArgumentNullException("featureName"); } switch (featureName) { case "USE_OPTIMIZED_CONTROLS": optimizedControlsFeatureEnabled = enabled; break; case "USE_READ_VALUE_CACHING": readValueCachingFeatureEnabled = enabled; break; case "PARANOID_READ_VALUE_CACHING_CHECKS": paranoidReadValueCachingChecksEnabled = enabled; break; default: if (m_FeatureFlags == null) { m_FeatureFlags = new HashSet(); } if (enabled) { m_FeatureFlags.Add(featureName.ToUpperInvariant()); } else { m_FeatureFlags.Remove(featureName.ToUpperInvariant()); } break; } OnChange(); } internal bool IsFeatureEnabled(string featureName) { if (m_FeatureFlags != null) { return m_FeatureFlags.Contains(featureName.ToUpperInvariant()); } return false; } internal void OnChange() { if ((Object)(object)InputSystem.settings == (Object)(object)this) { InputSystem.s_Manager.ApplySettings(); } } } public class DefaultInputActions : IInputActionCollection2, IInputActionCollection, IEnumerable, IEnumerable, IDisposable { public struct PlayerActions { private DefaultInputActions m_Wrapper; public InputAction Move => m_Wrapper.m_Player_Move; public InputAction Look => m_Wrapper.m_Player_Look; public InputAction Fire => m_Wrapper.m_Player_Fire; public bool enabled => Get().enabled; public PlayerActions(DefaultInputActions wrapper) { m_Wrapper = wrapper; } public InputActionMap Get() { return m_Wrapper.m_Player; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public static implicit operator InputActionMap(PlayerActions set) { return set.Get(); } public void SetCallbacks(IPlayerActions instance) { if (m_Wrapper.m_PlayerActionsCallbackInterface != null) { Move.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMove; Move.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMove; Move.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnMove; Look.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnLook; Look.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnLook; Look.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnLook; Fire.started -= m_Wrapper.m_PlayerActionsCallbackInterface.OnFire; Fire.performed -= m_Wrapper.m_PlayerActionsCallbackInterface.OnFire; Fire.canceled -= m_Wrapper.m_PlayerActionsCallbackInterface.OnFire; } m_Wrapper.m_PlayerActionsCallbackInterface = instance; if (instance != null) { Move.started += instance.OnMove; Move.performed += instance.OnMove; Move.canceled += instance.OnMove; Look.started += instance.OnLook; Look.performed += instance.OnLook; Look.canceled += instance.OnLook; Fire.started += instance.OnFire; Fire.performed += instance.OnFire; Fire.canceled += instance.OnFire; } } } public struct UIActions { private DefaultInputActions m_Wrapper; public InputAction Navigate => m_Wrapper.m_UI_Navigate; public InputAction Submit => m_Wrapper.m_UI_Submit; public InputAction Cancel => m_Wrapper.m_UI_Cancel; public InputAction Point => m_Wrapper.m_UI_Point; public InputAction Click => m_Wrapper.m_UI_Click; public InputAction ScrollWheel => m_Wrapper.m_UI_ScrollWheel; public InputAction MiddleClick => m_Wrapper.m_UI_MiddleClick; public InputAction RightClick => m_Wrapper.m_UI_RightClick; public InputAction TrackedDevicePosition => m_Wrapper.m_UI_TrackedDevicePosition; public InputAction TrackedDeviceOrientation => m_Wrapper.m_UI_TrackedDeviceOrientation; public bool enabled => Get().enabled; public UIActions(DefaultInputActions wrapper) { m_Wrapper = wrapper; } public InputActionMap Get() { return m_Wrapper.m_UI; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public static implicit operator InputActionMap(UIActions set) { return set.Get(); } public void SetCallbacks(IUIActions instance) { if (m_Wrapper.m_UIActionsCallbackInterface != null) { Navigate.started -= m_Wrapper.m_UIActionsCallbackInterface.OnNavigate; Navigate.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnNavigate; Navigate.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnNavigate; Submit.started -= m_Wrapper.m_UIActionsCallbackInterface.OnSubmit; Submit.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnSubmit; Submit.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnSubmit; Cancel.started -= m_Wrapper.m_UIActionsCallbackInterface.OnCancel; Cancel.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnCancel; Cancel.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnCancel; Point.started -= m_Wrapper.m_UIActionsCallbackInterface.OnPoint; Point.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnPoint; Point.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnPoint; Click.started -= m_Wrapper.m_UIActionsCallbackInterface.OnClick; Click.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnClick; Click.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnClick; ScrollWheel.started -= m_Wrapper.m_UIActionsCallbackInterface.OnScrollWheel; ScrollWheel.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnScrollWheel; ScrollWheel.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnScrollWheel; MiddleClick.started -= m_Wrapper.m_UIActionsCallbackInterface.OnMiddleClick; MiddleClick.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnMiddleClick; MiddleClick.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnMiddleClick; RightClick.started -= m_Wrapper.m_UIActionsCallbackInterface.OnRightClick; RightClick.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnRightClick; RightClick.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnRightClick; TrackedDevicePosition.started -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDevicePosition; TrackedDevicePosition.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDevicePosition; TrackedDevicePosition.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDevicePosition; TrackedDeviceOrientation.started -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDeviceOrientation; TrackedDeviceOrientation.performed -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDeviceOrientation; TrackedDeviceOrientation.canceled -= m_Wrapper.m_UIActionsCallbackInterface.OnTrackedDeviceOrientation; } m_Wrapper.m_UIActionsCallbackInterface = instance; if (instance != null) { Navigate.started += instance.OnNavigate; Navigate.performed += instance.OnNavigate; Navigate.canceled += instance.OnNavigate; Submit.started += instance.OnSubmit; Submit.performed += instance.OnSubmit; Submit.canceled += instance.OnSubmit; Cancel.started += instance.OnCancel; Cancel.performed += instance.OnCancel; Cancel.canceled += instance.OnCancel; Point.started += instance.OnPoint; Point.performed += instance.OnPoint; Point.canceled += instance.OnPoint; Click.started += instance.OnClick; Click.performed += instance.OnClick; Click.canceled += instance.OnClick; ScrollWheel.started += instance.OnScrollWheel; ScrollWheel.performed += instance.OnScrollWheel; ScrollWheel.canceled += instance.OnScrollWheel; MiddleClick.started += instance.OnMiddleClick; MiddleClick.performed += instance.OnMiddleClick; MiddleClick.canceled += instance.OnMiddleClick; RightClick.started += instance.OnRightClick; RightClick.performed += instance.OnRightClick; RightClick.canceled += instance.OnRightClick; TrackedDevicePosition.started += instance.OnTrackedDevicePosition; TrackedDevicePosition.performed += instance.OnTrackedDevicePosition; TrackedDevicePosition.canceled += instance.OnTrackedDevicePosition; TrackedDeviceOrientation.started += instance.OnTrackedDeviceOrientation; TrackedDeviceOrientation.performed += instance.OnTrackedDeviceOrientation; TrackedDeviceOrientation.canceled += instance.OnTrackedDeviceOrientation; } } } public interface IPlayerActions { void OnMove(InputAction.CallbackContext context); void OnLook(InputAction.CallbackContext context); void OnFire(InputAction.CallbackContext context); } public interface IUIActions { void OnNavigate(InputAction.CallbackContext context); void OnSubmit(InputAction.CallbackContext context); void OnCancel(InputAction.CallbackContext context); void OnPoint(InputAction.CallbackContext context); void OnClick(InputAction.CallbackContext context); void OnScrollWheel(InputAction.CallbackContext context); void OnMiddleClick(InputAction.CallbackContext context); void OnRightClick(InputAction.CallbackContext context); void OnTrackedDevicePosition(InputAction.CallbackContext context); void OnTrackedDeviceOrientation(InputAction.CallbackContext context); } private readonly InputActionMap m_Player; private IPlayerActions m_PlayerActionsCallbackInterface; private readonly InputAction m_Player_Move; private readonly InputAction m_Player_Look; private readonly InputAction m_Player_Fire; private readonly InputActionMap m_UI; private IUIActions m_UIActionsCallbackInterface; private readonly InputAction m_UI_Navigate; private readonly InputAction m_UI_Submit; private readonly InputAction m_UI_Cancel; private readonly InputAction m_UI_Point; private readonly InputAction m_UI_Click; private readonly InputAction m_UI_ScrollWheel; private readonly InputAction m_UI_MiddleClick; private readonly InputAction m_UI_RightClick; private readonly InputAction m_UI_TrackedDevicePosition; private readonly InputAction m_UI_TrackedDeviceOrientation; private int m_KeyboardMouseSchemeIndex = -1; private int m_GamepadSchemeIndex = -1; private int m_TouchSchemeIndex = -1; private int m_JoystickSchemeIndex = -1; private int m_XRSchemeIndex = -1; public InputActionAsset asset { get; } public InputBinding? bindingMask { get { return asset.bindingMask; } set { asset.bindingMask = value; } } public ReadOnlyArray? devices { get { return asset.devices; } set { asset.devices = value; } } public ReadOnlyArray controlSchemes => asset.controlSchemes; public IEnumerable bindings => asset.bindings; public PlayerActions Player => new PlayerActions(this); public UIActions UI => new UIActions(this); public InputControlScheme KeyboardMouseScheme { get { if (m_KeyboardMouseSchemeIndex == -1) { m_KeyboardMouseSchemeIndex = asset.FindControlSchemeIndex("Keyboard&Mouse"); } return asset.controlSchemes[m_KeyboardMouseSchemeIndex]; } } public InputControlScheme GamepadScheme { get { if (m_GamepadSchemeIndex == -1) { m_GamepadSchemeIndex = asset.FindControlSchemeIndex("Gamepad"); } return asset.controlSchemes[m_GamepadSchemeIndex]; } } public InputControlScheme TouchScheme { get { if (m_TouchSchemeIndex == -1) { m_TouchSchemeIndex = asset.FindControlSchemeIndex("Touch"); } return asset.controlSchemes[m_TouchSchemeIndex]; } } public InputControlScheme JoystickScheme { get { if (m_JoystickSchemeIndex == -1) { m_JoystickSchemeIndex = asset.FindControlSchemeIndex("Joystick"); } return asset.controlSchemes[m_JoystickSchemeIndex]; } } public InputControlScheme XRScheme { get { if (m_XRSchemeIndex == -1) { m_XRSchemeIndex = asset.FindControlSchemeIndex("XR"); } return asset.controlSchemes[m_XRSchemeIndex]; } } public DefaultInputActions() { asset = InputActionAsset.FromJson("{\n \"name\": \"DefaultInputActions\",\n \"maps\": [\n {\n \"name\": \"Player\",\n \"id\": \"df70fa95-8a34-4494-b137-73ab6b9c7d37\",\n \"actions\": [\n {\n \"name\": \"Move\",\n \"type\": \"Value\",\n \"id\": \"351f2ccd-1f9f-44bf-9bec-d62ac5c5f408\",\n \"expectedControlType\": \"Vector2\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": true\n },\n {\n \"name\": \"Look\",\n \"type\": \"Value\",\n \"id\": \"6b444451-8a00-4d00-a97e-f47457f736a8\",\n \"expectedControlType\": \"Vector2\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": true\n },\n {\n \"name\": \"Fire\",\n \"type\": \"Button\",\n \"id\": \"6c2ab1b8-8984-453a-af3d-a3c78ae1679a\",\n \"expectedControlType\": \"Button\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n }\n ],\n \"bindings\": [\n {\n \"name\": \"\",\n \"id\": \"978bfe49-cc26-4a3d-ab7b-7d7a29327403\",\n \"path\": \"/leftStick\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"WASD\",\n \"id\": \"00ca640b-d935-4593-8157-c05846ea39b3\",\n \"path\": \"Dpad\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"\",\n \"action\": \"Move\",\n \"isComposite\": true,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"up\",\n \"id\": \"e2062cb9-1b15-46a2-838c-2f8d72a0bdd9\",\n \"path\": \"/w\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"up\",\n \"id\": \"8180e8bd-4097-4f4e-ab88-4523101a6ce9\",\n \"path\": \"/upArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"320bffee-a40b-4347-ac70-c210eb8bc73a\",\n \"path\": \"/s\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"1c5327b5-f71c-4f60-99c7-4e737386f1d1\",\n \"path\": \"/downArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"d2581a9b-1d11-4566-b27d-b92aff5fabbc\",\n \"path\": \"/a\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"2e46982e-44cc-431b-9f0b-c11910bf467a\",\n \"path\": \"/leftArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"fcfe95b8-67b9-4526-84b5-5d0bc98d6400\",\n \"path\": \"/d\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"77bff152-3580-4b21-b6de-dcd0c7e41164\",\n \"path\": \"/rightArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"\",\n \"id\": \"1635d3fe-58b6-4ba9-a4e2-f4b964f6b5c8\",\n \"path\": \"/{Primary2DAxis}\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"XR\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"3ea4d645-4504-4529-b061-ab81934c3752\",\n \"path\": \"/stick\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Move\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"c1f7a91b-d0fd-4a62-997e-7fb9b69bf235\",\n \"path\": \"/rightStick\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Look\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"8c8e490b-c610-4785-884f-f04217b23ca4\",\n \"path\": \"/delta\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse;Touch\",\n \"action\": \"Look\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"3e5f5442-8668-4b27-a940-df99bad7e831\",\n \"path\": \"/{Hatswitch}\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Look\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"143bb1cd-cc10-4eca-a2f0-a3664166fe91\",\n \"path\": \"/rightTrigger\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Fire\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"05f6913d-c316-48b2-a6bb-e225f14c7960\",\n \"path\": \"/leftButton\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Fire\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"886e731e-7071-4ae4-95c0-e61739dad6fd\",\n \"path\": \"/primaryTouch/tap\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Touch\",\n \"action\": \"Fire\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"ee3d0cd2-254e-47a7-a8cb-bc94d9658c54\",\n \"path\": \"/trigger\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Fire\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"8255d333-5683-4943-a58a-ccb207ff1dce\",\n \"path\": \"/{PrimaryAction}\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"XR\",\n \"action\": \"Fire\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n }\n ]\n },\n {\n \"name\": \"UI\",\n \"id\": \"272f6d14-89ba-496f-b7ff-215263d3219f\",\n \"actions\": [\n {\n \"name\": \"Navigate\",\n \"type\": \"PassThrough\",\n \"id\": \"c95b2375-e6d9-4b88-9c4c-c5e76515df4b\",\n \"expectedControlType\": \"Vector2\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"Submit\",\n \"type\": \"Button\",\n \"id\": \"7607c7b6-cd76-4816-beef-bd0341cfe950\",\n \"expectedControlType\": \"Button\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"Cancel\",\n \"type\": \"Button\",\n \"id\": \"15cef263-9014-4fd5-94d9-4e4a6234a6ef\",\n \"expectedControlType\": \"Button\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"Point\",\n \"type\": \"PassThrough\",\n \"id\": \"32b35790-4ed0-4e9a-aa41-69ac6d629449\",\n \"expectedControlType\": \"Vector2\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": true\n },\n {\n \"name\": \"Click\",\n \"type\": \"PassThrough\",\n \"id\": \"3c7022bf-7922-4f7c-a998-c437916075ad\",\n \"expectedControlType\": \"Button\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": true\n },\n {\n \"name\": \"ScrollWheel\",\n \"type\": \"PassThrough\",\n \"id\": \"0489e84a-4833-4c40-bfae-cea84b696689\",\n \"expectedControlType\": \"Vector2\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"MiddleClick\",\n \"type\": \"PassThrough\",\n \"id\": \"dad70c86-b58c-4b17-88ad-f5e53adf419e\",\n \"expectedControlType\": \"Button\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"RightClick\",\n \"type\": \"PassThrough\",\n \"id\": \"44b200b1-1557-4083-816c-b22cbdf77ddf\",\n \"expectedControlType\": \"Button\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"TrackedDevicePosition\",\n \"type\": \"PassThrough\",\n \"id\": \"24908448-c609-4bc3-a128-ea258674378a\",\n \"expectedControlType\": \"Vector3\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n },\n {\n \"name\": \"TrackedDeviceOrientation\",\n \"type\": \"PassThrough\",\n \"id\": \"9caa3d8a-6b2f-4e8e-8bad-6ede561bd9be\",\n \"expectedControlType\": \"Quaternion\",\n \"processors\": \"\",\n \"interactions\": \"\",\n \"initialStateCheck\": false\n }\n ],\n \"bindings\": [\n {\n \"name\": \"Gamepad\",\n \"id\": \"809f371f-c5e2-4e7a-83a1-d867598f40dd\",\n \"path\": \"2DVector\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"\",\n \"action\": \"Navigate\",\n \"isComposite\": true,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"up\",\n \"id\": \"14a5d6e8-4aaf-4119-a9ef-34b8c2c548bf\",\n \"path\": \"/leftStick/up\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"up\",\n \"id\": \"9144cbe6-05e1-4687-a6d7-24f99d23dd81\",\n \"path\": \"/rightStick/up\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"2db08d65-c5fb-421b-983f-c71163608d67\",\n \"path\": \"/leftStick/down\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"58748904-2ea9-4a80-8579-b500e6a76df8\",\n \"path\": \"/rightStick/down\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"8ba04515-75aa-45de-966d-393d9bbd1c14\",\n \"path\": \"/leftStick/left\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"712e721c-bdfb-4b23-a86c-a0d9fcfea921\",\n \"path\": \"/rightStick/left\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"fcd248ae-a788-4676-a12e-f4d81205600b\",\n \"path\": \"/leftStick/right\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"1f04d9bc-c50b-41a1-bfcc-afb75475ec20\",\n \"path\": \"/rightStick/right\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"\",\n \"id\": \"fb8277d4-c5cd-4663-9dc7-ee3f0b506d90\",\n \"path\": \"/dpad\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Gamepad\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"Joystick\",\n \"id\": \"e25d9774-381c-4a61-b47c-7b6b299ad9f9\",\n \"path\": \"2DVector\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"\",\n \"action\": \"Navigate\",\n \"isComposite\": true,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"up\",\n \"id\": \"3db53b26-6601-41be-9887-63ac74e79d19\",\n \"path\": \"/stick/up\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"0cb3e13e-3d90-4178-8ae6-d9c5501d653f\",\n \"path\": \"/stick/down\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"0392d399-f6dd-4c82-8062-c1e9c0d34835\",\n \"path\": \"/stick/left\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"942a66d9-d42f-43d6-8d70-ecb4ba5363bc\",\n \"path\": \"/stick/right\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Joystick\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"Keyboard\",\n \"id\": \"ff527021-f211-4c02-933e-5976594c46ed\",\n \"path\": \"2DVector\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"\",\n \"action\": \"Navigate\",\n \"isComposite\": true,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"up\",\n \"id\": \"563fbfdd-0f09-408d-aa75-8642c4f08ef0\",\n \"path\": \"/w\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"up\",\n \"id\": \"eb480147-c587-4a33-85ed-eb0ab9942c43\",\n \"path\": \"/upArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"2bf42165-60bc-42ca-8072-8c13ab40239b\",\n \"path\": \"/s\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"down\",\n \"id\": \"85d264ad-e0a0-4565-b7ff-1a37edde51ac\",\n \"path\": \"/downArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"74214943-c580-44e4-98eb-ad7eebe17902\",\n \"path\": \"/a\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"left\",\n \"id\": \"cea9b045-a000-445b-95b8-0c171af70a3b\",\n \"path\": \"/leftArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"8607c725-d935-4808-84b1-8354e29bab63\",\n \"path\": \"/d\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"right\",\n \"id\": \"4cda81dc-9edd-4e03-9d7c-a71a14345d0b\",\n \"path\": \"/rightArrow\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Navigate\",\n \"isComposite\": false,\n \"isPartOfComposite\": true\n },\n {\n \"name\": \"\",\n \"id\": \"9e92bb26-7e3b-4ec4-b06b-3c8f8e498ddc\",\n \"path\": \"*/{Submit}\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse;Gamepad;Touch;Joystick;XR\",\n \"action\": \"Submit\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"82627dcc-3b13-4ba9-841d-e4b746d6553e\",\n \"path\": \"*/{Cancel}\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse;Gamepad;Touch;Joystick;XR\",\n \"action\": \"Cancel\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"c52c8e0b-8179-41d3-b8a1-d149033bbe86\",\n \"path\": \"/position\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Point\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"e1394cbc-336e-44ce-9ea8-6007ed6193f7\",\n \"path\": \"/position\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Keyboard&Mouse\",\n \"action\": \"Point\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"5693e57a-238a-46ed-b5ae-e64e6e574302\",\n \"path\": \"/touch*/position\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Touch\",\n \"action\": \"Point\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"4faf7dc9-b979-4210-aa8c-e808e1ef89f5\",\n \"path\": \"/leftButton\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Click\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"8d66d5ba-88d7-48e6-b1cd-198bbfef7ace\",\n \"path\": \"/tip\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"Click\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"47c2a644-3ebc-4dae-a106-589b7ca75b59\",\n \"path\": \"/touch*/press\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"Touch\",\n \"action\": \"Click\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"bb9e6b34-44bf-4381-ac63-5aa15d19f677\",\n \"path\": \"/trigger\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"XR\",\n \"action\": \"Click\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"38c99815-14ea-4617-8627-164d27641299\",\n \"path\": \"/scroll\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"ScrollWheel\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"24066f69-da47-44f3-a07e-0015fb02eb2e\",\n \"path\": \"/middleButton\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"MiddleClick\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"4c191405-5738-4d4b-a523-c6a301dbf754\",\n \"path\": \"/rightButton\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \";Keyboard&Mouse\",\n \"action\": \"RightClick\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"7236c0d9-6ca3-47cf-a6ee-a97f5b59ea77\",\n \"path\": \"/devicePosition\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"XR\",\n \"action\": \"TrackedDevicePosition\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n },\n {\n \"name\": \"\",\n \"id\": \"23e01e3a-f935-4948-8d8b-9bcac77714fb\",\n \"path\": \"/deviceRotation\",\n \"interactions\": \"\",\n \"processors\": \"\",\n \"groups\": \"XR\",\n \"action\": \"TrackedDeviceOrientation\",\n \"isComposite\": false,\n \"isPartOfComposite\": false\n }\n ]\n }\n ],\n \"controlSchemes\": [\n {\n \"name\": \"Keyboard&Mouse\",\n \"bindingGroup\": \"Keyboard&Mouse\",\n \"devices\": [\n {\n \"devicePath\": \"\",\n \"isOptional\": false,\n \"isOR\": false\n },\n {\n \"devicePath\": \"\",\n \"isOptional\": false,\n \"isOR\": false\n }\n ]\n },\n {\n \"name\": \"Gamepad\",\n \"bindingGroup\": \"Gamepad\",\n \"devices\": [\n {\n \"devicePath\": \"\",\n \"isOptional\": false,\n \"isOR\": false\n }\n ]\n },\n {\n \"name\": \"Touch\",\n \"bindingGroup\": \"Touch\",\n \"devices\": [\n {\n \"devicePath\": \"\",\n \"isOptional\": false,\n \"isOR\": false\n }\n ]\n },\n {\n \"name\": \"Joystick\",\n \"bindingGroup\": \"Joystick\",\n \"devices\": [\n {\n \"devicePath\": \"\",\n \"isOptional\": false,\n \"isOR\": false\n }\n ]\n },\n {\n \"name\": \"XR\",\n \"bindingGroup\": \"XR\",\n \"devices\": [\n {\n \"devicePath\": \"\",\n \"isOptional\": false,\n \"isOR\": false\n }\n ]\n }\n ]\n}"); m_Player = asset.FindActionMap("Player", throwIfNotFound: true); m_Player_Move = m_Player.FindAction("Move", throwIfNotFound: true); m_Player_Look = m_Player.FindAction("Look", throwIfNotFound: true); m_Player_Fire = m_Player.FindAction("Fire", throwIfNotFound: true); m_UI = asset.FindActionMap("UI", throwIfNotFound: true); m_UI_Navigate = m_UI.FindAction("Navigate", throwIfNotFound: true); m_UI_Submit = m_UI.FindAction("Submit", throwIfNotFound: true); m_UI_Cancel = m_UI.FindAction("Cancel", throwIfNotFound: true); m_UI_Point = m_UI.FindAction("Point", throwIfNotFound: true); m_UI_Click = m_UI.FindAction("Click", throwIfNotFound: true); m_UI_ScrollWheel = m_UI.FindAction("ScrollWheel", throwIfNotFound: true); m_UI_MiddleClick = m_UI.FindAction("MiddleClick", throwIfNotFound: true); m_UI_RightClick = m_UI.FindAction("RightClick", throwIfNotFound: true); m_UI_TrackedDevicePosition = m_UI.FindAction("TrackedDevicePosition", throwIfNotFound: true); m_UI_TrackedDeviceOrientation = m_UI.FindAction("TrackedDeviceOrientation", throwIfNotFound: true); } public void Dispose() { Object.Destroy((Object)(object)asset); } public bool Contains(InputAction action) { return asset.Contains(action); } public IEnumerator GetEnumerator() { return asset.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Enable() { asset.Enable(); } public void Disable() { asset.Disable(); } public InputAction FindAction(string actionNameOrId, bool throwIfNotFound = false) { return asset.FindAction(actionNameOrId, throwIfNotFound); } public int FindBinding(InputBinding bindingMask, out InputAction action) { return asset.FindBinding(bindingMask, out action); } } [DebuggerDisplay("Value = {Get()}")] public class InputValue { internal InputAction.CallbackContext? m_Context; public bool isPressed => Get() >= ButtonControl.s_GlobalDefaultButtonPressPoint; public object Get() { return m_Context.Value.ReadValueAsObject(); } public TValue Get() where TValue : struct { if (!m_Context.HasValue) { throw new InvalidOperationException("Values can only be retrieved while in message callbacks"); } return m_Context.Value.ReadValue(); } } [AddComponentMenu("Input/Player Input")] [DisallowMultipleComponent] [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/PlayerInput.html")] public class PlayerInput : MonoBehaviour { [Serializable] public class ActionEvent : UnityEvent { [SerializeField] private string m_ActionId; [SerializeField] private string m_ActionName; public string actionId => m_ActionId; public string actionName => m_ActionName; public ActionEvent() { } public ActionEvent(InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } if (action.isSingletonAction) { throw new ArgumentException($"Action must be part of an asset (given action '{action}' is a singleton)"); } if ((Object)(object)action.actionMap.asset == (Object)null) { throw new ArgumentException($"Action must be part of an asset (given action '{action}' is not)"); } m_ActionId = action.id.ToString(); m_ActionName = action.actionMap.name + "/" + action.name; } public ActionEvent(Guid actionGUID, string name = null) { m_ActionId = actionGUID.ToString(); m_ActionName = name; } } [Serializable] public class DeviceLostEvent : UnityEvent { } [Serializable] public class DeviceRegainedEvent : UnityEvent { } [Serializable] public class ControlsChangedEvent : UnityEvent { } public const string DeviceLostMessage = "OnDeviceLost"; public const string DeviceRegainedMessage = "OnDeviceRegained"; public const string ControlsChangedMessage = "OnControlsChanged"; [Tooltip("Input actions associated with the player.")] [SerializeField] internal InputActionAsset m_Actions; [Tooltip("Determine how notifications should be sent when an input-related event associated with the player happens.")] [SerializeField] internal PlayerNotifications m_NotificationBehavior; [Tooltip("UI InputModule that should have it's input actions synchronized to this PlayerInput's actions.")] [SerializeField] internal InputSystemUIInputModule m_UIInputModule; [Tooltip("Event that is triggered when the PlayerInput loses a paired device (e.g. its battery runs out).")] [SerializeField] internal DeviceLostEvent m_DeviceLostEvent; [SerializeField] internal DeviceRegainedEvent m_DeviceRegainedEvent; [SerializeField] internal ControlsChangedEvent m_ControlsChangedEvent; [SerializeField] internal ActionEvent[] m_ActionEvents; [SerializeField] internal bool m_NeverAutoSwitchControlSchemes; [SerializeField] internal string m_DefaultControlScheme; [SerializeField] internal string m_DefaultActionMap; [SerializeField] internal int m_SplitScreenIndex = -1; [Tooltip("Reference to the player's view camera. Note that this is only required when using split-screen and/or per-player UIs. Otherwise it is safe to leave this property uninitialized.")] [SerializeField] internal Camera m_Camera; [NonSerialized] private InputValue m_InputValueObject; [NonSerialized] internal InputActionMap m_CurrentActionMap; [NonSerialized] private int m_PlayerIndex = -1; [NonSerialized] private bool m_InputActive; [NonSerialized] private bool m_Enabled; [NonSerialized] internal bool m_ActionsInitialized; [NonSerialized] private Dictionary m_ActionMessageNames; [NonSerialized] private InputUser m_InputUser; [NonSerialized] private Action m_ActionTriggeredDelegate; [NonSerialized] private CallbackArray> m_DeviceLostCallbacks; [NonSerialized] private CallbackArray> m_DeviceRegainedCallbacks; [NonSerialized] private CallbackArray> m_ControlsChangedCallbacks; [NonSerialized] private CallbackArray> m_ActionTriggeredCallbacks; [NonSerialized] private Action m_UnpairedDeviceUsedDelegate; [NonSerialized] private Func m_PreFilterUnpairedDeviceUsedDelegate; [NonSerialized] private bool m_OnUnpairedDeviceUsedHooked; [NonSerialized] private Action m_DeviceChangeDelegate; [NonSerialized] private bool m_OnDeviceChangeHooked; internal static int s_AllActivePlayersCount; internal static PlayerInput[] s_AllActivePlayers; private static Action s_UserChangeDelegate; private static int s_InitPairWithDevicesCount; private static InputDevice[] s_InitPairWithDevices; private static int s_InitPlayerIndex = -1; private static int s_InitSplitScreenIndex = -1; private static string s_InitControlScheme; internal static bool s_DestroyIfDeviceSetupUnsuccessful; public bool inputIsActive => m_InputActive; [Obsolete("Use inputIsActive instead.")] public bool active => inputIsActive; public int playerIndex => m_PlayerIndex; public int splitScreenIndex => m_SplitScreenIndex; public InputActionAsset actions { get { if (!m_ActionsInitialized && ((Component)this).gameObject.activeInHierarchy) { InitializeActions(); } return m_Actions; } set { if ((Object)(object)m_Actions == (Object)(object)value) { return; } if ((Object)(object)m_Actions != (Object)null) { m_Actions.Disable(); if (m_ActionsInitialized) { UninitializeActions(); } } m_Actions = value; if (m_Enabled) { ClearCaches(); AssignUserAndDevices(); InitializeActions(); if (m_InputActive) { ActivateInput(); } } } } public string currentControlScheme { get { if (!m_InputUser.valid) { return null; } return m_InputUser.controlScheme?.name; } } public string defaultControlScheme { get { return m_DefaultControlScheme; } set { m_DefaultControlScheme = value; } } public bool neverAutoSwitchControlSchemes { get { return m_NeverAutoSwitchControlSchemes; } set { if (m_NeverAutoSwitchControlSchemes == value) { return; } m_NeverAutoSwitchControlSchemes = value; if (m_Enabled) { if (!value && !m_OnUnpairedDeviceUsedHooked) { StartListeningForUnpairedDeviceActivity(); } else if (value && m_OnUnpairedDeviceUsedHooked) { StopListeningForUnpairedDeviceActivity(); } } } } public InputActionMap currentActionMap { get { return m_CurrentActionMap; } set { InputActionMap inputActionMap = m_CurrentActionMap; m_CurrentActionMap = null; inputActionMap?.Disable(); m_CurrentActionMap = value; m_CurrentActionMap?.Enable(); } } public string defaultActionMap { get { return m_DefaultActionMap; } set { m_DefaultActionMap = value; } } public PlayerNotifications notificationBehavior { get { return m_NotificationBehavior; } set { if (m_NotificationBehavior != value) { if (m_Enabled) { UninitializeActions(); } m_NotificationBehavior = value; if (m_Enabled) { InitializeActions(); } } } } public ReadOnlyArray actionEvents { get { return m_ActionEvents; } set { if (m_Enabled) { UninitializeActions(); } m_ActionEvents = value.ToArray(); if (m_Enabled) { InitializeActions(); } } } public DeviceLostEvent deviceLostEvent { get { if (m_DeviceLostEvent == null) { m_DeviceLostEvent = new DeviceLostEvent(); } return m_DeviceLostEvent; } } public DeviceRegainedEvent deviceRegainedEvent { get { if (m_DeviceRegainedEvent == null) { m_DeviceRegainedEvent = new DeviceRegainedEvent(); } return m_DeviceRegainedEvent; } } public ControlsChangedEvent controlsChangedEvent { get { if (m_ControlsChangedEvent == null) { m_ControlsChangedEvent = new ControlsChangedEvent(); } return m_ControlsChangedEvent; } } public Camera camera { get { return m_Camera; } set { m_Camera = value; } } public InputSystemUIInputModule uiInputModule { get { return m_UIInputModule; } set { if (!((Object)(object)m_UIInputModule == (Object)(object)value)) { if ((Object)(object)m_UIInputModule != (Object)null && (Object)(object)m_UIInputModule.actionsAsset == (Object)(object)m_Actions) { m_UIInputModule.actionsAsset = null; } m_UIInputModule = value; if ((Object)(object)m_UIInputModule != (Object)null && (Object)(object)m_Actions != (Object)null) { m_UIInputModule.actionsAsset = m_Actions; } } } } public InputUser user => m_InputUser; public ReadOnlyArray devices { get { if (!m_InputUser.valid) { return default(ReadOnlyArray); } return m_InputUser.pairedDevices; } } public bool hasMissingRequiredDevices { get { if (user.valid) { return user.hasMissingRequiredDevices; } return false; } } public static ReadOnlyArray all => new ReadOnlyArray(s_AllActivePlayers, 0, s_AllActivePlayersCount); public static bool isSinglePlayer { get { if (s_AllActivePlayersCount <= 1) { if (!((Object)(object)PlayerInputManager.instance == (Object)null)) { return !PlayerInputManager.instance.joiningEnabled; } return true; } return false; } } public event Action onActionTriggered { add { if (value == null) { throw new ArgumentNullException("value"); } m_ActionTriggeredCallbacks.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } m_ActionTriggeredCallbacks.RemoveCallback(value); } } public event Action onDeviceLost { add { if (value == null) { throw new ArgumentNullException("value"); } m_DeviceLostCallbacks.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } m_DeviceLostCallbacks.RemoveCallback(value); } } public event Action onDeviceRegained { add { if (value == null) { throw new ArgumentNullException("value"); } m_DeviceRegainedCallbacks.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } m_DeviceRegainedCallbacks.RemoveCallback(value); } } public event Action onControlsChanged { add { if (value == null) { throw new ArgumentNullException("value"); } m_ControlsChangedCallbacks.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } m_ControlsChangedCallbacks.RemoveCallback(value); } } public TDevice GetDevice() where TDevice : InputDevice { foreach (InputDevice device in devices) { if (device is TDevice result) { return result; } } return null; } public void ActivateInput() { m_InputActive = true; if (m_CurrentActionMap == null && (Object)(object)m_Actions != (Object)null && !string.IsNullOrEmpty(m_DefaultActionMap)) { SwitchCurrentActionMap(m_DefaultActionMap); } else { m_CurrentActionMap?.Enable(); } } public void DeactivateInput() { m_CurrentActionMap?.Disable(); m_InputActive = false; } [Obsolete("Use DeactivateInput instead.")] public void PassivateInput() { DeactivateInput(); } public bool SwitchCurrentControlScheme(params InputDevice[] devices) { if (devices == null) { throw new ArgumentNullException("devices"); } if ((Object)(object)actions == (Object)null) { throw new InvalidOperationException("Must set actions on PlayerInput in order to be able to switch control schemes"); } InputControlScheme? inputControlScheme = InputControlScheme.FindControlSchemeForDevices(devices, actions.controlSchemes); if (!inputControlScheme.HasValue) { return false; } InputControlScheme controlScheme = inputControlScheme.Value; SwitchControlSchemeInternal(ref controlScheme, devices); return true; } public void SwitchCurrentControlScheme(string controlScheme, params InputDevice[] devices) { if (string.IsNullOrEmpty(controlScheme)) { throw new ArgumentNullException("controlScheme"); } if (devices == null) { throw new ArgumentNullException("devices"); } user.FindControlScheme(controlScheme, out var scheme); SwitchControlSchemeInternal(ref scheme, devices); } public void SwitchCurrentActionMap(string mapNameOrId) { if (!m_Enabled) { Debug.LogError((object)("Cannot switch to actions '" + mapNameOrId + "'; input is not enabled"), (Object)(object)this); return; } if ((Object)(object)m_Actions == (Object)null) { Debug.LogError((object)("Cannot switch to actions '" + mapNameOrId + "'; no actions set on PlayerInput"), (Object)(object)this); return; } InputActionMap inputActionMap = m_Actions.FindActionMap(mapNameOrId); if (inputActionMap == null) { Debug.LogError((object)$"Cannot find action map '{mapNameOrId}' in actions '{m_Actions}'", (Object)(object)this); } else { currentActionMap = inputActionMap; } } public static PlayerInput GetPlayerByIndex(int playerIndex) { for (int i = 0; i < s_AllActivePlayersCount; i++) { if (s_AllActivePlayers[i].playerIndex == playerIndex) { return s_AllActivePlayers[i]; } } return null; } public static PlayerInput FindFirstPairedToDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } for (int i = 0; i < s_AllActivePlayersCount; i++) { if (s_AllActivePlayers[i].devices.ContainsReference(device)) { return s_AllActivePlayers[i]; } } return null; } public static PlayerInput Instantiate(GameObject prefab, int playerIndex = -1, string controlScheme = null, int splitScreenIndex = -1, InputDevice pairWithDevice = null) { if ((Object)(object)prefab == (Object)null) { throw new ArgumentNullException("prefab"); } s_InitPlayerIndex = playerIndex; s_InitSplitScreenIndex = splitScreenIndex; s_InitControlScheme = controlScheme; if (pairWithDevice != null) { ArrayHelpers.AppendWithCapacity(ref s_InitPairWithDevices, ref s_InitPairWithDevicesCount, pairWithDevice); } return DoInstantiate(prefab); } public static PlayerInput Instantiate(GameObject prefab, int playerIndex = -1, string controlScheme = null, int splitScreenIndex = -1, params InputDevice[] pairWithDevices) { if ((Object)(object)prefab == (Object)null) { throw new ArgumentNullException("prefab"); } s_InitPlayerIndex = playerIndex; s_InitSplitScreenIndex = splitScreenIndex; s_InitControlScheme = controlScheme; if (pairWithDevices != null) { for (int i = 0; i < pairWithDevices.Length; i++) { ArrayHelpers.AppendWithCapacity(ref s_InitPairWithDevices, ref s_InitPairWithDevicesCount, pairWithDevices[i]); } } return DoInstantiate(prefab); } private static PlayerInput DoInstantiate(GameObject prefab) { bool flag = s_DestroyIfDeviceSetupUnsuccessful; GameObject val; try { val = Object.Instantiate(prefab); val.SetActive(true); } finally { s_InitPairWithDevicesCount = 0; if (s_InitPairWithDevices != null) { Array.Clear(s_InitPairWithDevices, 0, s_InitPairWithDevicesCount); } s_InitControlScheme = null; s_InitPlayerIndex = -1; s_InitSplitScreenIndex = -1; s_DestroyIfDeviceSetupUnsuccessful = false; } PlayerInput componentInChildren = val.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null) { Object.DestroyImmediate((Object)(object)val); Debug.LogError((object)"The GameObject does not have a PlayerInput component", (Object)(object)prefab); return null; } if (flag && (!componentInChildren.user.valid || componentInChildren.hasMissingRequiredDevices)) { Object.DestroyImmediate((Object)(object)val); return null; } return componentInChildren; } private void InitializeActions() { if (m_ActionsInitialized || (Object)(object)m_Actions == (Object)null) { return; } for (int i = 0; i < s_AllActivePlayersCount; i++) { if (!((Object)(object)s_AllActivePlayers[i].m_Actions == (Object)(object)m_Actions) || !((Object)(object)s_AllActivePlayers[i] != (Object)(object)this)) { continue; } InputActionAsset inputActionAsset = m_Actions; m_Actions = Object.Instantiate(m_Actions); for (int j = 0; j < inputActionAsset.actionMaps.Count; j++) { for (int k = 0; k < inputActionAsset.actionMaps[j].bindings.Count; k++) { m_Actions.actionMaps[j].ApplyBindingOverride(k, inputActionAsset.actionMaps[j].bindings[k]); } } break; } if ((Object)(object)uiInputModule != (Object)null) { uiInputModule.actionsAsset = m_Actions; } switch (m_NotificationBehavior) { case PlayerNotifications.SendMessages: case PlayerNotifications.BroadcastMessages: InstallOnActionTriggeredHook(); if (m_ActionMessageNames == null) { CacheMessageNames(); } break; case PlayerNotifications.InvokeCSharpEvents: InstallOnActionTriggeredHook(); break; case PlayerNotifications.InvokeUnityEvents: { if (m_ActionEvents == null) { break; } ActionEvent[] array = m_ActionEvents; foreach (ActionEvent actionEvent in array) { string actionId = actionEvent.actionId; if (!string.IsNullOrEmpty(actionId)) { InputAction inputAction = m_Actions.FindAction(actionId); if (inputAction != null) { inputAction.performed += ((UnityEvent)actionEvent).Invoke; inputAction.canceled += ((UnityEvent)actionEvent).Invoke; inputAction.started += ((UnityEvent)actionEvent).Invoke; } } } break; } } m_ActionsInitialized = true; } private void UninitializeActions() { if (!m_ActionsInitialized || (Object)(object)m_Actions == (Object)null) { return; } UninstallOnActionTriggeredHook(); if (m_NotificationBehavior == PlayerNotifications.InvokeUnityEvents && m_ActionEvents != null) { ActionEvent[] array = m_ActionEvents; foreach (ActionEvent actionEvent in array) { string actionId = actionEvent.actionId; if (!string.IsNullOrEmpty(actionId)) { InputAction inputAction = m_Actions.FindAction(actionId); if (inputAction != null) { inputAction.performed -= ((UnityEvent)actionEvent).Invoke; inputAction.canceled -= ((UnityEvent)actionEvent).Invoke; inputAction.started -= ((UnityEvent)actionEvent).Invoke; } } } } m_CurrentActionMap = null; m_ActionsInitialized = false; } private void InstallOnActionTriggeredHook() { if (m_ActionTriggeredDelegate == null) { m_ActionTriggeredDelegate = OnActionTriggered; } foreach (InputActionMap actionMap in m_Actions.actionMaps) { actionMap.actionTriggered += m_ActionTriggeredDelegate; } } private void UninstallOnActionTriggeredHook() { if (m_ActionTriggeredDelegate == null) { return; } foreach (InputActionMap actionMap in m_Actions.actionMaps) { actionMap.actionTriggered -= m_ActionTriggeredDelegate; } } private void OnActionTriggered(InputAction.CallbackContext context) { if (!m_InputActive) { return; } switch (m_NotificationBehavior) { case PlayerNotifications.InvokeCSharpEvents: DelegateHelpers.InvokeCallbacksSafe(ref m_ActionTriggeredCallbacks, context, "PlayerInput.onActionTriggered"); break; case PlayerNotifications.SendMessages: case PlayerNotifications.BroadcastMessages: { InputAction action = context.action; if (context.performed || (context.canceled && action.type == InputActionType.Value)) { if (m_ActionMessageNames == null) { CacheMessageNames(); } string text = m_ActionMessageNames[action.m_Id]; if (m_InputValueObject == null) { m_InputValueObject = new InputValue(); } m_InputValueObject.m_Context = context; if (m_NotificationBehavior == PlayerNotifications.BroadcastMessages) { ((Component)this).BroadcastMessage(text, (object)m_InputValueObject, (SendMessageOptions)1); } else { ((Component)this).SendMessage(text, (object)m_InputValueObject, (SendMessageOptions)1); } m_InputValueObject.m_Context = null; } break; } } } private void CacheMessageNames() { if ((Object)(object)m_Actions == (Object)null) { return; } if (m_ActionMessageNames != null) { m_ActionMessageNames.Clear(); } else { m_ActionMessageNames = new Dictionary(); } foreach (InputAction action in m_Actions) { action.MakeSureIdIsInPlace(); string text = CSharpCodeHelpers.MakeTypeName(action.name); m_ActionMessageNames[action.m_Id] = "On" + text; } } private void ClearCaches() { } private void AssignUserAndDevices() { if (m_InputUser.valid) { m_InputUser.UnpairDevices(); } if ((Object)(object)m_Actions == (Object)null) { if (s_InitPairWithDevicesCount > 0) { for (int i = 0; i < s_InitPairWithDevicesCount; i++) { m_InputUser = InputUser.PerformPairingWithDevice(s_InitPairWithDevices[i], m_InputUser); } } else { m_InputUser = default(InputUser); } return; } if (m_Actions.controlSchemes.Count > 0) { if (!string.IsNullOrEmpty(s_InitControlScheme)) { InputControlScheme? inputControlScheme = m_Actions.FindControlScheme(s_InitControlScheme); if (!inputControlScheme.HasValue) { Debug.LogError((object)$"No control scheme '{s_InitControlScheme}' in '{m_Actions}'", (Object)(object)this); } else { TryToActivateControlScheme(inputControlScheme.Value); } } else if (!string.IsNullOrEmpty(m_DefaultControlScheme)) { InputControlScheme? inputControlScheme2 = m_Actions.FindControlScheme(m_DefaultControlScheme); if (!inputControlScheme2.HasValue) { Debug.LogError((object)$"Cannot find default control scheme '{m_DefaultControlScheme}' in '{m_Actions}'", (Object)(object)this); } else { TryToActivateControlScheme(inputControlScheme2.Value); } } if (s_InitPairWithDevicesCount > 0 && (!m_InputUser.valid || !m_InputUser.controlScheme.HasValue)) { InputControlScheme? inputControlScheme3 = InputControlScheme.FindControlSchemeForDevices(new ReadOnlyArray(s_InitPairWithDevices, 0, s_InitPairWithDevicesCount), m_Actions.controlSchemes, null, allowUnsuccesfulMatch: true); if (inputControlScheme3.HasValue) { TryToActivateControlScheme(inputControlScheme3.Value); } } else if ((!m_InputUser.valid || !m_InputUser.controlScheme.HasValue) && string.IsNullOrEmpty(s_InitControlScheme)) { using InputControlList inputControlList = InputUser.GetUnpairedInputDevices(); InputControlScheme? inputControlScheme4 = InputControlScheme.FindControlSchemeForDevices(inputControlList, m_Actions.controlSchemes); if (inputControlScheme4.HasValue) { TryToActivateControlScheme(inputControlScheme4.Value); } } } else if (s_InitPairWithDevicesCount > 0) { for (int j = 0; j < s_InitPairWithDevicesCount; j++) { m_InputUser = InputUser.PerformPairingWithDevice(s_InitPairWithDevices[j], m_InputUser); } } else { using InputControlList inputControlList2 = InputUser.GetUnpairedInputDevices(); for (int k = 0; k < inputControlList2.Count; k++) { InputDevice device = inputControlList2[k]; if (HaveBindingForDevice(device)) { m_InputUser = InputUser.PerformPairingWithDevice(device, m_InputUser); } } } if (m_InputUser.valid) { m_InputUser.AssociateActionsWithUser(m_Actions); } } private bool HaveBindingForDevice(InputDevice device) { if ((Object)(object)m_Actions == (Object)null) { return false; } ReadOnlyArray actionMaps = m_Actions.actionMaps; for (int i = 0; i < actionMaps.Count; i++) { if (actionMaps[i].IsUsableWithDevice(device)) { return true; } } return false; } private void UnassignUserAndDevices() { if (m_InputUser.valid) { m_InputUser.UnpairDevicesAndRemoveUser(); } if ((Object)(object)m_Actions != (Object)null) { m_Actions.devices = null; } } private bool TryToActivateControlScheme(InputControlScheme controlScheme) { if (s_InitPairWithDevicesCount > 0) { for (int i = 0; i < s_InitPairWithDevicesCount; i++) { InputDevice device = s_InitPairWithDevices[i]; if (!controlScheme.SupportsDevice(device)) { return false; } } for (int j = 0; j < s_InitPairWithDevicesCount; j++) { InputDevice device2 = s_InitPairWithDevices[j]; m_InputUser = InputUser.PerformPairingWithDevice(device2, m_InputUser); } } if (!m_InputUser.valid) { m_InputUser = InputUser.CreateUserWithoutPairedDevices(); } m_InputUser.ActivateControlScheme(controlScheme).AndPairRemainingDevices(); if (user.hasMissingRequiredDevices) { m_InputUser.ActivateControlScheme(null); m_InputUser.UnpairDevices(); return false; } return true; } private void AssignPlayerIndex() { if (s_InitPlayerIndex != -1) { m_PlayerIndex = s_InitPlayerIndex; return; } int num = int.MaxValue; int num2 = int.MinValue; for (int i = 0; i < s_AllActivePlayersCount; i++) { int val = s_AllActivePlayers[i].playerIndex; num = Math.Min(num, val); num2 = Math.Max(num2, val); } if (num != int.MaxValue && num > 0) { m_PlayerIndex = num - 1; } else if (num2 != int.MinValue) { for (int j = num; j < num2; j++) { if ((Object)(object)GetPlayerByIndex(j) == (Object)null) { m_PlayerIndex = j; return; } } m_PlayerIndex = num2 + 1; } else { m_PlayerIndex = 0; } } private void OnEnable() { m_Enabled = true; using (InputActionRebindingExtensions.DeferBindingResolution()) { AssignPlayerIndex(); InitializeActions(); AssignUserAndDevices(); ActivateInput(); } if (s_InitSplitScreenIndex >= 0) { m_SplitScreenIndex = splitScreenIndex; } else { m_SplitScreenIndex = playerIndex; } ArrayHelpers.AppendWithCapacity(ref s_AllActivePlayers, ref s_AllActivePlayersCount, this); for (int i = 1; i < s_AllActivePlayersCount; i++) { int num = i; while (num > 0 && s_AllActivePlayers[num - 1].playerIndex > s_AllActivePlayers[num].playerIndex) { s_AllActivePlayers.SwapElements(num, num - 1); num--; } } if (s_AllActivePlayersCount == 1) { if (s_UserChangeDelegate == null) { s_UserChangeDelegate = OnUserChange; } InputUser.onChange += s_UserChangeDelegate; } if (isSinglePlayer) { if ((Object)(object)m_Actions != (Object)null && m_Actions.controlSchemes.Count == 0) { StartListeningForDeviceChanges(); } else if (!neverAutoSwitchControlSchemes) { StartListeningForUnpairedDeviceActivity(); } } HandleControlsChanged(); PlayerInputManager.instance?.NotifyPlayerJoined(this); } private void StartListeningForUnpairedDeviceActivity() { if (!m_OnUnpairedDeviceUsedHooked) { if (m_UnpairedDeviceUsedDelegate == null) { m_UnpairedDeviceUsedDelegate = OnUnpairedDeviceUsed; } if (m_PreFilterUnpairedDeviceUsedDelegate == null) { m_PreFilterUnpairedDeviceUsedDelegate = OnPreFilterUnpairedDeviceUsed; } InputUser.onUnpairedDeviceUsed += m_UnpairedDeviceUsedDelegate; InputUser.onPrefilterUnpairedDeviceActivity += m_PreFilterUnpairedDeviceUsedDelegate; InputUser.listenForUnpairedDeviceActivity++; m_OnUnpairedDeviceUsedHooked = true; } } private void StopListeningForUnpairedDeviceActivity() { if (m_OnUnpairedDeviceUsedHooked) { InputUser.onUnpairedDeviceUsed -= m_UnpairedDeviceUsedDelegate; InputUser.onPrefilterUnpairedDeviceActivity -= m_PreFilterUnpairedDeviceUsedDelegate; InputUser.listenForUnpairedDeviceActivity--; m_OnUnpairedDeviceUsedHooked = false; } } private void StartListeningForDeviceChanges() { if (!m_OnDeviceChangeHooked) { if (m_DeviceChangeDelegate == null) { m_DeviceChangeDelegate = OnDeviceChange; } InputSystem.onDeviceChange += m_DeviceChangeDelegate; m_OnDeviceChangeHooked = true; } } private void StopListeningForDeviceChanges() { if (m_OnDeviceChangeHooked) { InputSystem.onDeviceChange -= m_DeviceChangeDelegate; m_OnDeviceChangeHooked = false; } } private void OnDisable() { m_Enabled = false; int num = s_AllActivePlayers.IndexOfReference(this, s_AllActivePlayersCount); if (num != -1) { s_AllActivePlayers.EraseAtWithCapacity(ref s_AllActivePlayersCount, num); } if (s_AllActivePlayersCount == 0 && s_UserChangeDelegate != null) { InputUser.onChange -= s_UserChangeDelegate; } StopListeningForUnpairedDeviceActivity(); StopListeningForDeviceChanges(); PlayerInputManager.instance?.NotifyPlayerLeft(this); using (InputActionRebindingExtensions.DeferBindingResolution()) { DeactivateInput(); UnassignUserAndDevices(); UninitializeActions(); } m_PlayerIndex = -1; } public void DebugLogAction(InputAction.CallbackContext context) { Debug.Log((object)context.ToString()); } private void HandleDeviceLost() { switch (m_NotificationBehavior) { case PlayerNotifications.SendMessages: ((Component)this).SendMessage("OnDeviceLost", (object)this, (SendMessageOptions)1); break; case PlayerNotifications.BroadcastMessages: ((Component)this).BroadcastMessage("OnDeviceLost", (object)this, (SendMessageOptions)1); break; case PlayerNotifications.InvokeUnityEvents: ((UnityEvent)m_DeviceLostEvent)?.Invoke(this); break; case PlayerNotifications.InvokeCSharpEvents: DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceLostCallbacks, this, "onDeviceLost"); break; } } private void HandleDeviceRegained() { switch (m_NotificationBehavior) { case PlayerNotifications.SendMessages: ((Component)this).SendMessage("OnDeviceRegained", (object)this, (SendMessageOptions)1); break; case PlayerNotifications.BroadcastMessages: ((Component)this).BroadcastMessage("OnDeviceRegained", (object)this, (SendMessageOptions)1); break; case PlayerNotifications.InvokeUnityEvents: ((UnityEvent)m_DeviceRegainedEvent)?.Invoke(this); break; case PlayerNotifications.InvokeCSharpEvents: DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceRegainedCallbacks, this, "onDeviceRegained"); break; } } private void HandleControlsChanged() { switch (m_NotificationBehavior) { case PlayerNotifications.SendMessages: ((Component)this).SendMessage("OnControlsChanged", (object)this, (SendMessageOptions)1); break; case PlayerNotifications.BroadcastMessages: ((Component)this).BroadcastMessage("OnControlsChanged", (object)this, (SendMessageOptions)1); break; case PlayerNotifications.InvokeUnityEvents: ((UnityEvent)m_ControlsChangedEvent)?.Invoke(this); break; case PlayerNotifications.InvokeCSharpEvents: DelegateHelpers.InvokeCallbacksSafe(ref m_ControlsChangedCallbacks, this, "onControlsChanged"); break; } } private static void OnUserChange(InputUser user, InputUserChange change, InputDevice device) { switch (change) { case InputUserChange.DeviceLost: case InputUserChange.DeviceRegained: { for (int j = 0; j < s_AllActivePlayersCount; j++) { PlayerInput playerInput2 = s_AllActivePlayers[j]; if (playerInput2.m_InputUser == user) { switch (change) { case InputUserChange.DeviceLost: playerInput2.HandleDeviceLost(); break; case InputUserChange.DeviceRegained: playerInput2.HandleDeviceRegained(); break; } } } break; } case InputUserChange.ControlsChanged: { for (int i = 0; i < s_AllActivePlayersCount; i++) { PlayerInput playerInput = s_AllActivePlayers[i]; if (playerInput.m_InputUser == user) { playerInput.HandleControlsChanged(); } } break; } } } private static bool OnPreFilterUnpairedDeviceUsed(InputDevice device, InputEventPtr eventPtr) { InputActionAsset inputActionAsset = all[0].actions; if ((Object)(object)inputActionAsset != (Object)null) { return inputActionAsset.IsUsableWithDevice(device); } return false; } private void OnUnpairedDeviceUsed(InputControl control, InputEventPtr eventPtr) { if (!isSinglePlayer || neverAutoSwitchControlSchemes) { return; } PlayerInput playerInput = all[0]; if ((Object)(object)playerInput.m_Actions == (Object)null) { return; } InputDevice device = control.device; using (InputActionRebindingExtensions.DeferBindingResolution()) { using InputControlList inputControlList = InputUser.GetUnpairedInputDevices(); if (inputControlList.Count > 1) { int index = inputControlList.IndexOf(device); inputControlList.SwapElements(0, index); } ReadOnlyArray readOnlyArray = playerInput.devices; for (int i = 0; i < readOnlyArray.Count; i++) { inputControlList.Add(readOnlyArray[i]); } if (!InputControlScheme.FindControlSchemeForDevices(inputControlList, playerInput.m_Actions.controlSchemes, out var controlScheme, out var matchResult, device)) { return; } try { bool valid = playerInput.user.valid; if (valid) { playerInput.user.UnpairDevices(); } InputControlList inputControlList2 = matchResult.devices; for (int j = 0; j < inputControlList2.Count; j++) { playerInput.m_InputUser = InputUser.PerformPairingWithDevice(inputControlList2[j], playerInput.m_InputUser); if (!valid && (Object)(object)playerInput.actions != (Object)null) { playerInput.m_InputUser.AssociateActionsWithUser(playerInput.actions); } } playerInput.user.ActivateControlScheme(controlScheme); } finally { matchResult.Dispose(); } } } private void OnDeviceChange(InputDevice device, InputDeviceChange change) { if (change == InputDeviceChange.Added && isSinglePlayer && (Object)(object)m_Actions != (Object)null && m_Actions.controlSchemes.Count == 0 && HaveBindingForDevice(device) && m_InputUser.valid) { InputUser.PerformPairingWithDevice(device, m_InputUser); } } private void SwitchControlSchemeInternal(ref InputControlScheme controlScheme, params InputDevice[] devices) { using (InputActionRebindingExtensions.DeferBindingResolution()) { for (int num = user.pairedDevices.Count - 1; num >= 0; num--) { if (!devices.ContainsReference(user.pairedDevices[num])) { user.UnpairDevice(user.pairedDevices[num]); } } foreach (InputDevice inputDevice in devices) { if (!user.pairedDevices.ContainsReference(inputDevice)) { InputUser.PerformPairingWithDevice(inputDevice, user); } } if (!user.controlScheme.HasValue || !user.controlScheme.Value.Equals(controlScheme)) { user.ActivateControlScheme(controlScheme); } } } } [AddComponentMenu("Input/Player Input Manager")] [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/PlayerInputManager.html")] public class PlayerInputManager : MonoBehaviour { [Serializable] public class PlayerJoinedEvent : UnityEvent { } [Serializable] public class PlayerLeftEvent : UnityEvent { } public const string PlayerJoinedMessage = "OnPlayerJoined"; public const string PlayerLeftMessage = "OnPlayerLeft"; [SerializeField] internal PlayerNotifications m_NotificationBehavior; [Tooltip("Set a limit for the maximum number of players who are able to join.")] [SerializeField] internal int m_MaxPlayerCount = -1; [SerializeField] internal bool m_AllowJoining = true; [SerializeField] internal PlayerJoinBehavior m_JoinBehavior; [SerializeField] internal PlayerJoinedEvent m_PlayerJoinedEvent; [SerializeField] internal PlayerLeftEvent m_PlayerLeftEvent; [SerializeField] internal InputActionProperty m_JoinAction; [SerializeField] internal GameObject m_PlayerPrefab; [SerializeField] internal bool m_SplitScreen; [SerializeField] internal bool m_MaintainAspectRatioInSplitScreen; [Tooltip("Explicitly set a fixed number of screens or otherwise allow the screen to be divided automatically to best fit the number of players.")] [SerializeField] internal int m_FixedNumberOfSplitScreens = -1; [SerializeField] internal Rect m_SplitScreenRect = new Rect(0f, 0f, 1f, 1f); [NonSerialized] private bool m_JoinActionDelegateHooked; [NonSerialized] private bool m_UnpairedDeviceUsedDelegateHooked; [NonSerialized] private Action m_JoinActionDelegate; [NonSerialized] private Action m_UnpairedDeviceUsedDelegate; [NonSerialized] private CallbackArray> m_PlayerJoinedCallbacks; [NonSerialized] private CallbackArray> m_PlayerLeftCallbacks; public bool splitScreen { get { return m_SplitScreen; } set { //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (m_SplitScreen == value) { return; } m_SplitScreen = value; if (!m_SplitScreen) { foreach (PlayerInput item in PlayerInput.all) { Camera camera = item.camera; if ((Object)(object)camera != (Object)null) { camera.rect = new Rect(0f, 0f, 1f, 1f); } } return; } UpdateSplitScreen(); } } public bool maintainAspectRatioInSplitScreen => m_MaintainAspectRatioInSplitScreen; public int fixedNumberOfSplitScreens => m_FixedNumberOfSplitScreens; public Rect splitScreenArea => m_SplitScreenRect; public int playerCount => PlayerInput.s_AllActivePlayersCount; public int maxPlayerCount => m_MaxPlayerCount; public bool joiningEnabled => m_AllowJoining; public PlayerJoinBehavior joinBehavior { get { return m_JoinBehavior; } set { if (m_JoinBehavior != value) { bool allowJoining = m_AllowJoining; if (allowJoining) { DisableJoining(); } m_JoinBehavior = value; if (allowJoining) { EnableJoining(); } } } } public InputActionProperty joinAction { get { return m_JoinAction; } set { if (m_JoinAction == value) { return; } int num; if (m_AllowJoining) { num = ((m_JoinBehavior == PlayerJoinBehavior.JoinPlayersWhenJoinActionIsTriggered) ? 1 : 0); if (num != 0) { DisableJoining(); } } else { num = 0; } m_JoinAction = value; if (num != 0) { EnableJoining(); } } } public PlayerNotifications notificationBehavior { get { return m_NotificationBehavior; } set { m_NotificationBehavior = value; } } public PlayerJoinedEvent playerJoinedEvent { get { if (m_PlayerJoinedEvent == null) { m_PlayerJoinedEvent = new PlayerJoinedEvent(); } return m_PlayerJoinedEvent; } } public PlayerLeftEvent playerLeftEvent { get { if (m_PlayerLeftEvent == null) { m_PlayerLeftEvent = new PlayerLeftEvent(); } return m_PlayerLeftEvent; } } public GameObject playerPrefab { get { return m_PlayerPrefab; } set { m_PlayerPrefab = value; } } public static PlayerInputManager instance { get; private set; } internal static string[] messages => new string[2] { "OnPlayerJoined", "OnPlayerLeft" }; public event Action onPlayerJoined { add { if (value == null) { throw new ArgumentNullException("value"); } m_PlayerJoinedCallbacks.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } m_PlayerJoinedCallbacks.RemoveCallback(value); } } public event Action onPlayerLeft { add { if (value == null) { throw new ArgumentNullException("value"); } m_PlayerLeftCallbacks.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } m_PlayerLeftCallbacks.RemoveCallback(value); } } public void EnableJoining() { switch (m_JoinBehavior) { case PlayerJoinBehavior.JoinPlayersWhenButtonIsPressed: ValidateInputActionAsset(); if (!m_UnpairedDeviceUsedDelegateHooked) { if (m_UnpairedDeviceUsedDelegate == null) { m_UnpairedDeviceUsedDelegate = OnUnpairedDeviceUsed; } InputUser.onUnpairedDeviceUsed += m_UnpairedDeviceUsedDelegate; m_UnpairedDeviceUsedDelegateHooked = true; InputUser.listenForUnpairedDeviceActivity++; } break; case PlayerJoinBehavior.JoinPlayersWhenJoinActionIsTriggered: if (m_JoinAction.action != null) { if (!m_JoinActionDelegateHooked) { if (m_JoinActionDelegate == null) { m_JoinActionDelegate = JoinPlayerFromActionIfNotAlreadyJoined; } m_JoinAction.action.performed += m_JoinActionDelegate; m_JoinActionDelegateHooked = true; } m_JoinAction.action.Enable(); } else { Debug.LogError((object)"No join action configured on PlayerInputManager but join behavior is set to JoinPlayersWhenJoinActionIsTriggered", (Object)(object)this); } break; } m_AllowJoining = true; } public void DisableJoining() { switch (m_JoinBehavior) { case PlayerJoinBehavior.JoinPlayersWhenButtonIsPressed: if (m_UnpairedDeviceUsedDelegateHooked) { InputUser.onUnpairedDeviceUsed -= m_UnpairedDeviceUsedDelegate; m_UnpairedDeviceUsedDelegateHooked = false; InputUser.listenForUnpairedDeviceActivity--; } break; case PlayerJoinBehavior.JoinPlayersWhenJoinActionIsTriggered: if (m_JoinActionDelegateHooked) { if (m_JoinAction.action != null) { m_JoinAction.action.performed -= m_JoinActionDelegate; } m_JoinActionDelegateHooked = false; } m_JoinAction.action?.Disable(); break; } m_AllowJoining = false; } internal void JoinPlayerFromUI() { if (!CheckIfPlayerCanJoin()) { return; } throw new NotImplementedException(); } public void JoinPlayerFromAction(InputAction.CallbackContext context) { if (CheckIfPlayerCanJoin()) { InputDevice device = context.control.device; JoinPlayer(-1, -1, null, device); } } public void JoinPlayerFromActionIfNotAlreadyJoined(InputAction.CallbackContext context) { if (CheckIfPlayerCanJoin()) { InputDevice device = context.control.device; if (!((Object)(object)PlayerInput.FindFirstPairedToDevice(device) != (Object)null)) { JoinPlayer(-1, -1, null, device); } } } public PlayerInput JoinPlayer(int playerIndex = -1, int splitScreenIndex = -1, string controlScheme = null, InputDevice pairWithDevice = null) { if (!CheckIfPlayerCanJoin(playerIndex)) { return null; } PlayerInput.s_DestroyIfDeviceSetupUnsuccessful = true; return PlayerInput.Instantiate(m_PlayerPrefab, playerIndex, controlScheme, splitScreenIndex, pairWithDevice); } public PlayerInput JoinPlayer(int playerIndex = -1, int splitScreenIndex = -1, string controlScheme = null, params InputDevice[] pairWithDevices) { if (!CheckIfPlayerCanJoin(playerIndex)) { return null; } PlayerInput.s_DestroyIfDeviceSetupUnsuccessful = true; return PlayerInput.Instantiate(m_PlayerPrefab, playerIndex, controlScheme, splitScreenIndex, pairWithDevices); } private bool CheckIfPlayerCanJoin(int playerIndex = -1) { if ((Object)(object)m_PlayerPrefab == (Object)null) { Debug.LogError((object)"playerPrefab must be set in order to be able to join new players", (Object)(object)this); return false; } if (m_MaxPlayerCount >= 0 && playerCount >= m_MaxPlayerCount) { Debug.LogError((object)("Have reached maximum player count of " + maxPlayerCount), (Object)(object)this); return false; } if (playerIndex != -1) { for (int i = 0; i < PlayerInput.s_AllActivePlayersCount; i++) { if (PlayerInput.s_AllActivePlayers[i].playerIndex == playerIndex) { Debug.LogError((object)$"Player index #{playerIndex} is already taken by player {PlayerInput.s_AllActivePlayers[i]}", (Object)(object)PlayerInput.s_AllActivePlayers[i]); return false; } } } return true; } private void OnUnpairedDeviceUsed(InputControl control, InputEventPtr eventPtr) { if (m_AllowJoining && m_JoinBehavior == PlayerJoinBehavior.JoinPlayersWhenButtonIsPressed && control is ButtonControl && IsDeviceUsableWithPlayerActions(control.device)) { JoinPlayer(-1, -1, null, control.device); } } private void OnEnable() { if ((Object)(object)instance == (Object)null) { instance = this; if ((Object)(object)joinAction.reference != (Object)null && (Object)(object)joinAction.action?.actionMap?.asset != (Object)null) { InputActionReference reference = InputActionReference.Create(Object.Instantiate(joinAction.action.actionMap.asset).FindAction(joinAction.action.name)); joinAction = new InputActionProperty(reference); } for (int i = 0; i < PlayerInput.s_AllActivePlayersCount; i++) { NotifyPlayerJoined(PlayerInput.s_AllActivePlayers[i]); } if (m_AllowJoining) { EnableJoining(); } } else { Debug.LogWarning((object)"Multiple PlayerInputManagers in the game. There should only be one PlayerInputManager", (Object)(object)this); } } private void OnDisable() { if ((Object)(object)instance == (Object)(object)this) { instance = null; } if (m_AllowJoining) { DisableJoining(); } } private void UpdateSplitScreen() { //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) if (!m_SplitScreen) { return; } int num = 0; foreach (PlayerInput item in PlayerInput.all) { if (item.playerIndex >= num) { num = item.playerIndex + 1; } } if (m_FixedNumberOfSplitScreens > 0) { if (m_FixedNumberOfSplitScreens < num) { Debug.LogWarning((object)$"Highest playerIndex of {num} exceeds fixed number of split-screens of {m_FixedNumberOfSplitScreens}", (Object)(object)this); } num = m_FixedNumberOfSplitScreens; } int num2 = Mathf.CeilToInt(Mathf.Sqrt((float)num)); int num3 = num2; if (!m_MaintainAspectRatioInSplitScreen && num2 * (num2 - 1) >= num) { num3--; } foreach (PlayerInput item2 in PlayerInput.all) { int splitScreenIndex = item2.splitScreenIndex; if (splitScreenIndex >= num2 * num3) { Debug.LogError((object)$"Split-screen index of {splitScreenIndex} on player is out of range (have {num2 * num3} screens); resetting to playerIndex", (Object)(object)item2); item2.m_SplitScreenIndex = item2.playerIndex; } Camera camera = item2.camera; if ((Object)(object)camera == (Object)null) { Debug.LogError((object)"Player has no camera associated with it. Cannot set up split-screen. Point PlayerInput.camera to camera for player.", (Object)(object)item2); continue; } int num4 = splitScreenIndex % num2; int num5 = splitScreenIndex / num2; Rect val = default(Rect); ((Rect)(ref val)).width = ((Rect)(ref m_SplitScreenRect)).width / (float)num2; ((Rect)(ref val)).height = ((Rect)(ref m_SplitScreenRect)).height / (float)num3; Rect rect = val; ((Rect)(ref rect)).x = ((Rect)(ref m_SplitScreenRect)).x + (float)num4 * ((Rect)(ref rect)).width; ((Rect)(ref rect)).y = ((Rect)(ref m_SplitScreenRect)).y + ((Rect)(ref m_SplitScreenRect)).height - (float)(num5 + 1) * ((Rect)(ref rect)).height; camera.rect = rect; } } private bool IsDeviceUsableWithPlayerActions(InputDevice device) { if ((Object)(object)m_PlayerPrefab == (Object)null) { return true; } PlayerInput componentInChildren = m_PlayerPrefab.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null) { return true; } InputActionAsset actions = componentInChildren.actions; if ((Object)(object)actions == (Object)null) { return true; } if (actions.controlSchemes.Count > 0) { using (InputControlList devices = InputUser.GetUnpairedInputDevices()) { if (!InputControlScheme.FindControlSchemeForDevices(devices, actions.controlSchemes, device).HasValue) { return false; } } return true; } foreach (InputActionMap actionMap in actions.actionMaps) { if (actionMap.IsUsableWithDevice(device)) { return true; } } return false; } private void ValidateInputActionAsset() { } internal void NotifyPlayerJoined(PlayerInput player) { UpdateSplitScreen(); switch (m_NotificationBehavior) { case PlayerNotifications.SendMessages: ((Component)this).SendMessage("OnPlayerJoined", (object)player, (SendMessageOptions)1); break; case PlayerNotifications.BroadcastMessages: ((Component)this).BroadcastMessage("OnPlayerJoined", (object)player, (SendMessageOptions)1); break; case PlayerNotifications.InvokeUnityEvents: ((UnityEvent)m_PlayerJoinedEvent)?.Invoke(player); break; case PlayerNotifications.InvokeCSharpEvents: DelegateHelpers.InvokeCallbacksSafe(ref m_PlayerJoinedCallbacks, player, "onPlayerJoined"); break; } } internal void NotifyPlayerLeft(PlayerInput player) { UpdateSplitScreen(); switch (m_NotificationBehavior) { case PlayerNotifications.SendMessages: ((Component)this).SendMessage("OnPlayerLeft", (object)player, (SendMessageOptions)1); break; case PlayerNotifications.BroadcastMessages: ((Component)this).BroadcastMessage("OnPlayerLeft", (object)player, (SendMessageOptions)1); break; case PlayerNotifications.InvokeUnityEvents: ((UnityEvent)m_PlayerLeftEvent)?.Invoke(player); break; case PlayerNotifications.InvokeCSharpEvents: DelegateHelpers.InvokeCallbacksSafe(ref m_PlayerLeftCallbacks, player, "onPlayerLeft"); break; } } } public enum PlayerJoinBehavior { JoinPlayersWhenButtonIsPressed, JoinPlayersWhenJoinActionIsTriggered, JoinPlayersManually } public enum PlayerNotifications { SendMessages, BroadcastMessages, InvokeUnityEvents, InvokeCSharpEvents } internal struct DynamicBitfield { public InlinedArray array; public int length; public void SetLength(int newLength) { int num = BitCountToULongCount(newLength); if (array.length < num) { array.SetLength(num); } length = newLength; } public void SetBit(int bitIndex) { array[bitIndex / 64] |= (ulong)(1L << bitIndex % 64); } public bool TestBit(int bitIndex) { return (array[bitIndex / 64] & (ulong)(1L << bitIndex % 64)) != 0; } public void ClearBit(int bitIndex) { array[bitIndex / 64] &= (ulong)(~(1L << bitIndex % 64)); } private static int BitCountToULongCount(int bitCount) { return (bitCount + 63) / 64; } } } namespace UnityEngine.InputSystem.XR { [StructLayout(LayoutKind.Explicit, Size = 60)] public struct PoseState : IInputStateTypeInfo { internal const int kSizeInBytes = 60; internal static readonly FourCC s_Format = new FourCC('P', 'o', 's', 'e'); [FieldOffset(0)] [InputControl(displayName = "Is Tracked", layout = "Button", sizeInBits = 8u)] public bool isTracked; [FieldOffset(4)] [InputControl(displayName = "Tracking State", layout = "Integer")] public InputTrackingState trackingState; [FieldOffset(8)] [InputControl(displayName = "Position", noisy = true)] public Vector3 position; [FieldOffset(20)] [InputControl(displayName = "Rotation", noisy = true)] public Quaternion rotation; [FieldOffset(36)] [InputControl(displayName = "Velocity", noisy = true)] public Vector3 velocity; [FieldOffset(48)] [InputControl(displayName = "Angular Velocity", noisy = true)] public Vector3 angularVelocity; public FourCC format => s_Format; public PoseState(bool isTracked, InputTrackingState trackingState, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 angularVelocity) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) this.isTracked = isTracked; this.trackingState = trackingState; this.position = position; this.rotation = rotation; this.velocity = velocity; this.angularVelocity = angularVelocity; } } [Preserve] [InputControlLayout(stateType = typeof(PoseState))] public class PoseControl : InputControl { public ButtonControl isTracked { get; private set; } public IntegerControl trackingState { get; private set; } public Vector3Control position { get; private set; } public QuaternionControl rotation { get; private set; } public Vector3Control velocity { get; private set; } public Vector3Control angularVelocity { get; private set; } public PoseControl() { m_StateBlock.format = PoseState.s_Format; } protected override void FinishSetup() { isTracked = GetChildControl("isTracked"); trackingState = GetChildControl("trackingState"); position = GetChildControl("position"); rotation = GetChildControl("rotation"); velocity = GetChildControl("velocity"); angularVelocity = GetChildControl("angularVelocity"); base.FinishSetup(); } public unsafe override PoseState ReadUnprocessedValueFromState(void* statePtr) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1349481317) { return Unsafe.Read((byte*)statePtr + (int)m_StateBlock.byteOffset); } return new PoseState { isTracked = (isTracked.ReadUnprocessedValueFromStateWithCaching(statePtr) > 0.5f), trackingState = (InputTrackingState)trackingState.ReadUnprocessedValueFromStateWithCaching(statePtr), position = position.ReadUnprocessedValueFromStateWithCaching(statePtr), rotation = rotation.ReadUnprocessedValueFromStateWithCaching(statePtr), velocity = velocity.ReadUnprocessedValueFromStateWithCaching(statePtr), angularVelocity = angularVelocity.ReadUnprocessedValueFromStateWithCaching(statePtr) }; } public unsafe override void WriteValueIntoState(PoseState value, void* statePtr) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected I4, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1349481317) { Unsafe.Write((byte*)statePtr + (int)m_StateBlock.byteOffset, value); return; } isTracked.WriteValueIntoState(value.isTracked, statePtr); trackingState.WriteValueIntoState((uint)(int)value.trackingState, statePtr); position.WriteValueIntoState(value.position, statePtr); rotation.WriteValueIntoState(value.rotation, statePtr); velocity.WriteValueIntoState(value.velocity, statePtr); angularVelocity.WriteValueIntoState(value.angularVelocity, statePtr); } protected override FourCC CalculateOptimizedControlDataType() { if (m_StateBlock.sizeInBits == 480 && m_StateBlock.bitOffset == 0 && isTracked.optimizedControlDataType == 1113150533 && trackingState.optimizedControlDataType == 1229870112 && position.optimizedControlDataType == 1447379763 && rotation.optimizedControlDataType == 1364541780 && velocity.optimizedControlDataType == 1447379763 && angularVelocity.optimizedControlDataType == 1447379763 && trackingState.m_StateBlock.byteOffset == isTracked.m_StateBlock.byteOffset + 4 && position.m_StateBlock.byteOffset == isTracked.m_StateBlock.byteOffset + 8 && rotation.m_StateBlock.byteOffset == isTracked.m_StateBlock.byteOffset + 20 && velocity.m_StateBlock.byteOffset == isTracked.m_StateBlock.byteOffset + 36 && angularVelocity.m_StateBlock.byteOffset == isTracked.m_StateBlock.byteOffset + 48) { return 1349481317; } return 0; } } [InputControlLayout(isGenericTypeOfDevice = true, displayName = "XR HMD", canRunInBackground = true)] public class XRHMD : TrackedDevice { [InputControl(noisy = true)] public Vector3Control leftEyePosition { get; private set; } [InputControl(noisy = true)] public QuaternionControl leftEyeRotation { get; private set; } [InputControl(noisy = true)] public Vector3Control rightEyePosition { get; private set; } [InputControl(noisy = true)] public QuaternionControl rightEyeRotation { get; private set; } [InputControl(noisy = true)] public Vector3Control centerEyePosition { get; private set; } [InputControl(noisy = true)] public QuaternionControl centerEyeRotation { get; private set; } protected override void FinishSetup() { base.FinishSetup(); centerEyePosition = GetChildControl("centerEyePosition"); centerEyeRotation = GetChildControl("centerEyeRotation"); leftEyePosition = GetChildControl("leftEyePosition"); leftEyeRotation = GetChildControl("leftEyeRotation"); rightEyePosition = GetChildControl("rightEyePosition"); rightEyeRotation = GetChildControl("rightEyeRotation"); } } [InputControlLayout(commonUsages = new string[] { "LeftHand", "RightHand" }, isGenericTypeOfDevice = true, displayName = "XR Controller")] public class XRController : TrackedDevice { public static XRController leftHand => InputSystem.GetDevice(CommonUsages.LeftHand); public static XRController rightHand => InputSystem.GetDevice(CommonUsages.RightHand); protected override void FinishSetup() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) base.FinishSetup(); XRDeviceDescriptor xRDeviceDescriptor = XRDeviceDescriptor.FromJson(base.description.capabilities); if (xRDeviceDescriptor != null) { if ((xRDeviceDescriptor.characteristics & 0x100) != 0) { InputSystem.SetDeviceUsage(this, CommonUsages.LeftHand); } else if ((xRDeviceDescriptor.characteristics & 0x200) != 0) { InputSystem.SetDeviceUsage(this, CommonUsages.RightHand); } } } } public class XRControllerWithRumble : XRController { public void SendImpulse(float amplitude, float duration) { SendHapticImpulseCommand command = SendHapticImpulseCommand.Create(0, amplitude, duration); ExecuteCommand(ref command); } } [Serializable] [AddComponentMenu("XR/Tracked Pose Driver (Input System)")] public class TrackedPoseDriver : MonoBehaviour, ISerializationCallbackReceiver { public enum TrackingType { RotationAndPosition, RotationOnly, PositionOnly } [Flags] private enum TrackingStates { None = 0, Position = 1, Rotation = 2 } public enum UpdateType { UpdateAndBeforeRender, Update, BeforeRender } [SerializeField] [Tooltip("Which Transform properties to update.")] private TrackingType m_TrackingType; [SerializeField] [Tooltip("Updates the Transform properties after these phases of Input System event processing.")] private UpdateType m_UpdateType; [SerializeField] [Tooltip("Ignore Tracking State and always treat the input pose as valid.")] private bool m_IgnoreTrackingState; [SerializeField] [Tooltip("The input action to read the position value of a tracked device. Must be a Vector 3 control type.")] private InputActionProperty m_PositionInput; [SerializeField] [Tooltip("The input action to read the rotation value of a tracked device. Must be a Quaternion control type.")] private InputActionProperty m_RotationInput; [SerializeField] [Tooltip("The input action to read the tracking state value of a tracked device. Identifies if position and rotation have valid data. Must be an Integer control type.")] private InputActionProperty m_TrackingStateInput; private Vector3 m_CurrentPosition = Vector3.zero; private Quaternion m_CurrentRotation = Quaternion.identity; private TrackingStates m_CurrentTrackingState = TrackingStates.Position | TrackingStates.Rotation; private bool m_RotationBound; private bool m_PositionBound; private bool m_TrackingStateBound; private bool m_IsFirstUpdate = true; [Obsolete] [SerializeField] [HideInInspector] private InputAction m_PositionAction; [Obsolete] [SerializeField] [HideInInspector] private InputAction m_RotationAction; [SerializeField] [HideInInspector] private bool m_HasMigratedActions; public TrackingType trackingType { get { return m_TrackingType; } set { m_TrackingType = value; } } public UpdateType updateType { get { return m_UpdateType; } set { m_UpdateType = value; } } public bool ignoreTrackingState { get { return m_IgnoreTrackingState; } set { m_IgnoreTrackingState = value; } } public InputActionProperty positionInput { get { return m_PositionInput; } set { if (Application.isPlaying) { UnbindPosition(); } m_PositionInput = value; if (Application.isPlaying && ((Behaviour)this).isActiveAndEnabled) { BindPosition(); } } } public InputActionProperty rotationInput { get { return m_RotationInput; } set { if (Application.isPlaying) { UnbindRotation(); } m_RotationInput = value; if (Application.isPlaying && ((Behaviour)this).isActiveAndEnabled) { BindRotation(); } } } public InputActionProperty trackingStateInput { get { return m_TrackingStateInput; } set { if (Application.isPlaying) { UnbindTrackingState(); } m_TrackingStateInput = value; if (Application.isPlaying && ((Behaviour)this).isActiveAndEnabled) { BindTrackingState(); } } } public InputAction positionAction { get { return m_PositionInput.action; } set { positionInput = new InputActionProperty(value); } } public InputAction rotationAction { get { return m_RotationInput.action; } set { rotationInput = new InputActionProperty(value); } } private void BindActions() { BindPosition(); BindRotation(); BindTrackingState(); } private void UnbindActions() { UnbindPosition(); UnbindRotation(); UnbindTrackingState(); } private void BindPosition() { if (m_PositionBound) { return; } InputAction action = m_PositionInput.action; if (action != null) { action.performed += OnPositionPerformed; action.canceled += OnPositionCanceled; m_PositionBound = true; if ((Object)(object)m_PositionInput.reference == (Object)null) { action.Rename(((Object)((Component)this).gameObject).name + " - TPD - Position"); action.Enable(); } } } private void BindRotation() { if (m_RotationBound) { return; } InputAction action = m_RotationInput.action; if (action != null) { action.performed += OnRotationPerformed; action.canceled += OnRotationCanceled; m_RotationBound = true; if ((Object)(object)m_RotationInput.reference == (Object)null) { action.Rename(((Object)((Component)this).gameObject).name + " - TPD - Rotation"); action.Enable(); } } } private void BindTrackingState() { if (m_TrackingStateBound) { return; } InputAction action = m_TrackingStateInput.action; if (action != null) { action.performed += OnTrackingStatePerformed; action.canceled += OnTrackingStateCanceled; m_TrackingStateBound = true; if ((Object)(object)m_TrackingStateInput.reference == (Object)null) { action.Rename(((Object)((Component)this).gameObject).name + " - TPD - Tracking State"); action.Enable(); } } } private void UnbindPosition() { if (!m_PositionBound) { return; } InputAction action = m_PositionInput.action; if (action != null) { if ((Object)(object)m_PositionInput.reference == (Object)null) { action.Disable(); } action.performed -= OnPositionPerformed; action.canceled -= OnPositionCanceled; m_PositionBound = false; } } private void UnbindRotation() { if (!m_RotationBound) { return; } InputAction action = m_RotationInput.action; if (action != null) { if ((Object)(object)m_RotationInput.reference == (Object)null) { action.Disable(); } action.performed -= OnRotationPerformed; action.canceled -= OnRotationCanceled; m_RotationBound = false; } } private void UnbindTrackingState() { if (!m_TrackingStateBound) { return; } InputAction action = m_TrackingStateInput.action; if (action != null) { if ((Object)(object)m_TrackingStateInput.reference == (Object)null) { action.Disable(); } action.performed -= OnTrackingStatePerformed; action.canceled -= OnTrackingStateCanceled; m_TrackingStateBound = false; } } private void OnPositionPerformed(InputAction.CallbackContext context) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) m_CurrentPosition = context.ReadValue(); } private void OnPositionCanceled(InputAction.CallbackContext context) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) m_CurrentPosition = Vector3.zero; } private void OnRotationPerformed(InputAction.CallbackContext context) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) m_CurrentRotation = context.ReadValue(); } private void OnRotationCanceled(InputAction.CallbackContext context) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) m_CurrentRotation = Quaternion.identity; } private void OnTrackingStatePerformed(InputAction.CallbackContext context) { m_CurrentTrackingState = (TrackingStates)context.ReadValue(); } private void OnTrackingStateCanceled(InputAction.CallbackContext context) { m_CurrentTrackingState = TrackingStates.None; } protected void Reset() { m_HasMigratedActions = true; m_PositionInput = new InputActionProperty(new InputAction("Position", InputActionType.Value, null, null, null, "Vector3")); m_RotationInput = new InputActionProperty(new InputAction("Rotation", InputActionType.Value, null, null, null, "Quaternion")); m_TrackingStateInput = new InputActionProperty(new InputAction("Tracking State", InputActionType.Value, null, null, null, "Integer")); } protected virtual void Awake() { if (HasStereoCamera(out var cameraComponent)) { XRDevice.DisableAutoXRCameraTracking(cameraComponent, true); } } protected void OnEnable() { InputSystem.onAfterUpdate += UpdateCallback; BindActions(); m_IsFirstUpdate = true; } protected void OnDisable() { UnbindActions(); InputSystem.onAfterUpdate -= UpdateCallback; } protected virtual void OnDestroy() { if (HasStereoCamera(out var cameraComponent)) { XRDevice.DisableAutoXRCameraTracking(cameraComponent, false); } } protected void UpdateCallback() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) if (m_IsFirstUpdate) { if (m_PositionInput.action != null) { m_CurrentPosition = m_PositionInput.action.ReadValue(); } if (m_RotationInput.action != null) { m_CurrentRotation = m_RotationInput.action.ReadValue(); } ReadTrackingState(); m_IsFirstUpdate = false; } if (InputState.currentUpdateType == InputUpdateType.BeforeRender) { OnBeforeRender(); } else { OnUpdate(); } } private unsafe void ReadTrackingState() { InputAction action = m_TrackingStateInput.action; if (action != null && !action.enabled) { m_CurrentTrackingState = TrackingStates.None; return; } if (action == null || action.m_BindingsCount == 0) { m_CurrentTrackingState = TrackingStates.Position | TrackingStates.Rotation; return; } InputActionMap orCreateActionMap = action.GetOrCreateActionMap(); orCreateActionMap.ResolveBindingsIfNecessary(); InputActionState state = orCreateActionMap.m_State; bool flag = false; if (state != null) { int actionIndexInState = action.m_ActionIndexInState; int totalBindingCount = state.totalBindingCount; for (int i = 0; i < totalBindingCount; i++) { ref InputActionState.BindingState reference = ref state.bindingStates[i]; if (reference.actionIndex == actionIndexInState && !reference.isComposite && reference.controlCount > 0) { flag = true; break; } } } if (flag) { m_CurrentTrackingState = (TrackingStates)action.ReadValue(); } } protected virtual void OnUpdate() { if (m_UpdateType == UpdateType.Update || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void OnBeforeRender() { if (m_UpdateType == UpdateType.BeforeRender || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void PerformUpdate() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) SetLocalTransform(m_CurrentPosition, m_CurrentRotation); } protected virtual void SetLocalTransform(Vector3 newPosition, Quaternion newRotation) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) bool num = m_IgnoreTrackingState || (m_CurrentTrackingState & TrackingStates.Position) != 0; if ((m_IgnoreTrackingState || (m_CurrentTrackingState & TrackingStates.Rotation) != TrackingStates.None) && (m_TrackingType == TrackingType.RotationAndPosition || m_TrackingType == TrackingType.RotationOnly)) { ((Component)this).transform.localRotation = newRotation; } if (num && (m_TrackingType == TrackingType.RotationAndPosition || m_TrackingType == TrackingType.PositionOnly)) { ((Component)this).transform.localPosition = newPosition; } } private bool HasStereoCamera(out Camera cameraComponent) { if (((Component)this).TryGetComponent(ref cameraComponent)) { return cameraComponent.stereoEnabled; } return false; } void ISerializationCallbackReceiver.OnBeforeSerialize() { } void ISerializationCallbackReceiver.OnAfterDeserialize() { if (!m_HasMigratedActions) { m_PositionInput = new InputActionProperty(m_PositionAction); m_RotationInput = new InputActionProperty(m_RotationAction); m_HasMigratedActions = true; } } } internal class XRLayoutBuilder { private string parentLayout; private string interfaceName; private XRDeviceDescriptor descriptor; private static readonly string[] poseSubControlNames = new string[6] { "/isTracked", "/trackingState", "/position", "/rotation", "/velocity", "/angularVelocity" }; private static readonly FeatureType[] poseSubControlTypes = new FeatureType[6] { FeatureType.Binary, FeatureType.DiscreteStates, FeatureType.Axis3D, FeatureType.Rotation, FeatureType.Axis3D, FeatureType.Axis3D }; private static uint GetSizeOfFeature(XRFeatureDescriptor featureDescriptor) { return featureDescriptor.featureType switch { FeatureType.Binary => 1u, FeatureType.DiscreteStates => 4u, FeatureType.Axis1D => 4u, FeatureType.Axis2D => 8u, FeatureType.Axis3D => 12u, FeatureType.Rotation => 16u, FeatureType.Hand => 104u, FeatureType.Bone => 32u, FeatureType.Eyes => 76u, FeatureType.Custom => featureDescriptor.customSize, _ => 0u, }; } private static string SanitizeString(string original, bool allowPaths = false) { int length = original.Length; StringBuilder stringBuilder = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = original[i]; if (char.IsUpper(c) || char.IsLower(c) || char.IsDigit(c) || c == '_' || (allowPaths && c == '/')) { stringBuilder.Append(c); } } return stringBuilder.ToString(); } internal static string OnFindLayoutForDevice(ref InputDeviceDescription description, string matchedLayout, InputDeviceExecuteCommandDelegate executeCommandDelegate) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 if (description.interfaceName != "XRInputV1" && description.interfaceName != "XRInput") { return null; } if (string.IsNullOrEmpty(description.capabilities)) { return null; } XRDeviceDescriptor xRDeviceDescriptor; try { xRDeviceDescriptor = XRDeviceDescriptor.FromJson(description.capabilities); } catch (Exception) { return null; } if (xRDeviceDescriptor == null) { return null; } if (string.IsNullOrEmpty(matchedLayout)) { if ((xRDeviceDescriptor.characteristics & 1) != 0) { matchedLayout = "XRHMD"; } else if ((xRDeviceDescriptor.characteristics & 0x44) == 68) { matchedLayout = "XRController"; } } string text = ((!string.IsNullOrEmpty(description.manufacturer)) ? (SanitizeString(description.interfaceName) + "::" + SanitizeString(description.manufacturer) + "::" + SanitizeString(description.product)) : (SanitizeString(description.interfaceName) + "::" + SanitizeString(description.product))); XRLayoutBuilder layout = new XRLayoutBuilder { descriptor = xRDeviceDescriptor, parentLayout = matchedLayout, interfaceName = description.interfaceName }; InputSystem.RegisterLayoutBuilder(() => layout.Build(), text, matchedLayout); return text; } private static string ConvertPotentialAliasToName(InputControlLayout layout, string nameOrAlias) { InternedString internedString = new InternedString(nameOrAlias); ReadOnlyArray controls = layout.controls; for (int i = 0; i < controls.Count; i++) { InputControlLayout.ControlItem controlItem = controls[i]; if (controlItem.name == internedString) { return nameOrAlias; } ReadOnlyArray aliases = controlItem.aliases; for (int j = 0; j < aliases.Count; j++) { if (aliases[j] == nameOrAlias) { return controlItem.name.ToString(); } } } return nameOrAlias; } private bool IsSubControl(string name) { return name.Contains('/'); } private string GetParentControlName(string name) { return name[..name.IndexOf('/')]; } private bool IsPoseControl(List features, int startIndex) { for (int i = 0; i < 6; i++) { if (!features[startIndex + i].name.EndsWith(poseSubControlNames[i]) || features[startIndex + i].featureType != poseSubControlTypes[i]) { return false; } } return true; } private InputControlLayout Build() { InputControlLayout.Builder builder = new InputControlLayout.Builder { stateFormat = new FourCC('X', 'R', 'S', '0'), extendsLayout = parentLayout, updateBeforeRender = true }; InputControlLayout inputControlLayout = ((!string.IsNullOrEmpty(parentLayout)) ? InputSystem.LoadLayout(parentLayout) : null); List list = new List(); List list2 = new List(); uint num = 0u; for (int i = 0; i < descriptor.inputFeatures.Count; i++) { XRFeatureDescriptor featureDescriptor = descriptor.inputFeatures[i]; list2.Clear(); if (featureDescriptor.usageHints != null) { foreach (UsageHint usageHint in featureDescriptor.usageHints) { if (!string.IsNullOrEmpty(usageHint.content)) { list2.Add(usageHint.content); } } } string name = featureDescriptor.name; name = SanitizeString(name, allowPaths: true); if (inputControlLayout != null) { name = ConvertPotentialAliasToName(inputControlLayout, name); } name = name.ToLower(); if (IsSubControl(name)) { string parentControlName = GetParentControlName(name); if (!list.Contains(parentControlName) && IsPoseControl(descriptor.inputFeatures, i)) { builder.AddControl(parentControlName).WithLayout("Pose").WithByteOffset(0u); list.Add(parentControlName); } } uint sizeOfFeature = GetSizeOfFeature(featureDescriptor); if (!(interfaceName == "XRInput") && sizeOfFeature >= 4 && num % 4 != 0) { num += 4 - num % 4; } switch (featureDescriptor.featureType) { case FeatureType.Binary: builder.AddControl(name).WithLayout("Button").WithByteOffset(num) .WithFormat(InputStateBlock.FormatBit) .WithUsages(list2); break; case FeatureType.DiscreteStates: builder.AddControl(name).WithLayout("Integer").WithByteOffset(num) .WithFormat(InputStateBlock.FormatInt) .WithUsages(list2); break; case FeatureType.Axis1D: builder.AddControl(name).WithLayout("Analog").WithRange(-1f, 1f) .WithByteOffset(num) .WithFormat(InputStateBlock.FormatFloat) .WithUsages(list2); break; case FeatureType.Axis2D: builder.AddControl(name).WithLayout("Stick").WithByteOffset(num) .WithFormat(InputStateBlock.FormatVector2) .WithUsages(list2); builder.AddControl(name + "/x").WithLayout("Analog").WithRange(-1f, 1f); builder.AddControl(name + "/y").WithLayout("Analog").WithRange(-1f, 1f); break; case FeatureType.Axis3D: builder.AddControl(name).WithLayout("Vector3").WithByteOffset(num) .WithFormat(InputStateBlock.FormatVector3) .WithUsages(list2); break; case FeatureType.Rotation: builder.AddControl(name).WithLayout("Quaternion").WithByteOffset(num) .WithFormat(InputStateBlock.FormatQuaternion) .WithUsages(list2); break; case FeatureType.Bone: builder.AddControl(name).WithLayout("Bone").WithByteOffset(num) .WithUsages(list2); break; case FeatureType.Eyes: builder.AddControl(name).WithLayout("Eyes").WithByteOffset(num) .WithUsages(list2); break; } num += sizeOfFeature; } return builder.Build(); } } public static class XRUtilities { public const string InterfaceMatchAnyVersion = "^(XRInput)"; public const string InterfaceV1 = "XRInput"; public const string InterfaceCurrent = "XRInputV1"; } public enum FeatureType { Custom, Binary, DiscreteStates, Axis1D, Axis2D, Axis3D, Rotation, Hand, Bone, Eyes } [Serializable] public struct UsageHint { public string content; } [Serializable] public struct XRFeatureDescriptor { public string name; public List usageHints; public FeatureType featureType; public uint customSize; } [Serializable] public class XRDeviceDescriptor { public string deviceName; public string manufacturer; public string serialNumber; public InputDeviceCharacteristics characteristics; public int deviceId; public List inputFeatures; public string ToJson() { return JsonUtility.ToJson((object)this); } public static XRDeviceDescriptor FromJson(string json) { return JsonUtility.FromJson(json); } } public struct Bone { public uint m_ParentBoneIndex; public Vector3 m_Position; public Quaternion m_Rotation; public uint parentBoneIndex { get { return m_ParentBoneIndex; } set { m_ParentBoneIndex = value; } } public Vector3 position { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_Position; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_Position = value; } } public Quaternion rotation { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_Rotation; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_Rotation = value; } } } public struct Eyes { public Vector3 m_LeftEyePosition; public Quaternion m_LeftEyeRotation; public Vector3 m_RightEyePosition; public Quaternion m_RightEyeRotation; public Vector3 m_FixationPoint; public float m_LeftEyeOpenAmount; public float m_RightEyeOpenAmount; public Vector3 leftEyePosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_LeftEyePosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_LeftEyePosition = value; } } public Quaternion leftEyeRotation { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_LeftEyeRotation; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_LeftEyeRotation = value; } } public Vector3 rightEyePosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_RightEyePosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_RightEyePosition = value; } } public Quaternion rightEyeRotation { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_RightEyeRotation; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_RightEyeRotation = value; } } public Vector3 fixationPoint { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_FixationPoint; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_FixationPoint = value; } } public float leftEyeOpenAmount { get { return m_LeftEyeOpenAmount; } set { m_LeftEyeOpenAmount = value; } } public float rightEyeOpenAmount { get { return m_RightEyeOpenAmount; } set { m_RightEyeOpenAmount = value; } } } public class BoneControl : InputControl { [InputControl(offset = 0u, displayName = "parentBoneIndex")] public IntegerControl parentBoneIndex { get; private set; } [InputControl(offset = 4u, displayName = "Position")] public Vector3Control position { get; private set; } [InputControl(offset = 16u, displayName = "Rotation")] public QuaternionControl rotation { get; private set; } protected override void FinishSetup() { parentBoneIndex = GetChildControl("parentBoneIndex"); position = GetChildControl("position"); rotation = GetChildControl("rotation"); base.FinishSetup(); } public unsafe override Bone ReadUnprocessedValueFromState(void* statePtr) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) return new Bone { parentBoneIndex = (uint)parentBoneIndex.ReadUnprocessedValueFromStateWithCaching(statePtr), position = position.ReadUnprocessedValueFromStateWithCaching(statePtr), rotation = rotation.ReadUnprocessedValueFromStateWithCaching(statePtr) }; } public unsafe override void WriteValueIntoState(Bone value, void* statePtr) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) parentBoneIndex.WriteValueIntoState((int)value.parentBoneIndex, statePtr); position.WriteValueIntoState(value.position, statePtr); rotation.WriteValueIntoState(value.rotation, statePtr); } } public class EyesControl : InputControl { [InputControl(offset = 0u, displayName = "LeftEyePosition")] public Vector3Control leftEyePosition { get; private set; } [InputControl(offset = 12u, displayName = "LeftEyeRotation")] public QuaternionControl leftEyeRotation { get; private set; } [InputControl(offset = 28u, displayName = "RightEyePosition")] public Vector3Control rightEyePosition { get; private set; } [InputControl(offset = 40u, displayName = "RightEyeRotation")] public QuaternionControl rightEyeRotation { get; private set; } [InputControl(offset = 56u, displayName = "FixationPoint")] public Vector3Control fixationPoint { get; private set; } [InputControl(offset = 68u, displayName = "LeftEyeOpenAmount")] public AxisControl leftEyeOpenAmount { get; private set; } [InputControl(offset = 72u, displayName = "RightEyeOpenAmount")] public AxisControl rightEyeOpenAmount { get; private set; } protected override void FinishSetup() { leftEyePosition = GetChildControl("leftEyePosition"); leftEyeRotation = GetChildControl("leftEyeRotation"); rightEyePosition = GetChildControl("rightEyePosition"); rightEyeRotation = GetChildControl("rightEyeRotation"); fixationPoint = GetChildControl("fixationPoint"); leftEyeOpenAmount = GetChildControl("leftEyeOpenAmount"); rightEyeOpenAmount = GetChildControl("rightEyeOpenAmount"); base.FinishSetup(); } public unsafe override Eyes ReadUnprocessedValueFromState(void* statePtr) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) return new Eyes { leftEyePosition = leftEyePosition.ReadUnprocessedValueFromStateWithCaching(statePtr), leftEyeRotation = leftEyeRotation.ReadUnprocessedValueFromStateWithCaching(statePtr), rightEyePosition = rightEyePosition.ReadUnprocessedValueFromStateWithCaching(statePtr), rightEyeRotation = rightEyeRotation.ReadUnprocessedValueFromStateWithCaching(statePtr), fixationPoint = fixationPoint.ReadUnprocessedValueFromStateWithCaching(statePtr), leftEyeOpenAmount = leftEyeOpenAmount.ReadUnprocessedValueFromStateWithCaching(statePtr), rightEyeOpenAmount = rightEyeOpenAmount.ReadUnprocessedValueFromStateWithCaching(statePtr) }; } public unsafe override void WriteValueIntoState(Eyes value, void* statePtr) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) leftEyePosition.WriteValueIntoState(value.leftEyePosition, statePtr); leftEyeRotation.WriteValueIntoState(value.leftEyeRotation, statePtr); rightEyePosition.WriteValueIntoState(value.rightEyePosition, statePtr); rightEyeRotation.WriteValueIntoState(value.rightEyeRotation, statePtr); fixationPoint.WriteValueIntoState(value.fixationPoint, statePtr); leftEyeOpenAmount.WriteValueIntoState(value.leftEyeOpenAmount, statePtr); rightEyeOpenAmount.WriteValueIntoState(value.rightEyeOpenAmount, statePtr); } } internal static class XRSupport { public static void Initialize() { InputSystem.RegisterLayout("Pose"); InputSystem.RegisterLayout("Bone"); InputSystem.RegisterLayout("Eyes"); InputSystem.RegisterLayout(); InputSystem.RegisterLayout(); InputSystem.onFindLayoutForDevice += XRLayoutBuilder.OnFindLayoutForDevice; InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("(Windows Mixed Reality HMD)|(Microsoft HoloLens)|(^(WindowsMR Headset))")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("(^(Spatial Controller))|(^(OpenVR Controller\\(WindowsMR))")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("(^(Hand -))")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("^(Oculus Rift)|^(Oculus Quest)|^(Oculus Go)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("(^(Oculus Touch Controller))|(^(Oculus Quest Controller))")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("Oculus Remote")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("((Tracking Reference)|(^(Oculus Rift [a-zA-Z0-9]* \\(Camera)))")); InputSystem.RegisterLayout("GearVR", default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("Oculus HMD")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("^(Oculus Tracked Remote)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("Daydream HMD")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("^(Daydream Controller)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("^(OpenVR Headset)|^(Vive Pro)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("^(OpenVR Controller\\(WindowsMR)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithManufacturer("HTC").WithProduct("^(OpenVR Controller\\(((Vive. Controller)|(VIVE. Controller)|(Vive Controller)))")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithProduct("^(OpenVR Controller\\(Oculus)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithManufacturer("HTC").WithProduct("^(VIVE Tracker)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithManufacturer("HTC").WithProduct("^(OpenVR Controller\\(VIVE Tracker)")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("^(XRInput)").WithManufacturer("HTC").WithProduct("^(HTC V2-XD/XE)")); } } } namespace UnityEngine.InputSystem.XR.Haptics { public struct BufferedRumble { public HapticCapabilities capabilities { get; private set; } private InputDevice device { get; set; } public BufferedRumble(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } this.device = device; GetHapticCapabilitiesCommand command = GetHapticCapabilitiesCommand.Create(); device.ExecuteCommand(ref command); capabilities = command.capabilities; } public void EnqueueRumble(byte[] samples) { SendBufferedHapticCommand command = SendBufferedHapticCommand.Create(samples); device.ExecuteCommand(ref command); } } public struct HapticState { public uint samplesQueued { get; private set; } public uint samplesAvailable { get; private set; } public HapticState(uint samplesQueued, uint samplesAvailable) { this.samplesQueued = samplesQueued; this.samplesAvailable = samplesAvailable; } } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct GetCurrentHapticStateCommand : IInputDeviceCommandInfo { private const int kSize = 16; [FieldOffset(0)] private InputDeviceCommand baseCommand; [FieldOffset(8)] public uint samplesQueued; [FieldOffset(12)] public uint samplesAvailable; private static FourCC Type => new FourCC('X', 'H', 'S', '0'); public FourCC typeStatic => Type; public HapticState currentState => new HapticState(samplesQueued, samplesAvailable); public static GetCurrentHapticStateCommand Create() { return new GetCurrentHapticStateCommand { baseCommand = new InputDeviceCommand(Type, 16) }; } } public struct HapticCapabilities { public uint numChannels { get; private set; } public uint frequencyHz { get; private set; } public uint maxBufferSize { get; private set; } public HapticCapabilities(uint numChannels, uint frequencyHz, uint maxBufferSize) { this.numChannels = numChannels; this.frequencyHz = frequencyHz; this.maxBufferSize = maxBufferSize; } } [StructLayout(LayoutKind.Explicit, Size = 20)] public struct GetHapticCapabilitiesCommand : IInputDeviceCommandInfo { private const int kSize = 20; [FieldOffset(0)] private InputDeviceCommand baseCommand; [FieldOffset(8)] public uint numChannels; [FieldOffset(12)] public uint frequencyHz; [FieldOffset(16)] public uint maxBufferSize; private static FourCC Type => new FourCC('X', 'H', 'C', '0'); public FourCC typeStatic => Type; public HapticCapabilities capabilities => new HapticCapabilities(numChannels, frequencyHz, maxBufferSize); public static GetHapticCapabilitiesCommand Create() { return new GetHapticCapabilitiesCommand { baseCommand = new InputDeviceCommand(Type, 20) }; } } [StructLayout(LayoutKind.Explicit, Size = 1040)] public struct SendBufferedHapticCommand : IInputDeviceCommandInfo { private const int kMaxHapticBufferSize = 1024; private const int kSize = 1040; [FieldOffset(0)] private InputDeviceCommand baseCommand; [FieldOffset(8)] private int channel; [FieldOffset(12)] private int bufferSize; [FieldOffset(16)] private unsafe fixed byte buffer[1024]; private static FourCC Type => new FourCC('X', 'H', 'U', '0'); public FourCC typeStatic => Type; public unsafe static SendBufferedHapticCommand Create(byte[] rumbleBuffer) { if (rumbleBuffer == null) { throw new ArgumentNullException("rumbleBuffer"); } int num = Mathf.Min(1024, rumbleBuffer.Length); SendBufferedHapticCommand result = new SendBufferedHapticCommand { baseCommand = new InputDeviceCommand(Type, 1040), bufferSize = num }; SendBufferedHapticCommand* ptr = &result; fixed (byte* ptr2 = rumbleBuffer) { for (int i = 0; i < num; i++) { ptr->buffer[i] = ptr2[i]; } } return result; } } [StructLayout(LayoutKind.Explicit, Size = 20)] public struct SendHapticImpulseCommand : IInputDeviceCommandInfo { private const int kSize = 20; [FieldOffset(0)] private InputDeviceCommand baseCommand; [FieldOffset(8)] private int channel; [FieldOffset(12)] private float amplitude; [FieldOffset(16)] private float duration; private static FourCC Type => new FourCC('X', 'H', 'I', '0'); public FourCC typeStatic => Type; public static SendHapticImpulseCommand Create(int motorChannel, float motorAmplitude, float motorDuration) { return new SendHapticImpulseCommand { baseCommand = new InputDeviceCommand(Type, 20), channel = motorChannel, amplitude = motorAmplitude, duration = motorDuration }; } } } namespace UnityEngine.InputSystem.XInput { public interface IXboxOneRumble : IDualMotorRumble, IHaptics { void SetMotorSpeeds(float lowFrequency, float highFrequency, float leftTrigger, float rightTrigger); } [InputControlLayout(displayName = "Xbox Controller")] public class XInputController : Gamepad { internal enum DeviceType { Gamepad } public enum DeviceSubType { Unknown = 0, Gamepad = 1, Wheel = 2, ArcadeStick = 3, FlightStick = 4, DancePad = 5, Guitar = 6, GuitarAlternate = 7, DrumKit = 8, GuitarBass = 11, ArcadePad = 19 } [Flags] public new enum DeviceFlags { ForceFeedbackSupported = 1, Wireless = 2, VoiceSupported = 4, PluginModulesSupported = 8, NoNavigation = 0x10 } [Serializable] internal struct Capabilities { public DeviceType type; public DeviceSubType subType; public DeviceFlags flags; } private bool m_HaveParsedCapabilities; private DeviceSubType m_SubType; private DeviceFlags m_Flags; [InputControl(name = "buttonSouth", displayName = "A")] [InputControl(name = "buttonEast", displayName = "B")] [InputControl(name = "buttonWest", displayName = "X")] [InputControl(name = "buttonNorth", displayName = "Y")] [InputControl(name = "leftShoulder", displayName = "Left Bumper", shortDisplayName = "LB")] [InputControl(name = "rightShoulder", displayName = "Right Bumper", shortDisplayName = "RB")] [InputControl(name = "leftTrigger", shortDisplayName = "LT")] [InputControl(name = "rightTrigger", shortDisplayName = "RT")] [InputControl(name = "start", displayName = "Menu", alias = "menu")] [InputControl(name = "select", displayName = "View", alias = "view")] public ButtonControl menu { get; private set; } public ButtonControl view { get; private set; } public DeviceSubType subType { get { if (!m_HaveParsedCapabilities) { ParseCapabilities(); } return m_SubType; } } public DeviceFlags flags { get { if (!m_HaveParsedCapabilities) { ParseCapabilities(); } return m_Flags; } } protected override void FinishSetup() { base.FinishSetup(); menu = base.startButton; view = base.selectButton; } private void ParseCapabilities() { if (!string.IsNullOrEmpty(base.description.capabilities)) { Capabilities capabilities = JsonUtility.FromJson(base.description.capabilities); m_SubType = capabilities.subType; m_Flags = capabilities.flags; } m_HaveParsedCapabilities = true; } } [InputControlLayout(stateType = typeof(XInputControllerWindowsState), hideInUI = true)] public class XInputControllerWindows : XInputController { } internal static class XInputSupport { public static void Initialize() { InputSystem.RegisterLayout(); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("XInput")); } } } namespace UnityEngine.InputSystem.XInput.LowLevel { [StructLayout(LayoutKind.Explicit, Size = 4)] internal struct XInputControllerWindowsState : IInputStateTypeInfo { public enum Button { DPadUp = 0, DPadDown = 1, DPadLeft = 2, DPadRight = 3, Start = 4, Select = 5, LeftThumbstickPress = 6, RightThumbstickPress = 7, LeftShoulder = 8, RightShoulder = 9, A = 12, B = 13, X = 14, Y = 15 } [FieldOffset(0)] [InputControl(name = "dpad", layout = "Dpad", sizeInBits = 4u, bit = 0u)] [InputControl(name = "dpad/up", bit = 0u)] [InputControl(name = "dpad/down", bit = 1u)] [InputControl(name = "dpad/left", bit = 2u)] [InputControl(name = "dpad/right", bit = 3u)] [InputControl(name = "start", bit = 4u, displayName = "Start")] [InputControl(name = "select", bit = 5u, displayName = "Select")] [InputControl(name = "leftStickPress", bit = 6u)] [InputControl(name = "rightStickPress", bit = 7u)] [InputControl(name = "leftShoulder", bit = 8u)] [InputControl(name = "rightShoulder", bit = 9u)] [InputControl(name = "buttonSouth", bit = 12u, displayName = "A")] [InputControl(name = "buttonEast", bit = 13u, displayName = "B")] [InputControl(name = "buttonWest", bit = 14u, displayName = "X")] [InputControl(name = "buttonNorth", bit = 15u, displayName = "Y")] public ushort buttons; [FieldOffset(2)] [InputControl(name = "leftTrigger", format = "BYTE")] public byte leftTrigger; [FieldOffset(3)] [InputControl(name = "rightTrigger", format = "BYTE")] public byte rightTrigger; [FieldOffset(4)] [InputControl(name = "leftStick", layout = "Stick", format = "VC2S")] [InputControl(name = "leftStick/x", offset = 0u, format = "SHRT", parameters = "clamp=false,invert=false,normalize=false")] [InputControl(name = "leftStick/left", offset = 0u, format = "SHRT")] [InputControl(name = "leftStick/right", offset = 0u, format = "SHRT")] [InputControl(name = "leftStick/y", offset = 2u, format = "SHRT", parameters = "clamp=false,invert=false,normalize=false")] [InputControl(name = "leftStick/up", offset = 2u, format = "SHRT")] [InputControl(name = "leftStick/down", offset = 2u, format = "SHRT")] public short leftStickX; [FieldOffset(6)] public short leftStickY; [FieldOffset(8)] [InputControl(name = "rightStick", layout = "Stick", format = "VC2S")] [InputControl(name = "rightStick/x", offset = 0u, format = "SHRT", parameters = "clamp=false,invert=false,normalize=false")] [InputControl(name = "rightStick/left", offset = 0u, format = "SHRT")] [InputControl(name = "rightStick/right", offset = 0u, format = "SHRT")] [InputControl(name = "rightStick/y", offset = 2u, format = "SHRT", parameters = "clamp=false,invert=false,normalize=false")] [InputControl(name = "rightStick/up", offset = 2u, format = "SHRT")] [InputControl(name = "rightStick/down", offset = 2u, format = "SHRT")] public short rightStickX; [FieldOffset(10)] public short rightStickY; public FourCC format => new FourCC('X', 'I', 'N', 'P'); public XInputControllerWindowsState WithButton(Button button) { buttons |= (ushort)(1 << (int)button); return this; } } } namespace UnityEngine.InputSystem.Users { public struct InputUser : IEquatable { public struct ControlSchemeChangeSyntax { internal int m_UserIndex; public ControlSchemeChangeSyntax AndPairRemainingDevices() { UpdateControlSchemeMatch(m_UserIndex, autoPairMissing: true); return this; } } [Flags] internal enum UserFlags { BindToAllDevices = 1, UserAccountSelectionInProgress = 2 } private struct UserData { public InputUserAccountHandle? platformUserAccountHandle; public string platformUserAccountName; public string platformUserAccountId; public int deviceCount; public int deviceStartIndex; public IInputActionCollection actions; public InputControlScheme? controlScheme; public InputControlScheme.MatchResult controlSchemeMatch; public int lostDeviceCount; public int lostDeviceStartIndex; public UserFlags flags; } private struct CompareDevicesByUserAccount : IComparer { public InputUserAccountHandle platformUserAccountHandle; public int Compare(InputDevice x, InputDevice y) { InputUserAccountHandle? userAccountHandleForDevice = GetUserAccountHandleForDevice(x); InputUserAccountHandle? userAccountHandleForDevice2 = GetUserAccountHandleForDevice(x); InputUserAccountHandle? inputUserAccountHandle = userAccountHandleForDevice; InputUserAccountHandle inputUserAccountHandle2 = platformUserAccountHandle; if (inputUserAccountHandle.HasValue && inputUserAccountHandle.GetValueOrDefault() == inputUserAccountHandle2 && userAccountHandleForDevice2 == platformUserAccountHandle) { return 0; } if (userAccountHandleForDevice == platformUserAccountHandle) { return -1; } if (userAccountHandleForDevice2 == platformUserAccountHandle) { return 1; } return 0; } private static InputUserAccountHandle? GetUserAccountHandleForDevice(InputDevice device) { return null; } } private struct OngoingAccountSelection { public InputDevice device; public uint userId; } private struct GlobalState { internal int pairingStateVersion; internal uint lastUserId; internal int allUserCount; internal int allPairedDeviceCount; internal int allLostDeviceCount; internal InputUser[] allUsers; internal UserData[] allUserData; internal InputDevice[] allPairedDevices; internal InputDevice[] allLostDevices; internal InlinedArray ongoingAccountSelections; internal CallbackArray> onChange; internal CallbackArray> onUnpairedDeviceUsed; internal CallbackArray> onPreFilterUnpairedDeviceUsed; internal Action actionChangeDelegate; internal Action onDeviceChangeDelegate; internal Action onEventDelegate; internal bool onActionChangeHooked; internal bool onDeviceChangeHooked; internal bool onEventHooked; internal int listenForUnpairedDeviceActivity; } public const uint InvalidId = 0u; private uint m_Id; private static GlobalState s_GlobalState; public bool valid { get { if (m_Id == 0) { return false; } for (int i = 0; i < s_GlobalState.allUserCount; i++) { if (s_GlobalState.allUsers[i].m_Id == m_Id) { return true; } } return false; } } public int index { get { if (m_Id == 0) { throw new InvalidOperationException("Invalid user"); } int num = TryFindUserIndex(m_Id); if (num == -1) { throw new InvalidOperationException($"User with ID {m_Id} is no longer valid"); } return num; } } public uint id => m_Id; public InputUserAccountHandle? platformUserAccountHandle => s_GlobalState.allUserData[index].platformUserAccountHandle; public string platformUserAccountName => s_GlobalState.allUserData[index].platformUserAccountName; public string platformUserAccountId => s_GlobalState.allUserData[index].platformUserAccountId; public ReadOnlyArray pairedDevices { get { int num = index; return new ReadOnlyArray(s_GlobalState.allPairedDevices, s_GlobalState.allUserData[num].deviceStartIndex, s_GlobalState.allUserData[num].deviceCount); } } public ReadOnlyArray lostDevices { get { int num = index; return new ReadOnlyArray(s_GlobalState.allLostDevices, s_GlobalState.allUserData[num].lostDeviceStartIndex, s_GlobalState.allUserData[num].lostDeviceCount); } } public IInputActionCollection actions => s_GlobalState.allUserData[index].actions; public InputControlScheme? controlScheme => s_GlobalState.allUserData[index].controlScheme; public InputControlScheme.MatchResult controlSchemeMatch => s_GlobalState.allUserData[index].controlSchemeMatch; public bool hasMissingRequiredDevices => s_GlobalState.allUserData[index].controlSchemeMatch.hasMissingRequiredDevices; public static ReadOnlyArray all => new ReadOnlyArray(s_GlobalState.allUsers, 0, s_GlobalState.allUserCount); public static int listenForUnpairedDeviceActivity { get { return s_GlobalState.listenForUnpairedDeviceActivity; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", "Cannot be negative"); } if (value > 0 && s_GlobalState.onUnpairedDeviceUsed.length > 0) { HookIntoEvents(); } else if (value == 0) { UnhookFromDeviceStateChange(); } s_GlobalState.listenForUnpairedDeviceActivity = value; } } public static event Action onChange { add { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onChange.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onChange.RemoveCallback(value); } } public static event Action onUnpairedDeviceUsed { add { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onUnpairedDeviceUsed.AddCallback(value); if (s_GlobalState.listenForUnpairedDeviceActivity > 0) { HookIntoEvents(); } } remove { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onUnpairedDeviceUsed.RemoveCallback(value); if (s_GlobalState.onUnpairedDeviceUsed.length == 0) { UnhookFromDeviceStateChange(); } } } public static event Func onPrefilterUnpairedDeviceActivity { add { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onPreFilterUnpairedDeviceUsed.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onPreFilterUnpairedDeviceUsed.RemoveCallback(value); } } public override string ToString() { if (!valid) { return $" (id: {m_Id})"; } string text = string.Join(",", pairedDevices); return $"User #{index} (id: {m_Id}, devices: {text}, actions: {actions})"; } public void AssociateActionsWithUser(IInputActionCollection actions) { int num = index; if (s_GlobalState.allUserData[num].actions == actions) { return; } IInputActionCollection inputActionCollection = s_GlobalState.allUserData[num].actions; if (inputActionCollection != null) { inputActionCollection.devices = null; inputActionCollection.bindingMask = null; } s_GlobalState.allUserData[num].actions = actions; if (actions != null) { HookIntoActionChange(); actions.devices = pairedDevices; if (s_GlobalState.allUserData[num].controlScheme.HasValue) { ActivateControlSchemeInternal(num, s_GlobalState.allUserData[num].controlScheme.Value); } } } public ControlSchemeChangeSyntax ActivateControlScheme(string schemeName) { if (!string.IsNullOrEmpty(schemeName)) { FindControlScheme(schemeName, out var scheme); return ActivateControlScheme(scheme); } return ActivateControlScheme(default(InputControlScheme)); } private bool TryFindControlScheme(string schemeName, out InputControlScheme scheme) { if (string.IsNullOrEmpty(schemeName)) { scheme = default(InputControlScheme); return false; } if (s_GlobalState.allUserData[index].actions == null) { throw new InvalidOperationException($"Cannot set control scheme '{schemeName}' by name on user #{index} as not actions have been associated with the user yet (AssociateActionsWithUser)"); } ReadOnlyArray controlSchemes = s_GlobalState.allUserData[index].actions.controlSchemes; for (int i = 0; i < controlSchemes.Count; i++) { if (string.Compare(controlSchemes[i].name, schemeName, StringComparison.InvariantCultureIgnoreCase) == 0) { scheme = controlSchemes[i]; return true; } } scheme = default(InputControlScheme); return false; } internal void FindControlScheme(string schemeName, out InputControlScheme scheme) { if (TryFindControlScheme(schemeName, out scheme)) { return; } throw new ArgumentException($"Cannot find control scheme '{schemeName}' in actions '{s_GlobalState.allUserData[index].actions}'"); } public ControlSchemeChangeSyntax ActivateControlScheme(InputControlScheme scheme) { int num = index; InputControlScheme? inputControlScheme = s_GlobalState.allUserData[num].controlScheme; InputControlScheme inputControlScheme2 = scheme; if (!inputControlScheme.HasValue || inputControlScheme.GetValueOrDefault() != inputControlScheme2 || (scheme == default(InputControlScheme) && s_GlobalState.allUserData[num].controlScheme.HasValue)) { ActivateControlSchemeInternal(num, scheme); Notify(num, InputUserChange.ControlSchemeChanged, null); } return new ControlSchemeChangeSyntax { m_UserIndex = num }; } private void ActivateControlSchemeInternal(int userIndex, InputControlScheme scheme) { bool flag = scheme == default(InputControlScheme); if (flag) { s_GlobalState.allUserData[userIndex].controlScheme = null; } else { s_GlobalState.allUserData[userIndex].controlScheme = scheme; } if (s_GlobalState.allUserData[userIndex].actions == null) { return; } if (flag) { s_GlobalState.allUserData[userIndex].actions.bindingMask = null; s_GlobalState.allUserData[userIndex].controlSchemeMatch.Dispose(); s_GlobalState.allUserData[userIndex].controlSchemeMatch = default(InputControlScheme.MatchResult); return; } s_GlobalState.allUserData[userIndex].actions.bindingMask = new InputBinding { groups = scheme.bindingGroup }; UpdateControlSchemeMatch(userIndex); if (s_GlobalState.allUserData[userIndex].controlSchemeMatch.isSuccessfulMatch) { RemoveLostDevicesForUser(userIndex); } } public void UnpairDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } int userIndex = index; if (pairedDevices.ContainsReference(device)) { RemoveDeviceFromUser(userIndex, device); } } public void UnpairDevices() { int num = index; RemoveLostDevicesForUser(num); using (InputActionRebindingExtensions.DeferBindingResolution()) { while (s_GlobalState.allUserData[num].deviceCount > 0) { UnpairDevice(s_GlobalState.allPairedDevices[s_GlobalState.allUserData[num].deviceStartIndex + s_GlobalState.allUserData[num].deviceCount - 1]); } } if (s_GlobalState.allUserData[num].controlScheme.HasValue) { UpdateControlSchemeMatch(num); } } private static void RemoveLostDevicesForUser(int userIndex) { int lostDeviceCount = s_GlobalState.allUserData[userIndex].lostDeviceCount; if (lostDeviceCount <= 0) { return; } int lostDeviceStartIndex = s_GlobalState.allUserData[userIndex].lostDeviceStartIndex; ArrayHelpers.EraseSliceWithCapacity(ref s_GlobalState.allLostDevices, ref s_GlobalState.allLostDeviceCount, lostDeviceStartIndex, lostDeviceCount); s_GlobalState.allUserData[userIndex].lostDeviceCount = 0; s_GlobalState.allUserData[userIndex].lostDeviceStartIndex = 0; for (int i = 0; i < s_GlobalState.allUserCount; i++) { if (s_GlobalState.allUserData[i].lostDeviceStartIndex > lostDeviceStartIndex) { s_GlobalState.allUserData[i].lostDeviceStartIndex -= lostDeviceCount; } } } public void UnpairDevicesAndRemoveUser() { UnpairDevices(); RemoveUser(index); m_Id = 0u; } public static InputControlList GetUnpairedInputDevices() { InputControlList list = new InputControlList((Allocator)2); GetUnpairedInputDevices(ref list); return list; } public static int GetUnpairedInputDevices(ref InputControlList list) { int count = list.Count; foreach (InputDevice device in InputSystem.devices) { if (!s_GlobalState.allPairedDevices.ContainsReference(s_GlobalState.allPairedDeviceCount, device)) { list.Add(device); } } return list.Count - count; } public static InputUser? FindUserPairedToDevice(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } int num = TryFindUserIndex(device); if (num == -1) { return null; } return s_GlobalState.allUsers[num]; } public static InputUser? FindUserByAccount(InputUserAccountHandle platformUserAccountHandle) { if (platformUserAccountHandle == default(InputUserAccountHandle)) { throw new ArgumentException("Empty platform user account handle", "platformUserAccountHandle"); } int num = TryFindUserIndex(platformUserAccountHandle); if (num == -1) { return null; } return s_GlobalState.allUsers[num]; } public static InputUser CreateUserWithoutPairedDevices() { int num = AddUser(); return s_GlobalState.allUsers[num]; } public static InputUser PerformPairingWithDevice(InputDevice device, InputUser user = default(InputUser), InputUserPairingOptions options = InputUserPairingOptions.None) { if (device == null) { throw new ArgumentNullException("device"); } if (user != default(InputUser) && !user.valid) { throw new ArgumentException("Invalid user", "user"); } int num; if (user == default(InputUser)) { num = AddUser(); } else { num = user.index; if ((options & InputUserPairingOptions.UnpairCurrentDevicesFromUser) != InputUserPairingOptions.None) { user.UnpairDevices(); } if (user.pairedDevices.ContainsReference(device)) { if ((options & InputUserPairingOptions.ForcePlatformUserAccountSelection) != InputUserPairingOptions.None) { InitiateUserAccountSelection(num, device, options); } return user; } } if (!InitiateUserAccountSelection(num, device, options)) { AddDeviceToUser(num, device); } return s_GlobalState.allUsers[num]; } private static bool InitiateUserAccountSelection(int userIndex, InputDevice device, InputUserPairingOptions options) { long num = (((options & InputUserPairingOptions.ForcePlatformUserAccountSelection) == 0) ? UpdatePlatformUserAccount(userIndex, device) : 0); if (((options & InputUserPairingOptions.ForcePlatformUserAccountSelection) != InputUserPairingOptions.None || (num != -1 && (num & 2) == 0L && (options & InputUserPairingOptions.ForceNoPlatformUserAccountSelection) == 0)) && InitiateUserAccountSelectionAtPlatformLevel(device)) { s_GlobalState.allUserData[userIndex].flags |= UserFlags.UserAccountSelectionInProgress; s_GlobalState.ongoingAccountSelections.Append(new OngoingAccountSelection { device = device, userId = s_GlobalState.allUsers[userIndex].id }); HookIntoDeviceChange(); Notify(userIndex, InputUserChange.AccountSelectionInProgress, device); return true; } return false; } public bool Equals(InputUser other) { return m_Id == other.m_Id; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputUser) { return Equals((InputUser)obj); } return false; } public override int GetHashCode() { return (int)m_Id; } public static bool operator ==(InputUser left, InputUser right) { return left.m_Id == right.m_Id; } public static bool operator !=(InputUser left, InputUser right) { return left.m_Id != right.m_Id; } private static int AddUser() { uint num = ++s_GlobalState.lastUserId; int count = s_GlobalState.allUserCount; ArrayHelpers.AppendWithCapacity(ref s_GlobalState.allUsers, ref count, new InputUser { m_Id = num }); int num2 = ArrayHelpers.AppendWithCapacity(ref s_GlobalState.allUserData, ref s_GlobalState.allUserCount, default(UserData)); Notify(num2, InputUserChange.Added, null); return num2; } private static void RemoveUser(int userIndex) { if (s_GlobalState.allUserData[userIndex].controlScheme.HasValue && s_GlobalState.allUserData[userIndex].actions != null) { s_GlobalState.allUserData[userIndex].actions.bindingMask = null; } s_GlobalState.allUserData[userIndex].controlSchemeMatch.Dispose(); RemoveLostDevicesForUser(userIndex); for (int i = 0; i < s_GlobalState.ongoingAccountSelections.length; i++) { if (s_GlobalState.ongoingAccountSelections[i].userId == s_GlobalState.allUsers[userIndex].id) { s_GlobalState.ongoingAccountSelections.RemoveAtByMovingTailWithCapacity(i); i--; } } Notify(userIndex, InputUserChange.Removed, null); int count = s_GlobalState.allUserCount; s_GlobalState.allUsers.EraseAtWithCapacity(ref count, userIndex); s_GlobalState.allUserData.EraseAtWithCapacity(ref s_GlobalState.allUserCount, userIndex); if (s_GlobalState.allUserCount == 0) { UnhookFromDeviceChange(); UnhookFromActionChange(); } } private static void Notify(int userIndex, InputUserChange change, InputDevice device) { if (s_GlobalState.onChange.length == 0) { return; } s_GlobalState.onChange.LockForChanges(); for (int i = 0; i < s_GlobalState.onChange.length; i++) { try { s_GlobalState.onChange[i](s_GlobalState.allUsers[userIndex], change, device); } catch (Exception ex) { Debug.LogError((object)(ex.GetType().Name + " while executing 'InputUser.onChange' callbacks")); Debug.LogException(ex); } } s_GlobalState.onChange.UnlockForChanges(); } private static int TryFindUserIndex(uint userId) { for (int i = 0; i < s_GlobalState.allUserCount; i++) { if (s_GlobalState.allUsers[i].m_Id == userId) { return i; } } return -1; } private static int TryFindUserIndex(InputUserAccountHandle platformHandle) { for (int i = 0; i < s_GlobalState.allUserCount; i++) { if (s_GlobalState.allUserData[i].platformUserAccountHandle == platformHandle) { return i; } } return -1; } private static int TryFindUserIndex(InputDevice device) { int num = s_GlobalState.allPairedDevices.IndexOfReference(device, s_GlobalState.allPairedDeviceCount); if (num == -1) { return -1; } for (int i = 0; i < s_GlobalState.allUserCount; i++) { int deviceStartIndex = s_GlobalState.allUserData[i].deviceStartIndex; if (deviceStartIndex <= num && num < deviceStartIndex + s_GlobalState.allUserData[i].deviceCount) { return i; } } return -1; } private static void AddDeviceToUser(int userIndex, InputDevice device, bool asLostDevice = false, bool dontUpdateControlScheme = false) { int num = (asLostDevice ? s_GlobalState.allUserData[userIndex].lostDeviceCount : s_GlobalState.allUserData[userIndex].deviceCount); int num2 = (asLostDevice ? s_GlobalState.allUserData[userIndex].lostDeviceStartIndex : s_GlobalState.allUserData[userIndex].deviceStartIndex); s_GlobalState.pairingStateVersion++; if (num > 0) { ArrayHelpers.MoveSlice(asLostDevice ? s_GlobalState.allLostDevices : s_GlobalState.allPairedDevices, num2, asLostDevice ? (s_GlobalState.allLostDeviceCount - num) : (s_GlobalState.allPairedDeviceCount - num), num); for (int i = 0; i < s_GlobalState.allUserCount; i++) { if (i != userIndex && (asLostDevice ? s_GlobalState.allUserData[i].lostDeviceStartIndex : s_GlobalState.allUserData[i].deviceStartIndex) > num2) { if (asLostDevice) { s_GlobalState.allUserData[i].lostDeviceStartIndex -= num; } else { s_GlobalState.allUserData[i].deviceStartIndex -= num; } } } } if (asLostDevice) { s_GlobalState.allUserData[userIndex].lostDeviceStartIndex = s_GlobalState.allLostDeviceCount - num; ArrayHelpers.AppendWithCapacity(ref s_GlobalState.allLostDevices, ref s_GlobalState.allLostDeviceCount, device); s_GlobalState.allUserData[userIndex].lostDeviceCount++; } else { s_GlobalState.allUserData[userIndex].deviceStartIndex = s_GlobalState.allPairedDeviceCount - num; ArrayHelpers.AppendWithCapacity(ref s_GlobalState.allPairedDevices, ref s_GlobalState.allPairedDeviceCount, device); s_GlobalState.allUserData[userIndex].deviceCount++; IInputActionCollection inputActionCollection = s_GlobalState.allUserData[userIndex].actions; if (inputActionCollection != null) { inputActionCollection.devices = s_GlobalState.allUsers[userIndex].pairedDevices; if (!dontUpdateControlScheme && s_GlobalState.allUserData[userIndex].controlScheme.HasValue) { UpdateControlSchemeMatch(userIndex); } } } HookIntoDeviceChange(); Notify(userIndex, asLostDevice ? InputUserChange.DeviceLost : InputUserChange.DevicePaired, device); } private static void RemoveDeviceFromUser(int userIndex, InputDevice device, bool asLostDevice = false) { int num = (asLostDevice ? s_GlobalState.allLostDevices.IndexOfReference(device, s_GlobalState.allLostDeviceCount) : s_GlobalState.allPairedDevices.IndexOfReference(device, s_GlobalState.allUserData[userIndex].deviceStartIndex, s_GlobalState.allUserData[userIndex].deviceCount)); if (num == -1) { return; } if (asLostDevice) { s_GlobalState.allLostDevices.EraseAtWithCapacity(ref s_GlobalState.allLostDeviceCount, num); s_GlobalState.allUserData[userIndex].lostDeviceCount--; } else { s_GlobalState.pairingStateVersion++; s_GlobalState.allPairedDevices.EraseAtWithCapacity(ref s_GlobalState.allPairedDeviceCount, num); s_GlobalState.allUserData[userIndex].deviceCount--; } for (int i = 0; i < s_GlobalState.allUserCount; i++) { if ((asLostDevice ? s_GlobalState.allUserData[i].lostDeviceStartIndex : s_GlobalState.allUserData[i].deviceStartIndex) > num) { if (asLostDevice) { s_GlobalState.allUserData[i].lostDeviceStartIndex--; } else { s_GlobalState.allUserData[i].deviceStartIndex--; } } } if (asLostDevice) { return; } for (int j = 0; j < s_GlobalState.ongoingAccountSelections.length; j++) { if (s_GlobalState.ongoingAccountSelections[j].userId == s_GlobalState.allUsers[userIndex].id && s_GlobalState.ongoingAccountSelections[j].device == device) { s_GlobalState.ongoingAccountSelections.RemoveAtByMovingTailWithCapacity(j); j--; } } IInputActionCollection inputActionCollection = s_GlobalState.allUserData[userIndex].actions; if (inputActionCollection != null) { inputActionCollection.devices = s_GlobalState.allUsers[userIndex].pairedDevices; if (s_GlobalState.allUsers[userIndex].controlScheme.HasValue) { UpdateControlSchemeMatch(userIndex); } } Notify(userIndex, InputUserChange.DeviceUnpaired, device); } private static void UpdateControlSchemeMatch(int userIndex, bool autoPairMissing = false) { if (!s_GlobalState.allUserData[userIndex].controlScheme.HasValue) { return; } s_GlobalState.allUserData[userIndex].controlSchemeMatch.Dispose(); InputControlScheme.MatchResult matchResult = default(InputControlScheme.MatchResult); try { InputControlScheme value = s_GlobalState.allUserData[userIndex].controlScheme.Value; if (value.deviceRequirements.Count > 0) { InputControlList list = new InputControlList((Allocator)2); try { list.AddSlice(s_GlobalState.allUsers[userIndex].pairedDevices); if (autoPairMissing) { int count = list.Count; int unpairedInputDevices = GetUnpairedInputDevices(ref list); if (s_GlobalState.allUserData[userIndex].platformUserAccountHandle.HasValue) { list.Sort(count, unpairedInputDevices, new CompareDevicesByUserAccount { platformUserAccountHandle = s_GlobalState.allUserData[userIndex].platformUserAccountHandle.Value }); } } matchResult = value.PickDevicesFrom(list); if (matchResult.isSuccessfulMatch && autoPairMissing) { s_GlobalState.allUserData[userIndex].controlSchemeMatch = matchResult; foreach (InputDevice device in matchResult.devices) { if (!s_GlobalState.allUsers[userIndex].pairedDevices.ContainsReference(device)) { AddDeviceToUser(userIndex, device, asLostDevice: false, dontUpdateControlScheme: true); } } } } finally { list.Dispose(); } } s_GlobalState.allUserData[userIndex].controlSchemeMatch = matchResult; } catch (Exception) { matchResult.Dispose(); throw; } } private static long UpdatePlatformUserAccount(int userIndex, InputDevice device) { InputUserAccountHandle? platformAccountHandle; string platformAccountName; string platformAccountId; long num = QueryPairedPlatformUserAccount(device, out platformAccountHandle, out platformAccountName, out platformAccountId); if (num == -1) { if ((s_GlobalState.allUserData[userIndex].flags & UserFlags.UserAccountSelectionInProgress) != 0) { Notify(userIndex, InputUserChange.AccountSelectionCanceled, null); } s_GlobalState.allUserData[userIndex].platformUserAccountHandle = null; s_GlobalState.allUserData[userIndex].platformUserAccountName = null; s_GlobalState.allUserData[userIndex].platformUserAccountId = null; return num; } if ((s_GlobalState.allUserData[userIndex].flags & UserFlags.UserAccountSelectionInProgress) != 0) { if ((num & 4) == 0L) { if ((num & 0x10) != 0L) { Notify(userIndex, InputUserChange.AccountSelectionCanceled, device); } else { s_GlobalState.allUserData[userIndex].flags &= ~UserFlags.UserAccountSelectionInProgress; s_GlobalState.allUserData[userIndex].platformUserAccountHandle = platformAccountHandle; s_GlobalState.allUserData[userIndex].platformUserAccountName = platformAccountName; s_GlobalState.allUserData[userIndex].platformUserAccountId = platformAccountId; Notify(userIndex, InputUserChange.AccountSelectionComplete, device); } } } else { InputUserAccountHandle? inputUserAccountHandle = s_GlobalState.allUserData[userIndex].platformUserAccountHandle; InputUserAccountHandle? inputUserAccountHandle2 = platformAccountHandle; if (inputUserAccountHandle.HasValue != inputUserAccountHandle2.HasValue || (inputUserAccountHandle.HasValue && inputUserAccountHandle.GetValueOrDefault() != inputUserAccountHandle2.GetValueOrDefault()) || s_GlobalState.allUserData[userIndex].platformUserAccountId != platformAccountId) { s_GlobalState.allUserData[userIndex].platformUserAccountHandle = platformAccountHandle; s_GlobalState.allUserData[userIndex].platformUserAccountName = platformAccountName; s_GlobalState.allUserData[userIndex].platformUserAccountId = platformAccountId; Notify(userIndex, InputUserChange.AccountChanged, device); } else if (s_GlobalState.allUserData[userIndex].platformUserAccountName != platformAccountName) { Notify(userIndex, InputUserChange.AccountNameChanged, device); } } return num; } private static long QueryPairedPlatformUserAccount(InputDevice device, out InputUserAccountHandle? platformAccountHandle, out string platformAccountName, out string platformAccountId) { QueryPairedUserAccountCommand command = QueryPairedUserAccountCommand.Create(); long num = device.ExecuteCommand(ref command); if (num == -1) { platformAccountHandle = null; platformAccountName = null; platformAccountId = null; return -1L; } if ((num & 2) != 0L) { platformAccountHandle = new InputUserAccountHandle(device.description.interfaceName ?? "", command.handle); platformAccountName = command.name; platformAccountId = command.id; } else { platformAccountHandle = null; platformAccountName = null; platformAccountId = null; } return num; } private static bool InitiateUserAccountSelectionAtPlatformLevel(InputDevice device) { InitiateUserAccountPairingCommand command = InitiateUserAccountPairingCommand.Create(); long num = device.ExecuteCommand(ref command); if (num == -2) { throw new InvalidOperationException("User pairing already in progress"); } return num == 1; } private static void OnActionChange(object obj, InputActionChange change) { if (change != InputActionChange.BoundControlsChanged) { return; } for (int i = 0; i < s_GlobalState.allUserCount; i++) { if (s_GlobalState.allUsers[i].actions == obj) { Notify(i, InputUserChange.ControlsChanged, null); } } } private static void OnDeviceChange(InputDevice device, InputDeviceChange change) { switch (change) { case InputDeviceChange.Removed: { for (int num6 = s_GlobalState.allPairedDevices.IndexOfReference(device, s_GlobalState.allPairedDeviceCount); num6 != -1; num6 = s_GlobalState.allPairedDevices.IndexOfReference(device, s_GlobalState.allPairedDeviceCount)) { int userIndex2 = -1; for (int l = 0; l < s_GlobalState.allUserCount; l++) { int deviceStartIndex2 = s_GlobalState.allUserData[l].deviceStartIndex; if (deviceStartIndex2 <= num6 && num6 < deviceStartIndex2 + s_GlobalState.allUserData[l].deviceCount) { userIndex2 = l; break; } } AddDeviceToUser(userIndex2, device, asLostDevice: true); RemoveDeviceFromUser(userIndex2, device); } break; } case InputDeviceChange.Added: { for (int num5 = FindLostDevice(device); num5 != -1; num5 = FindLostDevice(device, num5)) { int userIndex = -1; for (int k = 0; k < s_GlobalState.allUserCount; k++) { int lostDeviceStartIndex = s_GlobalState.allUserData[k].lostDeviceStartIndex; if (lostDeviceStartIndex <= num5 && num5 < lostDeviceStartIndex + s_GlobalState.allUserData[k].lostDeviceCount) { userIndex = k; break; } } RemoveDeviceFromUser(userIndex, s_GlobalState.allLostDevices[num5], asLostDevice: true); Notify(userIndex, InputUserChange.DeviceRegained, device); AddDeviceToUser(userIndex, device); } break; } case InputDeviceChange.ConfigurationChanged: { bool flag = false; for (int i = 0; i < s_GlobalState.ongoingAccountSelections.length; i++) { if (s_GlobalState.ongoingAccountSelections[i].device != device) { continue; } InputUser inputUser = new InputUser { m_Id = s_GlobalState.ongoingAccountSelections[i].userId }; int num = inputUser.index; if ((UpdatePlatformUserAccount(num, device) & 4) == 0L) { flag = true; s_GlobalState.ongoingAccountSelections.RemoveAtByMovingTailWithCapacity(i); i--; if (!s_GlobalState.allUsers[num].pairedDevices.ContainsReference(device)) { AddDeviceToUser(num, device); } } } if (flag) { break; } int num2 = s_GlobalState.allPairedDevices.IndexOfReference(device, s_GlobalState.allPairedDeviceCount); while (num2 != -1) { int num3 = -1; for (int j = 0; j < s_GlobalState.allUserCount; j++) { int deviceStartIndex = s_GlobalState.allUserData[j].deviceStartIndex; if (deviceStartIndex <= num2 && num2 < deviceStartIndex + s_GlobalState.allUserData[j].deviceCount) { num3 = j; break; } } UpdatePlatformUserAccount(num3, device); int num4 = num2 + Math.Max(1, s_GlobalState.allUserData[num3].deviceCount); num2 = s_GlobalState.allPairedDevices.IndexOfReference(device, num4, s_GlobalState.allPairedDeviceCount - num4); } break; } } } private static int FindLostDevice(InputDevice device, int startIndex = 0) { int deviceId = device.deviceId; for (int i = startIndex; i < s_GlobalState.allLostDeviceCount; i++) { InputDevice inputDevice = s_GlobalState.allLostDevices[i]; if (device == inputDevice || inputDevice.deviceId == deviceId) { return i; } } return -1; } private static void OnEvent(InputEventPtr eventPtr, InputDevice device) { if (s_GlobalState.listenForUnpairedDeviceActivity == 0) { return; } FourCC type = eventPtr.type; if ((type != 1398030676 && type != 1145852993) || !device.enabled || s_GlobalState.allPairedDevices.ContainsReference(s_GlobalState.allPairedDeviceCount, device) || !DelegateHelpers.InvokeCallbacksSafe_AnyCallbackReturnsTrue(ref s_GlobalState.onPreFilterUnpairedDeviceUsed, device, eventPtr, "InputUser.onPreFilterUnpairedDeviceActivity")) { return; } foreach (InputControl item in eventPtr.EnumerateChangedControls(device, 0.0001f)) { bool flag = false; s_GlobalState.onUnpairedDeviceUsed.LockForChanges(); for (int i = 0; i < s_GlobalState.onUnpairedDeviceUsed.length; i++) { int pairingStateVersion = s_GlobalState.pairingStateVersion; try { s_GlobalState.onUnpairedDeviceUsed[i](item, eventPtr); } catch (Exception ex) { Debug.LogError((object)(ex.GetType().Name + " while executing 'InputUser.onUnpairedDeviceUsed' callbacks")); Debug.LogException(ex); } if (pairingStateVersion != s_GlobalState.pairingStateVersion && FindUserPairedToDevice(device).HasValue) { flag = true; break; } } s_GlobalState.onUnpairedDeviceUsed.UnlockForChanges(); if (flag) { break; } } } internal static ISavedState SaveAndResetState() { SavedStructState result = new SavedStructState(ref s_GlobalState, delegate(ref GlobalState state) { s_GlobalState = state; }, delegate { DisposeAndResetGlobalState(); }); s_GlobalState = default(GlobalState); return result; } private static void HookIntoActionChange() { if (!s_GlobalState.onActionChangeHooked) { if (s_GlobalState.actionChangeDelegate == null) { s_GlobalState.actionChangeDelegate = OnActionChange; } InputSystem.onActionChange += OnActionChange; s_GlobalState.onActionChangeHooked = true; } } private static void UnhookFromActionChange() { if (s_GlobalState.onActionChangeHooked) { InputSystem.onActionChange -= OnActionChange; s_GlobalState.onActionChangeHooked = false; } } private static void HookIntoDeviceChange() { if (!s_GlobalState.onDeviceChangeHooked) { if (s_GlobalState.onDeviceChangeDelegate == null) { s_GlobalState.onDeviceChangeDelegate = OnDeviceChange; } InputSystem.onDeviceChange += s_GlobalState.onDeviceChangeDelegate; s_GlobalState.onDeviceChangeHooked = true; } } private static void UnhookFromDeviceChange() { if (s_GlobalState.onDeviceChangeHooked) { InputSystem.onDeviceChange -= s_GlobalState.onDeviceChangeDelegate; s_GlobalState.onDeviceChangeHooked = false; } } private static void HookIntoEvents() { if (!s_GlobalState.onEventHooked) { if (s_GlobalState.onEventDelegate == null) { s_GlobalState.onEventDelegate = OnEvent; } InputSystem.onEvent += s_GlobalState.onEventDelegate; s_GlobalState.onEventHooked = true; } } private static void UnhookFromDeviceStateChange() { if (s_GlobalState.onEventHooked) { InputSystem.onEvent -= s_GlobalState.onEventDelegate; s_GlobalState.onEventHooked = false; } } private static void DisposeAndResetGlobalState() { for (int i = 0; i < s_GlobalState.allUserCount; i++) { s_GlobalState.allUserData[i].controlSchemeMatch.Dispose(); } uint lastUserId = s_GlobalState.lastUserId; s_GlobalState = default(GlobalState); s_GlobalState.lastUserId = lastUserId; } internal static void ResetGlobals() { UnhookFromActionChange(); UnhookFromDeviceChange(); UnhookFromDeviceStateChange(); DisposeAndResetGlobalState(); } } public struct InputUserAccountHandle : IEquatable { private string m_ApiName; private ulong m_Handle; public string apiName => m_ApiName; public ulong handle => m_Handle; public InputUserAccountHandle(string apiName, ulong handle) { if (string.IsNullOrEmpty(apiName)) { throw new ArgumentNullException("apiName"); } m_ApiName = apiName; m_Handle = handle; } public override string ToString() { if (m_ApiName == null) { return base.ToString(); } return $"{m_ApiName}({m_Handle})"; } public bool Equals(InputUserAccountHandle other) { if (string.Equals(apiName, other.apiName)) { return object.Equals(handle, other.handle); } return false; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputUserAccountHandle) { return Equals((InputUserAccountHandle)obj); } return false; } public static bool operator ==(InputUserAccountHandle left, InputUserAccountHandle right) { return left.Equals(right); } public static bool operator !=(InputUserAccountHandle left, InputUserAccountHandle right) { return !left.Equals(right); } public override int GetHashCode() { return (((apiName != null) ? apiName.GetHashCode() : 0) * 397) ^ handle.GetHashCode(); } } public enum InputUserChange { Added, Removed, DevicePaired, DeviceUnpaired, DeviceLost, DeviceRegained, AccountChanged, AccountNameChanged, AccountSelectionInProgress, AccountSelectionCanceled, AccountSelectionComplete, ControlSchemeChanged, ControlsChanged } [Flags] public enum InputUserPairingOptions { None = 0, ForcePlatformUserAccountSelection = 1, ForceNoPlatformUserAccountSelection = 2, UnpairCurrentDevicesFromUser = 8 } [Serializable] internal class InputUserSettings { [SerializeField] private string m_CustomBindings; public string customBindings { get; set; } public bool invertMouseX { get; set; } public bool invertMouseY { get; set; } public float? mouseSmoothing { get; set; } public float? mouseSensitivity { get; set; } public bool invertStickX { get; set; } public bool invertStickY { get; set; } public bool swapSticks { get; set; } public bool swapBumpers { get; set; } public bool swapTriggers { get; set; } public bool swapDpadAndLeftStick { get; set; } public float vibrationStrength { get; set; } public virtual void Apply(IInputActionCollection actions) { } } } namespace UnityEngine.InputSystem.UI { internal class BaseInputOverride : BaseInput { public override string compositionString { get; } } internal class ExtendedAxisEventData : AxisEventData { public ExtendedAxisEventData(EventSystem eventSystem) : base(eventSystem) { } public override string ToString() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) return $"MoveDir: {((AxisEventData)this).moveDir}\nMoveVector: {((AxisEventData)this).moveVector}"; } } public class ExtendedPointerEventData : PointerEventData { public InputControl control { get; set; } public InputDevice device { get; set; } public int touchId { get; set; } public UIPointerType pointerType { get; set; } public int uiToolkitPointerId { get; set; } public Vector3 trackedDevicePosition { get; set; } public Quaternion trackedDeviceOrientation { get; set; } public ExtendedPointerEventData(EventSystem eventSystem) : base(eventSystem) { } public override string ToString() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(((PointerEventData)this).ToString()); stringBuilder.AppendLine("button: " + ((object)((PointerEventData)this).button/*cast due to .constrained prefix*/).ToString()); stringBuilder.AppendLine("clickTime: " + ((PointerEventData)this).clickTime); stringBuilder.AppendLine("clickCount: " + ((PointerEventData)this).clickCount); stringBuilder.AppendLine("device: " + device); stringBuilder.AppendLine("pointerType: " + pointerType); stringBuilder.AppendLine("touchId: " + touchId); stringBuilder.AppendLine("pressPosition: " + ((object)((PointerEventData)this).pressPosition/*cast due to .constrained prefix*/).ToString()); stringBuilder.AppendLine("trackedDevicePosition: " + ((object)trackedDevicePosition/*cast due to .constrained prefix*/).ToString()); stringBuilder.AppendLine("trackedDeviceOrientation: " + ((object)trackedDeviceOrientation/*cast due to .constrained prefix*/).ToString()); stringBuilder.AppendLine("pressure" + ((PointerEventData)this).pressure); stringBuilder.AppendLine("radius: " + ((object)((PointerEventData)this).radius/*cast due to .constrained prefix*/).ToString()); stringBuilder.AppendLine("azimuthAngle: " + ((PointerEventData)this).azimuthAngle); stringBuilder.AppendLine("altitudeAngle: " + ((PointerEventData)this).altitudeAngle); stringBuilder.AppendLine("twist: " + ((PointerEventData)this).twist); return stringBuilder.ToString(); } internal static int MakePointerIdForTouch(int deviceId, int touchId) { return (deviceId << 24) + touchId; } internal static int TouchIdFromPointerId(int pointerId) { return pointerId & 0xFF; } internal void ReadDeviceState() { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) if (control.parent is Pen pen) { uiToolkitPointerId = GetPenPointerId(pen); ((PointerEventData)this).pressure = pen.pressure.magnitude; ((PointerEventData)this).azimuthAngle = (pen.tilt.value.x + 1f) * (float)Math.PI / 2f; ((PointerEventData)this).altitudeAngle = (pen.tilt.value.y + 1f) * (float)Math.PI / 2f; ((PointerEventData)this).twist = pen.twist.value * (float)Math.PI * 2f; } else if (control.parent is TouchControl touchControl) { uiToolkitPointerId = GetTouchPointerId(touchControl); ((PointerEventData)this).pressure = touchControl.pressure.magnitude; ((PointerEventData)this).radius = touchControl.radius.value; } else if (control.parent is Touchscreen touchscreen) { uiToolkitPointerId = GetTouchPointerId(touchscreen.primaryTouch); ((PointerEventData)this).pressure = touchscreen.pressure.magnitude; ((PointerEventData)this).radius = touchscreen.radius.value; } else { uiToolkitPointerId = PointerId.mousePointerId; } } private static int GetPenPointerId(Pen pen) { int num = 0; foreach (InputDevice device in InputSystem.devices) { if (device is Pen pen2) { if (pen == pen2) { return PointerId.penPointerIdBase + Mathf.Min(num, PointerId.penPointerCount - 1); } num++; } } return PointerId.penPointerIdBase; } private static int GetTouchPointerId(TouchControl touchControl) { int num = ((Touchscreen)touchControl.device).touches.IndexOfReference(touchControl); return PointerId.touchPointerIdBase + Mathf.Clamp(num, 0, PointerId.touchPointerCount - 1); } } public enum UIPointerType { None, MouseOrPen, Touch, Tracked } public enum UIPointerBehavior { SingleMouseOrPenButMultiTouchAndTrack, SingleUnifiedPointer, AllPointersAsIs } [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/UISupport.html#setting-up-ui-input")] public class InputSystemUIInputModule : BaseInputModule { private struct InputActionReferenceState { public int refCount; public bool enabledByInputModule; } public enum CursorLockBehavior { OutsideScreen, ScreenCenter } private const float kClickSpeed = 0.3f; [FormerlySerializedAs("m_RepeatDelay")] [Tooltip("The Initial delay (in seconds) between an initial move action and a repeated move action.")] [SerializeField] private float m_MoveRepeatDelay = 0.5f; [FormerlySerializedAs("m_RepeatRate")] [Tooltip("The speed (in seconds) that the move action repeats itself once repeating (max 1 per frame).")] [SerializeField] private float m_MoveRepeatRate = 0.1f; [Tooltip("Scales the Eventsystem.DragThreshold, for tracked devices, to make selection easier.")] private float m_TrackedDeviceDragThresholdMultiplier = 2f; [Tooltip("Transform representing the real world origin for tracking devices. When using the XR Interaction Toolkit, this should be pointing to the XR Rig's Transform.")] [SerializeField] private Transform m_XRTrackingOrigin; internal const float kPixelPerLine = 20f; [SerializeField] [HideInInspector] private InputActionAsset m_ActionsAsset; [SerializeField] [HideInInspector] private InputActionReference m_PointAction; [SerializeField] [HideInInspector] private InputActionReference m_MoveAction; [SerializeField] [HideInInspector] private InputActionReference m_SubmitAction; [SerializeField] [HideInInspector] private InputActionReference m_CancelAction; [SerializeField] [HideInInspector] private InputActionReference m_LeftClickAction; [SerializeField] [HideInInspector] private InputActionReference m_MiddleClickAction; [SerializeField] [HideInInspector] private InputActionReference m_RightClickAction; [SerializeField] [HideInInspector] private InputActionReference m_ScrollWheelAction; [SerializeField] [HideInInspector] private InputActionReference m_TrackedDevicePositionAction; [SerializeField] [HideInInspector] private InputActionReference m_TrackedDeviceOrientationAction; [SerializeField] private bool m_DeselectOnBackgroundClick = true; [SerializeField] private UIPointerBehavior m_PointerBehavior; [SerializeField] [HideInInspector] internal CursorLockBehavior m_CursorLockBehavior; private static Dictionary s_InputActionReferenceCounts = new Dictionary(); [NonSerialized] private bool m_ActionsHooked; [NonSerialized] private bool m_NeedToPurgeStalePointers; private Action m_OnPointDelegate; private Action m_OnMoveDelegate; private Action m_OnLeftClickDelegate; private Action m_OnRightClickDelegate; private Action m_OnMiddleClickDelegate; private Action m_OnScrollWheelDelegate; private Action m_OnTrackedDevicePositionDelegate; private Action m_OnTrackedDeviceOrientationDelegate; private Action m_OnControlsChangedDelegate; [NonSerialized] private int m_CurrentPointerId = -1; [NonSerialized] private int m_CurrentPointerIndex = -1; [NonSerialized] internal UIPointerType m_CurrentPointerType; internal InlinedArray m_PointerIds; internal InlinedArray m_PointerTouchControls; internal InlinedArray m_PointerStates; private NavigationModel m_NavigationState; [NonSerialized] private GameObject m_LocalMultiPlayerRoot; public bool deselectOnBackgroundClick { get { return m_DeselectOnBackgroundClick; } set { m_DeselectOnBackgroundClick = value; } } public UIPointerBehavior pointerBehavior { get { return m_PointerBehavior; } set { m_PointerBehavior = value; } } public CursorLockBehavior cursorLockBehavior { get { return m_CursorLockBehavior; } set { m_CursorLockBehavior = value; } } internal GameObject localMultiPlayerRoot { get { return m_LocalMultiPlayerRoot; } set { m_LocalMultiPlayerRoot = value; } } public float moveRepeatDelay { get { return m_MoveRepeatDelay; } set { m_MoveRepeatDelay = value; } } public float moveRepeatRate { get { return m_MoveRepeatRate; } set { m_MoveRepeatRate = value; } } private bool explictlyIgnoreFocus => InputSystem.settings.backgroundBehavior == InputSettings.BackgroundBehavior.IgnoreFocus; private bool shouldIgnoreFocus { get { if (!explictlyIgnoreFocus) { return InputRuntime.s_Instance.runInBackground; } return true; } } [Obsolete("'repeatRate' has been obsoleted; use 'moveRepeatRate' instead. (UnityUpgradable) -> moveRepeatRate", false)] public float repeatRate { get { return moveRepeatRate; } set { moveRepeatRate = value; } } [Obsolete("'repeatDelay' has been obsoleted; use 'moveRepeatDelay' instead. (UnityUpgradable) -> moveRepeatDelay", false)] public float repeatDelay { get { return moveRepeatDelay; } set { moveRepeatDelay = value; } } public Transform xrTrackingOrigin { get { return m_XRTrackingOrigin; } set { m_XRTrackingOrigin = value; } } public float trackedDeviceDragThresholdMultiplier { get { return m_TrackedDeviceDragThresholdMultiplier; } set { m_TrackedDeviceDragThresholdMultiplier = value; } } public InputActionReference point { get { return m_PointAction; } set { SwapAction(ref m_PointAction, value, m_ActionsHooked, m_OnPointDelegate); } } public InputActionReference scrollWheel { get { return m_ScrollWheelAction; } set { SwapAction(ref m_ScrollWheelAction, value, m_ActionsHooked, m_OnScrollWheelDelegate); } } public InputActionReference leftClick { get { return m_LeftClickAction; } set { SwapAction(ref m_LeftClickAction, value, m_ActionsHooked, m_OnLeftClickDelegate); } } public InputActionReference middleClick { get { return m_MiddleClickAction; } set { SwapAction(ref m_MiddleClickAction, value, m_ActionsHooked, m_OnMiddleClickDelegate); } } public InputActionReference rightClick { get { return m_RightClickAction; } set { SwapAction(ref m_RightClickAction, value, m_ActionsHooked, m_OnRightClickDelegate); } } public InputActionReference move { get { return m_MoveAction; } set { SwapAction(ref m_MoveAction, value, m_ActionsHooked, m_OnMoveDelegate); } } public InputActionReference submit { get { return m_SubmitAction; } set { SwapAction(ref m_SubmitAction, value, m_ActionsHooked, null); } } public InputActionReference cancel { get { return m_CancelAction; } set { SwapAction(ref m_CancelAction, value, m_ActionsHooked, null); } } public InputActionReference trackedDeviceOrientation { get { return m_TrackedDeviceOrientationAction; } set { SwapAction(ref m_TrackedDeviceOrientationAction, value, m_ActionsHooked, m_OnTrackedDeviceOrientationDelegate); } } public InputActionReference trackedDevicePosition { get { return m_TrackedDevicePositionAction; } set { SwapAction(ref m_TrackedDevicePositionAction, value, m_ActionsHooked, m_OnTrackedDevicePositionDelegate); } } [Obsolete("'trackedDeviceSelect' has been obsoleted; use 'leftClick' instead.", true)] public InputActionReference trackedDeviceSelect { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public InputActionAsset actionsAsset { get { return m_ActionsAsset; } set { if ((Object)(object)value != (Object)(object)m_ActionsAsset) { UnhookActions(); m_ActionsAsset = value; point = UpdateReferenceForNewAsset(point); move = UpdateReferenceForNewAsset(move); leftClick = UpdateReferenceForNewAsset(leftClick); rightClick = UpdateReferenceForNewAsset(rightClick); middleClick = UpdateReferenceForNewAsset(middleClick); scrollWheel = UpdateReferenceForNewAsset(scrollWheel); submit = UpdateReferenceForNewAsset(submit); cancel = UpdateReferenceForNewAsset(cancel); trackedDeviceOrientation = UpdateReferenceForNewAsset(trackedDeviceOrientation); trackedDevicePosition = UpdateReferenceForNewAsset(trackedDevicePosition); HookActions(); } } } public override void ActivateModule() { ((BaseInputModule)this).ActivateModule(); GameObject val = ((BaseInputModule)this).eventSystem.currentSelectedGameObject; if ((Object)(object)val == (Object)null) { val = ((BaseInputModule)this).eventSystem.firstSelectedGameObject; } ((BaseInputModule)this).eventSystem.SetSelectedGameObject(val, ((BaseInputModule)this).GetBaseEventData()); } public override bool IsPointerOverGameObject(int pointerOrTouchId) { if (InputSystem.isProcessingEvents) { Debug.LogWarning((object)"Calling IsPointerOverGameObject() from within event processing (such as from InputAction callbacks) will not work as expected; it will query UI state from the last frame"); } int num = -1; if (pointerOrTouchId < 0) { if (m_CurrentPointerId != -1) { num = m_CurrentPointerIndex; } else if (m_PointerStates.length > 0) { num = 0; } } else { num = GetPointerStateIndexFor(pointerOrTouchId); } if (num == -1) { return false; } return (Object)(object)((PointerEventData)m_PointerStates[num].eventData).pointerEnter != (Object)null; } public RaycastResult GetLastRaycastResult(int pointerOrTouchId) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) int pointerStateIndexFor = GetPointerStateIndexFor(pointerOrTouchId); if (pointerStateIndexFor == -1) { return default(RaycastResult); } return ((PointerEventData)m_PointerStates[pointerStateIndexFor].eventData).pointerCurrentRaycast; } private RaycastResult PerformRaycast(ExtendedPointerEventData eventData) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (eventData == null) { throw new ArgumentNullException("eventData"); } if (eventData.pointerType == UIPointerType.Tracked && TrackedDeviceRaycaster.s_Instances.length > 0) { for (int i = 0; i < TrackedDeviceRaycaster.s_Instances.length; i++) { TrackedDeviceRaycaster trackedDeviceRaycaster = TrackedDeviceRaycaster.s_Instances[i]; base.m_RaycastResultCache.Clear(); trackedDeviceRaycaster.PerformRaycast(eventData, base.m_RaycastResultCache); if (base.m_RaycastResultCache.Count > 0) { RaycastResult result = base.m_RaycastResultCache[0]; base.m_RaycastResultCache.Clear(); return result; } } return default(RaycastResult); } ((BaseInputModule)this).eventSystem.RaycastAll((PointerEventData)(object)eventData, base.m_RaycastResultCache); RaycastResult result2 = BaseInputModule.FindFirstRaycast(base.m_RaycastResultCache); base.m_RaycastResultCache.Clear(); return result2; } private void ProcessPointer(ref PointerModel state) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) ExtendedPointerEventData eventData = state.eventData; UIPointerType pointerType = eventData.pointerType; if (pointerType == UIPointerType.MouseOrPen && (int)Cursor.lockState == 1) { ((PointerEventData)eventData).position = ((m_CursorLockBehavior == CursorLockBehavior.OutsideScreen) ? new Vector2(-1f, -1f) : new Vector2((float)Screen.width / 2f, (float)Screen.height / 2f)); ((PointerEventData)eventData).delta = default(Vector2); } else if (pointerType == UIPointerType.Tracked) { Vector3 val = state.worldPosition; Quaternion val2 = state.worldOrientation; if ((Object)(object)m_XRTrackingOrigin != (Object)null) { val = m_XRTrackingOrigin.TransformPoint(val); val2 = m_XRTrackingOrigin.rotation * val2; } eventData.trackedDeviceOrientation = val2; eventData.trackedDevicePosition = val; } else { ((PointerEventData)eventData).delta = state.screenPosition - ((PointerEventData)eventData).position; ((PointerEventData)eventData).position = state.screenPosition; } ((AbstractEventData)eventData).Reset(); ((PointerEventData)eventData).pointerCurrentRaycast = PerformRaycast(eventData); if (pointerType == UIPointerType.Tracked) { RaycastResult pointerCurrentRaycast = ((PointerEventData)eventData).pointerCurrentRaycast; if (((RaycastResult)(ref pointerCurrentRaycast)).isValid) { Vector2 screenPosition = ((PointerEventData)eventData).pointerCurrentRaycast.screenPosition; ((PointerEventData)eventData).delta = screenPosition - ((PointerEventData)eventData).position; ((PointerEventData)eventData).position = ((PointerEventData)eventData).pointerCurrentRaycast.screenPosition; } } ((PointerEventData)eventData).button = (InputButton)0; state.leftButton.CopyPressStateTo((PointerEventData)(object)eventData); ProcessPointerMovement(ref state, eventData); if (state.changedThisFrame || (!((Object)(object)xrTrackingOrigin == (Object)null) && state.pointerType == UIPointerType.Tracked)) { ProcessPointerButton(ref state.leftButton, (PointerEventData)(object)eventData); ProcessPointerButtonDrag(ref state.leftButton, eventData); ProcessPointerScroll(ref state, (PointerEventData)(object)eventData); ((PointerEventData)eventData).button = (InputButton)1; state.rightButton.CopyPressStateTo((PointerEventData)(object)eventData); ProcessPointerButton(ref state.rightButton, (PointerEventData)(object)eventData); ProcessPointerButtonDrag(ref state.rightButton, eventData); ((PointerEventData)eventData).button = (InputButton)2; state.middleButton.CopyPressStateTo((PointerEventData)(object)eventData); ProcessPointerButton(ref state.middleButton, (PointerEventData)(object)eventData); ProcessPointerButtonDrag(ref state.middleButton, eventData); } } private bool PointerShouldIgnoreTransform(Transform t) { if (((BaseInputModule)this).eventSystem is MultiplayerEventSystem multiplayerEventSystem && (Object)(object)multiplayerEventSystem.playerRoot != (Object)null && !t.IsChildOf(multiplayerEventSystem.playerRoot.transform)) { return true; } return false; } private void ProcessPointerMovement(ref PointerModel pointer, ExtendedPointerEventData eventData) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) object obj; if (eventData.pointerType != UIPointerType.Touch || pointer.leftButton.isPressed || pointer.leftButton.wasReleasedThisFrame) { RaycastResult pointerCurrentRaycast = ((PointerEventData)eventData).pointerCurrentRaycast; obj = ((RaycastResult)(ref pointerCurrentRaycast)).gameObject; } else { obj = null; } GameObject currentPointerTarget = (GameObject)obj; ProcessPointerMovement(eventData, currentPointerTarget); } private void ProcessPointerMovement(ExtendedPointerEventData eventData, GameObject currentPointerTarget) { bool flag = ((PointerEventData)eventData).IsPointerMoving(); if (flag) { for (int i = 0; i < ((PointerEventData)eventData).hovered.Count; i++) { ExecuteEvents.Execute(((PointerEventData)eventData).hovered[i], (BaseEventData)(object)eventData, ExecuteEvents.pointerMoveHandler); } } if ((Object)(object)currentPointerTarget == (Object)null || (Object)(object)((PointerEventData)eventData).pointerEnter == (Object)null) { for (int j = 0; j < ((PointerEventData)eventData).hovered.Count; j++) { ExecuteEvents.Execute(((PointerEventData)eventData).hovered[j], (BaseEventData)(object)eventData, ExecuteEvents.pointerExitHandler); } ((PointerEventData)eventData).hovered.Clear(); if ((Object)(object)currentPointerTarget == (Object)null) { ((PointerEventData)eventData).pointerEnter = null; return; } } if ((Object)(object)((PointerEventData)eventData).pointerEnter == (Object)(object)currentPointerTarget && Object.op_Implicit((Object)(object)currentPointerTarget)) { return; } GameObject obj = BaseInputModule.FindCommonRoot(((PointerEventData)eventData).pointerEnter, currentPointerTarget); Transform val = ((obj != null) ? obj.transform : null); if ((Object)(object)((PointerEventData)eventData).pointerEnter != (Object)null) { Transform val2 = ((PointerEventData)eventData).pointerEnter.transform; while ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)val) { ExecuteEvents.Execute(((Component)val2).gameObject, (BaseEventData)(object)eventData, ExecuteEvents.pointerExitHandler); ((PointerEventData)eventData).hovered.Remove(((Component)val2).gameObject); val2 = val2.parent; } } ((PointerEventData)eventData).pointerEnter = currentPointerTarget; if (!((Object)(object)currentPointerTarget != (Object)null)) { return; } Transform val3 = currentPointerTarget.transform; while ((Object)(object)val3 != (Object)null && (Object)(object)val3 != (Object)(object)val && !PointerShouldIgnoreTransform(val3)) { ExecuteEvents.Execute(((Component)val3).gameObject, (BaseEventData)(object)eventData, ExecuteEvents.pointerEnterHandler); if (flag) { ExecuteEvents.Execute(((Component)val3).gameObject, (BaseEventData)(object)eventData, ExecuteEvents.pointerMoveHandler); } ((PointerEventData)eventData).hovered.Add(((Component)val3).gameObject); val3 = val3.parent; } } private void ProcessPointerButton(ref PointerModel.ButtonState button, PointerEventData eventData) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) RaycastResult pointerCurrentRaycast = eventData.pointerCurrentRaycast; GameObject gameObject = ((RaycastResult)(ref pointerCurrentRaycast)).gameObject; if ((Object)(object)gameObject != (Object)null && PointerShouldIgnoreTransform(gameObject.transform)) { return; } if (button.wasPressedThisFrame) { button.pressTime = InputRuntime.s_Instance.unscaledGameTime; eventData.delta = Vector2.zero; eventData.dragging = false; eventData.pressPosition = eventData.position; eventData.pointerPressRaycast = eventData.pointerCurrentRaycast; eventData.eligibleForClick = true; eventData.useDragThreshold = true; GameObject eventHandler = ExecuteEvents.GetEventHandler(gameObject); if ((Object)(object)eventHandler != (Object)(object)((BaseInputModule)this).eventSystem.currentSelectedGameObject && ((Object)(object)eventHandler != (Object)null || m_DeselectOnBackgroundClick)) { ((BaseInputModule)this).eventSystem.SetSelectedGameObject((GameObject)null, (BaseEventData)(object)eventData); } GameObject val = ExecuteEvents.ExecuteHierarchy(gameObject, (BaseEventData)(object)eventData, ExecuteEvents.pointerDownHandler); if ((Object)(object)val == (Object)null) { val = ExecuteEvents.GetEventHandler(gameObject); } button.clickedOnSameGameObject = (Object)(object)val == (Object)(object)eventData.lastPress && button.pressTime - eventData.clickTime <= 0.3f; if (eventData.clickCount > 0 && !button.clickedOnSameGameObject) { eventData.clickCount = 0; eventData.clickTime = 0f; } eventData.pointerPress = val; eventData.rawPointerPress = gameObject; eventData.pointerDrag = ExecuteEvents.GetEventHandler(gameObject); if ((Object)(object)eventData.pointerDrag != (Object)null) { ExecuteEvents.Execute(eventData.pointerDrag, (BaseEventData)(object)eventData, ExecuteEvents.initializePotentialDrag); } } if (button.wasReleasedThisFrame) { GameObject eventHandler2 = ExecuteEvents.GetEventHandler(gameObject); int num; if ((Object)(object)eventData.pointerPress == (Object)(object)eventHandler2) { num = (eventData.eligibleForClick ? 1 : 0); if (num != 0) { if (button.clickedOnSameGameObject) { int clickCount = eventData.clickCount + 1; eventData.clickCount = clickCount; } else { eventData.clickCount = 1; } eventData.clickTime = InputRuntime.s_Instance.unscaledGameTime; } } else { num = 0; } ExecuteEvents.Execute(eventData.pointerPress, (BaseEventData)(object)eventData, ExecuteEvents.pointerUpHandler); if (num != 0) { ExecuteEvents.Execute(eventData.pointerPress, (BaseEventData)(object)eventData, ExecuteEvents.pointerClickHandler); } else if (eventData.dragging && (Object)(object)eventData.pointerDrag != (Object)null) { ExecuteEvents.ExecuteHierarchy(gameObject, (BaseEventData)(object)eventData, ExecuteEvents.dropHandler); } eventData.eligibleForClick = false; eventData.pointerPress = null; eventData.rawPointerPress = null; if (eventData.dragging && (Object)(object)eventData.pointerDrag != (Object)null) { ExecuteEvents.Execute(eventData.pointerDrag, (BaseEventData)(object)eventData, ExecuteEvents.endDragHandler); } eventData.dragging = false; eventData.pointerDrag = null; button.ignoreNextClick = false; } button.CopyPressStateFrom(eventData); } private void ProcessPointerButtonDrag(ref PointerModel.ButtonState button, ExtendedPointerEventData eventData) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) if (!((PointerEventData)eventData).IsPointerMoving() || (eventData.pointerType == UIPointerType.MouseOrPen && (int)Cursor.lockState == 1) || (Object)(object)((PointerEventData)eventData).pointerDrag == (Object)null) { return; } if (!((PointerEventData)eventData).dragging) { if (((PointerEventData)eventData).useDragThreshold) { Vector2 val = ((PointerEventData)eventData).pressPosition - ((PointerEventData)eventData).position; if (!((double)((Vector2)(ref val)).sqrMagnitude >= (double)((BaseInputModule)this).eventSystem.pixelDragThreshold * (double)((BaseInputModule)this).eventSystem.pixelDragThreshold * (double)((eventData.pointerType == UIPointerType.Tracked) ? m_TrackedDeviceDragThresholdMultiplier : 1f))) { goto IL_009e; } } ExecuteEvents.Execute(((PointerEventData)eventData).pointerDrag, (BaseEventData)(object)eventData, ExecuteEvents.beginDragHandler); ((PointerEventData)eventData).dragging = true; } goto IL_009e; IL_009e: if (((PointerEventData)eventData).dragging) { if ((Object)(object)((PointerEventData)eventData).pointerPress != (Object)(object)((PointerEventData)eventData).pointerDrag) { ExecuteEvents.Execute(((PointerEventData)eventData).pointerPress, (BaseEventData)(object)eventData, ExecuteEvents.pointerUpHandler); ((PointerEventData)eventData).eligibleForClick = false; ((PointerEventData)eventData).pointerPress = null; ((PointerEventData)eventData).rawPointerPress = null; } ExecuteEvents.Execute(((PointerEventData)eventData).pointerDrag, (BaseEventData)(object)eventData, ExecuteEvents.dragHandler); button.CopyPressStateFrom((PointerEventData)(object)eventData); } } private static void ProcessPointerScroll(ref PointerModel pointer, PointerEventData eventData) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) Vector2 scrollDelta = pointer.scrollDelta; if (!Mathf.Approximately(((Vector2)(ref scrollDelta)).sqrMagnitude, 0f)) { eventData.scrollDelta = scrollDelta; ExecuteEvents.ExecuteHierarchy(ExecuteEvents.GetEventHandler(eventData.pointerEnter), (BaseEventData)(object)eventData, ExecuteEvents.scrollHandler); } } internal void ProcessNavigation(ref NavigationModel navigationState) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Invalid comparison between Unknown and I4 //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) bool flag = false; if ((Object)(object)((BaseInputModule)this).eventSystem.currentSelectedGameObject != (Object)null) { BaseEventData baseEventData = ((BaseInputModule)this).GetBaseEventData(); ExecuteEvents.Execute(((BaseInputModule)this).eventSystem.currentSelectedGameObject, baseEventData, ExecuteEvents.updateSelectedHandler); flag = ((AbstractEventData)baseEventData).used; } if (!((BaseInputModule)this).eventSystem.sendNavigationEvents) { return; } Vector2 val = navigationState.move; if (!flag && (!Mathf.Approximately(val.x, 0f) || !Mathf.Approximately(val.y, 0f))) { float unscaledGameTime = InputRuntime.s_Instance.unscaledGameTime; Vector2 val2 = navigationState.move; MoveDirection val3 = (MoveDirection)4; if (((Vector2)(ref val2)).sqrMagnitude > 0f) { val3 = ((!(Mathf.Abs(val2.x) > Mathf.Abs(val2.y))) ? ((MoveDirection)((val2.y > 0f) ? 1 : 3)) : ((MoveDirection)((val2.x > 0f) ? 2 : 0))); } if (val3 != m_NavigationState.lastMoveDirection) { m_NavigationState.consecutiveMoveCount = 0; } if ((int)val3 != 4) { bool flag2 = true; if (m_NavigationState.consecutiveMoveCount != 0) { flag2 = ((m_NavigationState.consecutiveMoveCount <= 1) ? (unscaledGameTime > m_NavigationState.lastMoveTime + moveRepeatDelay) : (unscaledGameTime > m_NavigationState.lastMoveTime + moveRepeatRate)); } if (flag2) { AxisEventData val4 = m_NavigationState.eventData; if (val4 == null) { val4 = (AxisEventData)(object)new ExtendedAxisEventData(((BaseInputModule)this).eventSystem); m_NavigationState.eventData = val4; } ((AbstractEventData)val4).Reset(); val4.moveVector = val2; val4.moveDir = val3; if (IsMoveAllowed(val4)) { ExecuteEvents.Execute(((BaseInputModule)this).eventSystem.currentSelectedGameObject, (BaseEventData)(object)val4, ExecuteEvents.moveHandler); flag = ((AbstractEventData)val4).used; m_NavigationState.consecutiveMoveCount++; m_NavigationState.lastMoveTime = unscaledGameTime; m_NavigationState.lastMoveDirection = val3; } } } else { m_NavigationState.consecutiveMoveCount = 0; } } else { m_NavigationState.consecutiveMoveCount = 0; } if (!flag && (Object)(object)((BaseInputModule)this).eventSystem.currentSelectedGameObject != (Object)null) { InputAction inputAction = m_SubmitAction?.action; InputAction inputAction2 = m_CancelAction?.action; BaseEventData baseEventData2 = ((BaseInputModule)this).GetBaseEventData(); if (inputAction2 != null && inputAction2.WasPressedThisFrame()) { ExecuteEvents.Execute(((BaseInputModule)this).eventSystem.currentSelectedGameObject, baseEventData2, ExecuteEvents.cancelHandler); } if (!((AbstractEventData)baseEventData2).used && inputAction != null && inputAction.WasPressedThisFrame()) { ExecuteEvents.Execute(((BaseInputModule)this).eventSystem.currentSelectedGameObject, baseEventData2, ExecuteEvents.submitHandler); } } } private bool IsMoveAllowed(AxisEventData eventData) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected I4, but got Unknown if ((Object)(object)m_LocalMultiPlayerRoot == (Object)null) { return true; } if ((Object)(object)((BaseInputModule)this).eventSystem.currentSelectedGameObject == (Object)null) { return true; } Selectable component = ((BaseInputModule)this).eventSystem.currentSelectedGameObject.GetComponent(); if ((Object)(object)component == (Object)null) { return true; } Selectable val = null; MoveDirection moveDir = eventData.moveDir; switch ((int)moveDir) { case 2: val = component.FindSelectableOnRight(); break; case 1: val = component.FindSelectableOnUp(); break; case 0: val = component.FindSelectableOnLeft(); break; case 3: val = component.FindSelectableOnDown(); break; } if ((Object)(object)val == (Object)null) { return true; } return ((Component)val).transform.IsChildOf(m_LocalMultiPlayerRoot.transform); } private void SwapAction(ref InputActionReference property, InputActionReference newValue, bool actionsHooked, Action actionCallback) { if (!((Object)(object)property == (Object)(object)newValue) && (!((Object)(object)property != (Object)null) || !((Object)(object)newValue != (Object)null) || property.action != newValue.action)) { if ((Object)(object)property != (Object)null && actionCallback != null && actionsHooked) { property.action.performed -= actionCallback; property.action.canceled -= actionCallback; } bool flag = property?.action == null; bool flag2 = property?.action != null && property.action.enabled; TryDisableInputAction(property); property = newValue; if (newValue?.action != null && actionCallback != null && actionsHooked) { property.action.performed += actionCallback; property.action.canceled += actionCallback; } if (((Behaviour)this).isActiveAndEnabled && newValue?.action != null && (flag2 || flag)) { EnableInputAction(property); } } } public void AssignDefaultActions() { DefaultInputActions defaultInputActions = new DefaultInputActions(); actionsAsset = defaultInputActions.asset; cancel = InputActionReference.Create(defaultInputActions.UI.Cancel); submit = InputActionReference.Create(defaultInputActions.UI.Submit); move = InputActionReference.Create(defaultInputActions.UI.Navigate); leftClick = InputActionReference.Create(defaultInputActions.UI.Click); rightClick = InputActionReference.Create(defaultInputActions.UI.RightClick); middleClick = InputActionReference.Create(defaultInputActions.UI.MiddleClick); point = InputActionReference.Create(defaultInputActions.UI.Point); scrollWheel = InputActionReference.Create(defaultInputActions.UI.ScrollWheel); trackedDeviceOrientation = InputActionReference.Create(defaultInputActions.UI.TrackedDeviceOrientation); trackedDevicePosition = InputActionReference.Create(defaultInputActions.UI.TrackedDevicePosition); } public void UnassignActions() { actionsAsset = null; cancel = null; submit = null; move = null; leftClick = null; rightClick = null; middleClick = null; point = null; scrollWheel = null; trackedDeviceOrientation = null; trackedDevicePosition = null; } protected override void Awake() { ((UIBehaviour)this).Awake(); m_NavigationState.Reset(); } protected override void OnDestroy() { ((UIBehaviour)this).OnDestroy(); UnhookActions(); } protected override void OnEnable() { ((BaseInputModule)this).OnEnable(); if (m_OnControlsChangedDelegate == null) { m_OnControlsChangedDelegate = OnControlsChanged; } InputActionState.s_GlobalState.onActionControlsChanged.AddCallback(m_OnControlsChangedDelegate); if (HasNoActions()) { AssignDefaultActions(); } ResetPointers(); HookActions(); EnableAllActions(); } protected override void OnDisable() { ResetPointers(); InputActionState.s_GlobalState.onActionControlsChanged.RemoveCallback(m_OnControlsChangedDelegate); DisableAllActions(); UnhookActions(); ((BaseInputModule)this).OnDisable(); } private void ResetPointers() { int length = m_PointerStates.length; for (int i = 0; i < length; i++) { SendPointerExitEventsAndRemovePointer(0); } m_CurrentPointerId = -1; m_CurrentPointerIndex = -1; m_CurrentPointerType = UIPointerType.None; } private bool HasNoActions() { if ((Object)(object)m_ActionsAsset != (Object)null) { return false; } if (m_PointAction?.action == null && m_LeftClickAction?.action == null && m_RightClickAction?.action == null && m_MiddleClickAction?.action == null && m_SubmitAction?.action == null && m_CancelAction?.action == null && m_ScrollWheelAction?.action == null && m_TrackedDeviceOrientationAction?.action == null) { return m_TrackedDevicePositionAction?.action == null; } return false; } private void EnableAllActions() { EnableInputAction(m_PointAction); EnableInputAction(m_LeftClickAction); EnableInputAction(m_RightClickAction); EnableInputAction(m_MiddleClickAction); EnableInputAction(m_MoveAction); EnableInputAction(m_SubmitAction); EnableInputAction(m_CancelAction); EnableInputAction(m_ScrollWheelAction); EnableInputAction(m_TrackedDeviceOrientationAction); EnableInputAction(m_TrackedDevicePositionAction); } private void DisableAllActions() { TryDisableInputAction(m_PointAction, isComponentDisabling: true); TryDisableInputAction(m_LeftClickAction, isComponentDisabling: true); TryDisableInputAction(m_RightClickAction, isComponentDisabling: true); TryDisableInputAction(m_MiddleClickAction, isComponentDisabling: true); TryDisableInputAction(m_MoveAction, isComponentDisabling: true); TryDisableInputAction(m_SubmitAction, isComponentDisabling: true); TryDisableInputAction(m_CancelAction, isComponentDisabling: true); TryDisableInputAction(m_ScrollWheelAction, isComponentDisabling: true); TryDisableInputAction(m_TrackedDeviceOrientationAction, isComponentDisabling: true); TryDisableInputAction(m_TrackedDevicePositionAction, isComponentDisabling: true); } private void EnableInputAction(InputActionReference inputActionReference) { InputAction inputAction = inputActionReference?.action; if (inputAction != null) { if (s_InputActionReferenceCounts.TryGetValue(inputAction, out var value)) { value.refCount++; s_InputActionReferenceCounts[inputAction] = value; } else { value = new InputActionReferenceState { refCount = 1, enabledByInputModule = !inputAction.enabled }; s_InputActionReferenceCounts.Add(inputAction, value); } inputAction.Enable(); } } private void TryDisableInputAction(InputActionReference inputActionReference, bool isComponentDisabling = false) { InputAction inputAction = inputActionReference?.action; if (inputAction != null && (((Behaviour)this).isActiveAndEnabled || isComponentDisabling) && s_InputActionReferenceCounts.TryGetValue(inputAction, out var value)) { if (value.refCount - 1 == 0 && value.enabledByInputModule) { inputAction.Disable(); s_InputActionReferenceCounts.Remove(inputAction); } else { value.refCount--; s_InputActionReferenceCounts[inputAction] = value; } } } private int GetPointerStateIndexFor(int pointerOrTouchId) { if (pointerOrTouchId == m_CurrentPointerId) { return m_CurrentPointerIndex; } for (int i = 0; i < m_PointerIds.length; i++) { if (m_PointerIds[i] == pointerOrTouchId) { return i; } } for (int j = 0; j < m_PointerStates.length; j++) { ExtendedPointerEventData eventData = m_PointerStates[j].eventData; if (eventData.touchId == pointerOrTouchId || (eventData.touchId != 0 && eventData.device.deviceId == pointerOrTouchId)) { return j; } } return -1; } private ref PointerModel GetPointerStateForIndex(int index) { if (index == 0) { return ref m_PointerStates.firstValue; } return ref m_PointerStates.additionalValues[index - 1]; } private int GetDisplayIndexFor(InputControl control) { int result = 0; if (control.device is Pointer pointer) { result = pointer.displayIndex.ReadValue(); } return result; } private int GetPointerStateIndexFor(ref InputAction.CallbackContext context) { if (CheckForRemovedDevice(ref context)) { return -1; } InputActionPhase phase = context.phase; return GetPointerStateIndexFor(context.control, phase != InputActionPhase.Canceled); } private int GetPointerStateIndexFor(InputControl control, bool createIfNotExists = true) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) InputDevice device = control.device; InputControl parent = control.parent; int num = m_PointerTouchControls.IndexOfReference(parent); if (num != -1) { m_CurrentPointerId = m_PointerIds[num]; m_CurrentPointerIndex = num; m_CurrentPointerType = UIPointerType.Touch; return num; } int num2 = device.deviceId; int num3 = 0; Vector2 screenPosition = Vector2.zero; if (parent is TouchControl touchControl) { num3 = touchControl.touchId.value; screenPosition = touchControl.position.value; } else if (parent is Touchscreen touchscreen) { num3 = touchscreen.primaryTouch.touchId.value; screenPosition = touchscreen.primaryTouch.position.value; } int displayIndexFor = GetDisplayIndexFor(control); if (num3 != 0) { num2 = ExtendedPointerEventData.MakePointerIdForTouch(num2, num3); } if (m_CurrentPointerId == num2) { return m_CurrentPointerIndex; } if (num3 == 0) { for (int i = 0; i < m_PointerIds.length; i++) { if (m_PointerIds[i] == num2) { m_CurrentPointerId = num2; m_CurrentPointerIndex = i; m_CurrentPointerType = m_PointerStates[i].pointerType; return i; } } } if (!createIfNotExists) { return -1; } UIPointerType uIPointerType = UIPointerType.None; if (num3 != 0) { uIPointerType = UIPointerType.Touch; } else if (HaveControlForDevice(device, point)) { uIPointerType = UIPointerType.MouseOrPen; } else if (HaveControlForDevice(device, trackedDevicePosition)) { uIPointerType = UIPointerType.Tracked; } if ((m_PointerBehavior == UIPointerBehavior.SingleUnifiedPointer && uIPointerType != UIPointerType.None) || (m_PointerBehavior == UIPointerBehavior.SingleMouseOrPenButMultiTouchAndTrack && uIPointerType == UIPointerType.MouseOrPen)) { if (m_CurrentPointerIndex == -1) { m_CurrentPointerIndex = AllocatePointer(num2, displayIndexFor, num3, uIPointerType, control, device, (num3 != 0) ? parent : null); } else { ExtendedPointerEventData eventData = GetPointerStateForIndex(m_CurrentPointerIndex).eventData; eventData.control = control; eventData.device = device; eventData.pointerType = uIPointerType; ((PointerEventData)eventData).pointerId = num2; eventData.touchId = num3; eventData.trackedDeviceOrientation = default(Quaternion); eventData.trackedDevicePosition = default(Vector3); } if (uIPointerType == UIPointerType.Touch) { GetPointerStateForIndex(m_CurrentPointerIndex).screenPosition = screenPosition; } m_CurrentPointerId = num2; m_CurrentPointerType = uIPointerType; return m_CurrentPointerIndex; } int num4 = -1; if (uIPointerType != UIPointerType.None) { num4 = AllocatePointer(num2, displayIndexFor, num3, uIPointerType, control, device, (num3 != 0) ? parent : null); } else { if (m_CurrentPointerId != -1) { return m_CurrentPointerIndex; } ReadOnlyArray? readOnlyArray = point?.action?.controls; InputDevice inputDevice = ((readOnlyArray.HasValue && readOnlyArray.Value.Count > 0) ? readOnlyArray.Value[0].device : null); if (inputDevice != null && !(inputDevice is Touchscreen)) { num4 = AllocatePointer(inputDevice.deviceId, displayIndexFor, 0, UIPointerType.MouseOrPen, readOnlyArray.Value[0], inputDevice); } else { ReadOnlyArray? readOnlyArray2 = trackedDevicePosition?.action?.controls; InputDevice inputDevice2 = ((readOnlyArray2.HasValue && readOnlyArray2.Value.Count > 0) ? readOnlyArray2.Value[0].device : null); num4 = ((inputDevice2 == null) ? AllocatePointer(num2, displayIndexFor, 0, UIPointerType.None, control, device) : AllocatePointer(inputDevice2.deviceId, displayIndexFor, 0, UIPointerType.Tracked, readOnlyArray2.Value[0], inputDevice2)); } } if (uIPointerType == UIPointerType.Touch) { GetPointerStateForIndex(num4).screenPosition = screenPosition; } m_CurrentPointerId = num2; m_CurrentPointerIndex = num4; m_CurrentPointerType = uIPointerType; return num4; } private int AllocatePointer(int pointerId, int displayIndex, int touchId, UIPointerType pointerType, InputControl control, InputDevice device, InputControl touchControl = null) { ExtendedPointerEventData extendedPointerEventData = null; if (m_PointerStates.Capacity > m_PointerStates.length) { extendedPointerEventData = ((m_PointerStates.length != 0) ? m_PointerStates.additionalValues[m_PointerStates.length - 1].eventData : m_PointerStates.firstValue.eventData); } if (extendedPointerEventData == null) { extendedPointerEventData = new ExtendedPointerEventData(((BaseInputModule)this).eventSystem); } ((PointerEventData)extendedPointerEventData).pointerId = pointerId; extendedPointerEventData.touchId = touchId; extendedPointerEventData.pointerType = pointerType; extendedPointerEventData.control = control; extendedPointerEventData.device = device; m_PointerIds.AppendWithCapacity(pointerId); m_PointerTouchControls.AppendWithCapacity(touchControl); return m_PointerStates.AppendWithCapacity(new PointerModel(extendedPointerEventData)); } private void SendPointerExitEventsAndRemovePointer(int index) { ExtendedPointerEventData eventData = m_PointerStates[index].eventData; if ((Object)(object)((PointerEventData)eventData).pointerEnter != (Object)null) { ProcessPointerMovement(eventData, null); } RemovePointerAtIndex(index); } private void RemovePointerAtIndex(int index) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) ExtendedPointerEventData eventData = m_PointerStates[index].eventData; if (index == m_CurrentPointerIndex) { m_CurrentPointerId = -1; m_CurrentPointerIndex = -1; m_CurrentPointerType = UIPointerType.None; } else if (m_CurrentPointerIndex == m_PointerIds.length - 1) { m_CurrentPointerIndex = index; } m_PointerIds.RemoveAtByMovingTailWithCapacity(index); m_PointerTouchControls.RemoveAtByMovingTailWithCapacity(index); m_PointerStates.RemoveAtByMovingTailWithCapacity(index); ((PointerEventData)eventData).hovered.Clear(); eventData.device = null; ((PointerEventData)eventData).pointerCurrentRaycast = default(RaycastResult); ((PointerEventData)eventData).pointerPressRaycast = default(RaycastResult); ((PointerEventData)eventData).pointerPress = null; ((PointerEventData)eventData).pointerPress = null; ((PointerEventData)eventData).pointerDrag = null; ((PointerEventData)eventData).pointerEnter = null; ((PointerEventData)eventData).rawPointerPress = null; if (m_PointerStates.length == 0) { m_PointerStates.firstValue.eventData = eventData; } else { m_PointerStates.additionalValues[m_PointerStates.length - 1].eventData = eventData; } } private void PurgeStalePointers() { for (int i = 0; i < m_PointerStates.length; i++) { InputDevice device = GetPointerStateForIndex(i).eventData.device; if (!device.added || (!HaveControlForDevice(device, point) && !HaveControlForDevice(device, trackedDevicePosition) && !HaveControlForDevice(device, trackedDeviceOrientation))) { SendPointerExitEventsAndRemovePointer(i); i--; } } m_NeedToPurgeStalePointers = false; } private static bool HaveControlForDevice(InputDevice device, InputActionReference actionReference) { InputAction inputAction = actionReference?.action; if (inputAction == null) { return false; } ReadOnlyArray controls = inputAction.controls; for (int i = 0; i < controls.Count; i++) { if (controls[i].device == device) { return true; } } return false; } private void OnPointCallback(InputAction.CallbackContext context) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (!CheckForRemovedDevice(ref context) && !context.canceled) { int pointerStateIndexFor = GetPointerStateIndexFor(context.control); if (pointerStateIndexFor != -1) { GetPointerStateForIndex(pointerStateIndexFor).screenPosition = context.ReadValue(); } } } private bool IgnoreNextClick(ref InputAction.CallbackContext context, bool wasPressed) { if (explictlyIgnoreFocus) { return false; } return context.canceled && !InputRuntime.s_Instance.isPlayerFocused && !context.control.device.canRunInBackground && wasPressed; } private void OnLeftClickCallback(InputAction.CallbackContext context) { int pointerStateIndexFor = GetPointerStateIndexFor(ref context); if (pointerStateIndexFor != -1) { ref PointerModel pointerStateForIndex = ref GetPointerStateForIndex(pointerStateIndexFor); bool isPressed = pointerStateForIndex.leftButton.isPressed; pointerStateForIndex.leftButton.isPressed = context.ReadValueAsButton(); pointerStateForIndex.changedThisFrame = true; if (IgnoreNextClick(ref context, isPressed)) { pointerStateForIndex.leftButton.ignoreNextClick = true; } } } private void OnRightClickCallback(InputAction.CallbackContext context) { int pointerStateIndexFor = GetPointerStateIndexFor(ref context); if (pointerStateIndexFor != -1) { ref PointerModel pointerStateForIndex = ref GetPointerStateForIndex(pointerStateIndexFor); bool isPressed = pointerStateForIndex.rightButton.isPressed; pointerStateForIndex.rightButton.isPressed = context.ReadValueAsButton(); pointerStateForIndex.changedThisFrame = true; if (IgnoreNextClick(ref context, isPressed)) { pointerStateForIndex.rightButton.ignoreNextClick = true; } } } private void OnMiddleClickCallback(InputAction.CallbackContext context) { int pointerStateIndexFor = GetPointerStateIndexFor(ref context); if (pointerStateIndexFor != -1) { ref PointerModel pointerStateForIndex = ref GetPointerStateForIndex(pointerStateIndexFor); bool isPressed = pointerStateForIndex.middleButton.isPressed; pointerStateForIndex.middleButton.isPressed = context.ReadValueAsButton(); pointerStateForIndex.changedThisFrame = true; if (IgnoreNextClick(ref context, isPressed)) { pointerStateForIndex.middleButton.ignoreNextClick = true; } } } private bool CheckForRemovedDevice(ref InputAction.CallbackContext context) { if (context.canceled && !context.control.device.added) { m_NeedToPurgeStalePointers = true; return true; } return false; } private void OnScrollCallback(InputAction.CallbackContext context) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) int pointerStateIndexFor = GetPointerStateIndexFor(ref context); if (pointerStateIndexFor != -1) { GetPointerStateForIndex(pointerStateIndexFor).scrollDelta = context.ReadValue() * 0.05f; } } private void OnMoveCallback(InputAction.CallbackContext context) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) m_NavigationState.move = context.ReadValue(); } private void OnTrackedDeviceOrientationCallback(InputAction.CallbackContext context) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) int pointerStateIndexFor = GetPointerStateIndexFor(ref context); if (pointerStateIndexFor != -1) { GetPointerStateForIndex(pointerStateIndexFor).worldOrientation = context.ReadValue(); } } private void OnTrackedDevicePositionCallback(InputAction.CallbackContext context) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) int pointerStateIndexFor = GetPointerStateIndexFor(ref context); if (pointerStateIndexFor != -1) { GetPointerStateForIndex(pointerStateIndexFor).worldPosition = context.ReadValue(); } } private void OnControlsChanged(object obj) { m_NeedToPurgeStalePointers = true; } private void FilterPointerStatesByType() { UIPointerType uIPointerType = UIPointerType.None; for (int i = 0; i < m_PointerStates.length; i++) { ref PointerModel pointerStateForIndex = ref GetPointerStateForIndex(i); pointerStateForIndex.eventData.ReadDeviceState(); pointerStateForIndex.CopyTouchOrPenStateFrom((PointerEventData)(object)pointerStateForIndex.eventData); if (pointerStateForIndex.changedThisFrame && uIPointerType == UIPointerType.None) { uIPointerType = pointerStateForIndex.pointerType; } } if (m_PointerBehavior != UIPointerBehavior.SingleMouseOrPenButMultiTouchAndTrack) { return; } switch (uIPointerType) { case UIPointerType.MouseOrPen: { for (int j = 0; j < m_PointerStates.length; j++) { if (m_PointerStates[j].pointerType != UIPointerType.MouseOrPen) { SendPointerExitEventsAndRemovePointer(j); j--; } } return; } case UIPointerType.None: return; } for (int k = 0; k < m_PointerStates.length; k++) { if (m_PointerStates[k].pointerType == UIPointerType.MouseOrPen) { SendPointerExitEventsAndRemovePointer(k); k--; } } } public override void Process() { if (m_NeedToPurgeStalePointers) { PurgeStalePointers(); } if (!((BaseInputModule)this).eventSystem.isFocused && !shouldIgnoreFocus) { for (int i = 0; i < m_PointerStates.length; i++) { m_PointerStates[i].OnFrameFinished(); } return; } ProcessNavigation(ref m_NavigationState); FilterPointerStatesByType(); for (int j = 0; j < m_PointerStates.length; j++) { ref PointerModel pointerStateForIndex = ref GetPointerStateForIndex(j); ProcessPointer(ref pointerStateForIndex); if (pointerStateForIndex.pointerType == UIPointerType.Touch && !pointerStateForIndex.leftButton.isPressed && !pointerStateForIndex.leftButton.wasReleasedThisFrame) { RemovePointerAtIndex(j); j--; } else { pointerStateForIndex.OnFrameFinished(); } } } public override int ConvertUIToolkitPointerId(PointerEventData sourcePointerData) { if (m_PointerBehavior == UIPointerBehavior.SingleUnifiedPointer) { return PointerId.mousePointerId; } if (!(sourcePointerData is ExtendedPointerEventData extendedPointerEventData)) { return ((BaseInputModule)this).ConvertUIToolkitPointerId(sourcePointerData); } return extendedPointerEventData.uiToolkitPointerId; } private void HookActions() { if (!m_ActionsHooked) { if (m_OnPointDelegate == null) { m_OnPointDelegate = OnPointCallback; } if (m_OnLeftClickDelegate == null) { m_OnLeftClickDelegate = OnLeftClickCallback; } if (m_OnRightClickDelegate == null) { m_OnRightClickDelegate = OnRightClickCallback; } if (m_OnMiddleClickDelegate == null) { m_OnMiddleClickDelegate = OnMiddleClickCallback; } if (m_OnScrollWheelDelegate == null) { m_OnScrollWheelDelegate = OnScrollCallback; } if (m_OnMoveDelegate == null) { m_OnMoveDelegate = OnMoveCallback; } if (m_OnTrackedDeviceOrientationDelegate == null) { m_OnTrackedDeviceOrientationDelegate = OnTrackedDeviceOrientationCallback; } if (m_OnTrackedDevicePositionDelegate == null) { m_OnTrackedDevicePositionDelegate = OnTrackedDevicePositionCallback; } SetActionCallbacks(install: true); } } private void UnhookActions() { if (m_ActionsHooked) { SetActionCallbacks(install: false); } } private void SetActionCallbacks(bool install) { m_ActionsHooked = install; SetActionCallback(m_PointAction, m_OnPointDelegate, install); SetActionCallback(m_MoveAction, m_OnMoveDelegate, install); SetActionCallback(m_LeftClickAction, m_OnLeftClickDelegate, install); SetActionCallback(m_RightClickAction, m_OnRightClickDelegate, install); SetActionCallback(m_MiddleClickAction, m_OnMiddleClickDelegate, install); SetActionCallback(m_ScrollWheelAction, m_OnScrollWheelDelegate, install); SetActionCallback(m_TrackedDeviceOrientationAction, m_OnTrackedDeviceOrientationDelegate, install); SetActionCallback(m_TrackedDevicePositionAction, m_OnTrackedDevicePositionDelegate, install); } private static void SetActionCallback(InputActionReference actionReference, Action callback, bool install) { if ((!install && callback == null) || (Object)(object)actionReference == (Object)null) { return; } InputAction action = actionReference.action; if (action != null) { if (install) { action.performed += callback; action.canceled += callback; } else { action.performed -= callback; action.canceled -= callback; } } } private InputActionReference UpdateReferenceForNewAsset(InputActionReference actionReference) { InputAction inputAction = actionReference?.action; if (inputAction == null) { return null; } InputActionMap actionMap = inputAction.actionMap; InputActionMap inputActionMap = m_ActionsAsset?.FindActionMap(actionMap.name); if (inputActionMap == null) { return null; } InputAction inputAction2 = inputActionMap.FindAction(inputAction.name); if (inputAction2 == null) { return null; } return InputActionReference.Create(inputAction2); } } [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/UISupport.html#multiplayer-uis")] public class MultiplayerEventSystem : EventSystem { [Tooltip("If set, only process mouse and navigation events for any game objects which are children of this game object.")] [SerializeField] private GameObject m_PlayerRoot; public GameObject playerRoot { get { return m_PlayerRoot; } set { m_PlayerRoot = value; InitializePlayerRoot(); } } protected override void OnEnable() { ((EventSystem)this).OnEnable(); InitializePlayerRoot(); } protected override void OnDisable() { ((EventSystem)this).OnDisable(); } private void InitializePlayerRoot() { if (!((Object)(object)m_PlayerRoot == (Object)null)) { InputSystemUIInputModule component = ((Component)this).GetComponent(); if ((Object)(object)component != (Object)null) { component.localMultiPlayerRoot = m_PlayerRoot; } } } protected override void Update() { EventSystem current = EventSystem.current; EventSystem.current = (EventSystem)(object)this; try { ((EventSystem)this).Update(); } finally { EventSystem.current = current; } } } internal struct NavigationModel { public Vector2 move; public int consecutiveMoveCount; public MoveDirection lastMoveDirection; public float lastMoveTime; public AxisEventData eventData; public void Reset() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) move = Vector2.zero; } } internal struct PointerModel { public struct ButtonState { private bool m_IsPressed; private FramePressState m_FramePressState; private float m_PressTime; private RaycastResult m_PressRaycast; private GameObject m_PressObject; private GameObject m_RawPressObject; private GameObject m_LastPressObject; private GameObject m_DragObject; private Vector2 m_PressPosition; private float m_ClickTime; private int m_ClickCount; private bool m_Dragging; private bool m_ClickedOnSameGameObject; private bool m_IgnoreNextClick; public bool isPressed { get { return m_IsPressed; } set { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (m_IsPressed != value) { m_IsPressed = value; if ((int)m_FramePressState == 3 && value) { m_FramePressState = (FramePressState)0; } else if ((int)m_FramePressState == 3 && !value) { m_FramePressState = (FramePressState)1; } else if ((int)m_FramePressState == 0 && !value) { m_FramePressState = (FramePressState)2; } } } } public bool ignoreNextClick { get { return m_IgnoreNextClick; } set { m_IgnoreNextClick = value; } } public float pressTime { get { return m_PressTime; } set { m_PressTime = value; } } public bool clickedOnSameGameObject { get { return m_ClickedOnSameGameObject; } set { m_ClickedOnSameGameObject = value; } } public bool wasPressedThisFrame { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 if ((int)m_FramePressState != 0) { return (int)m_FramePressState == 2; } return true; } } public bool wasReleasedThisFrame { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 if ((int)m_FramePressState != 1) { return (int)m_FramePressState == 2; } return true; } } public void CopyPressStateTo(PointerEventData eventData) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) eventData.pointerPressRaycast = m_PressRaycast; eventData.pressPosition = m_PressPosition; eventData.clickCount = m_ClickCount; eventData.clickTime = m_ClickTime; eventData.pointerPress = m_LastPressObject; eventData.pointerPress = m_PressObject; eventData.rawPointerPress = m_RawPressObject; eventData.pointerDrag = m_DragObject; eventData.dragging = m_Dragging; if (ignoreNextClick) { eventData.eligibleForClick = false; } } public void CopyPressStateFrom(PointerEventData eventData) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) m_PressRaycast = eventData.pointerPressRaycast; m_PressObject = eventData.pointerPress; m_RawPressObject = eventData.rawPointerPress; m_LastPressObject = eventData.lastPress; m_PressPosition = eventData.pressPosition; m_ClickTime = eventData.clickTime; m_ClickCount = eventData.clickCount; m_DragObject = eventData.pointerDrag; m_Dragging = eventData.dragging; } public void OnEndFrame() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_FramePressState = (FramePressState)3; } } public bool changedThisFrame; public ButtonState leftButton; public ButtonState rightButton; public ButtonState middleButton; public ExtendedPointerEventData eventData; private Vector2 m_ScreenPosition; private Vector2 m_ScrollDelta; private Vector3 m_WorldPosition; private Quaternion m_WorldOrientation; private float m_Pressure; private float m_AzimuthAngle; private float m_AltitudeAngle; private float m_Twist; private Vector2 m_Radius; public UIPointerType pointerType => eventData.pointerType; public Vector2 screenPosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_ScreenPosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (m_ScreenPosition != value) { m_ScreenPosition = value; changedThisFrame = true; } } } public Vector3 worldPosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_WorldPosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (m_WorldPosition != value) { m_WorldPosition = value; changedThisFrame = true; } } } public Quaternion worldOrientation { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_WorldOrientation; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (m_WorldOrientation != value) { m_WorldOrientation = value; changedThisFrame = true; } } } public Vector2 scrollDelta { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_ScrollDelta; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (m_ScrollDelta != value) { changedThisFrame = true; m_ScrollDelta = value; } } } public float pressure { get { return m_Pressure; } set { if (m_Pressure != value) { changedThisFrame = true; m_Pressure = value; } } } public float azimuthAngle { get { return m_AzimuthAngle; } set { if (m_AzimuthAngle != value) { changedThisFrame = true; m_AzimuthAngle = value; } } } public float altitudeAngle { get { return m_AltitudeAngle; } set { if (m_AltitudeAngle != value) { changedThisFrame = true; m_AltitudeAngle = value; } } } public float twist { get { return m_Twist; } set { if (m_Twist != value) { changedThisFrame = true; m_Twist = value; } } } public Vector2 radius { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_Radius; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (m_Radius != value) { changedThisFrame = true; m_Radius = value; } } } public PointerModel(ExtendedPointerEventData eventData) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) this.eventData = eventData; changedThisFrame = false; leftButton = default(ButtonState); leftButton.OnEndFrame(); rightButton = default(ButtonState); rightButton.OnEndFrame(); middleButton = default(ButtonState); middleButton.OnEndFrame(); m_ScreenPosition = default(Vector2); m_ScrollDelta = default(Vector2); m_WorldOrientation = default(Quaternion); m_WorldPosition = default(Vector3); m_Pressure = 0f; m_AzimuthAngle = 0f; m_AltitudeAngle = 0f; m_Twist = 0f; m_Radius = default(Vector2); } public void OnFrameFinished() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) changedThisFrame = false; scrollDelta = default(Vector2); leftButton.OnEndFrame(); rightButton.OnEndFrame(); middleButton.OnEndFrame(); } public void CopyTouchOrPenStateFrom(PointerEventData eventData) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) pressure = eventData.pressure; azimuthAngle = eventData.azimuthAngle; altitudeAngle = eventData.altitudeAngle; twist = eventData.twist; radius = eventData.radius; } } [AddComponentMenu("Event/Tracked Device Raycaster")] [RequireComponent(typeof(Canvas))] public class TrackedDeviceRaycaster : BaseRaycaster { private struct RaycastHitData { public Graphic graphic { get; } public Vector3 worldHitPosition { get; } public Vector2 screenPosition { get; } public float distance { get; } public RaycastHitData(Graphic graphic, Vector3 worldHitPosition, Vector2 screenPosition, float distance) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) this.graphic = graphic; this.worldHitPosition = worldHitPosition; this.screenPosition = screenPosition; this.distance = distance; } } [NonSerialized] private List m_RaycastResultsCache = new List(); internal static InlinedArray s_Instances; private static readonly List s_SortedGraphics = new List(); [FormerlySerializedAs("ignoreReversedGraphics")] [SerializeField] private bool m_IgnoreReversedGraphics; [FormerlySerializedAs("checkFor2DOcclusion")] [SerializeField] private bool m_CheckFor2DOcclusion; [FormerlySerializedAs("checkFor3DOcclusion")] [SerializeField] private bool m_CheckFor3DOcclusion; [Tooltip("Maximum distance (in 3D world space) that rays are traced to find a hit.")] [SerializeField] private float m_MaxDistance = 1000f; [SerializeField] private LayerMask m_BlockingMask; [NonSerialized] private Canvas m_Canvas; public override Camera eventCamera { get { Canvas val = canvas; if (!((Object)(object)val != (Object)null)) { return null; } return val.worldCamera; } } public LayerMask blockingMask { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_BlockingMask; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_BlockingMask = value; } } public bool checkFor3DOcclusion { get { return m_CheckFor3DOcclusion; } set { m_CheckFor3DOcclusion = value; } } public bool checkFor2DOcclusion { get { return m_CheckFor2DOcclusion; } set { m_CheckFor2DOcclusion = value; } } public bool ignoreReversedGraphics { get { return m_IgnoreReversedGraphics; } set { m_IgnoreReversedGraphics = value; } } public float maxDistance { get { return m_MaxDistance; } set { m_MaxDistance = value; } } private Canvas canvas { get { if ((Object)(object)m_Canvas != (Object)null) { return m_Canvas; } m_Canvas = ((Component)this).GetComponent(); return m_Canvas; } } protected override void OnEnable() { ((BaseRaycaster)this).OnEnable(); s_Instances.AppendWithCapacity(this); } protected override void OnDisable() { int num = s_Instances.IndexOfReference(this); if (num != -1) { s_Instances.RemoveAtByMovingTailWithCapacity(num); } ((BaseRaycaster)this).OnDisable(); } public override void Raycast(PointerEventData eventData, List resultAppendList) { if (eventData is ExtendedPointerEventData { pointerType: UIPointerType.Tracked } extendedPointerEventData) { PerformRaycast(extendedPointerEventData, resultAppendList); } } internal void PerformRaycast(ExtendedPointerEventData eventData, List resultAppendList) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)canvas == (Object)null || (Object)(object)((BaseRaycaster)this).eventCamera == (Object)null) { return; } Ray val = default(Ray); ((Ray)(ref val))..ctor(eventData.trackedDevicePosition, eventData.trackedDeviceOrientation * Vector3.forward); float distance = m_MaxDistance; RaycastHit val2 = default(RaycastHit); if (m_CheckFor3DOcclusion && Physics.Raycast(val, ref val2, distance, LayerMask.op_Implicit(m_BlockingMask))) { distance = ((RaycastHit)(ref val2)).distance; } if (m_CheckFor2DOcclusion) { float num = distance; RaycastHit2D rayIntersection = Physics2D.GetRayIntersection(val, num, LayerMask.op_Implicit(m_BlockingMask)); if ((Object)(object)((RaycastHit2D)(ref rayIntersection)).collider != (Object)null) { distance = ((RaycastHit2D)(ref rayIntersection)).distance; } } m_RaycastResultsCache.Clear(); SortedRaycastGraphics(canvas, val, m_RaycastResultsCache); for (int i = 0; i < m_RaycastResultsCache.Count; i++) { bool flag = true; RaycastHitData raycastHitData = m_RaycastResultsCache[i]; GameObject gameObject = ((Component)raycastHitData.graphic).gameObject; if (m_IgnoreReversedGraphics) { Vector3 direction = ((Ray)(ref val)).direction; Vector3 val3 = gameObject.transform.rotation * Vector3.forward; flag = Vector3.Dot(direction, val3) > 0f; } if (flag & (raycastHitData.distance < distance)) { RaycastResult val4 = default(RaycastResult); ((RaycastResult)(ref val4)).gameObject = gameObject; val4.module = (BaseRaycaster)(object)this; val4.distance = raycastHitData.distance; val4.index = resultAppendList.Count; val4.depth = raycastHitData.graphic.depth; val4.worldPosition = raycastHitData.worldHitPosition; val4.screenPosition = raycastHitData.screenPosition; RaycastResult item = val4; resultAppendList.Add(item); } } } private void SortedRaycastGraphics(Canvas canvas, Ray ray, List results) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) IList graphicsForCanvas = GraphicRegistry.GetGraphicsForCanvas(canvas); s_SortedGraphics.Clear(); for (int i = 0; i < graphicsForCanvas.Count; i++) { Graphic val = graphicsForCanvas[i]; if (val.depth != -1 && RayIntersectsRectTransform(val.rectTransform, ray, out var worldPosition, out var distance)) { Vector2 val2 = Vector2.op_Implicit(((BaseRaycaster)this).eventCamera.WorldToScreenPoint(worldPosition)); if (val.Raycast(val2, ((BaseRaycaster)this).eventCamera)) { s_SortedGraphics.Add(new RaycastHitData(val, worldPosition, val2, distance)); } } } s_SortedGraphics.Sort((RaycastHitData g1, RaycastHitData g2) => g2.graphic.depth.CompareTo(g1.graphic.depth)); results.AddRange(s_SortedGraphics); } private static bool RayIntersectsRectTransform(RectTransform transform, Ray ray, out Vector3 worldPosition, out float distance) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[4]; transform.GetWorldCorners(array); Plane val = default(Plane); ((Plane)(ref val))..ctor(array[0], array[1], array[2]); float num = default(float); if (((Plane)(ref val)).Raycast(ray, ref num)) { Vector3 point = ((Ray)(ref ray)).GetPoint(num); Vector3 val2 = array[3] - array[0]; Vector3 val3 = array[1] - array[0]; float num2 = Vector3.Dot(point - array[0], val2); if (Vector3.Dot(point - array[0], val3) >= 0f && num2 >= 0f) { Vector3 val4 = array[1] - array[2]; Vector3 val5 = array[3] - array[2]; float num3 = Vector3.Dot(point - array[2], val4); float num4 = Vector3.Dot(point - array[2], val5); if (num3 >= 0f && num4 >= 0f) { worldPosition = point; distance = num; return true; } } } worldPosition = Vector3.zero; distance = 0f; return false; } } [AddComponentMenu("Input/Virtual Mouse")] [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/UISupport.html#virtual-mouse-cursor-control")] public class VirtualMouseInput : MonoBehaviour { public enum CursorMode { SoftwareCursor, HardwareCursorIfAvailable } [Header("Cursor")] [Tooltip("Whether the component should set the cursor position of the hardware mouse cursor, if one is available. If so, the software cursor pointed (to by 'Cursor Graphic') will be hidden.")] [SerializeField] private CursorMode m_CursorMode; [Tooltip("The graphic that represents the software cursor. This is hidden if a hardware cursor (see 'Cursor Mode') is used.")] [SerializeField] private Graphic m_CursorGraphic; [Tooltip("The transform for the software cursor. Will only be set if a software cursor is used (see 'Cursor Mode'). Moving the cursor updates the anchored position of the transform.")] [SerializeField] private RectTransform m_CursorTransform; [Header("Motion")] [Tooltip("Speed in pixels per second with which to move the cursor. Scaled by the input from 'Stick Action'.")] [SerializeField] private float m_CursorSpeed = 400f; [Tooltip("Scale factor to apply to 'Scroll Wheel Action' when setting the mouse 'scrollWheel' control.")] [SerializeField] private float m_ScrollSpeed = 45f; [Space(10f)] [Tooltip("Vector2 action that moves the cursor left/right (X) and up/down (Y) on screen.")] [SerializeField] private InputActionProperty m_StickAction; [Tooltip("Button action that triggers a left-click on the mouse.")] [SerializeField] private InputActionProperty m_LeftButtonAction; [Tooltip("Button action that triggers a middle-click on the mouse.")] [SerializeField] private InputActionProperty m_MiddleButtonAction; [Tooltip("Button action that triggers a right-click on the mouse.")] [SerializeField] private InputActionProperty m_RightButtonAction; [Tooltip("Button action that triggers a forward button (button #4) click on the mouse.")] [SerializeField] private InputActionProperty m_ForwardButtonAction; [Tooltip("Button action that triggers a back button (button #5) click on the mouse.")] [SerializeField] private InputActionProperty m_BackButtonAction; [Tooltip("Vector2 action that feeds into the mouse 'scrollWheel' action (scaled by 'Scroll Speed').")] [SerializeField] private InputActionProperty m_ScrollWheelAction; private Canvas m_Canvas; private Mouse m_VirtualMouse; private Mouse m_SystemMouse; private Action m_AfterInputUpdateDelegate; private Action m_ButtonActionTriggeredDelegate; private double m_LastTime; private Vector2 m_LastStickValue; public RectTransform cursorTransform { get { return m_CursorTransform; } set { m_CursorTransform = value; } } public float cursorSpeed { get { return m_CursorSpeed; } set { m_CursorSpeed = value; } } public CursorMode cursorMode { get { return m_CursorMode; } set { if (m_CursorMode != value) { if (m_CursorMode == CursorMode.HardwareCursorIfAvailable && m_SystemMouse != null) { InputSystem.EnableDevice(m_SystemMouse); m_SystemMouse = null; } m_CursorMode = value; if (m_CursorMode == CursorMode.HardwareCursorIfAvailable) { TryEnableHardwareCursor(); } else if ((Object)(object)m_CursorGraphic != (Object)null) { ((Behaviour)m_CursorGraphic).enabled = true; } } } } public Graphic cursorGraphic { get { return m_CursorGraphic; } set { m_CursorGraphic = value; TryFindCanvas(); } } public float scrollSpeed { get { return m_ScrollSpeed; } set { m_ScrollSpeed = value; } } public Mouse virtualMouse => m_VirtualMouse; public InputActionProperty stickAction { get { return m_StickAction; } set { SetAction(ref m_StickAction, value); } } public InputActionProperty leftButtonAction { get { return m_LeftButtonAction; } set { if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_LeftButtonAction, m_ButtonActionTriggeredDelegate, install: false); } SetAction(ref m_LeftButtonAction, value); if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_LeftButtonAction, m_ButtonActionTriggeredDelegate); } } } public InputActionProperty rightButtonAction { get { return m_RightButtonAction; } set { if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_RightButtonAction, m_ButtonActionTriggeredDelegate, install: false); } SetAction(ref m_RightButtonAction, value); if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_RightButtonAction, m_ButtonActionTriggeredDelegate); } } } public InputActionProperty middleButtonAction { get { return m_MiddleButtonAction; } set { if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_MiddleButtonAction, m_ButtonActionTriggeredDelegate, install: false); } SetAction(ref m_MiddleButtonAction, value); if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_MiddleButtonAction, m_ButtonActionTriggeredDelegate); } } } public InputActionProperty forwardButtonAction { get { return m_ForwardButtonAction; } set { if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_ForwardButtonAction, m_ButtonActionTriggeredDelegate, install: false); } SetAction(ref m_ForwardButtonAction, value); if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_ForwardButtonAction, m_ButtonActionTriggeredDelegate); } } } public InputActionProperty backButtonAction { get { return m_BackButtonAction; } set { if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_BackButtonAction, m_ButtonActionTriggeredDelegate, install: false); } SetAction(ref m_BackButtonAction, value); if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_BackButtonAction, m_ButtonActionTriggeredDelegate); } } } public InputActionProperty scrollWheelAction { get { return m_ScrollWheelAction; } set { SetAction(ref m_ScrollWheelAction, value); } } protected void OnEnable() { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) if (m_CursorMode == CursorMode.HardwareCursorIfAvailable) { TryEnableHardwareCursor(); } if (m_VirtualMouse == null) { m_VirtualMouse = (Mouse)InputSystem.AddDevice("VirtualMouse"); } else if (!m_VirtualMouse.added) { InputSystem.AddDevice(m_VirtualMouse); } if ((Object)(object)m_CursorTransform != (Object)null) { Vector2 anchoredPosition = m_CursorTransform.anchoredPosition; InputState.Change((InputControl)m_VirtualMouse.position, anchoredPosition, InputUpdateType.None, default(InputEventPtr)); m_SystemMouse?.WarpCursorPosition(anchoredPosition); } if (m_AfterInputUpdateDelegate == null) { m_AfterInputUpdateDelegate = OnAfterInputUpdate; } InputSystem.onAfterUpdate += m_AfterInputUpdateDelegate; if (m_ButtonActionTriggeredDelegate == null) { m_ButtonActionTriggeredDelegate = OnButtonActionTriggered; } SetActionCallback(m_LeftButtonAction, m_ButtonActionTriggeredDelegate); SetActionCallback(m_RightButtonAction, m_ButtonActionTriggeredDelegate); SetActionCallback(m_MiddleButtonAction, m_ButtonActionTriggeredDelegate); SetActionCallback(m_ForwardButtonAction, m_ButtonActionTriggeredDelegate); SetActionCallback(m_BackButtonAction, m_ButtonActionTriggeredDelegate); m_StickAction.action?.Enable(); m_LeftButtonAction.action?.Enable(); m_RightButtonAction.action?.Enable(); m_MiddleButtonAction.action?.Enable(); m_ForwardButtonAction.action?.Enable(); m_BackButtonAction.action?.Enable(); m_ScrollWheelAction.action?.Enable(); } protected void OnDisable() { //IL_015e: Unknown result type (might be due to invalid IL or missing references) if (m_VirtualMouse != null && m_VirtualMouse.added) { InputSystem.RemoveDevice(m_VirtualMouse); } if (m_SystemMouse != null) { InputSystem.EnableDevice(m_SystemMouse); m_SystemMouse = null; } if (m_AfterInputUpdateDelegate != null) { InputSystem.onAfterUpdate -= m_AfterInputUpdateDelegate; } m_StickAction.action?.Disable(); m_LeftButtonAction.action?.Disable(); m_RightButtonAction.action?.Disable(); m_MiddleButtonAction.action?.Disable(); m_ForwardButtonAction.action?.Disable(); m_BackButtonAction.action?.Disable(); m_ScrollWheelAction.action?.Disable(); if (m_ButtonActionTriggeredDelegate != null) { SetActionCallback(m_LeftButtonAction, m_ButtonActionTriggeredDelegate, install: false); SetActionCallback(m_RightButtonAction, m_ButtonActionTriggeredDelegate, install: false); SetActionCallback(m_MiddleButtonAction, m_ButtonActionTriggeredDelegate, install: false); SetActionCallback(m_ForwardButtonAction, m_ButtonActionTriggeredDelegate, install: false); SetActionCallback(m_BackButtonAction, m_ButtonActionTriggeredDelegate, install: false); } m_LastTime = 0.0; m_LastStickValue = default(Vector2); } private void TryFindCanvas() { Graphic obj = m_CursorGraphic; m_Canvas = ((obj != null) ? ((Component)obj).GetComponentInParent() : null); } private void TryEnableHardwareCursor() { //IL_0089: Unknown result type (might be due to invalid IL or missing references) ReadOnlyArray devices = InputSystem.devices; for (int i = 0; i < devices.Count; i++) { InputDevice inputDevice = devices[i]; if (inputDevice.native && inputDevice is Mouse systemMouse) { m_SystemMouse = systemMouse; break; } } if (m_SystemMouse == null) { if ((Object)(object)m_CursorGraphic != (Object)null) { ((Behaviour)m_CursorGraphic).enabled = true; } return; } InputSystem.DisableDevice(m_SystemMouse); if (m_VirtualMouse != null) { m_SystemMouse.WarpCursorPosition(m_VirtualMouse.position.value); } if ((Object)(object)m_CursorGraphic != (Object)null) { ((Behaviour)m_CursorGraphic).enabled = false; } } private void UpdateMotion() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) if (m_VirtualMouse == null) { return; } InputAction action = m_StickAction.action; if (action == null) { return; } Vector2 val = action.ReadValue(); if (Mathf.Approximately(0f, val.x) && Mathf.Approximately(0f, val.y)) { m_LastTime = 0.0; m_LastStickValue = default(Vector2); } else { double currentTime = InputState.currentTime; if (Mathf.Approximately(0f, m_LastStickValue.x) && Mathf.Approximately(0f, m_LastStickValue.y)) { m_LastTime = currentTime; } float num = (float)(currentTime - m_LastTime); Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(m_CursorSpeed * val.x * num, m_CursorSpeed * val.y * num); Vector2 val3 = m_VirtualMouse.position.value + val2; if ((Object)(object)m_Canvas != (Object)null) { Rect pixelRect = m_Canvas.pixelRect; val3.x = Mathf.Clamp(val3.x, ((Rect)(ref pixelRect)).xMin, ((Rect)(ref pixelRect)).xMax); val3.y = Mathf.Clamp(val3.y, ((Rect)(ref pixelRect)).yMin, ((Rect)(ref pixelRect)).yMax); } InputState.Change((InputControl)m_VirtualMouse.position, val3, InputUpdateType.None, default(InputEventPtr)); InputState.Change((InputControl)m_VirtualMouse.delta, val2, InputUpdateType.None, default(InputEventPtr)); if ((Object)(object)m_CursorTransform != (Object)null && (m_CursorMode == CursorMode.SoftwareCursor || (m_CursorMode == CursorMode.HardwareCursorIfAvailable && m_SystemMouse == null))) { m_CursorTransform.anchoredPosition = val3; } m_LastStickValue = val; m_LastTime = currentTime; m_SystemMouse?.WarpCursorPosition(val3); } InputAction action2 = m_ScrollWheelAction.action; if (action2 != null) { Vector2 state = action2.ReadValue(); state.x *= m_ScrollSpeed; state.y *= m_ScrollSpeed; InputState.Change((InputControl)m_VirtualMouse.scroll, state, InputUpdateType.None, default(InputEventPtr)); } } private void OnButtonActionTriggered(InputAction.CallbackContext context) { if (m_VirtualMouse != null) { InputAction action = context.action; MouseButton? mouseButton = null; if (action == m_LeftButtonAction.action) { mouseButton = MouseButton.Left; } else if (action == m_RightButtonAction.action) { mouseButton = MouseButton.Right; } else if (action == m_MiddleButtonAction.action) { mouseButton = MouseButton.Middle; } else if (action == m_ForwardButtonAction.action) { mouseButton = MouseButton.Forward; } else if (action == m_BackButtonAction.action) { mouseButton = MouseButton.Back; } if (mouseButton.HasValue) { bool state = context.control.IsPressed(); m_VirtualMouse.CopyState(out var state2); state2.WithButton(mouseButton.Value, state); InputState.Change(m_VirtualMouse, state2); } } } private static void SetActionCallback(InputActionProperty field, Action callback, bool install = true) { InputAction action = field.action; if (action != null) { if (install) { action.started += callback; action.canceled += callback; } else { action.started -= callback; action.canceled -= callback; } } } private static void SetAction(ref InputActionProperty field, InputActionProperty value) { InputActionProperty inputActionProperty = field; field = value; if (!((Object)(object)inputActionProperty.reference == (Object)null)) { return; } InputAction action = inputActionProperty.action; if (action != null && action.enabled) { action.Disable(); if ((Object)(object)value.reference == (Object)null) { value.action?.Enable(); } } } private void OnAfterInputUpdate() { UpdateMotion(); } } } namespace UnityEngine.InputSystem.Switch { [InputControlLayout(stateType = typeof(SwitchProControllerHIDInputState), displayName = "Switch Pro Controller")] public class SwitchProControllerHID : Gamepad, IInputStateCallbackReceiver, IEventPreProcessor { [StructLayout(LayoutKind.Explicit, Size = 7)] private struct SwitchInputOnlyReport { public const int kSize = 7; [FieldOffset(0)] public byte buttons0; [FieldOffset(1)] public byte buttons1; [FieldOffset(2)] public byte hat; [FieldOffset(3)] public byte leftX; [FieldOffset(4)] public byte leftY; [FieldOffset(5)] public byte rightX; [FieldOffset(6)] public byte rightY; [MethodImpl(MethodImplOptions.AggressiveInlining)] public SwitchProControllerHIDInputState ToHIDInputReport() { SwitchProControllerHIDInputState result = new SwitchProControllerHIDInputState { leftStickX = leftX, leftStickY = leftY, rightStickX = rightX, rightStickY = rightY }; result.Set(SwitchProControllerHIDInputState.Button.West, (buttons0 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.South, (buttons0 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.East, (buttons0 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.North, (buttons0 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.L, (buttons0 & 0x10) != 0); result.Set(SwitchProControllerHIDInputState.Button.R, (buttons0 & 0x20) != 0); result.Set(SwitchProControllerHIDInputState.Button.ZL, (buttons0 & 0x40) != 0); result.Set(SwitchProControllerHIDInputState.Button.ZR, (buttons0 & 0x80) != 0); result.Set(SwitchProControllerHIDInputState.Button.Minus, (buttons1 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.Plus, (buttons1 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.StickL, (buttons1 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.StickR, (buttons1 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.Home, (buttons1 & 0x10) != 0); result.Set(SwitchProControllerHIDInputState.Button.Capture, (buttons1 & 0x20) != 0); bool state = false; bool state2 = false; bool state3 = false; bool state4 = false; switch (hat) { case 0: state2 = true; break; case 1: state2 = true; state3 = true; break; case 2: state3 = true; break; case 3: state4 = true; state3 = true; break; case 4: state4 = true; break; case 5: state4 = true; state = true; break; case 6: state = true; break; case 7: state2 = true; state = true; break; } result.Set(SwitchProControllerHIDInputState.Button.Left, state); result.Set(SwitchProControllerHIDInputState.Button.Up, state2); result.Set(SwitchProControllerHIDInputState.Button.Right, state3); result.Set(SwitchProControllerHIDInputState.Button.Down, state4); return result; } } [StructLayout(LayoutKind.Explicit, Size = 12)] private struct SwitchSimpleInputReport { public const int kSize = 12; public const byte ExpectedReportId = 63; [FieldOffset(0)] public byte reportId; [FieldOffset(1)] public byte buttons0; [FieldOffset(2)] public byte buttons1; [FieldOffset(3)] public byte hat; [FieldOffset(4)] public ushort leftX; [FieldOffset(6)] public ushort leftY; [FieldOffset(8)] public ushort rightX; [FieldOffset(10)] public ushort rightY; [MethodImpl(MethodImplOptions.AggressiveInlining)] public SwitchProControllerHIDInputState ToHIDInputReport() { byte leftStickX = (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(leftX, 16u, 8u); byte leftStickY = (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(leftY, 16u, 8u); byte rightStickX = (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(rightX, 16u, 8u); byte rightStickY = (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(rightY, 16u, 8u); SwitchProControllerHIDInputState result = new SwitchProControllerHIDInputState { leftStickX = leftStickX, leftStickY = leftStickY, rightStickX = rightStickX, rightStickY = rightStickY }; result.Set(SwitchProControllerHIDInputState.Button.South, (buttons0 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.East, (buttons0 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.West, (buttons0 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.North, (buttons0 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.L, (buttons0 & 0x10) != 0); result.Set(SwitchProControllerHIDInputState.Button.R, (buttons0 & 0x20) != 0); result.Set(SwitchProControllerHIDInputState.Button.ZL, (buttons0 & 0x40) != 0); result.Set(SwitchProControllerHIDInputState.Button.ZR, (buttons0 & 0x80) != 0); result.Set(SwitchProControllerHIDInputState.Button.Minus, (buttons1 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.Plus, (buttons1 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.StickL, (buttons1 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.StickR, (buttons1 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.Home, (buttons1 & 0x10) != 0); result.Set(SwitchProControllerHIDInputState.Button.Capture, (buttons1 & 0x20) != 0); bool state = false; bool state2 = false; bool state3 = false; bool state4 = false; switch (hat) { case 0: state2 = true; break; case 1: state2 = true; state3 = true; break; case 2: state3 = true; break; case 3: state4 = true; state3 = true; break; case 4: state4 = true; break; case 5: state4 = true; state = true; break; case 6: state = true; break; case 7: state2 = true; state = true; break; } result.Set(SwitchProControllerHIDInputState.Button.Left, state); result.Set(SwitchProControllerHIDInputState.Button.Up, state2); result.Set(SwitchProControllerHIDInputState.Button.Right, state3); result.Set(SwitchProControllerHIDInputState.Button.Down, state4); return result; } } [StructLayout(LayoutKind.Explicit, Size = 25)] private struct SwitchFullInputReport { public const int kSize = 25; public const byte ExpectedReportId = 48; [FieldOffset(0)] public byte reportId; [FieldOffset(3)] public byte buttons0; [FieldOffset(4)] public byte buttons1; [FieldOffset(5)] public byte buttons2; [FieldOffset(6)] public byte left0; [FieldOffset(7)] public byte left1; [FieldOffset(8)] public byte left2; [FieldOffset(9)] public byte right0; [FieldOffset(10)] public byte right1; [FieldOffset(11)] public byte right2; [MethodImpl(MethodImplOptions.AggressiveInlining)] public SwitchProControllerHIDInputState ToHIDInputReport() { uint value = (uint)(left0 | ((left1 & 0xF) << 8)); uint value2 = (uint)(((left1 & 0xF0) >> 4) | (left2 << 4)); int value3 = right0 | ((right1 & 0xF) << 8); uint value4 = (uint)(((right1 & 0xF0) >> 4) | (right2 << 4)); byte leftStickX = (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(value, 12u, 8u); byte leftStickY = (byte)(255 - (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(value2, 12u, 8u)); byte rightStickX = (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits((uint)value3, 12u, 8u); byte rightStickY = (byte)(255 - (byte)NumberHelpers.RemapUIntBitsToNormalizeFloatToUIntBits(value4, 12u, 8u)); SwitchProControllerHIDInputState result = new SwitchProControllerHIDInputState { leftStickX = leftStickX, leftStickY = leftStickY, rightStickX = rightStickX, rightStickY = rightStickY }; result.Set(SwitchProControllerHIDInputState.Button.West, (buttons0 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.North, (buttons0 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.South, (buttons0 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.East, (buttons0 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.R, (buttons0 & 0x40) != 0); result.Set(SwitchProControllerHIDInputState.Button.ZR, (buttons0 & 0x80) != 0); result.Set(SwitchProControllerHIDInputState.Button.Minus, (buttons1 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.Plus, (buttons1 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.StickR, (buttons1 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.StickL, (buttons1 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.Home, (buttons1 & 0x10) != 0); result.Set(SwitchProControllerHIDInputState.Button.Capture, (buttons1 & 0x20) != 0); result.Set(SwitchProControllerHIDInputState.Button.Down, (buttons2 & 1) != 0); result.Set(SwitchProControllerHIDInputState.Button.Up, (buttons2 & 2) != 0); result.Set(SwitchProControllerHIDInputState.Button.Right, (buttons2 & 4) != 0); result.Set(SwitchProControllerHIDInputState.Button.Left, (buttons2 & 8) != 0); result.Set(SwitchProControllerHIDInputState.Button.L, (buttons2 & 0x40) != 0); result.Set(SwitchProControllerHIDInputState.Button.ZL, (buttons2 & 0x80) != 0); return result; } } [StructLayout(LayoutKind.Explicit)] private struct SwitchHIDGenericInputReport { [FieldOffset(0)] public byte reportId; public static FourCC Format => new FourCC('H', 'I', 'D'); } [StructLayout(LayoutKind.Explicit, Size = 49)] internal struct SwitchMagicOutputReport { internal enum ReportType { Magic = 0x80 } public enum CommandIdType { Status = 1, Handshake, Highspeed, ForceUSB } public const int kSize = 49; public const byte ExpectedReplyInputReportId = 129; [FieldOffset(0)] public byte reportType; [FieldOffset(1)] public byte commandId; } [StructLayout(LayoutKind.Explicit, Size = 57)] internal struct SwitchMagicOutputHIDBluetooth : IInputDeviceCommandInfo { public const int kSize = 57; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public SwitchMagicOutputReport report; public static FourCC Type => new FourCC('H', 'I', 'D', 'O'); public FourCC typeStatic => Type; public static SwitchMagicOutputHIDBluetooth Create(SwitchMagicOutputReport.CommandIdType type) { return new SwitchMagicOutputHIDBluetooth { baseCommand = new InputDeviceCommand(Type, 57), report = new SwitchMagicOutputReport { reportType = 128, commandId = (byte)type } }; } } [StructLayout(LayoutKind.Explicit, Size = 72)] internal struct SwitchMagicOutputHIDUSB : IInputDeviceCommandInfo { public const int kSize = 72; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public SwitchMagicOutputReport report; public static FourCC Type => new FourCC('H', 'I', 'D', 'O'); public FourCC typeStatic => Type; public static SwitchMagicOutputHIDUSB Create(SwitchMagicOutputReport.CommandIdType type) { return new SwitchMagicOutputHIDUSB { baseCommand = new InputDeviceCommand(Type, 72), report = new SwitchMagicOutputReport { reportType = 128, commandId = (byte)type } }; } } private static readonly SwitchMagicOutputReport.CommandIdType[] s_HandshakeSequence = new SwitchMagicOutputReport.CommandIdType[5] { SwitchMagicOutputReport.CommandIdType.Status, SwitchMagicOutputReport.CommandIdType.Handshake, SwitchMagicOutputReport.CommandIdType.Highspeed, SwitchMagicOutputReport.CommandIdType.Handshake, SwitchMagicOutputReport.CommandIdType.ForceUSB }; private int m_HandshakeStepIndex; private double m_HandshakeTimer; internal const byte JitterMaskLow = 120; internal const byte JitterMaskHigh = 135; [InputControl(name = "capture", displayName = "Capture")] public ButtonControl captureButton { get; protected set; } [InputControl(name = "home", displayName = "Home")] public ButtonControl homeButton { get; protected set; } protected override void OnAdded() { base.OnAdded(); captureButton = GetChildControl("capture"); homeButton = GetChildControl("home"); HandshakeRestart(); } private void HandshakeRestart() { m_HandshakeStepIndex = -1; m_HandshakeTimer = InputRuntime.s_Instance.currentTime; } private void HandshakeTick() { double currentTime = InputRuntime.s_Instance.currentTime; if (currentTime >= m_LastUpdateTimeInternal + 2.0 && currentTime >= m_HandshakeTimer + 2.0) { m_HandshakeStepIndex = 0; } else { if (m_HandshakeStepIndex + 1 >= s_HandshakeSequence.Length || !(currentTime > m_HandshakeTimer + 0.1)) { return; } m_HandshakeStepIndex++; } m_HandshakeTimer = currentTime; SwitchMagicOutputReport.CommandIdType type = s_HandshakeSequence[m_HandshakeStepIndex]; SwitchMagicOutputHIDBluetooth command = SwitchMagicOutputHIDBluetooth.Create(type); if (ExecuteCommand(ref command) <= 0) { SwitchMagicOutputHIDUSB command2 = SwitchMagicOutputHIDUSB.Create(type); ExecuteCommand(ref command2); } } public void OnNextUpdate() { HandshakeTick(); } public unsafe void OnStateEvent(InputEventPtr eventPtr) { if (eventPtr.type == 1398030676 && eventPtr.stateFormat == SwitchProControllerHIDInputState.Format) { SwitchProControllerHIDInputState* ptr = (SwitchProControllerHIDInputState*)((byte*)base.currentStatePtr + m_StateBlock.byteOffset); SwitchProControllerHIDInputState* state = (SwitchProControllerHIDInputState*)StateEvent.FromUnchecked(eventPtr)->state; if (state->leftStickX >= 120 && state->leftStickX <= 135 && state->leftStickY >= 120 && state->leftStickY <= 135 && state->rightStickX >= 120 && state->rightStickX <= 135 && state->rightStickY >= 120 && state->rightStickY <= 135 && state->buttons1 == ptr->buttons1 && state->buttons2 == ptr->buttons2) { InputSystem.s_Manager.DontMakeCurrentlyUpdatingDeviceCurrent(); } } InputState.Change(this, eventPtr); } public bool GetStateOffsetForEvent(InputControl control, InputEventPtr eventPtr, ref uint offset) { return false; } public unsafe bool PreProcessEvent(InputEventPtr eventPtr) { if (eventPtr.type == 1145852993) { return DeltaStateEvent.FromUnchecked(eventPtr)->stateFormat == SwitchProControllerHIDInputState.Format; } if (eventPtr.type != 1398030676) { return true; } StateEvent* ptr = StateEvent.FromUnchecked(eventPtr); uint stateSizeInBytes = ptr->stateSizeInBytes; if (ptr->stateFormat == SwitchProControllerHIDInputState.Format) { return true; } if (ptr->stateFormat != SwitchHIDGenericInputReport.Format || stateSizeInBytes < sizeof(SwitchHIDGenericInputReport)) { return false; } SwitchHIDGenericInputReport* state = (SwitchHIDGenericInputReport*)ptr->state; if (state->reportId == 63 && stateSizeInBytes >= 12) { SwitchProControllerHIDInputState switchProControllerHIDInputState = ((SwitchSimpleInputReport*)ptr->state)->ToHIDInputReport(); *(SwitchProControllerHIDInputState*)ptr->state = switchProControllerHIDInputState; ptr->stateFormat = SwitchProControllerHIDInputState.Format; return true; } if (state->reportId == 48 && stateSizeInBytes >= 25) { SwitchProControllerHIDInputState switchProControllerHIDInputState2 = ((SwitchFullInputReport*)ptr->state)->ToHIDInputReport(); *(SwitchProControllerHIDInputState*)ptr->state = switchProControllerHIDInputState2; ptr->stateFormat = SwitchProControllerHIDInputState.Format; return true; } if (stateSizeInBytes == 8 || stateSizeInBytes == 9) { int num = ((stateSizeInBytes == 9) ? 1 : 0); SwitchProControllerHIDInputState switchProControllerHIDInputState3 = ((SwitchInputOnlyReport*)((byte*)ptr->state + num))->ToHIDInputReport(); *(SwitchProControllerHIDInputState*)ptr->state = switchProControllerHIDInputState3; ptr->stateFormat = SwitchProControllerHIDInputState.Format; return true; } return false; } } internal static class SwitchSupportHID { public static void Initialize() { InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 1406).WithCapability("productId", 8201)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3853).WithCapability("productId", 146)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3853).WithCapability("productId", 170)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3853).WithCapability("productId", 193)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3853).WithCapability("productId", 220)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3853).WithCapability("productId", 246)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 384)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 385)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 389)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 390)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 391)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 8406).WithCapability("productId", 42770)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 8406).WithCapability("productId", 42774)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 388)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 3695).WithCapability("productId", 392)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 8406).WithCapability("productId", 42772)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 8406).WithCapability("productId", 42773)); } } } namespace UnityEngine.InputSystem.Switch.LowLevel { [StructLayout(LayoutKind.Explicit, Size = 7)] internal struct SwitchProControllerHIDInputState : IInputStateTypeInfo { public enum Button { Up = 0, Right = 1, Down = 2, Left = 3, West = 4, North = 5, South = 6, East = 7, L = 8, R = 9, StickL = 10, StickR = 11, ZL = 12, ZR = 13, Plus = 14, Minus = 15, Capture = 16, Home = 17, X = 5, B = 6, Y = 4, A = 7 } public static FourCC Format = new FourCC('S', 'P', 'V', 'S'); [FieldOffset(0)] [InputControl(name = "leftStick", layout = "Stick", format = "VC2B")] [InputControl(name = "leftStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5")] [InputControl(name = "leftStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.15,clampMax=0.5,invert")] [InputControl(name = "leftStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=0.85")] [InputControl(name = "leftStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5")] [InputControl(name = "leftStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.15,clampMax=0.5,invert")] [InputControl(name = "leftStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=0.85,invert=false")] public byte leftStickX; [FieldOffset(1)] public byte leftStickY; [FieldOffset(2)] [InputControl(name = "rightStick", layout = "Stick", format = "VC2B")] [InputControl(name = "rightStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5")] [InputControl(name = "rightStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "rightStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5")] [InputControl(name = "rightStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.15,clampMax=0.5,invert")] [InputControl(name = "rightStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0.15,normalizeMax=0.85,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=0.85,invert=false")] public byte rightStickX; [FieldOffset(3)] public byte rightStickY; [FieldOffset(4)] [InputControl(name = "dpad", format = "BIT", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/up", bit = 0u)] [InputControl(name = "dpad/right", bit = 1u)] [InputControl(name = "dpad/down", bit = 2u)] [InputControl(name = "dpad/left", bit = 3u)] [InputControl(name = "buttonWest", displayName = "Y", shortDisplayName = "Y", bit = 4u, usage = "SecondaryAction")] [InputControl(name = "buttonNorth", displayName = "X", shortDisplayName = "X", bit = 5u)] [InputControl(name = "buttonSouth", displayName = "B", shortDisplayName = "B", bit = 6u, usage = "Back")] [InputControl(name = "buttonEast", displayName = "A", shortDisplayName = "A", bit = 7u, usage = "PrimaryAction")] [InputControl(name = "leftShoulder", displayName = "L", shortDisplayName = "L", bit = 8u)] [InputControl(name = "rightShoulder", displayName = "R", shortDisplayName = "R", bit = 9u)] [InputControl(name = "leftStickPress", displayName = "Left Stick", bit = 10u)] [InputControl(name = "rightStickPress", displayName = "Right Stick", bit = 11u)] [InputControl(name = "leftTrigger", displayName = "ZL", shortDisplayName = "ZL", format = "BIT", bit = 12u)] [InputControl(name = "rightTrigger", displayName = "ZR", shortDisplayName = "ZR", format = "BIT", bit = 13u)] [InputControl(name = "start", displayName = "Plus", bit = 14u, usage = "Menu")] [InputControl(name = "select", displayName = "Minus", bit = 15u)] public ushort buttons1; [FieldOffset(6)] [InputControl(name = "capture", layout = "Button", displayName = "Capture", bit = 0u)] [InputControl(name = "home", layout = "Button", displayName = "Home", bit = 1u)] public byte buttons2; public FourCC format => Format; [MethodImpl(MethodImplOptions.AggressiveInlining)] public SwitchProControllerHIDInputState WithButton(Button button, bool value = true) { Set(button, value); return this; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(Button button, bool state) { if (button < Button.Capture) { ushort num = (ushort)(1 << (int)button); if (state) { buttons1 |= num; } else { buttons1 &= (ushort)(~num); } } else if (button < (Button)18) { byte b = (byte)(1 << (int)(button - 16)); if (state) { buttons2 |= b; } else { buttons2 &= (byte)(~b); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Press(Button button) { Set(button, state: true); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Release(Button button) { Set(button, state: false); } } } namespace UnityEngine.InputSystem.OnScreen { [AddComponentMenu("Input/On-Screen Button")] [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/OnScreen.html#on-screen-buttons")] public class OnScreenButton : OnScreenControl, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler { [InputControl(layout = "Button")] [SerializeField] private string m_ControlPath; protected override string controlPathInternal { get { return m_ControlPath; } set { m_ControlPath = value; } } public void OnPointerUp(PointerEventData eventData) { SendValueToControl(0f); } public void OnPointerDown(PointerEventData eventData) { SendValueToControl(1f); } } public abstract class OnScreenControl : MonoBehaviour { private struct OnScreenDeviceInfo { public InputEventPtr eventPtr; public NativeArray buffer; public InputDevice device; public OnScreenControl firstControl; public OnScreenDeviceInfo AddControl(OnScreenControl control) { control.m_NextControlOnDevice = firstControl; firstControl = control; return this; } public OnScreenDeviceInfo RemoveControl(OnScreenControl control) { if ((Object)(object)firstControl == (Object)(object)control) { firstControl = control.m_NextControlOnDevice; } else { OnScreenControl nextControlOnDevice = firstControl.m_NextControlOnDevice; OnScreenControl onScreenControl = firstControl; while ((Object)(object)nextControlOnDevice != (Object)null) { if (!((Object)(object)nextControlOnDevice != (Object)(object)control)) { onScreenControl.m_NextControlOnDevice = nextControlOnDevice.m_NextControlOnDevice; break; } onScreenControl = nextControlOnDevice; nextControlOnDevice = nextControlOnDevice.m_NextControlOnDevice; } } control.m_NextControlOnDevice = null; return this; } public void Destroy() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (buffer.IsCreated) { buffer.Dispose(); } if (device != null) { InputSystem.RemoveDevice(device); } device = null; buffer = default(NativeArray); } } private InputControl m_Control; private OnScreenControl m_NextControlOnDevice; private InputEventPtr m_InputEventPtr; private static InlinedArray s_OnScreenDevices; public string controlPath { get { return controlPathInternal; } set { controlPathInternal = value; if (((Behaviour)this).isActiveAndEnabled) { SetupInputControl(); } } } public InputControl control => m_Control; protected abstract string controlPathInternal { get; set; } private void SetupInputControl() { //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) string text = controlPathInternal; if (string.IsNullOrEmpty(text)) { return; } string text2 = InputControlPath.TryGetDeviceLayout(text); if (text2 == null) { Debug.LogError((object)("Cannot determine device layout to use based on control path '" + text + "' used in " + ((object)this).GetType().Name + " component"), (Object)(object)this); return; } InternedString internedString = new InternedString(text2); int num = -1; for (int i = 0; i < s_OnScreenDevices.length; i++) { if (s_OnScreenDevices[i].device.m_Layout == internedString) { num = i; break; } } InputDevice device; if (num == -1) { try { device = InputSystem.AddDevice(text2); } catch (Exception ex) { Debug.LogError((object)("Could not create device with layout '" + text2 + "' used in '" + ((object)this).GetType().Name + "' component")); Debug.LogException(ex); return; } InputSystem.AddDeviceUsage(device, "OnScreen"); InputEventPtr eventPtr; NativeArray buffer = StateEvent.From(device, out eventPtr, (Allocator)4); num = s_OnScreenDevices.Append(new OnScreenDeviceInfo { eventPtr = eventPtr, buffer = buffer, device = device }); } else { device = s_OnScreenDevices[num].device; } m_Control = InputControlPath.TryFindControl(device, text); if (m_Control == null) { Debug.LogError((object)("Cannot find control with path '" + text + "' on device of type '" + text2 + "' referenced by component '" + ((object)this).GetType().Name + "'"), (Object)(object)this); if ((Object)(object)s_OnScreenDevices[num].firstControl == (Object)null) { s_OnScreenDevices[num].Destroy(); s_OnScreenDevices.RemoveAt(num); } } else { m_InputEventPtr = s_OnScreenDevices[num].eventPtr; s_OnScreenDevices[num] = s_OnScreenDevices[num].AddControl(this); } } protected void SendValueToControl(TValue value) where TValue : struct { if (m_Control != null) { if (!(m_Control is InputControl inputControl)) { throw new ArgumentException("The control path " + controlPath + " yields a control of type " + m_Control.GetType().Name + " which is not an InputControl with value type " + typeof(TValue).Name, "value"); } m_InputEventPtr.internalTime = InputRuntime.s_Instance.currentTime; inputControl.WriteValueIntoEvent(value, m_InputEventPtr); InputSystem.QueueEvent(m_InputEventPtr); } } protected void SentDefaultValueToControl() { if (m_Control != null) { m_InputEventPtr.internalTime = InputRuntime.s_Instance.currentTime; m_Control.ResetToDefaultStateInEvent(m_InputEventPtr); InputSystem.QueueEvent(m_InputEventPtr); } } protected virtual void OnEnable() { SetupInputControl(); } protected virtual void OnDisable() { if (m_Control == null) { return; } InputDevice device = m_Control.device; for (int i = 0; i < s_OnScreenDevices.length; i++) { if (s_OnScreenDevices[i].device != device) { continue; } OnScreenDeviceInfo value = s_OnScreenDevices[i].RemoveControl(this); if ((Object)(object)value.firstControl == (Object)null) { s_OnScreenDevices[i].Destroy(); s_OnScreenDevices.RemoveAt(i); } else { s_OnScreenDevices[i] = value; if (!m_Control.CheckStateIsAtDefault()) { SentDefaultValueToControl(); } } m_Control = null; m_InputEventPtr = default(InputEventPtr); break; } } } [AddComponentMenu("Input/On-Screen Stick")] [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/OnScreen.html#on-screen-sticks")] public class OnScreenStick : OnScreenControl, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler, IDragHandler { public enum Behaviour { RelativePositionWithStaticOrigin, ExactPositionWithStaticOrigin, ExactPositionWithDynamicOrigin } private const string kDynamicOriginClickable = "DynamicOriginClickable"; [FormerlySerializedAs("movementRange")] [SerializeField] [Min(0f)] private float m_MovementRange = 50f; [SerializeField] [Tooltip("Defines the circular region where the onscreen control may have it's origin placed.")] [Min(0f)] private float m_DynamicOriginRange = 100f; [InputControl(layout = "Vector2")] [SerializeField] private string m_ControlPath; [SerializeField] [Tooltip("Choose how the onscreen stick will move relative to it's origin and the press position.\n\nRelativePositionWithStaticOrigin: The control's center of origin is fixed. The control will begin un-actuated at it's centered position and then move relative to the pointer or finger motion.\n\nExactPositionWithStaticOrigin: The control's center of origin is fixed. The stick will immediately jump to the exact position of the click or touch and begin tracking motion from there.\n\nExactPositionWithDynamicOrigin: The control's center of origin is determined by the initial press position. The stick will begin un-actuated at this center position and then track the current pointer or finger position.")] private Behaviour m_Behaviour; [SerializeField] [Tooltip("Set this to true to prevent cancellation of pointer events due to device switching. Cancellation will appear as the stick jumping back and forth between the pointer position and the stick center.")] private bool m_UseIsolatedInputActions; [SerializeField] [Tooltip("The action that will be used to detect pointer down events on the stick control. Note that if no bindings are set, default ones will be provided.")] private InputAction m_PointerDownAction; [SerializeField] [Tooltip("The action that will be used to detect pointer movement on the stick control. Note that if no bindings are set, default ones will be provided.")] private InputAction m_PointerMoveAction; private Vector3 m_StartPos; private Vector2 m_PointerDownPos; [NonSerialized] private List m_RaycastResults; [NonSerialized] private PointerEventData m_PointerEventData; public float movementRange { get { return m_MovementRange; } set { m_MovementRange = value; } } public float dynamicOriginRange { get { return m_DynamicOriginRange; } set { if (m_DynamicOriginRange != value) { m_DynamicOriginRange = value; UpdateDynamicOriginClickableArea(); } } } public bool useIsolatedInputActions { get { return m_UseIsolatedInputActions; } set { m_UseIsolatedInputActions = value; } } protected override string controlPathInternal { get { return m_ControlPath; } set { m_ControlPath = value; } } public Behaviour behaviour { get { return m_Behaviour; } set { m_Behaviour = value; } } public void OnPointerDown(PointerEventData eventData) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!m_UseIsolatedInputActions) { if (eventData == null) { throw new ArgumentNullException("eventData"); } BeginInteraction(eventData.position, eventData.pressEventCamera); } } public void OnDrag(PointerEventData eventData) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!m_UseIsolatedInputActions) { if (eventData == null) { throw new ArgumentNullException("eventData"); } MoveStick(eventData.position, eventData.pressEventCamera); } } public void OnPointerUp(PointerEventData eventData) { if (!m_UseIsolatedInputActions) { EndInteraction(); } } private void Start() { //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) if (m_UseIsolatedInputActions) { m_RaycastResults = new List(); m_PointerEventData = new PointerEventData(EventSystem.current); if (m_PointerDownAction == null || m_PointerDownAction.bindings.Count == 0) { if (m_PointerDownAction == null) { m_PointerDownAction = new InputAction(); } m_PointerDownAction.AddBinding("/leftButton"); m_PointerDownAction.AddBinding("/tip"); m_PointerDownAction.AddBinding("/touch*/press"); m_PointerDownAction.AddBinding("/trigger"); } if (m_PointerMoveAction == null || m_PointerMoveAction.bindings.Count == 0) { if (m_PointerMoveAction == null) { m_PointerMoveAction = new InputAction(); } m_PointerMoveAction.AddBinding("/position"); m_PointerMoveAction.AddBinding("/position"); m_PointerMoveAction.AddBinding("/touch*/position"); } m_PointerDownAction.started += OnPointerDown; m_PointerDownAction.canceled += OnPointerUp; m_PointerDownAction.Enable(); m_PointerMoveAction.Enable(); } m_StartPos = Vector2.op_Implicit(((RectTransform)((Component)this).transform).anchoredPosition); if (m_Behaviour == Behaviour.ExactPositionWithDynamicOrigin) { m_PointerDownPos = Vector2.op_Implicit(m_StartPos); GameObject val = new GameObject("DynamicOriginClickable", new Type[1] { typeof(Image) }); val.transform.SetParent(((Component)this).transform); Image component = val.GetComponent(); ((Graphic)component).color = new Color(1f, 1f, 1f, 0f); RectTransform val2 = (RectTransform)val.transform; val2.sizeDelta = new Vector2(m_DynamicOriginRange * 2f, m_DynamicOriginRange * 2f); ((Transform)val2).localScale = new Vector3(1f, 1f, 0f); val2.anchoredPosition3D = Vector3.zero; component.sprite = SpriteUtilities.CreateCircleSprite(16, new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue)); component.alphaHitTestMinimumThreshold = 0.5f; } } private void BeginInteraction(Vector2 pointerPosition, Camera uiCamera) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) Transform parent = ((Component)this).transform.parent; RectTransform val = ((parent != null) ? ((Component)parent).GetComponentInParent() : null); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"OnScreenStick needs to be attached as a child to a UI Canvas to function properly."); return; } switch (m_Behaviour) { case Behaviour.RelativePositionWithStaticOrigin: RectTransformUtility.ScreenPointToLocalPointInRectangle(val, pointerPosition, uiCamera, ref m_PointerDownPos); break; case Behaviour.ExactPositionWithStaticOrigin: RectTransformUtility.ScreenPointToLocalPointInRectangle(val, pointerPosition, uiCamera, ref m_PointerDownPos); MoveStick(pointerPosition, uiCamera); break; case Behaviour.ExactPositionWithDynamicOrigin: { Vector2 val2 = default(Vector2); RectTransformUtility.ScreenPointToLocalPointInRectangle(val, pointerPosition, uiCamera, ref val2); Vector2 pointerDownPos = (((RectTransform)((Component)this).transform).anchoredPosition = val2); m_PointerDownPos = pointerDownPos; break; } } } private void MoveStick(Vector2 pointerPosition, Camera uiCamera) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) Transform parent = ((Component)this).transform.parent; RectTransform val = ((parent != null) ? ((Component)parent).GetComponentInParent() : null); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"OnScreenStick needs to be attached as a child to a UI Canvas to function properly."); return; } Vector2 val2 = default(Vector2); RectTransformUtility.ScreenPointToLocalPointInRectangle(val, pointerPosition, uiCamera, ref val2); Vector2 val3 = val2 - m_PointerDownPos; switch (m_Behaviour) { case Behaviour.RelativePositionWithStaticOrigin: val3 = Vector2.ClampMagnitude(val3, movementRange); ((RectTransform)((Component)this).transform).anchoredPosition = Vector2.op_Implicit(m_StartPos) + val3; break; case Behaviour.ExactPositionWithStaticOrigin: val3 = val2 - Vector2.op_Implicit(m_StartPos); val3 = Vector2.ClampMagnitude(val3, movementRange); ((RectTransform)((Component)this).transform).anchoredPosition = Vector2.op_Implicit(m_StartPos) + val3; break; case Behaviour.ExactPositionWithDynamicOrigin: val3 = Vector2.ClampMagnitude(val3, movementRange); ((RectTransform)((Component)this).transform).anchoredPosition = m_PointerDownPos + val3; break; } Vector2 value = default(Vector2); ((Vector2)(ref value))..ctor(val3.x / movementRange, val3.y / movementRange); SendValueToControl(value); } private void EndInteraction() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) ((RectTransform)((Component)this).transform).anchoredPosition = (m_PointerDownPos = Vector2.op_Implicit(m_StartPos)); SendValueToControl(Vector2.zero); } private void OnPointerDown(InputAction.CallbackContext ctx) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) Vector2 val = Vector2.zero; if (ctx.control?.device is Pointer pointer) { val = pointer.position.ReadValue(); } m_PointerEventData.position = val; EventSystem.current.RaycastAll(m_PointerEventData, m_RaycastResults); if (m_RaycastResults.Count == 0) { return; } bool flag = false; foreach (RaycastResult raycastResult in m_RaycastResults) { RaycastResult current = raycastResult; if (!((Object)(object)((RaycastResult)(ref current)).gameObject != (Object)(object)((Component)this).gameObject)) { flag = true; break; } } if (flag) { BeginInteraction(val, GetCameraFromCanvas()); m_PointerMoveAction.performed += OnPointerMove; } } private void OnPointerMove(InputAction.CallbackContext ctx) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Vector2 pointerPosition = ((Pointer)ctx.control.device).position.ReadValue(); MoveStick(pointerPosition, GetCameraFromCanvas()); } private void OnPointerUp(InputAction.CallbackContext ctx) { EndInteraction(); m_PointerMoveAction.performed -= OnPointerMove; } private Camera GetCameraFromCanvas() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) Canvas componentInParent = ((Component)this).GetComponentInParent(); RenderMode? val = ((componentInParent != null) ? new RenderMode?(componentInParent.renderMode) : ((RenderMode?)null)); if (val != (RenderMode?)0 && (val != (RenderMode?)1 || !((Object)(object)((componentInParent != null) ? componentInParent.worldCamera : null) == (Object)null))) { return ((componentInParent != null) ? componentInParent.worldCamera : null) ?? Camera.main; } return null; } private void OnDrawGizmosSelected() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) Gizmos.matrix = ((Transform)(RectTransform)((Component)this).transform.parent).localToWorldMatrix; Vector2 val = ((RectTransform)((Component)this).transform).anchoredPosition; if (Application.isPlaying) { val = Vector2.op_Implicit(m_StartPos); } Gizmos.color = Color32.op_Implicit(new Color32((byte)84, (byte)173, (byte)219, byte.MaxValue)); Vector2 center = val; if (Application.isPlaying && m_Behaviour == Behaviour.ExactPositionWithDynamicOrigin) { center = m_PointerDownPos; } DrawGizmoCircle(center, m_MovementRange); if (m_Behaviour == Behaviour.ExactPositionWithDynamicOrigin) { Gizmos.color = Color32.op_Implicit(new Color32((byte)158, (byte)84, (byte)219, byte.MaxValue)); DrawGizmoCircle(val, m_DynamicOriginRange); } } private void DrawGizmoCircle(Vector2 center, float radius) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < 32; i++) { float num = (float)i / 32f * (float)Math.PI * 2f; float num2 = (float)(i + 1) / 32f * (float)Math.PI * 2f; Gizmos.DrawLine(new Vector3(center.x + Mathf.Cos(num) * radius, center.y + Mathf.Sin(num) * radius, 0f), new Vector3(center.x + Mathf.Cos(num2) * radius, center.y + Mathf.Sin(num2) * radius, 0f)); } } private void UpdateDynamicOriginClickableArea() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) Transform val = ((Component)this).transform.Find("DynamicOriginClickable"); if (Object.op_Implicit((Object)(object)val)) { ((RectTransform)val).sizeDelta = new Vector2(m_DynamicOriginRange * 2f, m_DynamicOriginRange * 2f); } } } } namespace UnityEngine.InputSystem.HID { public class HID : InputDevice { [Serializable] private class HIDLayoutBuilder { public string displayName; public HIDDeviceDescriptor hidDescriptor; public string parentLayout; public Type deviceType; public InputControlLayout Build() { InputControlLayout.Builder builder = new InputControlLayout.Builder { displayName = displayName, type = deviceType, extendsLayout = parentLayout, stateFormat = new FourCC('H', 'I', 'D') }; HIDElementDescriptor hIDElementDescriptor = Array.Find(hidDescriptor.elements, (HIDElementDescriptor element) => element.usagePage == UsagePage.GenericDesktop && element.usage == 48); HIDElementDescriptor hIDElementDescriptor2 = Array.Find(hidDescriptor.elements, (HIDElementDescriptor element) => element.usagePage == UsagePage.GenericDesktop && element.usage == 49); bool flag = hIDElementDescriptor.usage == 48 && hIDElementDescriptor2.usage == 49; if (flag) { int bit; int num; int sizeInBits; if (hIDElementDescriptor.reportOffsetInBits <= hIDElementDescriptor2.reportOffsetInBits) { bit = hIDElementDescriptor.reportOffsetInBits % 8; num = hIDElementDescriptor.reportOffsetInBits / 8; sizeInBits = hIDElementDescriptor2.reportOffsetInBits + hIDElementDescriptor2.reportSizeInBits - hIDElementDescriptor.reportOffsetInBits; } else { bit = hIDElementDescriptor2.reportOffsetInBits % 8; num = hIDElementDescriptor2.reportOffsetInBits / 8; sizeInBits = hIDElementDescriptor.reportOffsetInBits + hIDElementDescriptor.reportSizeInBits - hIDElementDescriptor2.reportSizeInBits; } builder.AddControl("stick").WithDisplayName("Stick").WithLayout("Stick") .WithBitOffset((uint)bit) .WithByteOffset((uint)num) .WithSizeInBits((uint)sizeInBits) .WithUsages(CommonUsages.Primary2DMotion); string text = hIDElementDescriptor.DetermineParameters(); string text2 = hIDElementDescriptor2.DetermineParameters(); builder.AddControl("stick/x").WithFormat(hIDElementDescriptor.isSigned ? InputStateBlock.FormatSBit : InputStateBlock.FormatBit).WithByteOffset((uint)(hIDElementDescriptor.reportOffsetInBits / 8 - num)) .WithBitOffset((uint)(hIDElementDescriptor.reportOffsetInBits % 8)) .WithSizeInBits((uint)hIDElementDescriptor.reportSizeInBits) .WithParameters(text) .WithDefaultState(hIDElementDescriptor.DetermineDefaultState()) .WithProcessors(hIDElementDescriptor.DetermineProcessors()); builder.AddControl("stick/y").WithFormat(hIDElementDescriptor2.isSigned ? InputStateBlock.FormatSBit : InputStateBlock.FormatBit).WithByteOffset((uint)(hIDElementDescriptor2.reportOffsetInBits / 8 - num)) .WithBitOffset((uint)(hIDElementDescriptor2.reportOffsetInBits % 8)) .WithSizeInBits((uint)hIDElementDescriptor2.reportSizeInBits) .WithParameters(text2) .WithDefaultState(hIDElementDescriptor2.DetermineDefaultState()) .WithProcessors(hIDElementDescriptor2.DetermineProcessors()); builder.AddControl("stick/up").WithParameters(StringHelpers.Join(",", text2, "clamp=2,clampMin=-1,clampMax=0,invert=true")); builder.AddControl("stick/down").WithParameters(StringHelpers.Join(",", text2, "clamp=2,clampMin=0,clampMax=1,invert=false")); builder.AddControl("stick/left").WithParameters(StringHelpers.Join(",", text, "clamp=2,clampMin=-1,clampMax=0,invert")); builder.AddControl("stick/right").WithParameters(StringHelpers.Join(",", text, "clamp=2,clampMin=0,clampMax=1")); } HIDElementDescriptor[] elements = hidDescriptor.elements; int num2 = elements.Length; for (int num3 = 0; num3 < num2; num3++) { ref HIDElementDescriptor reference = ref elements[num3]; if (reference.reportType != HIDReportType.Input || (flag && (reference.Is(UsagePage.GenericDesktop, 48) || reference.Is(UsagePage.GenericDesktop, 49)))) { continue; } string text3 = reference.DetermineLayout(); if (text3 != null) { string baseName = reference.DetermineName(); baseName = StringHelpers.MakeUniqueName(baseName, builder.controls, (InputControlLayout.ControlItem x) => x.name); InputControlLayout.Builder.ControlBuilder controlBuilder = builder.AddControl(baseName).WithDisplayName(reference.DetermineDisplayName()).WithLayout(text3) .WithByteOffset((uint)reference.reportOffsetInBits / 8u) .WithBitOffset((uint)reference.reportOffsetInBits % 8u) .WithSizeInBits((uint)reference.reportSizeInBits) .WithFormat(reference.DetermineFormat()) .WithDefaultState(reference.DetermineDefaultState()) .WithProcessors(reference.DetermineProcessors()); string text4 = reference.DetermineParameters(); if (!string.IsNullOrEmpty(text4)) { controlBuilder.WithParameters(text4); } InternedString[] array = reference.DetermineUsages(); if (array != null) { controlBuilder.WithUsages(array); } reference.AddChildControls(ref reference, baseName, ref builder); } } return builder.Build(); } } public enum HIDReportType { Unknown, Input, Output, Feature } public enum HIDCollectionType { Physical, Application, Logical, Report, NamedArray, UsageSwitch, UsageModifier } [Flags] public enum HIDElementFlags { Constant = 1, Variable = 2, Relative = 4, Wrap = 8, NonLinear = 0x10, NoPreferred = 0x20, NullState = 0x40, Volatile = 0x80, BufferedBytes = 0x100 } [Serializable] public struct HIDElementDescriptor { public int usage; public UsagePage usagePage; public int unit; public int unitExponent; public int logicalMin; public int logicalMax; public int physicalMin; public int physicalMax; public HIDReportType reportType; public int collectionIndex; public int reportId; public int reportSizeInBits; public int reportOffsetInBits; public HIDElementFlags flags; public int? usageMin; public int? usageMax; public bool hasNullState => (flags & HIDElementFlags.NullState) == HIDElementFlags.NullState; public bool hasPreferredState => (flags & HIDElementFlags.NoPreferred) != HIDElementFlags.NoPreferred; public bool isArray => (flags & HIDElementFlags.Variable) != HIDElementFlags.Variable; public bool isNonLinear => (flags & HIDElementFlags.NonLinear) == HIDElementFlags.NonLinear; public bool isRelative => (flags & HIDElementFlags.Relative) == HIDElementFlags.Relative; public bool isConstant => (flags & HIDElementFlags.Constant) == HIDElementFlags.Constant; public bool isWrapping => (flags & HIDElementFlags.Wrap) == HIDElementFlags.Wrap; internal bool isSigned => logicalMin < 0; internal float minFloatValue { get { if (isSigned) { int minValue = (int)(-(1L << reportSizeInBits - 1)); int maxValue = (int)((1L << reportSizeInBits - 1) - 1); return NumberHelpers.IntToNormalizedFloat(logicalMin, minValue, maxValue) * 2f - 1f; } uint maxValue2 = (uint)((1L << reportSizeInBits) - 1); return NumberHelpers.UIntToNormalizedFloat((uint)logicalMin, 0u, maxValue2); } } internal float maxFloatValue { get { if (isSigned) { int minValue = (int)(-(1L << reportSizeInBits - 1)); int maxValue = (int)((1L << reportSizeInBits - 1) - 1); return NumberHelpers.IntToNormalizedFloat(logicalMax, minValue, maxValue) * 2f - 1f; } uint maxValue2 = (uint)((1L << reportSizeInBits) - 1); return NumberHelpers.UIntToNormalizedFloat((uint)logicalMax, 0u, maxValue2); } } public bool Is(UsagePage usagePage, int usage) { if (usagePage == this.usagePage) { return usage == this.usage; } return false; } internal string DetermineName() { switch (usagePage) { case UsagePage.Button: if (usage == 1) { return "trigger"; } return $"button{usage}"; case UsagePage.GenericDesktop: { if (usage == 57) { return "hat"; } GenericDesktop genericDesktop = (GenericDesktop)usage; string text = genericDesktop.ToString(); return char.ToLowerInvariant(text[0]) + text.Substring(1); } default: return $"UsagePage({usagePage:X}) Usage({usage:X})"; } } internal string DetermineDisplayName() { switch (usagePage) { case UsagePage.Button: if (usage == 1) { return "Trigger"; } return $"Button {usage}"; case UsagePage.GenericDesktop: { GenericDesktop genericDesktop = (GenericDesktop)usage; return genericDesktop.ToString(); } default: return null; } } internal bool IsUsableElement() { int num = usage; if ((uint)(num - 48) <= 1u) { return usagePage == UsagePage.GenericDesktop; } return DetermineLayout() != null; } internal string DetermineLayout() { if (reportType != HIDReportType.Input) { return null; } switch (usagePage) { case UsagePage.Button: return "Button"; case UsagePage.GenericDesktop: switch (usage) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 64: case 65: case 66: case 67: case 68: case 69: return "Axis"; case 61: case 62: case 144: case 145: case 146: case 147: return "Button"; case 57: if (logicalMax - logicalMin + 1 == 8) { return "Dpad"; } break; } break; } return null; } internal FourCC DetermineFormat() { switch (reportSizeInBits) { case 8: if (!isSigned) { return InputStateBlock.FormatByte; } return InputStateBlock.FormatSByte; case 16: if (!isSigned) { return InputStateBlock.FormatUShort; } return InputStateBlock.FormatShort; case 32: if (!isSigned) { return InputStateBlock.FormatUInt; } return InputStateBlock.FormatInt; default: return InputStateBlock.FormatBit; } } internal InternedString[] DetermineUsages() { if (usagePage == UsagePage.Button && usage == 1) { return new InternedString[2] { CommonUsages.PrimaryTrigger, CommonUsages.PrimaryAction }; } if (usagePage == UsagePage.Button && usage == 2) { return new InternedString[2] { CommonUsages.SecondaryTrigger, CommonUsages.SecondaryAction }; } if (usagePage == UsagePage.GenericDesktop && usage == 53) { return new InternedString[1] { CommonUsages.Twist }; } return null; } internal string DetermineParameters() { if (usagePage == UsagePage.GenericDesktop) { switch (usage) { case 48: case 50: case 51: case 53: case 54: case 55: case 56: case 64: case 66: case 67: case 69: return DetermineAxisNormalizationParameters(); case 49: case 52: case 65: case 68: return StringHelpers.Join(",", "invert", DetermineAxisNormalizationParameters()); } } return null; } private string DetermineAxisNormalizationParameters() { if (logicalMin == 0 && logicalMax == 0) { return "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5"; } float num = minFloatValue; float num2 = maxFloatValue; if (Mathf.Approximately(0f, num) && Mathf.Approximately(0f, num2)) { return null; } float num3 = num + (num2 - num) / 2f; return string.Format(CultureInfo.InvariantCulture, "normalize,normalizeMin={0},normalizeMax={1},normalizeZero={2}", num, num2, num3); } internal string DetermineProcessors() { if (usagePage == UsagePage.GenericDesktop) { int num = usage; if ((uint)(num - 48) <= 8u || (uint)(num - 64) <= 5u) { return "axisDeadzone"; } } return null; } internal PrimitiveValue DetermineDefaultState() { if (usagePage == UsagePage.GenericDesktop) { switch (usage) { case 57: if (hasNullState) { if (logicalMin >= 1) { return new PrimitiveValue(logicalMin - 1); } ulong num2 = (ulong)((1L << reportSizeInBits) - 1); if ((ulong)logicalMax < num2) { return new PrimitiveValue(logicalMax + 1); } } break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 64: case 65: case 66: case 67: case 68: case 69: if (!isSigned) { int num = logicalMin + (logicalMax - logicalMin) / 2; if (num != 0) { return new PrimitiveValue(num); } } break; } } return default(PrimitiveValue); } internal void AddChildControls(ref HIDElementDescriptor element, string controlName, ref InputControlLayout.Builder builder) { if (usagePage == UsagePage.GenericDesktop && usage == 57) { PrimitiveValue primitiveValue = DetermineDefaultState(); if (!primitiveValue.isEmpty) { builder.AddControl(controlName + "/up").WithFormat(InputStateBlock.FormatBit).WithLayout("DiscreteButton") .WithParameters(string.Format(CultureInfo.InvariantCulture, "minValue={0},maxValue={1},nullValue={2},wrapAtValue={3}", logicalMax, logicalMin + 1, primitiveValue.ToString(), logicalMax)) .WithBitOffset((uint)element.reportOffsetInBits % 8u) .WithSizeInBits((uint)reportSizeInBits); builder.AddControl(controlName + "/right").WithFormat(InputStateBlock.FormatBit).WithLayout("DiscreteButton") .WithParameters(string.Format(CultureInfo.InvariantCulture, "minValue={0},maxValue={1}", logicalMin + 1, logicalMin + 3)) .WithBitOffset((uint)element.reportOffsetInBits % 8u) .WithSizeInBits((uint)reportSizeInBits); builder.AddControl(controlName + "/down").WithFormat(InputStateBlock.FormatBit).WithLayout("DiscreteButton") .WithParameters(string.Format(CultureInfo.InvariantCulture, "minValue={0},maxValue={1}", logicalMin + 3, logicalMin + 5)) .WithBitOffset((uint)element.reportOffsetInBits % 8u) .WithSizeInBits((uint)reportSizeInBits); builder.AddControl(controlName + "/left").WithFormat(InputStateBlock.FormatBit).WithLayout("DiscreteButton") .WithParameters(string.Format(CultureInfo.InvariantCulture, "minValue={0},maxValue={1}", logicalMin + 5, logicalMin + 7)) .WithBitOffset((uint)element.reportOffsetInBits % 8u) .WithSizeInBits((uint)reportSizeInBits); } } } } [Serializable] public struct HIDCollectionDescriptor { public HIDCollectionType type; public int usage; public UsagePage usagePage; public int parent; public int childCount; public int firstChild; } [Serializable] public struct HIDDeviceDescriptor { public int vendorId; public int productId; public int usage; public UsagePage usagePage; public int inputReportSize; public int outputReportSize; public int featureReportSize; public HIDElementDescriptor[] elements; public HIDCollectionDescriptor[] collections; public string ToJson() { return JsonUtility.ToJson((object)this, true); } public static HIDDeviceDescriptor FromJson(string json) { //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) try { HIDDeviceDescriptor result = default(HIDDeviceDescriptor); ReadOnlySpan readOnlySpan = json.AsSpan(); PredictiveParser predictiveParser = default(PredictiveParser); predictiveParser.ExpectSingleChar(readOnlySpan, '{'); predictiveParser.AcceptString(readOnlySpan, out var output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.vendorId = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.productId = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.usage = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.usagePage = (UsagePage)predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.inputReportSize = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.outputReportSize = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out output); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); result.featureReportSize = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.AcceptString(readOnlySpan, out var output2); if (output2.ToString() != "elements") { return result; } predictiveParser.ExpectSingleChar(readOnlySpan, ':'); predictiveParser.ExpectSingleChar(readOnlySpan, '['); List list = default(List); PooledObject> val = CollectionPool, HIDElementDescriptor>.Get(ref list); try { while (!predictiveParser.AcceptSingleChar(readOnlySpan, ']')) { predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectSingleChar(readOnlySpan, '{'); HIDElementDescriptor item = default(HIDElementDescriptor); predictiveParser.AcceptSingleChar(readOnlySpan, '}'); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.usage = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.usagePage = (UsagePage)predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.unit = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.unitExponent = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.logicalMin = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.logicalMax = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.physicalMin = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.physicalMax = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.collectionIndex = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.reportType = (HIDReportType)predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.reportId = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); predictiveParser.AcceptInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.reportSizeInBits = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.reportOffsetInBits = predictiveParser.ExpectInt(readOnlySpan); predictiveParser.AcceptSingleChar(readOnlySpan, ','); predictiveParser.ExpectString(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, ':'); item.flags = (HIDElementFlags)predictiveParser.ExpectInt(readOnlySpan); predictiveParser.ExpectSingleChar(readOnlySpan, '}'); list.Add(item); } result.elements = list.ToArray(); return result; } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } catch (Exception) { Debug.LogWarning((object)"Couldn't parse HID descriptor with fast parser. Using fallback"); return JsonUtility.FromJson(json); } } } public struct HIDDeviceDescriptorBuilder { public UsagePage usagePage; public int usage; private int m_CurrentReportId; private HIDReportType m_CurrentReportType; private int m_CurrentReportOffsetInBits; private List m_Elements; private List m_Collections; private int m_InputReportSize; private int m_OutputReportSize; private int m_FeatureReportSize; public HIDDeviceDescriptorBuilder(UsagePage usagePage, int usage) { this = default(HIDDeviceDescriptorBuilder); this.usagePage = usagePage; this.usage = usage; } public HIDDeviceDescriptorBuilder(GenericDesktop usage) : this(UsagePage.GenericDesktop, (int)usage) { } public HIDDeviceDescriptorBuilder StartReport(HIDReportType reportType, int reportId = 1) { m_CurrentReportId = reportId; m_CurrentReportType = reportType; m_CurrentReportOffsetInBits = 8; return this; } public HIDDeviceDescriptorBuilder AddElement(UsagePage usagePage, int usage, int sizeInBits) { if (m_Elements == null) { m_Elements = new List(); } else { foreach (HIDElementDescriptor element in m_Elements) { if (element.reportId == m_CurrentReportId && element.reportType == m_CurrentReportType && element.usagePage == usagePage && element.usage == usage) { throw new InvalidOperationException($"Cannot add two elements with the same usage page '{usagePage}' and usage '0x{usage:X} the to same device"); } } } m_Elements.Add(new HIDElementDescriptor { usage = usage, usagePage = usagePage, reportOffsetInBits = m_CurrentReportOffsetInBits, reportSizeInBits = sizeInBits, reportType = m_CurrentReportType, reportId = m_CurrentReportId }); m_CurrentReportOffsetInBits += sizeInBits; return this; } public HIDDeviceDescriptorBuilder AddElement(GenericDesktop usage, int sizeInBits) { return AddElement(UsagePage.GenericDesktop, (int)usage, sizeInBits); } public HIDDeviceDescriptorBuilder WithPhysicalMinMax(int min, int max) { int num = m_Elements.Count - 1; if (num < 0) { throw new InvalidOperationException("No element has been added to the descriptor yet"); } HIDElementDescriptor value = m_Elements[num]; value.physicalMin = min; value.physicalMax = max; m_Elements[num] = value; return this; } public HIDDeviceDescriptorBuilder WithLogicalMinMax(int min, int max) { int num = m_Elements.Count - 1; if (num < 0) { throw new InvalidOperationException("No element has been added to the descriptor yet"); } HIDElementDescriptor value = m_Elements[num]; value.logicalMin = min; value.logicalMax = max; m_Elements[num] = value; return this; } public HIDDeviceDescriptor Finish() { return new HIDDeviceDescriptor { usage = usage, usagePage = usagePage, elements = m_Elements?.ToArray(), collections = m_Collections?.ToArray() }; } } public enum UsagePage { Undefined = 0, GenericDesktop = 1, Simulation = 2, VRControls = 3, SportControls = 4, GameControls = 5, GenericDeviceControls = 6, Keyboard = 7, LEDs = 8, Button = 9, Ordinal = 10, Telephony = 11, Consumer = 12, Digitizer = 13, PID = 15, Unicode = 16, AlphanumericDisplay = 20, MedicalInstruments = 64, Monitor = 128, Power = 132, BarCodeScanner = 140, MagneticStripeReader = 142, Camera = 144, Arcade = 145, VendorDefined = 65280 } public enum GenericDesktop { Undefined = 0, Pointer = 1, Mouse = 2, Joystick = 4, Gamepad = 5, Keyboard = 6, Keypad = 7, MultiAxisController = 8, TabletPCControls = 9, AssistiveControl = 10, X = 48, Y = 49, Z = 50, Rx = 51, Ry = 52, Rz = 53, Slider = 54, Dial = 55, Wheel = 56, HatSwitch = 57, CountedBuffer = 58, ByteCount = 59, MotionWakeup = 60, Start = 61, Select = 62, Vx = 64, Vy = 65, Vz = 66, Vbrx = 67, Vbry = 68, Vbrz = 69, Vno = 70, FeatureNotification = 71, ResolutionMultiplier = 72, SystemControl = 128, SystemPowerDown = 129, SystemSleep = 130, SystemWakeUp = 131, SystemContextMenu = 132, SystemMainMenu = 133, SystemAppMenu = 134, SystemMenuHelp = 135, SystemMenuExit = 136, SystemMenuSelect = 137, SystemMenuRight = 138, SystemMenuLeft = 139, SystemMenuUp = 140, SystemMenuDown = 141, SystemColdRestart = 142, SystemWarmRestart = 143, DpadUp = 144, DpadDown = 145, DpadRight = 146, DpadLeft = 147, SystemDock = 160, SystemUndock = 161, SystemSetup = 162, SystemBreak = 163, SystemDebuggerBreak = 164, ApplicationBreak = 165, ApplicationDebuggerBreak = 166, SystemSpeakerMute = 167, SystemHibernate = 168, SystemDisplayInvert = 176, SystemDisplayInternal = 177, SystemDisplayExternal = 178, SystemDisplayBoth = 179, SystemDisplayDual = 180, SystemDisplayToggleIntExt = 181, SystemDisplaySwapPrimarySecondary = 182, SystemDisplayLCDAutoScale = 183 } public enum Simulation { Undefined = 0, FlightSimulationDevice = 1, AutomobileSimulationDevice = 2, TankSimulationDevice = 3, SpaceshipSimulationDevice = 4, SubmarineSimulationDevice = 5, SailingSimulationDevice = 6, MotorcycleSimulationDevice = 7, SportsSimulationDevice = 8, AirplaneSimulationDevice = 9, HelicopterSimulationDevice = 10, MagicCarpetSimulationDevice = 11, BicylcleSimulationDevice = 12, FlightControlStick = 32, FlightStick = 33, CyclicControl = 34, CyclicTrim = 35, FlightYoke = 36, TrackControl = 37, Aileron = 176, AileronTrim = 177, AntiTorqueControl = 178, AutopilotEnable = 179, ChaffRelease = 180, CollectiveControl = 181, DiveBreak = 182, ElectronicCountermeasures = 183, Elevator = 184, ElevatorTrim = 185, Rudder = 186, Throttle = 187, FlightCommunications = 188, FlareRelease = 189, LandingGear = 190, ToeBreak = 191, Trigger = 192, WeaponsArm = 193, WeaponsSelect = 194, WingFlaps = 195, Accelerator = 196, Brake = 197, Clutch = 198, Shifter = 199, Steering = 200, TurretDirection = 201, BarrelElevation = 202, DivePlane = 203, Ballast = 204, BicycleCrank = 205, HandleBars = 206, FrontBrake = 207, RearBrake = 208 } public enum Button { Undefined, Primary, Secondary, Tertiary } internal const string kHIDInterface = "HID"; internal const string kHIDNamespace = "HID"; private bool m_HaveParsedHIDDescriptor; private HIDDeviceDescriptor m_HIDDescriptor; public static FourCC QueryHIDReportDescriptorDeviceCommandType => new FourCC('H', 'I', 'D', 'D'); public static FourCC QueryHIDReportDescriptorSizeDeviceCommandType => new FourCC('H', 'I', 'D', 'S'); public static FourCC QueryHIDParsedReportDescriptorDeviceCommandType => new FourCC('H', 'I', 'D', 'P'); public HIDDeviceDescriptor hidDescriptor { get { if (!m_HaveParsedHIDDescriptor) { if (!string.IsNullOrEmpty(base.description.capabilities)) { m_HIDDescriptor = JsonUtility.FromJson(base.description.capabilities); } m_HaveParsedHIDDescriptor = true; } return m_HIDDescriptor; } } internal static string OnFindLayoutForDevice(ref InputDeviceDescription description, string matchedLayout, InputDeviceExecuteCommandDelegate executeDeviceCommand) { if (!string.IsNullOrEmpty(matchedLayout)) { return null; } if (description.interfaceName != "HID") { return null; } HIDDeviceDescriptor hIDDeviceDescriptor = ReadHIDDeviceDescriptor(ref description, executeDeviceCommand); if (!Enumerable.Contains(HIDSupport.supportedHIDUsages, new HIDSupport.HIDPageUsage(hIDDeviceDescriptor.usagePage, hIDDeviceDescriptor.usage))) { return null; } bool flag = false; if (hIDDeviceDescriptor.elements != null) { HIDElementDescriptor[] elements = hIDDeviceDescriptor.elements; foreach (HIDElementDescriptor hIDElementDescriptor in elements) { if (hIDElementDescriptor.IsUsableElement()) { flag = true; break; } } } if (!flag) { return null; } Type typeFromHandle = typeof(HID); string text = "HID"; if (hIDDeviceDescriptor.usagePage == UsagePage.GenericDesktop && (hIDDeviceDescriptor.usage == 4 || hIDDeviceDescriptor.usage == 5)) { text = "Joystick"; typeFromHandle = typeof(Joystick); } string text2 = ""; if (text != "Joystick") { text2 = ((hIDDeviceDescriptor.usagePage == UsagePage.GenericDesktop) ? $" {(GenericDesktop)hIDDeviceDescriptor.usage}" : $" {hIDDeviceDescriptor.usagePage}-{hIDDeviceDescriptor.usage}"); } InputDeviceMatcher inputDeviceMatcher = InputDeviceMatcher.FromDeviceDescription(description); string result; if (!string.IsNullOrEmpty(description.product) && !string.IsNullOrEmpty(description.manufacturer)) { result = "HID::" + description.manufacturer + " " + description.product + text2; } else if (!string.IsNullOrEmpty(description.product)) { result = "HID::" + description.product + text2; } else { if (hIDDeviceDescriptor.vendorId == 0) { return null; } result = string.Format("{0}::{1:X}-{2:X}{3}", "HID", hIDDeviceDescriptor.vendorId, hIDDeviceDescriptor.productId, text2); inputDeviceMatcher = inputDeviceMatcher.WithCapability("productId", hIDDeviceDescriptor.productId).WithCapability("vendorId", hIDDeviceDescriptor.vendorId); } inputDeviceMatcher = inputDeviceMatcher.WithCapability("usage", hIDDeviceDescriptor.usage).WithCapability("usagePage", hIDDeviceDescriptor.usagePage); HIDLayoutBuilder layout = new HIDLayoutBuilder { displayName = description.product, hidDescriptor = hIDDeviceDescriptor, parentLayout = text, deviceType = (typeFromHandle ?? typeof(HID)) }; InputSystem.RegisterLayoutBuilder(() => layout.Build(), result, text, inputDeviceMatcher); return result; } internal unsafe static HIDDeviceDescriptor ReadHIDDeviceDescriptor(ref InputDeviceDescription deviceDescription, InputDeviceExecuteCommandDelegate executeCommandDelegate) { //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) if (deviceDescription.interfaceName != "HID") { throw new ArgumentException($"Device '{deviceDescription}' is not a HID"); } bool flag = true; HIDDeviceDescriptor deviceDescriptor = default(HIDDeviceDescriptor); if (!string.IsNullOrEmpty(deviceDescription.capabilities)) { try { deviceDescriptor = HIDDeviceDescriptor.FromJson(deviceDescription.capabilities); if (deviceDescriptor.elements != null && deviceDescriptor.elements.Length != 0) { flag = false; } } catch (Exception ex) { Debug.LogError((object)$"Could not parse HID descriptor of device '{deviceDescription}'"); Debug.LogException(ex); } } if (flag) { InputDeviceCommand command = new InputDeviceCommand(QueryHIDReportDescriptorSizeDeviceCommandType); long num = executeCommandDelegate(ref command); if (num > 0) { NativeArray val = InputDeviceCommand.AllocateNative(QueryHIDReportDescriptorDeviceCommandType, (int)num); try { InputDeviceCommand* unsafePtr = (InputDeviceCommand*)NativeArrayUnsafeUtility.GetUnsafePtr(val); if (executeCommandDelegate(ref *unsafePtr) != num) { return default(HIDDeviceDescriptor); } if (!HIDParser.ParseReportDescriptor((byte*)unsafePtr->payloadPtr, (int)num, ref deviceDescriptor)) { return default(HIDDeviceDescriptor); } } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } deviceDescription.capabilities = deviceDescriptor.ToJson(); } else { NativeArray val2 = InputDeviceCommand.AllocateNative(QueryHIDParsedReportDescriptorDeviceCommandType, 2097152); try { InputDeviceCommand* unsafePtr2 = (InputDeviceCommand*)NativeArrayUnsafeUtility.GetUnsafePtr(val2); long num2 = executeCommandDelegate(ref *unsafePtr2); if (num2 < 0) { return default(HIDDeviceDescriptor); } byte[] array = new byte[num2]; fixed (byte* ptr = array) { UnsafeUtility.MemCpy((void*)ptr, unsafePtr2->payloadPtr, num2); } string text = Encoding.UTF8.GetString(array, 0, (int)num2); try { deviceDescriptor = HIDDeviceDescriptor.FromJson(text); } catch (Exception ex2) { Debug.LogError((object)$"Could not parse HID descriptor of device '{deviceDescription}'"); Debug.LogException(ex2); return default(HIDDeviceDescriptor); } deviceDescription.capabilities = text; } finally { ((IDisposable)val2/*cast due to .constrained prefix*/).Dispose(); } } } return deviceDescriptor; } public static string UsagePageToString(UsagePage usagePage) { if (usagePage < UsagePage.VendorDefined) { return usagePage.ToString(); } return "Vendor-Defined"; } public static string UsageToString(UsagePage usagePage, int usage) { switch (usagePage) { case UsagePage.GenericDesktop: { GenericDesktop genericDesktop = (GenericDesktop)usage; return genericDesktop.ToString(); } case UsagePage.Simulation: { Simulation simulation = (Simulation)usage; return simulation.ToString(); } default: return null; } } } internal static class HIDParser { private struct HIDReportData { public int reportId; public HID.HIDReportType reportType; public int currentBitOffset; public static int FindOrAddReport(int? reportId, HID.HIDReportType reportType, List reports) { int num = 1; if (reportId.HasValue) { num = reportId.Value; } for (int i = 0; i < reports.Count; i++) { if (reports[i].reportId == num && reports[i].reportType == reportType) { return i; } } reports.Add(new HIDReportData { reportId = num, reportType = reportType }); return reports.Count - 1; } } private enum HIDItemTypeAndTag { Input = 128, Output = 144, Feature = 176, Collection = 160, EndCollection = 192, UsagePage = 4, LogicalMinimum = 20, LogicalMaximum = 36, PhysicalMinimum = 52, PhysicalMaximum = 68, UnitExponent = 84, Unit = 100, ReportSize = 116, ReportID = 132, ReportCount = 148, Push = 164, Pop = 180, Usage = 8, UsageMinimum = 24, UsageMaximum = 40, DesignatorIndex = 56, DesignatorMinimum = 72, DesignatorMaximum = 88, StringIndex = 120, StringMinimum = 136, StringMaximum = 152, Delimiter = 168 } private struct HIDItemStateLocal { public int? usage; public int? usageMinimum; public int? usageMaximum; public int? designatorIndex; public int? designatorMinimum; public int? designatorMaximum; public int? stringIndex; public int? stringMinimum; public int? stringMaximum; public List usageList; public static void Reset(ref HIDItemStateLocal state) { List list = state.usageList; state = default(HIDItemStateLocal); if (list != null) { list.Clear(); state.usageList = list; } } public void SetUsage(int value) { if (usage.HasValue) { if (usageList == null) { usageList = new List(); } usageList.Add(usage.Value); } usage = value; } public int GetUsage(int index) { if (usageMinimum.HasValue && usageMaximum.HasValue) { int value = usageMinimum.Value; int value2 = usageMaximum.Value; int num = value2 - value; if (num < 0) { return 0; } if (index >= num) { return value2; } return value + index; } if (usageList != null && usageList.Count > 0) { int count = usageList.Count; if (index >= count) { return usage.Value; } return usageList[index]; } if (usage.HasValue) { return usage.Value; } return 0; } } private struct HIDItemStateGlobal { public int? usagePage; public int? logicalMinimum; public int? logicalMaximum; public int? physicalMinimum; public int? physicalMaximum; public int? unitExponent; public int? unit; public int? reportSize; public int? reportCount; public int? reportId; public HID.UsagePage GetUsagePage(int index, ref HIDItemStateLocal localItemState) { if (!usagePage.HasValue) { return (HID.UsagePage)(localItemState.GetUsage(index) >> 16); } return (HID.UsagePage)usagePage.Value; } public int GetPhysicalMin() { if (!physicalMinimum.HasValue || !physicalMaximum.HasValue || (physicalMinimum.Value == 0 && physicalMaximum.Value == 0)) { return logicalMinimum ?? 0; } return physicalMinimum.Value; } public int GetPhysicalMax() { if (!physicalMinimum.HasValue || !physicalMaximum.HasValue || (physicalMinimum.Value == 0 && physicalMaximum.Value == 0)) { return logicalMaximum ?? 0; } return physicalMaximum.Value; } } public unsafe static bool ParseReportDescriptor(byte[] buffer, ref HID.HIDDeviceDescriptor deviceDescriptor) { if (buffer == null) { throw new ArgumentNullException("buffer"); } fixed (byte* bufferPtr = buffer) { return ParseReportDescriptor(bufferPtr, buffer.Length, ref deviceDescriptor); } } public unsafe static bool ParseReportDescriptor(byte* bufferPtr, int bufferLength, ref HID.HIDDeviceDescriptor deviceDescriptor) { HIDItemStateLocal localItemState = default(HIDItemStateLocal); HIDItemStateGlobal hIDItemStateGlobal = default(HIDItemStateGlobal); List list = new List(); List list2 = new List(); List list3 = new List(); int num = -1; byte* ptr = bufferPtr + bufferLength; byte* ptr2 = bufferPtr; while (ptr2 < ptr) { byte num2 = *ptr2; if (num2 == 254) { throw new NotImplementedException("long item support"); } byte b = (byte)(num2 & 3); byte b2 = (byte)(num2 & 0xFC); ptr2++; switch (b2) { case 4: hIDItemStateGlobal.usagePage = ReadData(b, ptr2, ptr); break; case 148: hIDItemStateGlobal.reportCount = ReadData(b, ptr2, ptr); break; case 116: hIDItemStateGlobal.reportSize = ReadData(b, ptr2, ptr); break; case 132: hIDItemStateGlobal.reportId = ReadData(b, ptr2, ptr); break; case 20: hIDItemStateGlobal.logicalMinimum = ReadData(b, ptr2, ptr); break; case 36: hIDItemStateGlobal.logicalMaximum = ReadData(b, ptr2, ptr); break; case 52: hIDItemStateGlobal.physicalMinimum = ReadData(b, ptr2, ptr); break; case 68: hIDItemStateGlobal.physicalMaximum = ReadData(b, ptr2, ptr); break; case 84: hIDItemStateGlobal.unitExponent = ReadData(b, ptr2, ptr); break; case 100: hIDItemStateGlobal.unit = ReadData(b, ptr2, ptr); break; case 8: localItemState.SetUsage(ReadData(b, ptr2, ptr)); break; case 24: localItemState.usageMinimum = ReadData(b, ptr2, ptr); break; case 40: localItemState.usageMaximum = ReadData(b, ptr2, ptr); break; case 160: { int parent = num; num = list3.Count; list3.Add(new HID.HIDCollectionDescriptor { type = (HID.HIDCollectionType)ReadData(b, ptr2, ptr), parent = parent, usagePage = hIDItemStateGlobal.GetUsagePage(0, ref localItemState), usage = localItemState.GetUsage(0), firstChild = list2.Count }); HIDItemStateLocal.Reset(ref localItemState); break; } case 192: { if (num == -1) { return false; } HID.HIDCollectionDescriptor value2 = list3[num]; value2.childCount = list2.Count - value2.firstChild; list3[num] = value2; num = value2.parent; HIDItemStateLocal.Reset(ref localItemState); break; } case 128: case 144: case 176: { HID.HIDReportType reportType = b2 switch { 144 => HID.HIDReportType.Output, 128 => HID.HIDReportType.Input, _ => HID.HIDReportType.Feature, }; int index = HIDReportData.FindOrAddReport(hIDItemStateGlobal.reportId, reportType, list); HIDReportData value = list[index]; if (value.currentBitOffset == 0 && hIDItemStateGlobal.reportId.HasValue) { value.currentBitOffset = 8; } int num3 = hIDItemStateGlobal.reportCount ?? 1; int flags = ReadData(b, ptr2, ptr); for (int i = 0; i < num3; i++) { HID.HIDElementDescriptor item = new HID.HIDElementDescriptor { usage = (localItemState.GetUsage(i) & 0xFFFF), usagePage = hIDItemStateGlobal.GetUsagePage(i, ref localItemState), reportType = reportType, reportSizeInBits = (hIDItemStateGlobal.reportSize ?? 8), reportOffsetInBits = value.currentBitOffset, reportId = (hIDItemStateGlobal.reportId ?? 1), flags = (HID.HIDElementFlags)flags, logicalMin = (hIDItemStateGlobal.logicalMinimum ?? 0), logicalMax = (hIDItemStateGlobal.logicalMaximum ?? 0), physicalMin = hIDItemStateGlobal.GetPhysicalMin(), physicalMax = hIDItemStateGlobal.GetPhysicalMax(), unitExponent = (hIDItemStateGlobal.unitExponent ?? 0), unit = (hIDItemStateGlobal.unit ?? 0) }; value.currentBitOffset += item.reportSizeInBits; list2.Add(item); } list[index] = value; HIDItemStateLocal.Reset(ref localItemState); break; } } ptr2 = ((b != 3) ? (ptr2 + (int)b) : (ptr2 + 4)); } deviceDescriptor.elements = list2.ToArray(); deviceDescriptor.collections = list3.ToArray(); foreach (HID.HIDCollectionDescriptor item2 in list3) { if (item2.parent == -1 && item2.type == HID.HIDCollectionType.Application) { deviceDescriptor.usage = item2.usage; deviceDescriptor.usagePage = item2.usagePage; break; } } return true; } private unsafe static int ReadData(int itemSize, byte* currentPtr, byte* endPtr) { switch (itemSize) { case 0: return 0; case 1: if (currentPtr >= endPtr) { return 0; } return *currentPtr; case 2: { if (currentPtr + 2 >= endPtr) { return 0; } byte b4 = *currentPtr; return (currentPtr[1] << 8) | b4; } case 3: { if (currentPtr + 4 >= endPtr) { return 0; } byte b = *currentPtr; byte b2 = currentPtr[1]; byte b3 = currentPtr[2]; return (currentPtr[3] << 24) | (b3 << 24) | (b2 << 8) | b; } default: return 0; } } } public static class HIDSupport { public struct HIDPageUsage { public HID.UsagePage page; public int usage; public HIDPageUsage(HID.UsagePage page, int usage) { this.page = page; this.usage = usage; } public HIDPageUsage(HID.GenericDesktop usage) { page = HID.UsagePage.GenericDesktop; this.usage = (int)usage; } } private static HIDPageUsage[] s_SupportedHIDUsages; public static ReadOnlyArray supportedHIDUsages { get { return s_SupportedHIDUsages; } set { s_SupportedHIDUsages = value.ToArray(); InputSystem.s_Manager.AddAvailableDevicesThatAreNowRecognized(); for (int i = 0; i < InputSystem.devices.Count; i++) { InputDevice inputDevice = InputSystem.devices[i]; if (inputDevice is HID hID && !s_SupportedHIDUsages.Contains(new HIDPageUsage(hID.hidDescriptor.usagePage, hID.hidDescriptor.usage))) { InputSystem.RemoveLayout(inputDevice.layout); i--; } } } } internal static void Initialize() { s_SupportedHIDUsages = new HIDPageUsage[3] { new HIDPageUsage(HID.GenericDesktop.Joystick), new HIDPageUsage(HID.GenericDesktop.Gamepad), new HIDPageUsage(HID.GenericDesktop.MultiAxisController) }; InputSystem.RegisterLayout(); InputSystem.onFindLayoutForDevice += HID.OnFindLayoutForDevice; } } } namespace UnityEngine.InputSystem.EnhancedTouch { public static class EnhancedTouchSupport { private static int s_Enabled; private static InputSettings.UpdateMode s_UpdateMode; public static bool enabled => s_Enabled > 0; public static void Enable() { s_Enabled++; if (s_Enabled <= 1) { InputSystem.onDeviceChange += OnDeviceChange; InputSystem.onBeforeUpdate += Touch.BeginUpdate; InputSystem.onSettingsChange += OnSettingsChange; SetUpState(); } } public static void Disable() { if (enabled) { s_Enabled--; if (s_Enabled <= 0) { InputSystem.onDeviceChange -= OnDeviceChange; InputSystem.onBeforeUpdate -= Touch.BeginUpdate; InputSystem.onSettingsChange -= OnSettingsChange; TearDownState(); } } } internal static void Reset() { Touch.s_GlobalState.touchscreens = default(InlinedArray); Touch.s_GlobalState.playerState.Destroy(); Touch.s_GlobalState.playerState = default(Touch.FingerAndTouchState); s_Enabled = 0; } private static void SetUpState() { Touch.s_GlobalState.playerState.updateMask = InputUpdateType.Dynamic | InputUpdateType.Fixed | InputUpdateType.Manual; s_UpdateMode = InputSystem.settings.updateMode; foreach (InputDevice device in InputSystem.devices) { OnDeviceChange(device, InputDeviceChange.Added); } } internal static void TearDownState() { foreach (InputDevice device in InputSystem.devices) { OnDeviceChange(device, InputDeviceChange.Removed); } Touch.s_GlobalState.playerState.Destroy(); Touch.s_GlobalState.playerState = default(Touch.FingerAndTouchState); } private static void OnDeviceChange(InputDevice device, InputDeviceChange change) { switch (change) { case InputDeviceChange.Added: if (device is Touchscreen screen2) { Touch.AddTouchscreen(screen2); } break; case InputDeviceChange.Removed: if (device is Touchscreen screen) { Touch.RemoveTouchscreen(screen); } break; } } private static void OnSettingsChange() { InputSettings.UpdateMode updateMode = InputSystem.settings.updateMode; if (s_UpdateMode != updateMode) { TearDownState(); SetUpState(); } } [Conditional("DEVELOPMENT_BUILD")] [Conditional("UNITY_EDITOR")] internal static void CheckEnabled() { if (!enabled) { throw new InvalidOperationException("EnhancedTouch API is not enabled; call EnhancedTouchSupport.Enable()"); } } } public class Finger { internal readonly InputStateHistory m_StateHistory; public Touchscreen screen { get; } public int index { get; } public bool isActive => currentTouch.valid; public Vector2 screenPosition { get { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) Touch touch = lastTouch; if (!touch.valid) { return default(Vector2); } return touch.screenPosition; } } public Touch lastTouch { get { int count = m_StateHistory.Count; if (count == 0) { return default(Touch); } return new Touch(this, m_StateHistory[count - 1]); } } public Touch currentTouch { get { Touch result = lastTouch; if (!result.valid) { return default(Touch); } if (result.isInProgress) { return result; } if (result.updateStepCount == InputUpdate.s_UpdateStepCount) { return result; } return default(Touch); } } public TouchHistory touchHistory => new TouchHistory(this, m_StateHistory); internal Finger(Touchscreen screen, int index, InputUpdateType updateMask) { this.screen = screen; this.index = index; m_StateHistory = new InputStateHistory(screen.touches[index]) { historyDepth = Touch.maxHistoryLengthPerFinger, extraMemoryPerRecord = UnsafeUtility.SizeOf(), onRecordAdded = OnTouchRecorded, onShouldRecordStateChange = ShouldRecordTouch, updateMask = updateMask }; m_StateHistory.StartRecording(); if (screen.touches[index].isInProgress) { m_StateHistory.RecordStateChange(screen.touches[index], screen.touches[index].value); } } private unsafe static bool ShouldRecordTouch(InputControl control, double time, InputEventPtr eventPtr) { if (!eventPtr.valid) { return false; } FourCC type = eventPtr.type; if (type != 1398030676 && type != 1145852993) { return false; } TouchState* ptr = (TouchState*)((byte*)control.currentStatePtr + control.stateBlock.byteOffset); if (ptr->isTapRelease) { return false; } return true; } private unsafe void OnTouchRecorded(InputStateHistory.Record record) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) int recordIndex = record.recordIndex; InputStateHistory.RecordHeader* recordUnchecked = m_StateHistory.GetRecordUnchecked(recordIndex); TouchState* statePtrWithoutControlIndex = (TouchState*)recordUnchecked->statePtrWithoutControlIndex; statePtrWithoutControlIndex->updateStepCount = InputUpdate.s_UpdateStepCount; Touch.s_GlobalState.playerState.haveBuiltActiveTouches = false; Touch.ExtraDataPerTouchState* ptr = (Touch.ExtraDataPerTouchState*)((byte*)recordUnchecked + m_StateHistory.bytesPerRecord - UnsafeUtility.SizeOf()); ptr->uniqueId = ++Touch.s_GlobalState.playerState.lastId; Unsafe.Write(&ptr->accumulatedDelta, statePtrWithoutControlIndex->delta); if (statePtrWithoutControlIndex->phase != TouchPhase.Began) { if (recordIndex != m_StateHistory.m_HeadIndex) { int num = ((recordIndex == 0) ? (m_StateHistory.historyDepth - 1) : (recordIndex - 1)); TouchState* statePtrWithoutControlIndex2 = (TouchState*)m_StateHistory.GetRecordUnchecked(num)->statePtrWithoutControlIndex; Vector2* delta = &statePtrWithoutControlIndex->delta; Unsafe.Write(delta, *delta - statePtrWithoutControlIndex2->delta); statePtrWithoutControlIndex->beganInSameFrame = statePtrWithoutControlIndex2->beganInSameFrame && statePtrWithoutControlIndex2->updateStepCount == statePtrWithoutControlIndex->updateStepCount; } } else { statePtrWithoutControlIndex->beganInSameFrame = true; } switch (statePtrWithoutControlIndex->phase) { case TouchPhase.Began: DelegateHelpers.InvokeCallbacksSafe(ref Touch.s_GlobalState.onFingerDown, this, "Touch.onFingerDown"); break; case TouchPhase.Moved: DelegateHelpers.InvokeCallbacksSafe(ref Touch.s_GlobalState.onFingerMove, this, "Touch.onFingerMove"); break; case TouchPhase.Ended: case TouchPhase.Canceled: DelegateHelpers.InvokeCallbacksSafe(ref Touch.s_GlobalState.onFingerUp, this, "Touch.onFingerUp"); break; } } private unsafe Touch FindTouch(uint uniqueId) { foreach (InputStateHistory.Record item in m_StateHistory) { if (((Touch.ExtraDataPerTouchState*)item.GetUnsafeExtraMemoryPtrUnchecked())->uniqueId == uniqueId) { return new Touch(this, item); } } return default(Touch); } internal unsafe TouchHistory GetTouchHistory(Touch touch) { InputStateHistory.Record touchRecord = touch.m_TouchRecord; if (touchRecord.owner != m_StateHistory) { touch = FindTouch(touch.uniqueId); if (!touch.valid) { return default(TouchHistory); } } int touchId = touch.touchId; int num = touch.m_TouchRecord.index; int num2 = 0; if (touch.phase != TouchPhase.Began) { InputStateHistory.Record previous = touch.m_TouchRecord.previous; while (previous.valid) { TouchState* unsafeMemoryPtr = (TouchState*)previous.GetUnsafeMemoryPtr(); if (unsafeMemoryPtr->touchId != touchId) { break; } num2++; if (unsafeMemoryPtr->phase == TouchPhase.Began) { break; } previous = previous.previous; } } if (num2 == 0) { return default(TouchHistory); } num--; return new TouchHistory(this, m_StateHistory, num, num2); } } public struct Touch : IEquatable { internal struct GlobalState { internal InlinedArray touchscreens; internal int historyLengthPerFinger; internal CallbackArray> onFingerDown; internal CallbackArray> onFingerMove; internal CallbackArray> onFingerUp; internal FingerAndTouchState playerState; } internal struct FingerAndTouchState { public InputUpdateType updateMask; public Finger[] fingers; public Finger[] activeFingers; public Touch[] activeTouches; public int activeFingerCount; public int activeTouchCount; public int totalFingerCount; public uint lastId; public bool haveBuiltActiveTouches; public bool haveActiveTouchesNeedingRefreshNextUpdate; public InputStateHistory activeTouchState; public void AddFingers(Touchscreen screen) { int count = screen.touches.Count; ArrayHelpers.EnsureCapacity(ref fingers, totalFingerCount, count); for (int i = 0; i < count; i++) { Finger value = new Finger(screen, i, updateMask); ArrayHelpers.AppendWithCapacity(ref fingers, ref totalFingerCount, value); } } public void RemoveFingers(Touchscreen screen) { int count = screen.touches.Count; for (int i = 0; i < fingers.Length; i++) { if (fingers[i].screen == screen) { for (int j = 0; j < count; j++) { fingers[i + j].m_StateHistory.Dispose(); } ArrayHelpers.EraseSliceWithCapacity(ref fingers, ref totalFingerCount, i, count); break; } } haveBuiltActiveTouches = false; } public void Destroy() { for (int i = 0; i < totalFingerCount; i++) { fingers[i].m_StateHistory.Dispose(); } activeTouchState?.Dispose(); activeTouchState = null; } public void UpdateActiveFingers() { activeFingerCount = 0; for (int i = 0; i < totalFingerCount; i++) { Finger finger = fingers[i]; if (finger.currentTouch.valid) { ArrayHelpers.AppendWithCapacity(ref activeFingers, ref activeFingerCount, finger); } } } public unsafe void UpdateActiveTouches() { //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) if (haveBuiltActiveTouches) { return; } if (activeTouchState == null) { activeTouchState = new InputStateHistory { extraMemoryPerRecord = UnsafeUtility.SizeOf() }; } else { activeTouchState.Clear(); activeTouchState.m_ControlCount = 0; activeTouchState.m_Controls.Clear(); } activeTouchCount = 0; haveActiveTouchesNeedingRefreshNextUpdate = false; uint s_UpdateStepCount = InputUpdate.s_UpdateStepCount; for (int i = 0; i < totalFingerCount; i++) { ref Finger reference = ref fingers[i]; InputStateHistory stateHistory = reference.m_StateHistory; int count = stateHistory.Count; if (count == 0) { continue; } int index = activeTouchCount; int num = 0; TouchState* ptr = default(TouchState*); int num2 = stateHistory.UserIndexToRecordIndex(count - 1); InputStateHistory.RecordHeader* ptr2 = stateHistory.GetRecordUnchecked(num2); int bytesPerRecord = stateHistory.bytesPerRecord; int num3 = bytesPerRecord - stateHistory.extraMemoryPerRecord; for (int j = 0; j < count; j++) { if (j != 0) { num2--; if (num2 < 0) { num2 = stateHistory.historyDepth - 1; ptr2 = stateHistory.GetRecordUnchecked(num2); } else { ptr2 = (InputStateHistory.RecordHeader*)((byte*)ptr2 - bytesPerRecord); } } TouchState* statePtrWithoutControlIndex = (TouchState*)ptr2->statePtrWithoutControlIndex; bool flag = statePtrWithoutControlIndex->updateStepCount == s_UpdateStepCount; if (statePtrWithoutControlIndex->touchId == num && !statePtrWithoutControlIndex->phase.IsEndedOrCanceled()) { if (flag && statePtrWithoutControlIndex->phase == TouchPhase.Began) { ptr->phase = TouchPhase.Began; Unsafe.Write(&ptr->position, statePtrWithoutControlIndex->position); Unsafe.Write(&ptr->delta, default(Vector2)); haveActiveTouchesNeedingRefreshNextUpdate = true; } continue; } if (statePtrWithoutControlIndex->phase.IsEndedOrCanceled() && (!statePtrWithoutControlIndex->beganInSameFrame || statePtrWithoutControlIndex->updateStepCount != s_UpdateStepCount - 1) && !flag) { break; } ExtraDataPerTouchState* ptr3 = (ExtraDataPerTouchState*)((byte*)ptr2 + num3); int index2; InputStateHistory.RecordHeader* ptr4 = activeTouchState.AllocateRecord(out index2); TouchState* statePtrWithControlIndex = (TouchState*)ptr4->statePtrWithControlIndex; ExtraDataPerTouchState* ptr5 = (ExtraDataPerTouchState*)((byte*)ptr4 + activeTouchState.bytesPerRecord - UnsafeUtility.SizeOf()); ptr4->time = ptr2->time; ptr4->controlIndex = ArrayHelpers.AppendWithCapacity(ref activeTouchState.m_Controls, ref activeTouchState.m_ControlCount, reference.m_StateHistory.controls[0]); UnsafeUtility.MemCpy((void*)statePtrWithControlIndex, (void*)statePtrWithoutControlIndex, (long)UnsafeUtility.SizeOf()); UnsafeUtility.MemCpy((void*)ptr5, (void*)ptr3, (long)UnsafeUtility.SizeOf()); TouchPhase phase = statePtrWithoutControlIndex->phase; if ((phase == TouchPhase.Moved || phase == TouchPhase.Began) && !flag && (phase != TouchPhase.Moved || !statePtrWithoutControlIndex->beganInSameFrame || statePtrWithoutControlIndex->updateStepCount != s_UpdateStepCount - 1)) { statePtrWithControlIndex->phase = TouchPhase.Stationary; Unsafe.Write(&statePtrWithControlIndex->delta, default(Vector2)); } else if (!flag && !statePtrWithoutControlIndex->beganInSameFrame) { Unsafe.Write(&statePtrWithControlIndex->delta, default(Vector2)); } else { Unsafe.Write(&statePtrWithControlIndex->delta, ptr5->accumulatedDelta); } Touch value = new Touch(touchRecord: new InputStateHistory.Record(activeTouchState, index2, ptr4), finger: reference); ArrayHelpers.InsertAtWithCapacity(ref activeTouches, ref activeTouchCount, index, value); num = statePtrWithoutControlIndex->touchId; ptr = statePtrWithControlIndex; if (value.phase != TouchPhase.Stationary) { haveActiveTouchesNeedingRefreshNextUpdate = true; } } } haveBuiltActiveTouches = true; } } internal struct ExtraDataPerTouchState { public Vector2 accumulatedDelta; public uint uniqueId; } private readonly Finger m_Finger; internal InputStateHistory.Record m_TouchRecord; internal static GlobalState s_GlobalState = CreateGlobalState(); public bool valid => m_TouchRecord.valid; public Finger finger => m_Finger; public TouchPhase phase => state.phase; public bool began => phase == TouchPhase.Began; public bool inProgress { get { if (phase != TouchPhase.Moved && phase != TouchPhase.Stationary) { return phase == TouchPhase.Began; } return true; } } public bool ended { get { if (phase != TouchPhase.Ended) { return phase == TouchPhase.Canceled; } return true; } } public int touchId => state.touchId; public float pressure => state.pressure; public Vector2 radius => state.radius; public double startTime => state.startTime; public double time => m_TouchRecord.time; public Touchscreen screen => finger.screen; public Vector2 screenPosition => state.position; public Vector2 startScreenPosition => state.startPosition; public Vector2 delta => state.delta; public int tapCount => state.tapCount; public bool isTap => state.isTap; public int displayIndex => state.displayIndex; public bool isInProgress { get { TouchPhase touchPhase = phase; if ((uint)(touchPhase - 1) <= 1u || touchPhase == TouchPhase.Stationary) { return true; } return false; } } internal uint updateStepCount => state.updateStepCount; internal uint uniqueId => extraData.uniqueId; private unsafe ref TouchState state => ref *(TouchState*)m_TouchRecord.GetUnsafeMemoryPtr(); private unsafe ref ExtraDataPerTouchState extraData => ref *(ExtraDataPerTouchState*)m_TouchRecord.GetUnsafeExtraMemoryPtr(); public TouchHistory history { get { if (!valid) { throw new InvalidOperationException("Touch is invalid"); } return finger.GetTouchHistory(this); } } public static ReadOnlyArray activeTouches { get { s_GlobalState.playerState.UpdateActiveTouches(); return new ReadOnlyArray(s_GlobalState.playerState.activeTouches, 0, s_GlobalState.playerState.activeTouchCount); } } public static ReadOnlyArray fingers => new ReadOnlyArray(s_GlobalState.playerState.fingers, 0, s_GlobalState.playerState.totalFingerCount); public static ReadOnlyArray activeFingers { get { s_GlobalState.playerState.UpdateActiveFingers(); return new ReadOnlyArray(s_GlobalState.playerState.activeFingers, 0, s_GlobalState.playerState.activeFingerCount); } } public static IEnumerable screens => s_GlobalState.touchscreens; public static int maxHistoryLengthPerFinger => s_GlobalState.historyLengthPerFinger; public static event Action onFingerDown { add { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onFingerDown.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onFingerDown.RemoveCallback(value); } } public static event Action onFingerUp { add { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onFingerUp.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onFingerUp.RemoveCallback(value); } } public static event Action onFingerMove { add { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onFingerMove.AddCallback(value); } remove { if (value == null) { throw new ArgumentNullException("value"); } s_GlobalState.onFingerMove.RemoveCallback(value); } } internal Touch(Finger finger, InputStateHistory.Record touchRecord) { m_Finger = finger; m_TouchRecord = touchRecord; } public override string ToString() { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (!valid) { return ""; } return $"{{id={touchId} finger={finger.index} phase={phase} position={screenPosition} delta={delta} time={time}}}"; } public bool Equals(Touch other) { if (object.Equals(m_Finger, other.m_Finger)) { return m_TouchRecord.Equals(other.m_TouchRecord); } return false; } public override bool Equals(object obj) { if (obj is Touch other) { return Equals(other); } return false; } public override int GetHashCode() { return (((m_Finger != null) ? m_Finger.GetHashCode() : 0) * 397) ^ m_TouchRecord.GetHashCode(); } internal static void AddTouchscreen(Touchscreen screen) { s_GlobalState.touchscreens.AppendWithCapacity(screen, 5); s_GlobalState.playerState.AddFingers(screen); } internal static void RemoveTouchscreen(Touchscreen screen) { int index = s_GlobalState.touchscreens.IndexOfReference(screen); s_GlobalState.touchscreens.RemoveAtWithCapacity(index); s_GlobalState.playerState.RemoveFingers(screen); } internal static void BeginUpdate() { if (s_GlobalState.playerState.haveActiveTouchesNeedingRefreshNextUpdate) { s_GlobalState.playerState.haveBuiltActiveTouches = false; } } private static GlobalState CreateGlobalState() { return new GlobalState { historyLengthPerFinger = 64 }; } internal static ISavedState SaveAndResetState() { SavedStructState result = new SavedStructState(ref s_GlobalState, delegate(ref GlobalState state) { s_GlobalState = state; }, delegate { }); s_GlobalState = CreateGlobalState(); return result; } } public struct TouchHistory : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable { private class Enumerator : IEnumerator, IDisposable, IEnumerator { private readonly TouchHistory m_Owner; private int m_Index; public Touch Current => m_Owner[m_Index]; object IEnumerator.Current => Current; internal Enumerator(TouchHistory owner) { m_Owner = owner; m_Index = -1; } public bool MoveNext() { if (m_Index >= m_Owner.Count - 1) { return false; } m_Index++; return true; } public void Reset() { m_Index = -1; } public void Dispose() { } } private readonly InputStateHistory m_History; private readonly Finger m_Finger; private readonly int m_Count; private readonly int m_StartIndex; private readonly uint m_Version; public int Count => m_Count; public Touch this[int index] { get { CheckValid(); if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException($"Index {index} is out of range for history with {Count} entries", "index"); } return new Touch(m_Finger, m_History[m_StartIndex - index]); } } internal TouchHistory(Finger finger, InputStateHistory history, int startIndex = -1, int count = -1) { m_Finger = finger; m_History = history; m_Version = history.version; m_Count = ((count >= 0) ? count : m_History.Count); m_StartIndex = ((startIndex >= 0) ? startIndex : (m_History.Count - 1)); } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal void CheckValid() { if (m_Finger == null || m_History == null) { throw new InvalidOperationException("Touch history not initialized"); } if (m_History.version != m_Version) { throw new InvalidOperationException("Touch history is no longer valid; the recorded history has been changed"); } } } [AddComponentMenu("Input/Debug/Touch Simulation")] [ExecuteInEditMode] [HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/Touch.html#touch-simulation")] public class TouchSimulation : MonoBehaviour, IInputStateChangeMonitor { [NonSerialized] private int m_NumPointers; [NonSerialized] private Pointer[] m_Pointers; [NonSerialized] private Vector2[] m_CurrentPositions; [NonSerialized] private int[] m_CurrentDisplayIndices; [NonSerialized] private ButtonControl[] m_Touches; [NonSerialized] private int m_LastTouchId; [NonSerialized] private int m_PrimaryTouchIndex = -1; [NonSerialized] private Action m_OnDeviceChange; [NonSerialized] private Action m_OnEvent; internal static TouchSimulation s_Instance; public Touchscreen simulatedTouchscreen { get; private set; } public static TouchSimulation instance => s_Instance; public static void Enable() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)instance == (Object)null) { GameObject val = new GameObject(); val.SetActive(false); ((Object)val).hideFlags = (HideFlags)61; s_Instance = val.AddComponent(); ((Component)instance).gameObject.SetActive(true); } ((Behaviour)instance).enabled = true; } public static void Disable() { if ((Object)(object)instance != (Object)null) { ((Behaviour)instance).enabled = false; } } public static void Destroy() { Disable(); if ((Object)(object)s_Instance != (Object)null) { Object.Destroy((Object)(object)((Component)s_Instance).gameObject); s_Instance = null; } } protected void AddPointer(Pointer pointer) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (pointer == null) { throw new ArgumentNullException("pointer"); } if (!m_Pointers.ContainsReference(m_NumPointers, pointer)) { ArrayHelpers.AppendWithCapacity(ref m_Pointers, ref m_NumPointers, pointer); ArrayHelpers.Append(ref m_CurrentPositions, default(Vector2)); ArrayHelpers.Append(ref m_CurrentDisplayIndices, 0); InputSystem.DisableDevice(pointer, keepSendingEvents: true); } } protected void RemovePointer(Pointer pointer) { if (pointer == null) { throw new ArgumentNullException("pointer"); } int num = m_Pointers.IndexOfReference(pointer, m_NumPointers); if (num == -1) { return; } for (int i = 0; i < m_Touches.Length; i++) { ButtonControl buttonControl = m_Touches[i]; if (buttonControl == null || buttonControl.device == pointer) { UpdateTouch(i, num, TouchPhase.Canceled); } } m_Pointers.EraseAtWithCapacity(ref m_NumPointers, num); ArrayHelpers.EraseAt(ref m_CurrentPositions, num); ArrayHelpers.EraseAt(ref m_CurrentDisplayIndices, num); if (pointer.added) { InputSystem.EnableDevice(pointer); } } private unsafe void OnEvent(InputEventPtr eventPtr, InputDevice device) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) int num = m_Pointers.IndexOfReference(device, m_NumPointers); if (num < 0) { return; } FourCC type = eventPtr.type; if (type != 1398030676 && type != 1145852993) { return; } Pointer obj = m_Pointers[num]; Vector2Control position = obj.position; void* statePtrFromStateEventUnchecked = position.GetStatePtrFromStateEventUnchecked(eventPtr, type); if (statePtrFromStateEventUnchecked != null) { m_CurrentPositions[num] = position.ReadValueFromState(statePtrFromStateEventUnchecked); } IntegerControl displayIndex = obj.displayIndex; void* statePtrFromStateEventUnchecked2 = displayIndex.GetStatePtrFromStateEventUnchecked(eventPtr, type); if (statePtrFromStateEventUnchecked2 != null) { m_CurrentDisplayIndices[num] = displayIndex.ReadValueFromState(statePtrFromStateEventUnchecked2); } for (int i = 0; i < m_Touches.Length; i++) { ButtonControl buttonControl = m_Touches[i]; if (buttonControl == null || buttonControl.device != device) { continue; } void* statePtrFromStateEventUnchecked3 = buttonControl.GetStatePtrFromStateEventUnchecked(eventPtr, type); if (statePtrFromStateEventUnchecked3 == null) { if (statePtrFromStateEventUnchecked != null) { UpdateTouch(i, num, TouchPhase.Moved, eventPtr); } } else if (buttonControl.ReadValueFromState(statePtrFromStateEventUnchecked3) < ButtonControl.s_GlobalDefaultButtonPressPoint * ButtonControl.s_GlobalDefaultButtonReleaseThreshold) { UpdateTouch(i, num, TouchPhase.Ended, eventPtr); } } foreach (InputControl item in eventPtr.EnumerateControls(InputControlExtensions.Enumerate.IgnoreControlsInDefaultState, device)) { if (!item.isButton) { continue; } void* statePtrFromStateEventUnchecked4 = item.GetStatePtrFromStateEventUnchecked(eventPtr, type); float num2 = 0f; item.ReadValueFromStateIntoBuffer(statePtrFromStateEventUnchecked4, UnsafeUtility.AddressOf(ref num2), 4); if (num2 <= ButtonControl.s_GlobalDefaultButtonPressPoint) { continue; } int num3 = m_Touches.IndexOfReference(item); if (num3 < 0) { num3 = m_Touches.IndexOfReference(null); if (num3 >= 0) { m_Touches[num3] = (ButtonControl)item; UpdateTouch(num3, num, TouchPhase.Began, eventPtr); } } else { UpdateTouch(num3, num, TouchPhase.Moved, eventPtr); } } eventPtr.handled = true; } private void OnDeviceChange(InputDevice device, InputDeviceChange change) { if (device == simulatedTouchscreen && change == InputDeviceChange.Removed) { Disable(); return; } switch (change) { case InputDeviceChange.Added: if (device is Pointer pointer2 && !(device is Touchscreen)) { AddPointer(pointer2); } break; case InputDeviceChange.Removed: if (device is Pointer pointer) { RemovePointer(pointer); } break; } } protected void OnEnable() { if (simulatedTouchscreen != null) { if (!simulatedTouchscreen.added) { InputSystem.AddDevice(simulatedTouchscreen); } } else { simulatedTouchscreen = InputSystem.GetDevice("Simulated Touchscreen") as Touchscreen; if (simulatedTouchscreen == null) { simulatedTouchscreen = InputSystem.AddDevice("Simulated Touchscreen"); } } if (m_Touches == null) { m_Touches = new ButtonControl[simulatedTouchscreen.touches.Count]; } foreach (InputDevice device in InputSystem.devices) { OnDeviceChange(device, InputDeviceChange.Added); } if (m_OnDeviceChange == null) { m_OnDeviceChange = OnDeviceChange; } if (m_OnEvent == null) { m_OnEvent = OnEvent; } InputSystem.onDeviceChange += m_OnDeviceChange; InputSystem.onEvent += m_OnEvent; } protected void OnDisable() { if (simulatedTouchscreen != null && simulatedTouchscreen.added) { InputSystem.RemoveDevice(simulatedTouchscreen); } for (int i = 0; i < m_NumPointers; i++) { InputSystem.EnableDevice(m_Pointers[i]); } m_Pointers.Clear(m_NumPointers); m_Touches.Clear(); m_NumPointers = 0; m_LastTouchId = 0; m_PrimaryTouchIndex = -1; InputSystem.onDeviceChange -= m_OnDeviceChange; InputSystem.onEvent -= m_OnEvent; } private unsafe void UpdateTouch(int touchIndex, int pointerIndex, TouchPhase phase, InputEventPtr eventPtr = default(InputEventPtr)) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) Vector2 val = m_CurrentPositions[pointerIndex]; byte displayIndex = (byte)m_CurrentDisplayIndices[pointerIndex]; TouchState state = new TouchState { phase = phase, position = val, displayIndex = displayIndex }; double num = (eventPtr.valid ? eventPtr.time : InputState.currentTime); TouchState* ptr = (TouchState*)((byte*)simulatedTouchscreen.currentStatePtr + simulatedTouchscreen.touches[touchIndex].stateBlock.byteOffset); if (phase == TouchPhase.Began) { state.isPrimaryTouch = m_PrimaryTouchIndex < 0; state.startTime = num; state.startPosition = val; state.touchId = ++m_LastTouchId; state.tapCount = ptr->tapCount; if (state.isPrimaryTouch) { m_PrimaryTouchIndex = touchIndex; } } else { state.touchId = ptr->touchId; state.isPrimaryTouch = m_PrimaryTouchIndex == touchIndex; state.delta = val - ptr->position; state.startPosition = ptr->startPosition; state.startTime = ptr->startTime; state.tapCount = ptr->tapCount; if (phase == TouchPhase.Ended) { int isTap; if (num - ptr->startTime <= (double)Touchscreen.s_TapTime) { Vector2 val2 = val - ptr->startPosition; isTap = ((((Vector2)(ref val2)).sqrMagnitude <= Touchscreen.s_TapRadiusSquared) ? 1 : 0); } else { isTap = 0; } state.isTap = (byte)isTap != 0; if (state.isTap) { state.tapCount++; } } } if (state.isPrimaryTouch) { InputState.Change(simulatedTouchscreen.primaryTouch, state, InputUpdateType.None, eventPtr); } InputState.Change(simulatedTouchscreen.touches[touchIndex], state, InputUpdateType.None, eventPtr); if (phase.IsEndedOrCanceled()) { m_Touches[touchIndex] = null; if (m_PrimaryTouchIndex == touchIndex) { m_PrimaryTouchIndex = -1; } } } void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time, InputEventPtr eventPtr, long monitorIndex) { } void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time, long monitorIndex, int timerIndex) { } protected void InstallStateChangeMonitors(int startIndex = 0) { } protected void OnSourceControlChangedValue(InputControl control, double time, InputEventPtr eventPtr, long sourceDeviceAndButtonIndex) { } protected void UninstallStateChangeMonitors(int startIndex = 0) { } } } namespace UnityEngine.InputSystem.DualShock { [InputControlLayout(displayName = "PlayStation Controller")] public class DualShockGamepad : Gamepad, IDualShockHaptics, IDualMotorRumble, IHaptics { [InputControl(name = "buttonWest", displayName = "Square", shortDisplayName = "Square")] [InputControl(name = "buttonNorth", displayName = "Triangle", shortDisplayName = "Triangle")] [InputControl(name = "buttonEast", displayName = "Circle", shortDisplayName = "Circle")] [InputControl(name = "buttonSouth", displayName = "Cross", shortDisplayName = "Cross")] [InputControl] public ButtonControl touchpadButton { get; protected set; } [InputControl(name = "start", displayName = "Options")] public ButtonControl optionsButton { get; protected set; } [InputControl(name = "select", displayName = "Share")] public ButtonControl shareButton { get; protected set; } [InputControl(name = "leftShoulder", displayName = "L1", shortDisplayName = "L1")] public ButtonControl L1 { get; protected set; } [InputControl(name = "rightShoulder", displayName = "R1", shortDisplayName = "R1")] public ButtonControl R1 { get; protected set; } [InputControl(name = "leftTrigger", displayName = "L2", shortDisplayName = "L2")] public ButtonControl L2 { get; protected set; } [InputControl(name = "rightTrigger", displayName = "R2", shortDisplayName = "R2")] public ButtonControl R2 { get; protected set; } [InputControl(name = "leftStickPress", displayName = "L3", shortDisplayName = "L3")] public ButtonControl L3 { get; protected set; } [InputControl(name = "rightStickPress", displayName = "R3", shortDisplayName = "R3")] public ButtonControl R3 { get; protected set; } public new static DualShockGamepad current { get; private set; } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) { current = null; } } protected override void FinishSetup() { base.FinishSetup(); touchpadButton = GetChildControl("touchpadButton"); optionsButton = base.startButton; shareButton = base.selectButton; L1 = base.leftShoulder; R1 = base.rightShoulder; L2 = base.leftTrigger; R2 = base.rightTrigger; L3 = base.leftStickButton; R3 = base.rightStickButton; } public virtual void SetLightBarColor(Color color) { } } [InputControlLayout(stateType = typeof(DualSenseHIDInputReport), displayName = "DualSense HID")] public class DualSenseGamepadHID : DualShockGamepad, IEventMerger, IEventPreProcessor, IInputStateCallbackReceiver { [StructLayout(LayoutKind.Explicit)] internal struct DualSenseHIDGenericInputReport { [FieldOffset(0)] public byte reportId; public static FourCC Format => new FourCC('H', 'I', 'D'); } [StructLayout(LayoutKind.Explicit)] internal struct DualSenseHIDUSBInputReport { public const int ExpectedReportId = 1; [FieldOffset(0)] public byte reportId; [FieldOffset(1)] public byte leftStickX; [FieldOffset(2)] public byte leftStickY; [FieldOffset(3)] public byte rightStickX; [FieldOffset(4)] public byte rightStickY; [FieldOffset(5)] public byte leftTrigger; [FieldOffset(6)] public byte rightTrigger; [FieldOffset(8)] public byte buttons0; [FieldOffset(9)] public byte buttons1; [FieldOffset(10)] public byte buttons2; [MethodImpl(MethodImplOptions.AggressiveInlining)] public DualSenseHIDInputReport ToHIDInputReport() { return new DualSenseHIDInputReport { leftStickX = leftStickX, leftStickY = leftStickY, rightStickX = rightStickX, rightStickY = rightStickY, leftTrigger = leftTrigger, rightTrigger = rightTrigger, buttons0 = buttons0, buttons1 = buttons1, buttons2 = (byte)(buttons2 & 7) }; } } [StructLayout(LayoutKind.Explicit)] internal struct DualSenseHIDBluetoothInputReport { public const int ExpectedReportId = 49; [FieldOffset(0)] public byte reportId; [FieldOffset(2)] public byte leftStickX; [FieldOffset(3)] public byte leftStickY; [FieldOffset(4)] public byte rightStickX; [FieldOffset(5)] public byte rightStickY; [FieldOffset(6)] public byte leftTrigger; [FieldOffset(7)] public byte rightTrigger; [FieldOffset(9)] public byte buttons0; [FieldOffset(10)] public byte buttons1; [FieldOffset(11)] public byte buttons2; [MethodImpl(MethodImplOptions.AggressiveInlining)] public DualSenseHIDInputReport ToHIDInputReport() { return new DualSenseHIDInputReport { leftStickX = leftStickX, leftStickY = leftStickY, rightStickX = rightStickX, rightStickY = rightStickY, leftTrigger = leftTrigger, rightTrigger = rightTrigger, buttons0 = buttons0, buttons1 = buttons1, buttons2 = (byte)(buttons2 & 7) }; } } [StructLayout(LayoutKind.Explicit)] internal struct DualSenseHIDMinimalInputReport { public static int ExpectedSize1 = 10; public static int ExpectedSize2 = 78; [FieldOffset(0)] public byte reportId; [FieldOffset(1)] public byte leftStickX; [FieldOffset(2)] public byte leftStickY; [FieldOffset(3)] public byte rightStickX; [FieldOffset(4)] public byte rightStickY; [FieldOffset(5)] public byte buttons0; [FieldOffset(6)] public byte buttons1; [FieldOffset(7)] public byte buttons2; [FieldOffset(8)] public byte leftTrigger; [FieldOffset(9)] public byte rightTrigger; [MethodImpl(MethodImplOptions.AggressiveInlining)] public DualSenseHIDInputReport ToHIDInputReport() { return new DualSenseHIDInputReport { leftStickX = leftStickX, leftStickY = leftStickY, rightStickX = rightStickX, rightStickY = rightStickY, leftTrigger = leftTrigger, rightTrigger = rightTrigger, buttons0 = buttons0, buttons1 = buttons1, buttons2 = (byte)(buttons2 & 3) }; } } private float? m_LowFrequencyMotorSpeed; private float? m_HighFrequenceyMotorSpeed; private Color? m_LightBarColor; private byte outputSequenceId; internal const byte JitterMaskLow = 120; internal const byte JitterMaskHigh = 135; public ButtonControl leftTriggerButton { get; protected set; } public ButtonControl rightTriggerButton { get; protected set; } public ButtonControl playStationButton { get; protected set; } protected override void FinishSetup() { leftTriggerButton = GetChildControl("leftTriggerButton"); rightTriggerButton = GetChildControl("rightTriggerButton"); playStationButton = GetChildControl("systemButton"); base.FinishSetup(); } public override void PauseHaptics() { if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue) { SetMotorSpeedsAndLightBarColor(0f, 0f, m_LightBarColor); } } public override void ResetHaptics() { if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue) { m_HighFrequenceyMotorSpeed = null; m_LowFrequencyMotorSpeed = null; SetMotorSpeedsAndLightBarColor(m_LowFrequencyMotorSpeed, m_HighFrequenceyMotorSpeed, m_LightBarColor); } } public override void ResumeHaptics() { if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue) { SetMotorSpeedsAndLightBarColor(m_LowFrequencyMotorSpeed, m_HighFrequenceyMotorSpeed, m_LightBarColor); } } public override void SetLightBarColor(Color color) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) m_LightBarColor = color; SetMotorSpeedsAndLightBarColor(m_LowFrequencyMotorSpeed, m_HighFrequenceyMotorSpeed, m_LightBarColor); } public override void SetMotorSpeeds(float lowFrequency, float highFrequency) { m_LowFrequencyMotorSpeed = lowFrequency; m_HighFrequenceyMotorSpeed = highFrequency; SetMotorSpeedsAndLightBarColor(m_LowFrequencyMotorSpeed, m_HighFrequenceyMotorSpeed, m_LightBarColor); } public bool SetMotorSpeedsAndLightBarColor(float? lowFrequency, float? highFrequency, Color? color) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) float value = (lowFrequency.HasValue ? lowFrequency.Value : 0f); float value2 = (highFrequency.HasValue ? highFrequency.Value : 0f); Color val = (color.HasValue ? color.Value : Color.black); DualSenseHIDUSBOutputReport command = DualSenseHIDUSBOutputReport.Create(new DualSenseHIDOutputReportPayload { enableFlags1 = 3, enableFlags2 = 4, lowFrequencyMotorSpeed = (byte)NumberHelpers.NormalizedFloatToUInt(value, 0u, 255u), highFrequencyMotorSpeed = (byte)NumberHelpers.NormalizedFloatToUInt(value2, 0u, 255u), redColor = (byte)NumberHelpers.NormalizedFloatToUInt(val.r, 0u, 255u), greenColor = (byte)NumberHelpers.NormalizedFloatToUInt(val.g, 0u, 255u), blueColor = (byte)NumberHelpers.NormalizedFloatToUInt(val.b, 0u, 255u) }); return ExecuteCommand(ref command) >= 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static bool MergeForward(DualSenseHIDUSBInputReport* currentState, DualSenseHIDUSBInputReport* nextState) { if (currentState->buttons0 == nextState->buttons0 && currentState->buttons1 == nextState->buttons1) { return currentState->buttons2 == nextState->buttons2; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static bool MergeForward(DualSenseHIDBluetoothInputReport* currentState, DualSenseHIDBluetoothInputReport* nextState) { if (currentState->buttons0 == nextState->buttons0 && currentState->buttons1 == nextState->buttons1) { return currentState->buttons2 == nextState->buttons2; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static bool MergeForward(DualSenseHIDMinimalInputReport* currentState, DualSenseHIDMinimalInputReport* nextState) { if (currentState->buttons0 == nextState->buttons0 && currentState->buttons1 == nextState->buttons1) { return currentState->buttons2 == nextState->buttons2; } return false; } unsafe bool IEventMerger.MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr) { if (currentEventPtr.type != 1398030676 || nextEventPtr.type != 1398030676) { return false; } StateEvent* ptr = StateEvent.FromUnchecked(currentEventPtr); StateEvent* ptr2 = StateEvent.FromUnchecked(nextEventPtr); if (ptr->stateFormat != DualSenseHIDGenericInputReport.Format || ptr2->stateFormat != DualSenseHIDGenericInputReport.Format) { return false; } if (ptr->stateSizeInBytes != ptr2->stateSizeInBytes) { return false; } DualSenseHIDGenericInputReport* state = (DualSenseHIDGenericInputReport*)ptr->state; DualSenseHIDGenericInputReport* state2 = (DualSenseHIDGenericInputReport*)ptr2->state; if (state->reportId != state2->reportId) { return false; } if (state->reportId == 1) { if (ptr->stateSizeInBytes == DualSenseHIDMinimalInputReport.ExpectedSize1 || ptr->stateSizeInBytes == DualSenseHIDMinimalInputReport.ExpectedSize2) { DualSenseHIDMinimalInputReport* state3 = (DualSenseHIDMinimalInputReport*)ptr->state; DualSenseHIDMinimalInputReport* state4 = (DualSenseHIDMinimalInputReport*)ptr2->state; return MergeForward(state3, state4); } DualSenseHIDUSBInputReport* state5 = (DualSenseHIDUSBInputReport*)ptr->state; DualSenseHIDUSBInputReport* state6 = (DualSenseHIDUSBInputReport*)ptr2->state; return MergeForward(state5, state6); } if (state->reportId == 49) { DualSenseHIDBluetoothInputReport* state7 = (DualSenseHIDBluetoothInputReport*)ptr->state; DualSenseHIDBluetoothInputReport* state8 = (DualSenseHIDBluetoothInputReport*)ptr2->state; return MergeForward(state7, state8); } return false; } unsafe bool IEventPreProcessor.PreProcessEvent(InputEventPtr eventPtr) { if (eventPtr.type != 1398030676) { return eventPtr.type != 1145852993; } StateEvent* ptr = StateEvent.FromUnchecked(eventPtr); if (ptr->stateFormat == DualSenseHIDInputReport.Format) { return true; } uint stateSizeInBytes = ptr->stateSizeInBytes; if (ptr->stateFormat != DualSenseHIDGenericInputReport.Format || stateSizeInBytes < sizeof(DualSenseHIDInputReport)) { return false; } DualSenseHIDGenericInputReport* state = (DualSenseHIDGenericInputReport*)ptr->state; if (state->reportId == 1) { if (ptr->stateSizeInBytes == DualSenseHIDMinimalInputReport.ExpectedSize1 || ptr->stateSizeInBytes == DualSenseHIDMinimalInputReport.ExpectedSize2) { DualSenseHIDInputReport dualSenseHIDInputReport = ((DualSenseHIDMinimalInputReport*)ptr->state)->ToHIDInputReport(); *(DualSenseHIDInputReport*)ptr->state = dualSenseHIDInputReport; } else { DualSenseHIDInputReport dualSenseHIDInputReport2 = ((DualSenseHIDUSBInputReport*)ptr->state)->ToHIDInputReport(); *(DualSenseHIDInputReport*)ptr->state = dualSenseHIDInputReport2; } ptr->stateFormat = DualSenseHIDInputReport.Format; return true; } if (state->reportId == 49) { DualSenseHIDInputReport dualSenseHIDInputReport3 = ((DualSenseHIDBluetoothInputReport*)ptr->state)->ToHIDInputReport(); *(DualSenseHIDInputReport*)ptr->state = dualSenseHIDInputReport3; ptr->stateFormat = DualSenseHIDInputReport.Format; return true; } return false; } public void OnNextUpdate() { } public unsafe void OnStateEvent(InputEventPtr eventPtr) { if (eventPtr.type == 1398030676 && eventPtr.stateFormat == DualSenseHIDInputReport.Format) { DualSenseHIDInputReport* ptr = (DualSenseHIDInputReport*)((byte*)base.currentStatePtr + m_StateBlock.byteOffset); DualSenseHIDInputReport* state = (DualSenseHIDInputReport*)StateEvent.FromUnchecked(eventPtr)->state; if (state->leftStickX >= 120 && state->leftStickX <= 135 && state->leftStickY >= 120 && state->leftStickY <= 135 && state->rightStickX >= 120 && state->rightStickX <= 135 && state->rightStickY >= 120 && state->rightStickY <= 135 && state->leftTrigger == ptr->leftTrigger && state->rightTrigger == ptr->rightTrigger && state->buttons0 == ptr->buttons0 && state->buttons1 == ptr->buttons1 && state->buttons2 == ptr->buttons2) { InputSystem.s_Manager.DontMakeCurrentlyUpdatingDeviceCurrent(); } } InputState.Change(this, eventPtr); } public bool GetStateOffsetForEvent(InputControl control, InputEventPtr eventPtr, ref uint offset) { return false; } } [InputControlLayout(stateType = typeof(DualShock4HIDInputReport), hideInUI = true, isNoisy = true)] public class DualShock4GamepadHID : DualShockGamepad, IEventPreProcessor, IInputStateCallbackReceiver { [StructLayout(LayoutKind.Explicit)] internal struct DualShock4HIDGenericInputReport { [FieldOffset(0)] public byte leftStickX; [FieldOffset(1)] public byte leftStickY; [FieldOffset(2)] public byte rightStickX; [FieldOffset(3)] public byte rightStickY; [FieldOffset(4)] public byte buttons0; [FieldOffset(5)] public byte buttons1; [FieldOffset(6)] public byte buttons2; [FieldOffset(7)] public byte leftTrigger; [FieldOffset(8)] public byte rightTrigger; public static FourCC Format => new FourCC('H', 'I', 'D'); [MethodImpl(MethodImplOptions.AggressiveInlining)] public DualShock4HIDInputReport ToHIDInputReport() { return new DualShock4HIDInputReport { leftStickX = leftStickX, leftStickY = leftStickY, rightStickX = rightStickX, rightStickY = rightStickY, leftTrigger = leftTrigger, rightTrigger = rightTrigger, buttons1 = buttons0, buttons2 = buttons1, buttons3 = buttons2 }; } } private float? m_LowFrequencyMotorSpeed; private float? m_HighFrequenceyMotorSpeed; private Color? m_LightBarColor; internal const byte JitterMaskLow = 120; internal const byte JitterMaskHigh = 135; public ButtonControl leftTriggerButton { get; protected set; } public ButtonControl rightTriggerButton { get; protected set; } public ButtonControl playStationButton { get; protected set; } protected override void FinishSetup() { leftTriggerButton = GetChildControl("leftTriggerButton"); rightTriggerButton = GetChildControl("rightTriggerButton"); playStationButton = GetChildControl("systemButton"); base.FinishSetup(); } public override void PauseHaptics() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue || m_LightBarColor.HasValue) { DualShockHIDOutputReport command = DualShockHIDOutputReport.Create(); command.SetMotorSpeeds(0f, 0f); if (m_LightBarColor.HasValue) { command.SetColor(Color.black); } ExecuteCommand(ref command); } } public override void ResetHaptics() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue || m_LightBarColor.HasValue) { DualShockHIDOutputReport command = DualShockHIDOutputReport.Create(); command.SetMotorSpeeds(0f, 0f); if (m_LightBarColor.HasValue) { command.SetColor(Color.black); } ExecuteCommand(ref command); m_HighFrequenceyMotorSpeed = null; m_LowFrequencyMotorSpeed = null; m_LightBarColor = null; } } public override void ResumeHaptics() { //IL_007a: Unknown result type (might be due to invalid IL or missing references) if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue || m_LightBarColor.HasValue) { DualShockHIDOutputReport command = DualShockHIDOutputReport.Create(); if (m_LowFrequencyMotorSpeed.HasValue || m_HighFrequenceyMotorSpeed.HasValue) { command.SetMotorSpeeds(m_LowFrequencyMotorSpeed.Value, m_HighFrequenceyMotorSpeed.Value); } if (m_LightBarColor.HasValue) { command.SetColor(m_LightBarColor.Value); } ExecuteCommand(ref command); } } public override void SetLightBarColor(Color color) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) DualShockHIDOutputReport command = DualShockHIDOutputReport.Create(); command.SetColor(color); ExecuteCommand(ref command); m_LightBarColor = color; } public override void SetMotorSpeeds(float lowFrequency, float highFrequency) { DualShockHIDOutputReport command = DualShockHIDOutputReport.Create(); command.SetMotorSpeeds(lowFrequency, highFrequency); ExecuteCommand(ref command); m_LowFrequencyMotorSpeed = lowFrequency; m_HighFrequenceyMotorSpeed = highFrequency; } public bool SetMotorSpeedsAndLightBarColor(float lowFrequency, float highFrequency, Color color) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) DualShockHIDOutputReport command = DualShockHIDOutputReport.Create(); command.SetMotorSpeeds(lowFrequency, highFrequency); command.SetColor(color); long num = ExecuteCommand(ref command); m_LowFrequencyMotorSpeed = lowFrequency; m_HighFrequenceyMotorSpeed = highFrequency; m_LightBarColor = color; return num >= 0; } unsafe bool IEventPreProcessor.PreProcessEvent(InputEventPtr eventPtr) { if (eventPtr.type != 1398030676) { return eventPtr.type != 1145852993; } StateEvent* ptr = StateEvent.FromUnchecked(eventPtr); if (ptr->stateFormat == DualShock4HIDInputReport.Format) { return true; } uint stateSizeInBytes = ptr->stateSizeInBytes; if (ptr->stateFormat != DualShock4HIDGenericInputReport.Format || stateSizeInBytes < sizeof(DualShock4HIDGenericInputReport)) { return false; } byte* state = (byte*)ptr->state; switch (*state) { case 1: { if (stateSizeInBytes < sizeof(DualShock4HIDGenericInputReport) + 1) { return false; } DualShock4HIDInputReport dualShock4HIDInputReport2 = ((DualShock4HIDGenericInputReport*)(state + 1))->ToHIDInputReport(); *(DualShock4HIDInputReport*)ptr->state = dualShock4HIDInputReport2; ptr->stateFormat = DualShock4HIDInputReport.Format; return true; } case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: if ((state[1] & 0x80) != 0) { if (stateSizeInBytes < sizeof(DualShock4HIDGenericInputReport) + 3) { return false; } DualShock4HIDInputReport dualShock4HIDInputReport = ((DualShock4HIDGenericInputReport*)(state + 3))->ToHIDInputReport(); *(DualShock4HIDInputReport*)ptr->state = dualShock4HIDInputReport; ptr->stateFormat = DualShock4HIDInputReport.Format; return true; } return false; default: return false; } } public void OnNextUpdate() { } public unsafe void OnStateEvent(InputEventPtr eventPtr) { if (eventPtr.type == 1398030676 && eventPtr.stateFormat == DualShock4HIDInputReport.Format) { DualShock4HIDInputReport* ptr = (DualShock4HIDInputReport*)((byte*)base.currentStatePtr + m_StateBlock.byteOffset); DualShock4HIDInputReport* state = (DualShock4HIDInputReport*)StateEvent.FromUnchecked(eventPtr)->state; if (state->leftStickX >= 120 && state->leftStickX <= 135 && state->leftStickY >= 120 && state->leftStickY <= 135 && state->rightStickX >= 120 && state->rightStickX <= 135 && state->rightStickY >= 120 && state->rightStickY <= 135 && state->leftTrigger == ptr->leftTrigger && state->rightTrigger == ptr->rightTrigger && state->buttons1 == ptr->buttons1 && state->buttons2 == ptr->buttons2 && state->buttons3 == ptr->buttons3) { InputSystem.s_Manager.DontMakeCurrentlyUpdatingDeviceCurrent(); } } InputState.Change(this, eventPtr); } public bool GetStateOffsetForEvent(InputControl control, InputEventPtr eventPtr, ref uint offset) { return false; } } [InputControlLayout(stateType = typeof(DualShock3HIDInputReport), hideInUI = true, displayName = "PS3 Controller")] public class DualShock3GamepadHID : DualShockGamepad { public ButtonControl leftTriggerButton { get; private set; } public ButtonControl rightTriggerButton { get; private set; } public ButtonControl playStationButton { get; private set; } protected override void FinishSetup() { leftTriggerButton = GetChildControl("leftTriggerButton"); rightTriggerButton = GetChildControl("rightTriggerButton"); playStationButton = GetChildControl("systemButton"); base.FinishSetup(); } } internal static class DualShockSupport { public static void Initialize() { InputSystem.RegisterLayout(); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 1356).WithCapability("productId", 3302)); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 1356).WithCapability("productId", 2508)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 1356).WithCapability("productId", 1476)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithManufacturer("Sony.+Entertainment").WithProduct("Wireless Controller")); InputSystem.RegisterLayout(null, default(InputDeviceMatcher).WithInterface("HID").WithCapability("vendorId", 1356).WithCapability("productId", 616)); InputSystem.RegisterLayoutMatcher(default(InputDeviceMatcher).WithInterface("HID").WithManufacturer("Sony.+Entertainment").WithProduct("PLAYSTATION(R)3 Controller")); } } public interface IDualShockHaptics : IDualMotorRumble, IHaptics { void SetLightBarColor(Color color); } } namespace UnityEngine.InputSystem.DualShock.LowLevel { [StructLayout(LayoutKind.Explicit, Size = 9)] internal struct DualSenseHIDInputReport : IInputStateTypeInfo { public static FourCC Format = new FourCC('D', 'S', 'V', 'S'); [FieldOffset(0)] [InputControl(name = "leftStick", layout = "Stick", format = "VC2B")] [InputControl(name = "leftStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "leftStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "leftStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "leftStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "leftStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "leftStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1,invert=false")] public byte leftStickX; [FieldOffset(1)] public byte leftStickY; [FieldOffset(2)] [InputControl(name = "rightStick", layout = "Stick", format = "VC2B")] [InputControl(name = "rightStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "rightStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "rightStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "rightStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1,invert=false")] public byte rightStickX; [FieldOffset(3)] public byte rightStickY; [FieldOffset(4)] [InputControl(name = "leftTrigger", format = "BYTE")] public byte leftTrigger; [FieldOffset(5)] [InputControl(name = "rightTrigger", format = "BYTE")] public byte rightTrigger; [FieldOffset(6)] [InputControl(name = "dpad", format = "BIT", layout = "Dpad", sizeInBits = 4u, defaultState = 8)] [InputControl(name = "dpad/up", format = "BIT", layout = "DiscreteButton", parameters = "minValue=7,maxValue=1,nullValue=8,wrapAtValue=7", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/right", format = "BIT", layout = "DiscreteButton", parameters = "minValue=1,maxValue=3", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/down", format = "BIT", layout = "DiscreteButton", parameters = "minValue=3,maxValue=5", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/left", format = "BIT", layout = "DiscreteButton", parameters = "minValue=5, maxValue=7", bit = 0u, sizeInBits = 4u)] [InputControl(name = "buttonWest", displayName = "Square", bit = 4u)] [InputControl(name = "buttonSouth", displayName = "Cross", bit = 5u)] [InputControl(name = "buttonEast", displayName = "Circle", bit = 6u)] [InputControl(name = "buttonNorth", displayName = "Triangle", bit = 7u)] public byte buttons0; [FieldOffset(7)] [InputControl(name = "leftShoulder", bit = 0u)] [InputControl(name = "rightShoulder", bit = 1u)] [InputControl(name = "leftTriggerButton", layout = "Button", bit = 2u)] [InputControl(name = "rightTriggerButton", layout = "Button", bit = 3u)] [InputControl(name = "select", displayName = "Share", bit = 4u)] [InputControl(name = "start", displayName = "Options", bit = 5u)] [InputControl(name = "leftStickPress", bit = 6u)] [InputControl(name = "rightStickPress", bit = 7u)] public byte buttons1; [FieldOffset(8)] [InputControl(name = "systemButton", layout = "Button", displayName = "System", bit = 0u)] [InputControl(name = "touchpadButton", layout = "Button", displayName = "Touchpad Press", bit = 1u)] [InputControl(name = "micButton", layout = "Button", displayName = "Mic Mute", bit = 2u)] public byte buttons2; public FourCC format => Format; } [StructLayout(LayoutKind.Explicit, Size = 47)] internal struct DualSenseHIDOutputReportPayload { [FieldOffset(0)] public byte enableFlags1; [FieldOffset(1)] public byte enableFlags2; [FieldOffset(2)] public byte highFrequencyMotorSpeed; [FieldOffset(3)] public byte lowFrequencyMotorSpeed; [FieldOffset(44)] public byte redColor; [FieldOffset(45)] public byte greenColor; [FieldOffset(46)] public byte blueColor; } [StructLayout(LayoutKind.Explicit, Size = 56)] internal struct DualSenseHIDUSBOutputReport : IInputDeviceCommandInfo { internal const int kSize = 56; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public byte reportId; [FieldOffset(9)] public DualSenseHIDOutputReportPayload payload; public static FourCC Type => new FourCC('H', 'I', 'D', 'O'); public FourCC typeStatic => Type; public static DualSenseHIDUSBOutputReport Create(DualSenseHIDOutputReportPayload payload) { return new DualSenseHIDUSBOutputReport { baseCommand = new InputDeviceCommand(Type, 56), reportId = 2, payload = payload }; } } [StructLayout(LayoutKind.Explicit, Size = 86)] internal struct DualSenseHIDBluetoothOutputReport : IInputDeviceCommandInfo { internal const int kSize = 86; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public byte reportId; [FieldOffset(9)] public byte tag1; [FieldOffset(10)] public byte tag2; [FieldOffset(11)] public DualSenseHIDOutputReportPayload payload; [FieldOffset(82)] public uint crc32; [FieldOffset(8)] public unsafe fixed byte rawData[74]; public static FourCC Type => new FourCC('H', 'I', 'D', 'O'); public FourCC typeStatic => Type; public static DualSenseHIDBluetoothOutputReport Create(DualSenseHIDOutputReportPayload payload, byte outputSequenceId) { return new DualSenseHIDBluetoothOutputReport { baseCommand = new InputDeviceCommand(Type, 86), reportId = 49, tag1 = (byte)((outputSequenceId & 0xF) << 4), tag2 = 16, payload = payload }; } } [StructLayout(LayoutKind.Explicit, Size = 9)] internal struct DualShock4HIDInputReport : IInputStateTypeInfo { public static FourCC Format = new FourCC('D', '4', 'V', 'S'); [FieldOffset(0)] [InputControl(name = "leftStick", layout = "Stick", format = "VC2B")] [InputControl(name = "leftStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "leftStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "leftStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "leftStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "leftStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "leftStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1,invert=false")] public byte leftStickX; [FieldOffset(1)] public byte leftStickY; [FieldOffset(2)] [InputControl(name = "rightStick", layout = "Stick", format = "VC2B")] [InputControl(name = "rightStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "rightStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "rightStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "rightStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1,invert=false")] public byte rightStickX; [FieldOffset(3)] public byte rightStickY; [FieldOffset(4)] [InputControl(name = "dpad", format = "BIT", layout = "Dpad", sizeInBits = 4u, defaultState = 8)] [InputControl(name = "dpad/up", format = "BIT", layout = "DiscreteButton", parameters = "minValue=7,maxValue=1,nullValue=8,wrapAtValue=7", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/right", format = "BIT", layout = "DiscreteButton", parameters = "minValue=1,maxValue=3", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/down", format = "BIT", layout = "DiscreteButton", parameters = "minValue=3,maxValue=5", bit = 0u, sizeInBits = 4u)] [InputControl(name = "dpad/left", format = "BIT", layout = "DiscreteButton", parameters = "minValue=5, maxValue=7", bit = 0u, sizeInBits = 4u)] [InputControl(name = "buttonWest", displayName = "Square", bit = 4u)] [InputControl(name = "buttonSouth", displayName = "Cross", bit = 5u)] [InputControl(name = "buttonEast", displayName = "Circle", bit = 6u)] [InputControl(name = "buttonNorth", displayName = "Triangle", bit = 7u)] public byte buttons1; [FieldOffset(5)] [InputControl(name = "leftShoulder", bit = 0u)] [InputControl(name = "rightShoulder", bit = 1u)] [InputControl(name = "leftTriggerButton", layout = "Button", bit = 2u, synthetic = true)] [InputControl(name = "rightTriggerButton", layout = "Button", bit = 3u, synthetic = true)] [InputControl(name = "select", displayName = "Share", bit = 4u)] [InputControl(name = "start", displayName = "Options", bit = 5u)] [InputControl(name = "leftStickPress", bit = 6u)] [InputControl(name = "rightStickPress", bit = 7u)] public byte buttons2; [FieldOffset(6)] [InputControl(name = "systemButton", layout = "Button", displayName = "System", bit = 0u)] [InputControl(name = "touchpadButton", layout = "Button", displayName = "Touchpad Press", bit = 1u)] public byte buttons3; [FieldOffset(7)] [InputControl(name = "leftTrigger", format = "BYTE")] public byte leftTrigger; [FieldOffset(8)] [InputControl(name = "rightTrigger", format = "BYTE")] public byte rightTrigger; public FourCC format => Format; } [StructLayout(LayoutKind.Explicit, Size = 32)] internal struct DualShock3HIDInputReport : IInputStateTypeInfo { [FieldOffset(0)] private ushort padding1; [FieldOffset(2)] [InputControl(name = "select", displayName = "Share", bit = 0u)] [InputControl(name = "leftStickPress", bit = 1u)] [InputControl(name = "rightStickPress", bit = 2u)] [InputControl(name = "start", displayName = "Options", bit = 3u)] [InputControl(name = "dpad", format = "BIT", layout = "Dpad", bit = 4u, sizeInBits = 4u)] [InputControl(name = "dpad/up", bit = 4u)] [InputControl(name = "dpad/right", bit = 5u)] [InputControl(name = "dpad/down", bit = 6u)] [InputControl(name = "dpad/left", bit = 7u)] public byte buttons1; [FieldOffset(3)] [InputControl(name = "leftTriggerButton", layout = "Button", bit = 0u, synthetic = true)] [InputControl(name = "rightTriggerButton", layout = "Button", bit = 1u, synthetic = true)] [InputControl(name = "leftShoulder", bit = 2u)] [InputControl(name = "rightShoulder", bit = 3u)] [InputControl(name = "buttonNorth", displayName = "Triangle", bit = 4u)] [InputControl(name = "buttonEast", displayName = "Circle", bit = 5u)] [InputControl(name = "buttonSouth", displayName = "Cross", bit = 6u)] [InputControl(name = "buttonWest", displayName = "Square", bit = 7u)] public byte buttons2; [FieldOffset(4)] [InputControl(name = "systemButton", layout = "Button", displayName = "System", bit = 0u)] [InputControl(name = "touchpadButton", layout = "Button", displayName = "Touchpad Press", bit = 1u)] public byte buttons3; [FieldOffset(5)] private byte padding2; [FieldOffset(6)] [InputControl(name = "leftStick", layout = "Stick", format = "VC2B")] [InputControl(name = "leftStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "leftStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "leftStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "leftStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "leftStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "leftStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1,invert=false")] public byte leftStickX; [FieldOffset(7)] public byte leftStickY; [FieldOffset(8)] [InputControl(name = "rightStick", layout = "Stick", format = "VC2B")] [InputControl(name = "rightStick/x", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "rightStick/left", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/right", offset = 0u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1")] [InputControl(name = "rightStick/y", offset = 1u, format = "BYTE", parameters = "invert,normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5")] [InputControl(name = "rightStick/up", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0,clampMax=0.5,invert")] [InputControl(name = "rightStick/down", offset = 1u, format = "BYTE", parameters = "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5,clamp=1,clampMin=0.5,clampMax=1,invert=false")] public byte rightStickX; [FieldOffset(9)] public byte rightStickY; [FieldOffset(10)] private unsafe fixed byte padding3[8]; [FieldOffset(18)] [InputControl(name = "leftTrigger", format = "BYTE")] public byte leftTrigger; [FieldOffset(19)] [InputControl(name = "rightTrigger", format = "BYTE")] public byte rightTrigger; public FourCC format => new FourCC('H', 'I', 'D'); } [StructLayout(LayoutKind.Explicit, Size = 40)] internal struct DualShockHIDOutputReport : IInputDeviceCommandInfo { [Flags] public enum Flags { Rumble = 1, Color = 2 } internal const int kSize = 40; internal const int kReportId = 5; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public byte reportId; [FieldOffset(9)] public byte flags; [FieldOffset(10)] public unsafe fixed byte unknown1[2]; [FieldOffset(12)] public byte highFrequencyMotorSpeed; [FieldOffset(13)] public byte lowFrequencyMotorSpeed; [FieldOffset(14)] public byte redColor; [FieldOffset(15)] public byte greenColor; [FieldOffset(16)] public byte blueColor; [FieldOffset(17)] public unsafe fixed byte unknown2[23]; public static FourCC Type => new FourCC('H', 'I', 'D', 'O'); public FourCC typeStatic => Type; public void SetMotorSpeeds(float lowFreq, float highFreq) { flags |= 1; lowFrequencyMotorSpeed = (byte)Mathf.Clamp(lowFreq * 255f, 0f, 255f); highFrequencyMotorSpeed = (byte)Mathf.Clamp(highFreq * 255f, 0f, 255f); } public void SetColor(Color color) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) flags |= 2; redColor = (byte)Mathf.Clamp(color.r * 255f, 0f, 255f); greenColor = (byte)Mathf.Clamp(color.g * 255f, 0f, 255f); blueColor = (byte)Mathf.Clamp(color.b * 255f, 0f, 255f); } public static DualShockHIDOutputReport Create() { return new DualShockHIDOutputReport { baseCommand = new InputDeviceCommand(Type, 40), reportId = 5 }; } } } namespace UnityEngine.InputSystem.Haptics { internal struct DualMotorRumble { public float lowFrequencyMotorSpeed { get; private set; } public float highFrequencyMotorSpeed { get; private set; } public bool isRumbling { get { if (Mathf.Approximately(lowFrequencyMotorSpeed, 0f)) { return !Mathf.Approximately(highFrequencyMotorSpeed, 0f); } return true; } } public void PauseHaptics(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (isRumbling) { DualMotorRumbleCommand command = DualMotorRumbleCommand.Create(0f, 0f); device.ExecuteCommand(ref command); } } public void ResumeHaptics(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (isRumbling) { SetMotorSpeeds(device, lowFrequencyMotorSpeed, highFrequencyMotorSpeed); } } public void ResetHaptics(InputDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (isRumbling) { SetMotorSpeeds(device, 0f, 0f); } } public void SetMotorSpeeds(InputDevice device, float lowFrequency, float highFrequency) { if (device == null) { throw new ArgumentNullException("device"); } lowFrequencyMotorSpeed = Mathf.Clamp(lowFrequency, 0f, 1f); highFrequencyMotorSpeed = Mathf.Clamp(highFrequency, 0f, 1f); DualMotorRumbleCommand command = DualMotorRumbleCommand.Create(lowFrequencyMotorSpeed, highFrequencyMotorSpeed); device.ExecuteCommand(ref command); } } public interface IDualMotorRumble : IHaptics { void SetMotorSpeeds(float lowFrequency, float highFrequency); } public interface IHaptics { void PauseHaptics(); void ResumeHaptics(); void ResetHaptics(); } } namespace UnityEngine.InputSystem.LowLevel { [StructLayout(LayoutKind.Explicit, Size = 8)] public struct DisableDeviceCommand : IInputDeviceCommandInfo { internal const int kSize = 8; [FieldOffset(0)] public InputDeviceCommand baseCommand; public static FourCC Type => new FourCC('D', 'S', 'B', 'L'); public FourCC typeStatic => Type; public static DisableDeviceCommand Create() { return new DisableDeviceCommand { baseCommand = new InputDeviceCommand(Type) }; } } [StructLayout(LayoutKind.Explicit, Size = 8)] public struct EnableDeviceCommand : IInputDeviceCommandInfo { internal const int kSize = 8; [FieldOffset(0)] public InputDeviceCommand baseCommand; public static FourCC Type => new FourCC('E', 'N', 'B', 'L'); public FourCC typeStatic => Type; public static EnableDeviceCommand Create() { return new EnableDeviceCommand { baseCommand = new InputDeviceCommand(Type) }; } } [StructLayout(LayoutKind.Explicit, Size = 9)] public struct EnableIMECompositionCommand : IInputDeviceCommandInfo { internal const int kSize = 12; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] private byte m_ImeEnabled; public static FourCC Type => new FourCC('I', 'M', 'E', 'M'); public bool imeEnabled => m_ImeEnabled != 0; public FourCC typeStatic => Type; public static EnableIMECompositionCommand Create(bool enabled) { return new EnableIMECompositionCommand { baseCommand = new InputDeviceCommand(Type, 9), m_ImeEnabled = (byte)(enabled ? byte.MaxValue : 0) }; } } public interface IInputDeviceCommandInfo { FourCC typeStatic { get; } } [StructLayout(LayoutKind.Explicit, Size = 8)] public struct InitiateUserAccountPairingCommand : IInputDeviceCommandInfo { public enum Result { SuccessfullyInitiated = 1, ErrorNotSupported = -1, ErrorAlreadyInProgress = -2 } internal const int kSize = 8; [FieldOffset(0)] public InputDeviceCommand baseCommand; public static FourCC Type => new FourCC('P', 'A', 'I', 'R'); public FourCC typeStatic => Type; public static InitiateUserAccountPairingCommand Create() { return new InitiateUserAccountPairingCommand { baseCommand = new InputDeviceCommand(Type) }; } } public unsafe delegate long? InputDeviceCommandDelegate(InputDevice device, InputDeviceCommand* command); public delegate long InputDeviceExecuteCommandDelegate(ref InputDeviceCommand command); [StructLayout(LayoutKind.Explicit, Size = 8)] public struct InputDeviceCommand : IInputDeviceCommandInfo { internal const int kBaseCommandSize = 8; public const int BaseCommandSize = 8; public const long GenericFailure = -1L; public const long GenericSuccess = 1L; [FieldOffset(0)] public FourCC type; [FieldOffset(4)] public int sizeInBytes; public int payloadSizeInBytes => sizeInBytes - 8; public unsafe void* payloadPtr { get { fixed (InputDeviceCommand* ptr = &this) { void* ptr2 = ptr; return (byte*)ptr2 + 8; } } } public FourCC typeStatic => default(FourCC); public InputDeviceCommand(FourCC type, int sizeInBytes = 8) { this.type = type; this.sizeInBytes = sizeInBytes; } public unsafe static NativeArray AllocateNative(FourCC type, int payloadSize) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) int num = payloadSize + 8; NativeArray val = new NativeArray(num, (Allocator)2, (NativeArrayOptions)1); InputDeviceCommand* unsafePtr = (InputDeviceCommand*)NativeArrayUnsafeUtility.GetUnsafePtr(val); unsafePtr->type = type; unsafePtr->sizeInBytes = num; return val; } } [StructLayout(LayoutKind.Explicit, Size = 9)] public struct QueryCanRunInBackground : IInputDeviceCommandInfo { internal const int kSize = 9; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public bool canRunInBackground; public static FourCC Type => new FourCC('Q', 'R', 'I', 'B'); public FourCC typeStatic => Type; public static QueryCanRunInBackground Create() { return new QueryCanRunInBackground { baseCommand = new InputDeviceCommand(Type, 9), canRunInBackground = false }; } } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct QueryDimensionsCommand : IInputDeviceCommandInfo { internal const int kSize = 16; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public Vector2 outDimensions; public static FourCC Type => new FourCC('D', 'I', 'M', 'S'); public FourCC typeStatic => Type; public static QueryDimensionsCommand Create() { return new QueryDimensionsCommand { baseCommand = new InputDeviceCommand(Type, 16) }; } } [StructLayout(LayoutKind.Explicit, Size = 9)] public struct QueryEnabledStateCommand : IInputDeviceCommandInfo { internal const int kSize = 9; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public bool isEnabled; public static FourCC Type => new FourCC('Q', 'E', 'N', 'B'); public FourCC typeStatic => Type; public static QueryEnabledStateCommand Create() { return new QueryEnabledStateCommand { baseCommand = new InputDeviceCommand(Type, 9) }; } } [StructLayout(LayoutKind.Explicit, Size = 268)] public struct QueryKeyNameCommand : IInputDeviceCommandInfo { internal const int kMaxNameLength = 256; internal const int kSize = 268; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public int scanOrKeyCode; [FieldOffset(12)] public unsafe fixed byte nameBuffer[256]; public static FourCC Type => new FourCC('K', 'Y', 'C', 'F'); public FourCC typeStatic => Type; public unsafe string ReadKeyName() { fixed (QueryKeyNameCommand* ptr = &this) { return StringHelpers.ReadStringFromBuffer(new IntPtr(ptr->nameBuffer), 256); } } public static QueryKeyNameCommand Create(Key key) { return new QueryKeyNameCommand { baseCommand = new InputDeviceCommand(Type, 268), scanOrKeyCode = (int)key }; } } [StructLayout(LayoutKind.Explicit, Size = 264)] public struct QueryKeyboardLayoutCommand : IInputDeviceCommandInfo { internal const int kMaxNameLength = 256; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public unsafe fixed byte nameBuffer[256]; public static FourCC Type => new FourCC('K', 'B', 'L', 'T'); public FourCC typeStatic => Type; public unsafe string ReadLayoutName() { fixed (QueryKeyboardLayoutCommand* ptr = &this) { return StringHelpers.ReadStringFromBuffer(new IntPtr(ptr->nameBuffer), 256); } } public unsafe void WriteLayoutName(string name) { fixed (QueryKeyboardLayoutCommand* ptr = &this) { StringHelpers.WriteStringToBuffer(name, new IntPtr(ptr->nameBuffer), 256); } } public static QueryKeyboardLayoutCommand Create() { return new QueryKeyboardLayoutCommand { baseCommand = new InputDeviceCommand(Type, 264) }; } } [StructLayout(LayoutKind.Explicit, Size = 1040)] public struct QueryPairedUserAccountCommand : IInputDeviceCommandInfo { [Flags] public enum Result : long { DevicePairedToUserAccount = 2L, UserAccountSelectionInProgress = 4L, UserAccountSelectionComplete = 8L, UserAccountSelectionCanceled = 0x10L } internal const int kMaxNameLength = 256; internal const int kMaxIdLength = 256; internal const int kSize = 1040; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public ulong handle; [FieldOffset(16)] internal unsafe fixed byte nameBuffer[512]; [FieldOffset(528)] internal unsafe fixed byte idBuffer[512]; public static FourCC Type => new FourCC('P', 'A', 'C', 'C'); public unsafe string id { get { fixed (byte* value = idBuffer) { return StringHelpers.ReadStringFromBuffer(new IntPtr(value), 256); } } set { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length > 256) { throw new ArgumentException($"ID '{value}' exceeds maximum supported length of {256} characters", "value"); } fixed (byte* value2 = idBuffer) { StringHelpers.WriteStringToBuffer(value, new IntPtr(value2), 256); } } } public unsafe string name { get { fixed (byte* value = nameBuffer) { return StringHelpers.ReadStringFromBuffer(new IntPtr(value), 256); } } set { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length > 256) { throw new ArgumentException($"Name '{value}' exceeds maximum supported length of {256} characters", "value"); } fixed (byte* value2 = nameBuffer) { StringHelpers.WriteStringToBuffer(value, new IntPtr(value2), 256); } } } public FourCC typeStatic => Type; public static QueryPairedUserAccountCommand Create() { return new QueryPairedUserAccountCommand { baseCommand = new InputDeviceCommand(Type, 1040) }; } } [StructLayout(LayoutKind.Explicit, Size = 12)] internal struct QuerySamplingFrequencyCommand : IInputDeviceCommandInfo { internal const int kSize = 12; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public float frequency; public static FourCC Type => new FourCC('S', 'M', 'P', 'L'); public FourCC typeStatic => Type; public static QuerySamplingFrequencyCommand Create() { return new QuerySamplingFrequencyCommand { baseCommand = new InputDeviceCommand(Type, 12) }; } } [StructLayout(LayoutKind.Explicit, Size = 520)] internal struct QueryUserIdCommand : IInputDeviceCommandInfo { public const int kMaxIdLength = 256; internal const int kSize = 520; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public unsafe fixed byte idBuffer[512]; public static FourCC Type => new FourCC('U', 'S', 'E', 'R'); public FourCC typeStatic => Type; public unsafe string ReadId() { fixed (QueryUserIdCommand* ptr = &this) { return StringHelpers.ReadStringFromBuffer(new IntPtr(ptr->idBuffer), 256); } } public static QueryUserIdCommand Create() { return new QueryUserIdCommand { baseCommand = new InputDeviceCommand(Type, 520) }; } } [StructLayout(LayoutKind.Explicit, Size = 8)] public struct RequestResetCommand : IInputDeviceCommandInfo { internal const int kSize = 8; [FieldOffset(0)] public InputDeviceCommand baseCommand; public static FourCC Type => new FourCC('R', 'S', 'E', 'T'); public FourCC typeStatic => Type; public static RequestResetCommand Create() { return new RequestResetCommand { baseCommand = new InputDeviceCommand(Type) }; } } [StructLayout(LayoutKind.Explicit, Size = 8)] public struct RequestSyncCommand : IInputDeviceCommandInfo { internal const int kSize = 8; [FieldOffset(0)] public InputDeviceCommand baseCommand; public static FourCC Type => new FourCC('S', 'Y', 'N', 'C'); public FourCC typeStatic => Type; public static RequestSyncCommand Create() { return new RequestSyncCommand { baseCommand = new InputDeviceCommand(Type) }; } } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct SetIMECursorPositionCommand : IInputDeviceCommandInfo { internal const int kSize = 16; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] private Vector2 m_Position; public static FourCC Type => new FourCC('I', 'M', 'E', 'P'); public Vector2 position => m_Position; public FourCC typeStatic => Type; public static SetIMECursorPositionCommand Create(Vector2 cursorPosition) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) return new SetIMECursorPositionCommand { baseCommand = new InputDeviceCommand(Type, 16), m_Position = cursorPosition }; } } [StructLayout(LayoutKind.Explicit, Size = 12)] public struct SetSamplingFrequencyCommand : IInputDeviceCommandInfo { internal const int kSize = 12; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public float frequency; public static FourCC Type => new FourCC('S', 'S', 'P', 'L'); public FourCC typeStatic => Type; public static SetSamplingFrequencyCommand Create(float frequency) { return new SetSamplingFrequencyCommand { baseCommand = new InputDeviceCommand(Type, 12), frequency = frequency }; } } [StructLayout(LayoutKind.Explicit, Size = 9)] internal struct UseWindowsGamingInputCommand : IInputDeviceCommandInfo { internal const int kSize = 9; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public byte enable; public static FourCC Type => new FourCC('U', 'W', 'G', 'I'); public FourCC typeStatic => Type; public static UseWindowsGamingInputCommand Create(bool enable) { return new UseWindowsGamingInputCommand { baseCommand = new InputDeviceCommand(Type, 9), enable = (enable ? ((byte)1) : ((byte)0)) }; } } [StructLayout(LayoutKind.Explicit, Size = 16)] internal struct WarpMousePositionCommand : IInputDeviceCommandInfo { internal const int kSize = 16; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public Vector2 warpPositionInPlayerDisplaySpace; public static FourCC Type => new FourCC('W', 'P', 'M', 'S'); public FourCC typeStatic => Type; public static WarpMousePositionCommand Create(Vector2 position) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) return new WarpMousePositionCommand { baseCommand = new InputDeviceCommand(Type, 16), warpPositionInPlayerDisplaySpace = position }; } } [StructLayout(LayoutKind.Explicit, Size = 28)] public struct GamepadState : IInputStateTypeInfo { internal const string ButtonSouthShortDisplayName = "A"; internal const string ButtonNorthShortDisplayName = "Y"; internal const string ButtonWestShortDisplayName = "X"; internal const string ButtonEastShortDisplayName = "B"; [FieldOffset(0)] [InputControl(name = "dpad", layout = "Dpad", usage = "Hatswitch", displayName = "D-Pad", format = "BIT", sizeInBits = 4u, bit = 0u)] [InputControl(name = "buttonSouth", layout = "Button", bit = 6u, usages = new string[] { "PrimaryAction", "Submit" }, aliases = new string[] { "a", "cross" }, displayName = "Button South", shortDisplayName = "A")] [InputControl(name = "buttonWest", layout = "Button", bit = 7u, usage = "SecondaryAction", aliases = new string[] { "x", "square" }, displayName = "Button West", shortDisplayName = "X")] [InputControl(name = "buttonNorth", layout = "Button", bit = 4u, aliases = new string[] { "y", "triangle" }, displayName = "Button North", shortDisplayName = "Y")] [InputControl(name = "buttonEast", layout = "Button", bit = 5u, usages = new string[] { "Back", "Cancel" }, aliases = new string[] { "b", "circle" }, displayName = "Button East", shortDisplayName = "B")] [InputControl(name = "leftStickPress", layout = "Button", bit = 8u, displayName = "Left Stick Press")] [InputControl(name = "rightStickPress", layout = "Button", bit = 9u, displayName = "Right Stick Press")] [InputControl(name = "leftShoulder", layout = "Button", bit = 10u, displayName = "Left Shoulder", shortDisplayName = "LB")] [InputControl(name = "rightShoulder", layout = "Button", bit = 11u, displayName = "Right Shoulder", shortDisplayName = "RB")] [InputControl(name = "start", layout = "Button", bit = 12u, usage = "Menu", displayName = "Start")] [InputControl(name = "select", layout = "Button", bit = 13u, displayName = "Select")] public uint buttons; [FieldOffset(4)] [InputControl(layout = "Stick", usage = "Primary2DMotion", processors = "stickDeadzone", displayName = "Left Stick", shortDisplayName = "LS")] public Vector2 leftStick; [FieldOffset(12)] [InputControl(layout = "Stick", usage = "Secondary2DMotion", processors = "stickDeadzone", displayName = "Right Stick", shortDisplayName = "RS")] public Vector2 rightStick; [FieldOffset(20)] [InputControl(layout = "Button", format = "FLT", usage = "SecondaryTrigger", displayName = "Left Trigger", shortDisplayName = "LT")] public float leftTrigger; [FieldOffset(24)] [InputControl(layout = "Button", format = "FLT", usage = "SecondaryTrigger", displayName = "Right Trigger", shortDisplayName = "RT")] public float rightTrigger; public static FourCC Format => new FourCC('G', 'P', 'A', 'D'); public FourCC format => Format; public GamepadState(params GamepadButton[] buttons) { this = default(GamepadState); if (buttons == null) { throw new ArgumentNullException("buttons"); } foreach (GamepadButton gamepadButton in buttons) { uint num = (uint)(1 << (int)gamepadButton); this.buttons |= num; } } public GamepadState WithButton(GamepadButton button, bool value = true) { uint num = (uint)(1 << (int)button); if (value) { buttons |= num; } else { buttons &= ~num; } return this; } } public enum GamepadButton { DpadUp = 0, DpadDown = 1, DpadLeft = 2, DpadRight = 3, North = 4, East = 5, South = 6, West = 7, LeftStick = 8, RightStick = 9, LeftShoulder = 10, RightShoulder = 11, Start = 12, Select = 13, LeftTrigger = 32, RightTrigger = 33, X = 7, Y = 4, A = 6, B = 5, Cross = 6, Square = 7, Triangle = 4, Circle = 5 } [StructLayout(LayoutKind.Explicit, Size = 16)] internal struct DualMotorRumbleCommand : IInputDeviceCommandInfo { internal const int kSize = 16; [FieldOffset(0)] public InputDeviceCommand baseCommand; [FieldOffset(8)] public float lowFrequencyMotorSpeed; [FieldOffset(12)] public float highFrequencyMotorSpeed; public static FourCC Type => new FourCC('R', 'M', 'B', 'L'); public FourCC typeStatic => Type; public static DualMotorRumbleCommand Create(float lowFrequency, float highFrequency) { return new DualMotorRumbleCommand { baseCommand = new InputDeviceCommand(Type, 16), lowFrequencyMotorSpeed = lowFrequency, highFrequencyMotorSpeed = highFrequency }; } } internal interface ICustomDeviceReset { void Reset(); } internal interface IEventMerger { bool MergeForward(InputEventPtr currentEventPtr, InputEventPtr nextEventPtr); } internal interface IEventPreProcessor { bool PreProcessEvent(InputEventPtr currentEventPtr); } public interface IInputUpdateCallbackReceiver { void OnUpdate(); } public interface ITextInputReceiver { void OnTextInput(char character); void OnIMECompositionChanged(IMECompositionString compositionString); } internal struct JoystickState : IInputStateTypeInfo { public enum Button { HatSwitchUp, HatSwitchDown, HatSwitchLeft, HatSwitchRight, Trigger } [InputControl(name = "trigger", displayName = "Trigger", layout = "Button", usages = new string[] { "PrimaryTrigger", "PrimaryAction", "Submit" }, bit = 4u)] public int buttons; [InputControl(displayName = "Stick", layout = "Stick", usage = "Primary2DMotion", processors = "stickDeadzone")] public Vector2 stick; public static FourCC kFormat => new FourCC('J', 'O', 'Y'); public FourCC format => kFormat; } public struct KeyboardState : IInputStateTypeInfo { private const int kSizeInBits = 110; internal const int kSizeInBytes = 14; [InputControl(name = "anyKey", displayName = "Any Key", layout = "AnyKey", sizeInBits = 109u, synthetic = true)] [InputControl(name = "escape", displayName = "Escape", layout = "Key", usages = new string[] { "Back", "Cancel" }, bit = 60u)] [InputControl(name = "space", displayName = "Space", layout = "Key", bit = 1u)] [InputControl(name = "enter", displayName = "Enter", layout = "Key", usage = "Submit", bit = 2u)] [InputControl(name = "tab", displayName = "Tab", layout = "Key", bit = 3u)] [InputControl(name = "backquote", displayName = "`", layout = "Key", bit = 4u)] [InputControl(name = "quote", displayName = "'", layout = "Key", bit = 5u)] [InputControl(name = "semicolon", displayName = ";", layout = "Key", bit = 6u)] [InputControl(name = "comma", displayName = ",", layout = "Key", bit = 7u)] [InputControl(name = "period", displayName = ".", layout = "Key", bit = 8u)] [InputControl(name = "slash", displayName = "/", layout = "Key", bit = 9u)] [InputControl(name = "backslash", displayName = "\\", layout = "Key", bit = 10u)] [InputControl(name = "leftBracket", displayName = "[", layout = "Key", bit = 11u)] [InputControl(name = "rightBracket", displayName = "]", layout = "Key", bit = 12u)] [InputControl(name = "minus", displayName = "-", layout = "Key", bit = 13u)] [InputControl(name = "equals", displayName = "=", layout = "Key", bit = 14u)] [InputControl(name = "upArrow", displayName = "Up Arrow", layout = "Key", bit = 63u)] [InputControl(name = "downArrow", displayName = "Down Arrow", layout = "Key", bit = 64u)] [InputControl(name = "leftArrow", displayName = "Left Arrow", layout = "Key", bit = 61u)] [InputControl(name = "rightArrow", displayName = "Right Arrow", layout = "Key", bit = 62u)] [InputControl(name = "a", displayName = "A", layout = "Key", bit = 15u)] [InputControl(name = "b", displayName = "B", layout = "Key", bit = 16u)] [InputControl(name = "c", displayName = "C", layout = "Key", bit = 17u)] [InputControl(name = "d", displayName = "D", layout = "Key", bit = 18u)] [InputControl(name = "e", displayName = "E", layout = "Key", bit = 19u)] [InputControl(name = "f", displayName = "F", layout = "Key", bit = 20u)] [InputControl(name = "g", displayName = "G", layout = "Key", bit = 21u)] [InputControl(name = "h", displayName = "H", layout = "Key", bit = 22u)] [InputControl(name = "i", displayName = "I", layout = "Key", bit = 23u)] [InputControl(name = "j", displayName = "J", layout = "Key", bit = 24u)] [InputControl(name = "k", displayName = "K", layout = "Key", bit = 25u)] [InputControl(name = "l", displayName = "L", layout = "Key", bit = 26u)] [InputControl(name = "m", displayName = "M", layout = "Key", bit = 27u)] [InputControl(name = "n", displayName = "N", layout = "Key", bit = 28u)] [InputControl(name = "o", displayName = "O", layout = "Key", bit = 29u)] [InputControl(name = "p", displayName = "P", layout = "Key", bit = 30u)] [InputControl(name = "q", displayName = "Q", layout = "Key", bit = 31u)] [InputControl(name = "r", displayName = "R", layout = "Key", bit = 32u)] [InputControl(name = "s", displayName = "S", layout = "Key", bit = 33u)] [InputControl(name = "t", displayName = "T", layout = "Key", bit = 34u)] [InputControl(name = "u", displayName = "U", layout = "Key", bit = 35u)] [InputControl(name = "v", displayName = "V", layout = "Key", bit = 36u)] [InputControl(name = "w", displayName = "W", layout = "Key", bit = 37u)] [InputControl(name = "x", displayName = "X", layout = "Key", bit = 38u)] [InputControl(name = "y", displayName = "Y", layout = "Key", bit = 39u)] [InputControl(name = "z", displayName = "Z", layout = "Key", bit = 40u)] [InputControl(name = "1", displayName = "1", layout = "Key", bit = 41u)] [InputControl(name = "2", displayName = "2", layout = "Key", bit = 42u)] [InputControl(name = "3", displayName = "3", layout = "Key", bit = 43u)] [InputControl(name = "4", displayName = "4", layout = "Key", bit = 44u)] [InputControl(name = "5", displayName = "5", layout = "Key", bit = 45u)] [InputControl(name = "6", displayName = "6", layout = "Key", bit = 46u)] [InputControl(name = "7", displayName = "7", layout = "Key", bit = 47u)] [InputControl(name = "8", displayName = "8", layout = "Key", bit = 48u)] [InputControl(name = "9", displayName = "9", layout = "Key", bit = 49u)] [InputControl(name = "0", displayName = "0", layout = "Key", bit = 50u)] [InputControl(name = "leftShift", displayName = "Left Shift", layout = "Key", usage = "Modifier", bit = 51u)] [InputControl(name = "rightShift", displayName = "Right Shift", layout = "Key", usage = "Modifier", bit = 52u)] [InputControl(name = "shift", displayName = "Shift", layout = "DiscreteButton", usage = "Modifier", bit = 51u, sizeInBits = 2u, synthetic = true, parameters = "minValue=1,maxValue=3,writeMode=1")] [InputControl(name = "leftAlt", displayName = "Left Alt", layout = "Key", usage = "Modifier", bit = 53u)] [InputControl(name = "rightAlt", displayName = "Right Alt", layout = "Key", usage = "Modifier", bit = 54u, alias = "AltGr")] [InputControl(name = "alt", displayName = "Alt", layout = "DiscreteButton", usage = "Modifier", bit = 53u, sizeInBits = 2u, synthetic = true, parameters = "minValue=1,maxValue=3,writeMode=1")] [InputControl(name = "leftCtrl", displayName = "Left Control", layout = "Key", usage = "Modifier", bit = 55u)] [InputControl(name = "rightCtrl", displayName = "Right Control", layout = "Key", usage = "Modifier", bit = 56u)] [InputControl(name = "ctrl", displayName = "Control", layout = "DiscreteButton", usage = "Modifier", bit = 55u, sizeInBits = 2u, synthetic = true, parameters = "minValue=1,maxValue=3,writeMode=1")] [InputControl(name = "leftMeta", displayName = "Left System", layout = "Key", usage = "Modifier", bit = 57u, aliases = new string[] { "LeftWindows", "LeftApple", "LeftCommand" })] [InputControl(name = "rightMeta", displayName = "Right System", layout = "Key", usage = "Modifier", bit = 58u, aliases = new string[] { "RightWindows", "RightApple", "RightCommand" })] [InputControl(name = "contextMenu", displayName = "Context Menu", layout = "Key", usage = "Modifier", bit = 59u)] [InputControl(name = "backspace", displayName = "Backspace", layout = "Key", bit = 65u)] [InputControl(name = "pageDown", displayName = "Page Down", layout = "Key", bit = 66u)] [InputControl(name = "pageUp", displayName = "Page Up", layout = "Key", bit = 67u)] [InputControl(name = "home", displayName = "Home", layout = "Key", bit = 68u)] [InputControl(name = "end", displayName = "End", layout = "Key", bit = 69u)] [InputControl(name = "insert", displayName = "Insert", layout = "Key", bit = 70u)] [InputControl(name = "delete", displayName = "Delete", layout = "Key", bit = 71u)] [InputControl(name = "capsLock", displayName = "Caps Lock", layout = "Key", bit = 72u)] [InputControl(name = "numLock", displayName = "Num Lock", layout = "Key", bit = 73u)] [InputControl(name = "printScreen", displayName = "Print Screen", layout = "Key", bit = 74u)] [InputControl(name = "scrollLock", displayName = "Scroll Lock", layout = "Key", bit = 75u)] [InputControl(name = "pause", displayName = "Pause/Break", layout = "Key", bit = 76u)] [InputControl(name = "numpadEnter", displayName = "Numpad Enter", layout = "Key", bit = 77u)] [InputControl(name = "numpadDivide", displayName = "Numpad /", layout = "Key", bit = 78u)] [InputControl(name = "numpadMultiply", displayName = "Numpad *", layout = "Key", bit = 79u)] [InputControl(name = "numpadPlus", displayName = "Numpad +", layout = "Key", bit = 80u)] [InputControl(name = "numpadMinus", displayName = "Numpad -", layout = "Key", bit = 81u)] [InputControl(name = "numpadPeriod", displayName = "Numpad .", layout = "Key", bit = 82u)] [InputControl(name = "numpadEquals", displayName = "Numpad =", layout = "Key", bit = 83u)] [InputControl(name = "numpad1", displayName = "Numpad 1", layout = "Key", bit = 85u)] [InputControl(name = "numpad2", displayName = "Numpad 2", layout = "Key", bit = 86u)] [InputControl(name = "numpad3", displayName = "Numpad 3", layout = "Key", bit = 87u)] [InputControl(name = "numpad4", displayName = "Numpad 4", layout = "Key", bit = 88u)] [InputControl(name = "numpad5", displayName = "Numpad 5", layout = "Key", bit = 89u)] [InputControl(name = "numpad6", displayName = "Numpad 6", layout = "Key", bit = 90u)] [InputControl(name = "numpad7", displayName = "Numpad 7", layout = "Key", bit = 91u)] [InputControl(name = "numpad8", displayName = "Numpad 8", layout = "Key", bit = 92u)] [InputControl(name = "numpad9", displayName = "Numpad 9", layout = "Key", bit = 93u)] [InputControl(name = "numpad0", displayName = "Numpad 0", layout = "Key", bit = 84u)] [InputControl(name = "f1", displayName = "F1", layout = "Key", bit = 94u)] [InputControl(name = "f2", displayName = "F2", layout = "Key", bit = 95u)] [InputControl(name = "f3", displayName = "F3", layout = "Key", bit = 96u)] [InputControl(name = "f4", displayName = "F4", layout = "Key", bit = 97u)] [InputControl(name = "f5", displayName = "F5", layout = "Key", bit = 98u)] [InputControl(name = "f6", displayName = "F6", layout = "Key", bit = 99u)] [InputControl(name = "f7", displayName = "F7", layout = "Key", bit = 100u)] [InputControl(name = "f8", displayName = "F8", layout = "Key", bit = 101u)] [InputControl(name = "f9", displayName = "F9", layout = "Key", bit = 102u)] [InputControl(name = "f10", displayName = "F10", layout = "Key", bit = 103u)] [InputControl(name = "f11", displayName = "F11", layout = "Key", bit = 104u)] [InputControl(name = "f12", displayName = "F12", layout = "Key", bit = 105u)] [InputControl(name = "OEM1", layout = "Key", bit = 106u)] [InputControl(name = "OEM2", layout = "Key", bit = 107u)] [InputControl(name = "OEM3", layout = "Key", bit = 108u)] [InputControl(name = "OEM4", layout = "Key", bit = 109u)] [InputControl(name = "OEM5", layout = "Key", bit = 110u)] [InputControl(name = "IMESelected", layout = "Button", bit = 111u, synthetic = true)] public unsafe fixed byte keys[14]; public static FourCC Format => new FourCC('K', 'E', 'Y', 'S'); public FourCC format => Format; public unsafe KeyboardState(params Key[] pressedKeys) { if (pressedKeys == null) { throw new ArgumentNullException("pressedKeys"); } fixed (byte* ptr = keys) { UnsafeUtility.MemClear((void*)ptr, 14L); for (int i = 0; i < pressedKeys.Length; i++) { MemoryHelpers.WriteSingleBit(ptr, (uint)pressedKeys[i], value: true); } } } public unsafe void Set(Key key, bool state) { fixed (byte* ptr = keys) { MemoryHelpers.WriteSingleBit(ptr, (uint)key, state); } } public void Press(Key key) { Set(key, state: true); } public void Release(Key key) { Set(key, state: false); } } [StructLayout(LayoutKind.Explicit, Size = 30)] public struct MouseState : IInputStateTypeInfo { [FieldOffset(0)] [InputControl(usage = "Point", dontReset = true)] public Vector2 position; [FieldOffset(8)] [InputControl(usage = "Secondary2DMotion", layout = "Delta")] public Vector2 delta; [FieldOffset(16)] [InputControl(displayName = "Scroll", layout = "Delta")] [InputControl(name = "scroll/x", aliases = new string[] { "horizontal" }, usage = "ScrollHorizontal", displayName = "Left/Right")] [InputControl(name = "scroll/y", aliases = new string[] { "vertical" }, usage = "ScrollVertical", displayName = "Up/Down", shortDisplayName = "Wheel")] public Vector2 scroll; [FieldOffset(24)] [InputControl(name = "press", useStateFrom = "leftButton", synthetic = true, usages = new string[] { })] [InputControl(name = "leftButton", layout = "Button", bit = 0u, usage = "PrimaryAction", displayName = "Left Button", shortDisplayName = "LMB")] [InputControl(name = "rightButton", layout = "Button", bit = 1u, usage = "SecondaryAction", displayName = "Right Button", shortDisplayName = "RMB")] [InputControl(name = "middleButton", layout = "Button", bit = 2u, displayName = "Middle Button", shortDisplayName = "MMB")] [InputControl(name = "forwardButton", layout = "Button", bit = 3u, usage = "Forward", displayName = "Forward")] [InputControl(name = "backButton", layout = "Button", bit = 4u, usage = "Back", displayName = "Back")] [InputControl(name = "pressure", layout = "Axis", usage = "Pressure", offset = 4294967294u, format = "FLT", sizeInBits = 32u)] [InputControl(name = "radius", layout = "Vector2", usage = "Radius", offset = 4294967294u, format = "VEC2", sizeInBits = 64u)] [InputControl(name = "pointerId", layout = "Digital", format = "BIT", sizeInBits = 1u, offset = 4294967294u)] public ushort buttons; [FieldOffset(26)] [InputControl(name = "displayIndex", layout = "Integer", displayName = "Display Index")] public ushort displayIndex; [FieldOffset(28)] [InputControl(name = "clickCount", layout = "Integer", displayName = "Click Count", synthetic = true)] public ushort clickCount; public static FourCC Format => new FourCC('M', 'O', 'U', 'S'); public FourCC format => Format; public MouseState WithButton(MouseButton button, bool state = true) { uint num = (uint)(1 << (int)button); if (state) { buttons |= (ushort)num; } else { buttons &= (ushort)(~num); } return this; } } public enum MouseButton { Left, Right, Middle, Forward, Back } [StructLayout(LayoutKind.Explicit, Size = 36)] public struct PenState : IInputStateTypeInfo { [FieldOffset(0)] [InputControl(usage = "Point", dontReset = true)] public Vector2 position; [FieldOffset(8)] [InputControl(usage = "Secondary2DMotion", layout = "Delta")] public Vector2 delta; [FieldOffset(16)] [InputControl(layout = "Vector2", displayName = "Tilt", usage = "Tilt")] public Vector2 tilt; [FieldOffset(24)] [InputControl(layout = "Analog", usage = "Pressure", defaultState = 0f)] public float pressure; [FieldOffset(28)] [InputControl(layout = "Axis", displayName = "Twist", usage = "Twist")] public float twist; [FieldOffset(32)] [InputControl(name = "tip", displayName = "Tip", layout = "Button", bit = 0u, usage = "PrimaryAction")] [InputControl(name = "press", useStateFrom = "tip", synthetic = true, usages = new string[] { })] [InputControl(name = "eraser", displayName = "Eraser", layout = "Button", bit = 1u)] [InputControl(name = "inRange", displayName = "In Range?", layout = "Button", bit = 4u, synthetic = true)] [InputControl(name = "barrel1", displayName = "Barrel Button #1", layout = "Button", bit = 2u, alias = "barrelFirst", usage = "SecondaryAction")] [InputControl(name = "barrel2", displayName = "Barrel Button #2", layout = "Button", bit = 3u, alias = "barrelSecond")] [InputControl(name = "barrel3", displayName = "Barrel Button #3", layout = "Button", bit = 5u, alias = "barrelThird")] [InputControl(name = "barrel4", displayName = "Barrel Button #4", layout = "Button", bit = 6u, alias = "barrelFourth")] [InputControl(name = "radius", layout = "Vector2", format = "VEC2", sizeInBits = 64u, usage = "Radius", offset = 4294967294u)] [InputControl(name = "pointerId", layout = "Digital", format = "UINT", sizeInBits = 32u, offset = 4294967294u)] public ushort buttons; [FieldOffset(34)] private ushort displayIndex; public static FourCC Format => new FourCC('P', 'E', 'N'); public FourCC format => Format; public PenState WithButton(PenButton button, bool state = true) { uint num = (uint)(1 << (int)button); if (state) { buttons |= (ushort)num; } else { buttons &= (ushort)(~num); } return this; } } internal struct PointerState : IInputStateTypeInfo { private uint pointerId; [InputControl(layout = "Vector2", displayName = "Position", usage = "Point", dontReset = true)] public Vector2 position; [InputControl(layout = "Delta", displayName = "Delta", usage = "Secondary2DMotion")] public Vector2 delta; [InputControl(layout = "Analog", displayName = "Pressure", usage = "Pressure", defaultState = 1f)] public float pressure; [InputControl(layout = "Vector2", displayName = "Radius", usage = "Radius")] public Vector2 radius; [InputControl(name = "press", displayName = "Press", layout = "Button", format = "BIT", bit = 0u)] public ushort buttons; [InputControl(name = "displayIndex", layout = "Integer", displayName = "Display Index")] public ushort displayIndex; public static FourCC kFormat => new FourCC('P', 'T', 'R'); public FourCC format => kFormat; } internal struct AccelerometerState : IInputStateTypeInfo { [InputControl(displayName = "Acceleration", processors = "CompensateDirection", noisy = true)] public Vector3 acceleration; public static FourCC kFormat => new FourCC('A', 'C', 'C', 'L'); public FourCC format => kFormat; } internal struct GyroscopeState : IInputStateTypeInfo { [InputControl(displayName = "Angular Velocity", processors = "CompensateDirection", noisy = true)] public Vector3 angularVelocity; public static FourCC kFormat => new FourCC('G', 'Y', 'R', 'O'); public FourCC format => kFormat; } internal struct GravityState : IInputStateTypeInfo { [InputControl(displayName = "Gravity", processors = "CompensateDirection", noisy = true)] public Vector3 gravity; public static FourCC kFormat => new FourCC('G', 'R', 'V'); public FourCC format => kFormat; } internal struct AttitudeState : IInputStateTypeInfo { [InputControl(displayName = "Attitude", processors = "CompensateRotation", noisy = true)] public Quaternion attitude; public static FourCC kFormat => new FourCC('A', 'T', 'T', 'D'); public FourCC format => kFormat; } internal struct LinearAccelerationState : IInputStateTypeInfo { [InputControl(displayName = "Acceleration", processors = "CompensateDirection", noisy = true)] public Vector3 acceleration; public static FourCC kFormat => new FourCC('L', 'A', 'A', 'C'); public FourCC format => kFormat; } [Flags] internal enum TouchFlags : byte { IndirectTouch = 1, PrimaryTouch = 8, TapPress = 0x10, TapRelease = 0x20, OrphanedPrimaryTouch = 0x40, BeganInSameFrame = 0x80 } [StructLayout(LayoutKind.Explicit, Size = 56)] public struct TouchState : IInputStateTypeInfo { internal const int kSizeInBytes = 56; [FieldOffset(0)] [InputControl(displayName = "Touch ID", layout = "Integer", synthetic = true, dontReset = true)] public int touchId; [FieldOffset(4)] [InputControl(displayName = "Position", dontReset = true)] public Vector2 position; [FieldOffset(12)] [InputControl(displayName = "Delta", layout = "Delta")] public Vector2 delta; [FieldOffset(20)] [InputControl(displayName = "Pressure", layout = "Axis")] public float pressure; [FieldOffset(24)] [InputControl(displayName = "Radius")] public Vector2 radius; [FieldOffset(32)] [InputControl(name = "phase", displayName = "Touch Phase", layout = "TouchPhase", synthetic = true)] [InputControl(name = "press", displayName = "Touch Contact?", layout = "TouchPress", useStateFrom = "phase")] public byte phaseId; [FieldOffset(33)] [InputControl(name = "tapCount", displayName = "Tap Count", layout = "Integer")] public byte tapCount; [FieldOffset(34)] [InputControl(name = "displayIndex", displayName = "Display Index", layout = "Integer")] public byte displayIndex; [FieldOffset(35)] [InputControl(name = "indirectTouch", displayName = "Indirect Touch?", layout = "Button", bit = 0u, synthetic = true)] [InputControl(name = "tap", displayName = "Tap", layout = "Button", bit = 4u)] public byte flags; [FieldOffset(36)] internal uint updateStepCount; [FieldOffset(40)] [InputControl(displayName = "Start Time", layout = "Double", synthetic = true)] public double startTime; [FieldOffset(48)] [InputControl(displayName = "Start Position", synthetic = true)] public Vector2 startPosition; public static FourCC Format => new FourCC('T', 'O', 'U', 'C'); public TouchPhase phase { get { return (TouchPhase)phaseId; } set { phaseId = (byte)value; } } public bool isNoneEndedOrCanceled { get { if (phase != TouchPhase.None && phase != TouchPhase.Ended) { return phase == TouchPhase.Canceled; } return true; } } public bool isInProgress { get { if (phase != TouchPhase.Began && phase != TouchPhase.Moved) { return phase == TouchPhase.Stationary; } return true; } } public bool isPrimaryTouch { get { return (flags & 8) != 0; } set { if (value) { flags |= 8; } else { flags &= 247; } } } internal bool isOrphanedPrimaryTouch { get { return (flags & 0x40) != 0; } set { if (value) { flags |= 64; } else { flags &= 191; } } } public bool isIndirectTouch { get { return (flags & 1) != 0; } set { if (value) { flags |= 1; } else { flags &= 254; } } } public bool isTap { get { return isTapPress; } set { isTapPress = value; } } internal bool isTapPress { get { return (flags & 0x10) != 0; } set { if (value) { flags |= 16; } else { flags &= 239; } } } internal bool isTapRelease { get { return (flags & 0x20) != 0; } set { if (value) { flags |= 32; } else { flags &= 223; } } } internal bool beganInSameFrame { get { return (flags & 0x80) != 0; } set { if (value) { flags |= 128; } else { flags &= 127; } } } public FourCC format => Format; public override string ToString() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) return $"{{ id={touchId} phase={phase} pos={position} delta={delta} pressure={pressure} radius={radius} primary={isPrimaryTouch} }}"; } } [StructLayout(LayoutKind.Explicit, Size = 560)] internal struct TouchscreenState : IInputStateTypeInfo { public const int MaxTouches = 10; [FieldOffset(0)] [InputControl(name = "primaryTouch", displayName = "Primary Touch", layout = "Touch", synthetic = true)] [InputControl(name = "primaryTouch/tap", usage = "PrimaryAction")] [InputControl(name = "position", useStateFrom = "primaryTouch/position")] [InputControl(name = "delta", useStateFrom = "primaryTouch/delta", layout = "Delta")] [InputControl(name = "pressure", useStateFrom = "primaryTouch/pressure")] [InputControl(name = "radius", useStateFrom = "primaryTouch/radius")] [InputControl(name = "press", useStateFrom = "primaryTouch/phase", layout = "TouchPress", synthetic = true, usages = new string[] { })] public unsafe fixed byte primaryTouchData[56]; internal const int kTouchDataOffset = 56; [FieldOffset(56)] [InputControl(layout = "Touch", name = "touch", displayName = "Touch", arraySize = 10)] public unsafe fixed byte touchData[560]; public static FourCC Format => new FourCC('T', 'S', 'C', 'R'); public unsafe TouchState* primaryTouch { get { fixed (byte* result = primaryTouchData) { return (TouchState*)result; } } } public unsafe TouchState* touches { get { fixed (byte* result = touchData) { return (TouchState*)result; } } } public FourCC format => Format; } [StructLayout(LayoutKind.Explicit, Size = 37)] internal struct ActionEvent : IInputEventTypeInfo { [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(20)] private ushort m_ControlIndex; [FieldOffset(22)] private ushort m_BindingIndex; [FieldOffset(24)] private ushort m_InteractionIndex; [FieldOffset(26)] private byte m_StateIndex; [FieldOffset(27)] private byte m_Phase; [FieldOffset(28)] private double m_StartTime; [FieldOffset(36)] public unsafe fixed byte m_ValueData[1]; public static FourCC Type => new FourCC('A', 'C', 'T', 'N'); public double startTime { get { return m_StartTime; } set { m_StartTime = value; } } public InputActionPhase phase { get { return (InputActionPhase)m_Phase; } set { m_Phase = (byte)value; } } public unsafe byte* valueData { get { fixed (byte* result = m_ValueData) { return result; } } } public int valueSizeInBytes => (int)(baseEvent.sizeInBytes - 20 - 16); public int stateIndex { get { return m_StateIndex; } set { if (value < 0 || value > 255) { throw new NotSupportedException("State count cannot exceed byte.MaxValue"); } m_StateIndex = (byte)value; } } public int controlIndex { get { return m_ControlIndex; } set { if (value < 0 || value > 65535) { throw new NotSupportedException("Control count cannot exceed ushort.MaxValue"); } m_ControlIndex = (ushort)value; } } public int bindingIndex { get { return m_BindingIndex; } set { if (value < 0 || value > 65535) { throw new NotSupportedException("Binding count cannot exceed ushort.MaxValue"); } m_BindingIndex = (ushort)value; } } public int interactionIndex { get { if (m_InteractionIndex == ushort.MaxValue) { return -1; } return m_InteractionIndex; } set { if (value == -1) { m_InteractionIndex = ushort.MaxValue; return; } if (value < 0 || value >= 65535) { throw new NotSupportedException("Interaction count cannot exceed ushort.MaxValue-1"); } m_InteractionIndex = (ushort)value; } } public FourCC typeStatic => Type; public unsafe InputEventPtr ToEventPtr() { fixed (ActionEvent* eventPtr = &this) { return new InputEventPtr((InputEvent*)eventPtr); } } public static int GetEventSizeWithValueSize(int valueSizeInBytes) { return 36 + valueSizeInBytes; } public unsafe static ActionEvent* From(InputEventPtr ptr) { if (!ptr.valid) { throw new ArgumentNullException("ptr"); } if (!ptr.IsA()) { throw new InvalidCastException($"Cannot cast event with type '{ptr.type}' into ActionEvent"); } return (ActionEvent*)ptr.data; } } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 29)] public struct DeltaStateEvent : IInputEventTypeInfo { public const int Type = 1145852993; [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(20)] public FourCC stateFormat; [FieldOffset(24)] public uint stateOffset; [FieldOffset(28)] internal unsafe fixed byte stateData[1]; public uint deltaStateSizeInBytes => baseEvent.sizeInBytes - 28; public unsafe void* deltaState { get { fixed (byte* result = stateData) { return result; } } } public FourCC typeStatic => 1145852993; public unsafe InputEventPtr ToEventPtr() { fixed (DeltaStateEvent* eventPtr = &this) { return new InputEventPtr((InputEvent*)eventPtr); } } public unsafe static DeltaStateEvent* From(InputEventPtr ptr) { if (!ptr.valid) { throw new ArgumentNullException("ptr"); } if (!ptr.IsA()) { throw new InvalidCastException($"Cannot cast event with type '{ptr.type}' into DeltaStateEvent"); } return FromUnchecked(ptr); } internal unsafe static DeltaStateEvent* FromUnchecked(InputEventPtr ptr) { return (DeltaStateEvent*)ptr.data; } public unsafe static NativeArray From(InputControl control, out InputEventPtr eventPtr, Allocator allocator = (Allocator)2) { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) if (control == null) { throw new ArgumentNullException("control"); } InputDevice device = control.device; if (!device.added) { throw new ArgumentException($"Device for control '{control}' has not been added to system", "control"); } ref InputStateBlock stateBlock = ref device.m_StateBlock; ref InputStateBlock stateBlock2 = ref control.m_StateBlock; FourCC format = stateBlock.format; uint num = 0u; num = ((stateBlock2.bitOffset == 0) ? stateBlock2.alignedSizeInBytes : ((stateBlock2.bitOffset + stateBlock2.sizeInBits + 7) / 8)); uint byteOffset = stateBlock2.byteOffset; byte* ptr = (byte*)control.currentStatePtr + (int)byteOffset; uint num2 = 28 + num; NativeArray val = new NativeArray((int)num2.AlignToMultipleOf(4u), allocator, (NativeArrayOptions)1); DeltaStateEvent* unsafePtr = (DeltaStateEvent*)NativeArrayUnsafeUtility.GetUnsafePtr(val); Unsafe.Write(&unsafePtr->baseEvent, new InputEvent(1145852993, (int)num2, device.deviceId, InputRuntime.s_Instance.currentTime)); unsafePtr->stateFormat = format; unsafePtr->stateOffset = stateBlock2.byteOffset - stateBlock.byteOffset; UnsafeUtility.MemCpy(unsafePtr->deltaState, (void*)ptr, (long)num); eventPtr = unsafePtr->ToEventPtr(); return val; } } [StructLayout(LayoutKind.Explicit, Size = 20)] public struct DeviceConfigurationEvent : IInputEventTypeInfo { public const int Type = 1145259591; [FieldOffset(0)] public InputEvent baseEvent; public FourCC typeStatic => 1145259591; public unsafe InputEventPtr ToEventPtr() { fixed (DeviceConfigurationEvent* eventPtr = &this) { return new InputEventPtr((InputEvent*)eventPtr); } } public static DeviceConfigurationEvent Create(int deviceId, double time) { return new DeviceConfigurationEvent { baseEvent = new InputEvent(1145259591, 20, deviceId, time) }; } } [StructLayout(LayoutKind.Explicit, Size = 20)] public struct DeviceRemoveEvent : IInputEventTypeInfo { public const int Type = 1146242381; [FieldOffset(0)] public InputEvent baseEvent; public FourCC typeStatic => 1146242381; public unsafe InputEventPtr ToEventPtr() { fixed (DeviceRemoveEvent* eventPtr = &this) { return new InputEventPtr((InputEvent*)eventPtr); } } public static DeviceRemoveEvent Create(int deviceId, double time = -1.0) { return new DeviceRemoveEvent { baseEvent = new InputEvent(1146242381, 20, deviceId, time) }; } } [StructLayout(LayoutKind.Explicit, Size = 20)] public struct DeviceResetEvent : IInputEventTypeInfo { public const int Type = 1146245972; [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(8)] public bool hardReset; public FourCC typeStatic => 1146245972; public static DeviceResetEvent Create(int deviceId, bool hardReset = false, double time = -1.0) { DeviceResetEvent result = new DeviceResetEvent { baseEvent = new InputEvent(1146245972, 20, deviceId, time) }; result.hardReset = hardReset; return result; } } public interface IInputEventTypeInfo { FourCC typeStatic { get; } } [StructLayout(LayoutKind.Explicit, Size = 152)] public struct IMECompositionEvent : IInputEventTypeInfo { internal const int kIMECharBufferSize = 64; public const int Type = 1229800787; [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(20)] public IMECompositionString compositionString; public FourCC typeStatic => 1229800787; public static IMECompositionEvent Create(int deviceId, string compositionString, double time) { return new IMECompositionEvent { baseEvent = new InputEvent(1229800787, 152, deviceId, time), compositionString = new IMECompositionString(compositionString) }; } } [StructLayout(LayoutKind.Explicit, Size = 132)] public struct IMECompositionString : IEnumerable, IEnumerable { internal struct Enumerator : IEnumerator, IDisposable, IEnumerator { private IMECompositionString m_CompositionString; private char m_CurrentCharacter; private int m_CurrentIndex; public char Current => m_CurrentCharacter; object IEnumerator.Current => Current; public Enumerator(IMECompositionString compositionString) { m_CompositionString = compositionString; m_CurrentCharacter = '\0'; m_CurrentIndex = -1; } public unsafe bool MoveNext() { int count = m_CompositionString.Count; m_CurrentIndex++; if (m_CurrentIndex == count) { return false; } fixed (char* buffer = m_CompositionString.buffer) { m_CurrentCharacter = buffer[m_CurrentIndex]; } return true; } public void Reset() { m_CurrentIndex = -1; } public void Dispose() { } } [FieldOffset(0)] private int size; [FieldOffset(4)] private unsafe fixed char buffer[64]; public int Count => size; public unsafe char this[int index] { get { if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException("index"); } fixed (char* ptr = buffer) { return ptr[index]; } } } public unsafe IMECompositionString(string characters) { if (string.IsNullOrEmpty(characters)) { size = 0; return; } size = characters.Length; for (int i = 0; i < size; i++) { buffer[i] = characters[i]; } } public unsafe override string ToString() { fixed (char* value = buffer) { return new string(value, 0, size); } } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 20)] public struct InputEvent { private const uint kHandledMask = 2147483648u; private const uint kIdMask = 2147483647u; internal const int kBaseEventSize = 20; public const int InvalidEventId = 0; internal const int kAlignment = 4; [FieldOffset(0)] private NativeInputEvent m_Event; public FourCC type { get { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected I4, but got Unknown return new FourCC((int)m_Event.type); } set { //IL_000c: Unknown result type (might be due to invalid IL or missing references) m_Event.type = (NativeInputEventType)(int)value; } } public uint sizeInBytes { get { return m_Event.sizeInBytes; } set { if (value > 65535) { throw new ArgumentException("Maximum event size is " + ushort.MaxValue, "value"); } m_Event.sizeInBytes = (ushort)value; } } public int eventId { get { return (int)((long)m_Event.eventId & 0x7FFFFFFFL); } set { m_Event.eventId = value | (int)(m_Event.eventId & 0x80000000u); } } public int deviceId { get { return m_Event.deviceId; } set { m_Event.deviceId = (ushort)value; } } public double time { get { return m_Event.time - InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup; } set { m_Event.time = value + InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup; } } internal double internalTime { get { return m_Event.time; } set { m_Event.time = value; } } public bool handled { get { return (m_Event.eventId & 0x80000000u) == 2147483648u; } set { if (value) { m_Event.eventId = (int)(m_Event.eventId | 0x80000000u); } else { m_Event.eventId = (int)((long)m_Event.eventId & 0x7FFFFFFFL); } } } public InputEvent(FourCC type, int sizeInBytes, int deviceId, double time = -1.0) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (time < 0.0) { time = InputRuntime.s_Instance.currentTime; } m_Event.type = (NativeInputEventType)(int)type; m_Event.sizeInBytes = (ushort)sizeInBytes; m_Event.deviceId = (ushort)deviceId; m_Event.time = time; m_Event.eventId = 0; } public override string ToString() { return $"id={eventId} type={type} device={deviceId} size={sizeInBytes} time={time}"; } internal unsafe static InputEvent* GetNextInMemory(InputEvent* currentPtr) { uint num = currentPtr->sizeInBytes.AlignToMultipleOf(4u); return (InputEvent*)((byte*)currentPtr + num); } internal unsafe static InputEvent* GetNextInMemoryChecked(InputEvent* currentPtr, ref InputEventBuffer buffer) { uint num = currentPtr->sizeInBytes.AlignToMultipleOf(4u); InputEvent* ptr = (InputEvent*)((byte*)currentPtr + num); if (!buffer.Contains(ptr)) { throw new InvalidOperationException($"Event '{new InputEventPtr(currentPtr)}' is last event in given buffer with size {buffer.sizeInBytes}"); } return ptr; } public unsafe static bool Equals(InputEvent* first, InputEvent* second) { if (first == second) { return true; } if (first == null || second == null) { return false; } if (((NativeInputEvent)(&first->m_Event)).sizeInBytes != ((NativeInputEvent)(&second->m_Event)).sizeInBytes) { return false; } return UnsafeUtility.MemCmp((void*)first, (void*)second, (long)((NativeInputEvent)(&first->m_Event)).sizeInBytes) == 0; } } public struct InputEventBuffer : IEnumerable, IEnumerable, IDisposable, ICloneable { private struct Enumerator : IEnumerator, IDisposable, IEnumerator { private unsafe readonly InputEvent* m_Buffer; private readonly int m_EventCount; private unsafe InputEvent* m_CurrentEvent; private int m_CurrentIndex; public unsafe InputEventPtr Current => m_CurrentEvent; object IEnumerator.Current => Current; public unsafe Enumerator(InputEventBuffer buffer) { m_Buffer = buffer.bufferPtr; m_EventCount = buffer.m_EventCount; m_CurrentEvent = null; m_CurrentIndex = 0; } public unsafe bool MoveNext() { if (m_CurrentIndex == m_EventCount) { return false; } if (m_CurrentEvent == null) { m_CurrentEvent = m_Buffer; return m_CurrentEvent != null; } m_CurrentIndex++; if (m_CurrentIndex == m_EventCount) { return false; } m_CurrentEvent = InputEvent.GetNextInMemory(m_CurrentEvent); return true; } public unsafe void Reset() { m_CurrentEvent = null; m_CurrentIndex = 0; } public void Dispose() { } } public const long BufferSizeUnknown = -1L; private NativeArray m_Buffer; private long m_SizeInBytes; private int m_EventCount; private bool m_WeOwnTheBuffer; public int eventCount => m_EventCount; public long sizeInBytes => m_SizeInBytes; public long capacityInBytes { get { if (!m_Buffer.IsCreated) { return 0L; } return m_Buffer.Length; } } public NativeArray data => m_Buffer; public unsafe InputEventPtr bufferPtr => (InputEvent*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_Buffer); public unsafe InputEventBuffer(InputEvent* eventPtr, int eventCount, int sizeInBytes = -1, int capacityInBytes = -1) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) this = default(InputEventBuffer); if (eventPtr == null && eventCount != 0) { throw new ArgumentException("eventPtr is NULL but eventCount is != 0", "eventCount"); } if (capacityInBytes != 0 && capacityInBytes < sizeInBytes) { throw new ArgumentException($"capacity({capacityInBytes}) cannot be smaller than size({sizeInBytes})", "capacityInBytes"); } if (eventPtr != null) { if (capacityInBytes < 0) { capacityInBytes = sizeInBytes; } m_Buffer = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)eventPtr, (capacityInBytes > 0) ? capacityInBytes : 0, (Allocator)1); m_SizeInBytes = ((sizeInBytes >= 0) ? sizeInBytes : (-1)); m_EventCount = eventCount; m_WeOwnTheBuffer = false; } } public InputEventBuffer(NativeArray buffer, int eventCount, int sizeInBytes = -1, bool transferNativeArrayOwnership = false) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (eventCount > 0 && !buffer.IsCreated) { throw new ArgumentException("buffer has no data but eventCount is > 0", "eventCount"); } if (sizeInBytes > buffer.Length) { throw new ArgumentOutOfRangeException("sizeInBytes"); } m_Buffer = buffer; m_WeOwnTheBuffer = transferNativeArrayOwnership; m_SizeInBytes = ((sizeInBytes >= 0) ? sizeInBytes : buffer.Length); m_EventCount = eventCount; } public unsafe void AppendEvent(InputEvent* eventPtr, int capacityIncrementInBytes = 2048, Allocator allocator = (Allocator)4) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (eventPtr == null) { throw new ArgumentNullException("eventPtr"); } uint num = eventPtr->sizeInBytes; UnsafeUtility.MemCpy((void*)AllocateEvent((int)num, capacityIncrementInBytes, allocator), (void*)eventPtr, (long)num); } public unsafe InputEvent* AllocateEvent(int sizeInBytes, int capacityIncrementInBytes = 2048, Allocator allocator = (Allocator)4) { //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (sizeInBytes < 20) { throw new ArgumentException($"sizeInBytes must be >= sizeof(InputEvent) == {20} (was {sizeInBytes})", "sizeInBytes"); } int num = sizeInBytes.AlignToMultipleOf(4); long num2 = m_SizeInBytes + num; if (capacityInBytes < num2) { long num3 = num2.AlignToMultipleOf(capacityIncrementInBytes); if (num3 > int.MaxValue) { throw new NotImplementedException("NativeArray long support"); } NativeArray val = default(NativeArray); val..ctor((int)num3, allocator, (NativeArrayOptions)1); if (m_Buffer.IsCreated) { UnsafeUtility.MemCpy(NativeArrayUnsafeUtility.GetUnsafePtr(val), NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_Buffer), this.sizeInBytes); if (m_WeOwnTheBuffer) { m_Buffer.Dispose(); } } m_Buffer = val; m_WeOwnTheBuffer = true; } InputEvent* ptr = (InputEvent*)((byte*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_Buffer) + m_SizeInBytes); ptr->sizeInBytes = (uint)sizeInBytes; m_SizeInBytes += num; m_EventCount++; return ptr; } public unsafe bool Contains(InputEvent* eventPtr) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (eventPtr == null) { return false; } if (sizeInBytes == 0L) { return false; } void* unsafeBufferPointerWithoutChecks = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(data); if (eventPtr < unsafeBufferPointerWithoutChecks) { return false; } if (sizeInBytes != -1 && eventPtr >= (byte*)unsafeBufferPointerWithoutChecks + sizeInBytes) { return false; } return true; } public void Reset() { m_EventCount = 0; if (m_SizeInBytes != -1) { m_SizeInBytes = 0L; } } internal unsafe void AdvanceToNextEvent(ref InputEvent* currentReadPos, ref InputEvent* currentWritePos, ref int numEventsRetainedInBuffer, ref int numRemainingEvents, bool leaveEventInBuffer) { InputEvent* ptr = currentReadPos; if (numRemainingEvents > 1) { ptr = InputEvent.GetNextInMemory(currentReadPos); } if (leaveEventInBuffer) { uint num = currentReadPos->sizeInBytes; if (currentReadPos != currentWritePos) { UnsafeUtility.MemMove((void*)currentWritePos, (void*)currentReadPos, (long)num); } currentWritePos = (InputEvent*)((byte*)currentWritePos + num.AlignToMultipleOf(4u)); numEventsRetainedInBuffer++; } currentReadPos = ptr; numRemainingEvents--; } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { if (m_WeOwnTheBuffer) { m_Buffer.Dispose(); m_WeOwnTheBuffer = false; m_SizeInBytes = 0L; m_EventCount = 0; } } public InputEventBuffer Clone() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) InputEventBuffer result = default(InputEventBuffer); if (m_Buffer.IsCreated) { result.m_Buffer = new NativeArray(m_Buffer.Length, (Allocator)4, (NativeArrayOptions)1); result.m_Buffer.CopyFrom(m_Buffer); result.m_WeOwnTheBuffer = true; } result.m_SizeInBytes = m_SizeInBytes; result.m_EventCount = m_EventCount; return result; } object ICloneable.Clone() { return Clone(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct InputEventListener : IObservable { internal class ObserverState { public InlinedArray> observers; public Action onEventDelegate; public ObserverState() { onEventDelegate = delegate(InputEventPtr eventPtr, InputDevice device) { for (int num = observers.length - 1; num >= 0; num--) { observers[num].OnNext(eventPtr); } }; } } private class DisposableObserver : IDisposable { public IObserver observer; public void Dispose() { int num = s_ObserverState.observers.IndexOfReference(observer); if (num >= 0) { s_ObserverState.observers.RemoveAtWithCapacity(num); } if (s_ObserverState.observers.length == 0) { InputSystem.s_Manager.onEvent -= s_ObserverState.onEventDelegate; } } } internal static ObserverState s_ObserverState; public static InputEventListener operator +(InputEventListener _, Action callback) { if (callback == null) { throw new ArgumentNullException("callback"); } lock (InputSystem.s_Manager) { InputSystem.s_Manager.onEvent += callback; } return default(InputEventListener); } public static InputEventListener operator -(InputEventListener _, Action callback) { if (callback == null) { throw new ArgumentNullException("callback"); } lock (InputSystem.s_Manager) { InputSystem.s_Manager.onEvent -= callback; } return default(InputEventListener); } public IDisposable Subscribe(IObserver observer) { if (s_ObserverState == null) { s_ObserverState = new ObserverState(); } if (s_ObserverState.observers.length == 0) { InputSystem.s_Manager.onEvent += s_ObserverState.onEventDelegate; } s_ObserverState.observers.AppendWithCapacity(observer); return new DisposableObserver { observer = observer }; } } public struct InputEventPtr : IEquatable { private unsafe readonly InputEvent* m_EventPtr; public unsafe bool valid => m_EventPtr != null; public unsafe bool handled { get { if (!valid) { return false; } return m_EventPtr->handled; } set { if (!valid) { throw new InvalidOperationException("The InputEventPtr is not valid."); } m_EventPtr->handled = value; } } public unsafe int id { get { if (!valid) { return 0; } return m_EventPtr->eventId; } set { if (!valid) { throw new InvalidOperationException("The InputEventPtr is not valid."); } m_EventPtr->eventId = value; } } public unsafe FourCC type { get { if (!valid) { return default(FourCC); } return m_EventPtr->type; } } public unsafe uint sizeInBytes { get { if (!valid) { return 0u; } return m_EventPtr->sizeInBytes; } } public unsafe int deviceId { get { if (!valid) { return 0; } return m_EventPtr->deviceId; } set { if (!valid) { throw new InvalidOperationException("The InputEventPtr is not valid."); } m_EventPtr->deviceId = value; } } public unsafe double time { get { if (!valid) { return 0.0; } return m_EventPtr->time; } set { if (!valid) { throw new InvalidOperationException("The InputEventPtr is not valid."); } m_EventPtr->time = value; } } internal unsafe double internalTime { get { if (!valid) { return 0.0; } return m_EventPtr->internalTime; } set { if (!valid) { throw new InvalidOperationException("The InputEventPtr is not valid."); } m_EventPtr->internalTime = value; } } public unsafe InputEvent* data => m_EventPtr; internal unsafe FourCC stateFormat { get { FourCC fourCC = type; if (fourCC == 1398030676) { return StateEvent.FromUnchecked(this)->stateFormat; } if (fourCC == 1145852993) { return DeltaStateEvent.FromUnchecked(this)->stateFormat; } InputEventPtr inputEventPtr = this; throw new InvalidOperationException("Event must be a StateEvent or DeltaStateEvent but is " + inputEventPtr.ToString()); } } internal unsafe uint stateSizeInBytes { get { if (IsA()) { return StateEvent.From(this)->stateSizeInBytes; } if (IsA()) { return DeltaStateEvent.From(this)->deltaStateSizeInBytes; } InputEventPtr inputEventPtr = this; throw new InvalidOperationException("Event must be a StateEvent or DeltaStateEvent but is " + inputEventPtr.ToString()); } } internal unsafe uint stateOffset { get { if (IsA()) { return DeltaStateEvent.From(this)->stateOffset; } InputEventPtr inputEventPtr = this; throw new InvalidOperationException("Event must be a DeltaStateEvent but is " + inputEventPtr.ToString()); } } public unsafe InputEventPtr(InputEvent* eventPtr) { m_EventPtr = eventPtr; } public unsafe bool IsA() where TOtherEvent : struct, IInputEventTypeInfo { if (m_EventPtr == null) { return false; } return m_EventPtr->type == default(TOtherEvent).typeStatic; } public unsafe InputEventPtr Next() { if (!valid) { return default(InputEventPtr); } return new InputEventPtr(InputEvent.GetNextInMemory(m_EventPtr)); } public unsafe override string ToString() { if (!valid) { return "null"; } InputEvent eventPtr = *m_EventPtr; return eventPtr.ToString(); } public unsafe InputEvent* ToPointer() { return this; } public unsafe bool Equals(InputEventPtr other) { if (m_EventPtr != other.m_EventPtr) { return InputEvent.Equals(m_EventPtr, other.m_EventPtr); } return true; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputEventPtr other) { return Equals(other); } return false; } public unsafe override int GetHashCode() { return (int)m_EventPtr; } public unsafe static bool operator ==(InputEventPtr left, InputEventPtr right) { return left.m_EventPtr == right.m_EventPtr; } public unsafe static bool operator !=(InputEventPtr left, InputEventPtr right) { return left.m_EventPtr != right.m_EventPtr; } public unsafe static implicit operator InputEventPtr(InputEvent* eventPtr) { return new InputEventPtr(eventPtr); } public unsafe static InputEventPtr From(InputEvent* eventPtr) { return new InputEventPtr(eventPtr); } public unsafe static implicit operator InputEvent*(InputEventPtr eventPtr) { return eventPtr.data; } public unsafe static InputEvent* FromInputEventPtr(InputEventPtr eventPtr) { return eventPtr.data; } } internal struct InputEventStream { private InputEventBuffer m_NativeBuffer; private unsafe InputEvent* m_CurrentNativeEventReadPtr; private unsafe InputEvent* m_CurrentNativeEventWritePtr; private int m_RemainingNativeEventCount; private readonly int m_MaxAppendedEvents; private InputEventBuffer m_AppendBuffer; private unsafe InputEvent* m_CurrentAppendEventReadPtr; private unsafe InputEvent* m_CurrentAppendEventWritePtr; private int m_RemainingAppendEventCount; private int m_NumEventsRetainedInBuffer; private bool m_IsOpen; public bool isOpen => m_IsOpen; public int remainingEventCount => m_RemainingNativeEventCount + m_RemainingAppendEventCount; public int numEventsRetainedInBuffer => m_NumEventsRetainedInBuffer; public unsafe InputEvent* currentEventPtr { get { if (m_RemainingNativeEventCount <= 0) { if (m_RemainingAppendEventCount <= 0) { return null; } return m_CurrentAppendEventReadPtr; } return m_CurrentNativeEventReadPtr; } } public unsafe uint numBytesRetainedInBuffer => (uint)((byte*)m_CurrentNativeEventWritePtr - (byte*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_NativeBuffer.data)); public unsafe InputEventStream(ref InputEventBuffer eventBuffer, int maxAppendedEvents) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) m_CurrentNativeEventWritePtr = (m_CurrentNativeEventReadPtr = (InputEvent*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(eventBuffer.data)); m_NativeBuffer = eventBuffer; m_RemainingNativeEventCount = m_NativeBuffer.eventCount; m_NumEventsRetainedInBuffer = 0; m_CurrentAppendEventReadPtr = (m_CurrentAppendEventWritePtr = null); m_AppendBuffer = default(InputEventBuffer); m_RemainingAppendEventCount = 0; m_MaxAppendedEvents = maxAppendedEvents; m_IsOpen = true; } public unsafe void Close(ref InputEventBuffer eventBuffer) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (m_NumEventsRetainedInBuffer > 0) { void* unsafeBufferPointerWithoutChecks = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_NativeBuffer.data); long num = (byte*)m_CurrentNativeEventWritePtr - (byte*)unsafeBufferPointerWithoutChecks; m_NativeBuffer = new InputEventBuffer((InputEvent*)unsafeBufferPointerWithoutChecks, m_NumEventsRetainedInBuffer, (int)num, (int)m_NativeBuffer.capacityInBytes); } else { m_NativeBuffer.Reset(); } if (m_AppendBuffer.data.IsCreated) { m_AppendBuffer.Dispose(); } eventBuffer = m_NativeBuffer; m_IsOpen = false; } public void CleanUpAfterException() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (isOpen) { m_NativeBuffer.Reset(); if (m_AppendBuffer.data.IsCreated) { m_AppendBuffer.Dispose(); } m_IsOpen = false; } } public unsafe void Write(InputEvent* eventPtr) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) if (m_AppendBuffer.eventCount >= m_MaxAppendedEvents) { Debug.LogError((object)("Maximum number of queued events exceeded. Set the 'maxQueuedEventsPerUpdate' setting to a higher value if you need to queue more events than this. " + $"Current limit is '{m_MaxAppendedEvents}'.")); return; } bool isCreated = m_AppendBuffer.data.IsCreated; byte* data = (byte*)m_AppendBuffer.bufferPtr.data; m_AppendBuffer.AppendEvent(eventPtr, 2048, (Allocator)2); if (!isCreated) { m_CurrentAppendEventWritePtr = (m_CurrentAppendEventReadPtr = (InputEvent*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_AppendBuffer.data)); } else { byte* data2 = (byte*)m_AppendBuffer.bufferPtr.data; if (data != data2) { long num = (byte*)m_CurrentAppendEventWritePtr - data; long num2 = (byte*)m_CurrentAppendEventReadPtr - data; m_CurrentAppendEventWritePtr = (InputEvent*)(data2 + num); m_CurrentAppendEventReadPtr = (InputEvent*)(data2 + num2); } } m_RemainingAppendEventCount++; } public unsafe InputEvent* Advance(bool leaveEventInBuffer) { if (m_RemainingNativeEventCount > 0) { m_NativeBuffer.AdvanceToNextEvent(ref m_CurrentNativeEventReadPtr, ref m_CurrentNativeEventWritePtr, ref m_NumEventsRetainedInBuffer, ref m_RemainingNativeEventCount, leaveEventInBuffer); } else if (m_RemainingAppendEventCount > 0) { int num = 0; m_AppendBuffer.AdvanceToNextEvent(ref m_CurrentAppendEventReadPtr, ref m_CurrentAppendEventWritePtr, ref num, ref m_RemainingAppendEventCount, leaveEventInBuffer: false); } return currentEventPtr; } public unsafe InputEvent* Peek() { if (m_RemainingNativeEventCount > 1) { return InputEvent.GetNextInMemory(m_CurrentNativeEventReadPtr); } if (m_RemainingNativeEventCount == 1) { if (m_RemainingAppendEventCount <= 0) { return null; } return m_CurrentAppendEventReadPtr; } if (m_RemainingAppendEventCount > 1) { return InputEvent.GetNextInMemory(m_CurrentAppendEventReadPtr); } return null; } } [Serializable] public sealed class InputEventTrace : IDisposable, IEnumerable, IEnumerable { private class Enumerator : IEnumerator, IDisposable, IEnumerator { private InputEventTrace m_Trace; private int m_ChangeCounter; internal InputEventPtr m_Current; public InputEventPtr Current => m_Current; object IEnumerator.Current => Current; public Enumerator(InputEventTrace trace) { m_Trace = trace; m_ChangeCounter = trace.m_ChangeCounter; } public void Dispose() { m_Trace = null; m_Current = default(InputEventPtr); } public bool MoveNext() { if (m_Trace == null) { throw new ObjectDisposedException(ToString()); } if (m_Trace.m_ChangeCounter != m_ChangeCounter) { throw new InvalidOperationException("Trace has been modified while enumerating!"); } return m_Trace.GetNextEvent(ref m_Current); } public void Reset() { m_Current = default(InputEventPtr); m_ChangeCounter = m_Trace.m_ChangeCounter; } } [Flags] private enum FileFlags { FixedUpdate = 1 } public class ReplayController : IDisposable { private InputEventTrace m_EventTrace; private Enumerator m_Enumerator; private InlinedArray> m_DeviceIDMappings; private bool m_CreateNewDevices; private InlinedArray m_CreatedDevices; private Action m_OnFinished; private Action m_OnEvent; private double m_StartTimeAsPerFirstEvent; private double m_StartTimeAsPerRuntime; private int m_AllEventsByTimeIndex; private List m_AllEventsByTime; public InputEventTrace trace => m_EventTrace; public bool finished { get; private set; } public bool paused { get; set; } public int position { get; private set; } public IEnumerable createdDevices => m_CreatedDevices; internal ReplayController(InputEventTrace trace) { if (trace == null) { throw new ArgumentNullException("trace"); } m_EventTrace = trace; } public void Dispose() { InputSystem.onBeforeUpdate -= OnBeginFrame; finished = true; foreach (InputDevice createdDevice in m_CreatedDevices) { InputSystem.RemoveDevice(createdDevice); } m_CreatedDevices = default(InlinedArray); } public ReplayController WithDeviceMappedFromTo(InputDevice recordedDevice, InputDevice playbackDevice) { if (recordedDevice == null) { throw new ArgumentNullException("recordedDevice"); } if (playbackDevice == null) { throw new ArgumentNullException("playbackDevice"); } WithDeviceMappedFromTo(recordedDevice.deviceId, playbackDevice.deviceId); return this; } public ReplayController WithDeviceMappedFromTo(int recordedDeviceId, int playbackDeviceId) { for (int i = 0; i < m_DeviceIDMappings.length; i++) { if (m_DeviceIDMappings[i].Key == recordedDeviceId) { if (recordedDeviceId == playbackDeviceId) { m_DeviceIDMappings.RemoveAtWithCapacity(i); } else { m_DeviceIDMappings[i] = new KeyValuePair(recordedDeviceId, playbackDeviceId); } return this; } } if (recordedDeviceId == playbackDeviceId) { return this; } m_DeviceIDMappings.AppendWithCapacity(new KeyValuePair(recordedDeviceId, playbackDeviceId)); return this; } public ReplayController WithAllDevicesMappedToNewInstances() { m_CreateNewDevices = true; return this; } public ReplayController OnFinished(Action action) { m_OnFinished = action; return this; } public ReplayController OnEvent(Action action) { m_OnEvent = action; return this; } public ReplayController PlayOneEvent() { if (!MoveNext(skipFrameEvents: true, out var eventPtr)) { throw new InvalidOperationException("No more events"); } QueueEvent(eventPtr); return this; } public ReplayController Rewind() { m_Enumerator = null; m_AllEventsByTime = null; m_AllEventsByTimeIndex = -1; position = 0; return this; } public ReplayController PlayAllFramesOneByOne() { finished = false; InputSystem.onBeforeUpdate += OnBeginFrame; return this; } public ReplayController PlayAllEvents() { finished = false; try { InputEventPtr eventPtr; while (MoveNext(skipFrameEvents: true, out eventPtr)) { QueueEvent(eventPtr); } } finally { Finished(); } return this; } public ReplayController PlayAllEventsAccordingToTimestamps() { List list = new List(); InputEventPtr eventPtr; while (MoveNext(skipFrameEvents: true, out eventPtr)) { list.Add(eventPtr); } list.Sort((InputEventPtr a, InputEventPtr b) => a.time.CompareTo(b.time)); m_Enumerator.Dispose(); m_Enumerator = null; m_AllEventsByTime = list; position = 0; finished = false; m_StartTimeAsPerFirstEvent = -1.0; m_AllEventsByTimeIndex = -1; InputSystem.onBeforeUpdate += OnBeginFrame; return this; } private void OnBeginFrame() { if (paused) { return; } if (!MoveNext(skipFrameEvents: false, out var eventPtr)) { if (m_AllEventsByTime == null || m_AllEventsByTimeIndex >= m_AllEventsByTime.Count) { Finished(); } return; } if (eventPtr.type == FrameMarkerEvent) { if (!MoveNext(skipFrameEvents: false, out var eventPtr2)) { Finished(); return; } if (eventPtr2.type == FrameMarkerEvent) { int num = position - 1; position = num; m_Enumerator.m_Current = eventPtr; return; } eventPtr = eventPtr2; } while (true) { QueueEvent(eventPtr); if (!MoveNext(skipFrameEvents: false, out var eventPtr3)) { if (m_AllEventsByTime == null || m_AllEventsByTimeIndex >= m_AllEventsByTime.Count) { Finished(); } break; } if (eventPtr3.type == FrameMarkerEvent) { m_Enumerator.m_Current = eventPtr; int num = position - 1; position = num; break; } eventPtr = eventPtr3; } } private void Finished() { finished = true; InputSystem.onBeforeUpdate -= OnBeginFrame; m_OnFinished?.Invoke(); } private void QueueEvent(InputEventPtr eventPtr) { double internalTime = eventPtr.internalTime; if (m_AllEventsByTime != null) { eventPtr.internalTime = m_StartTimeAsPerRuntime + (eventPtr.internalTime - m_StartTimeAsPerFirstEvent); } else { eventPtr.internalTime = InputRuntime.s_Instance.currentTime; } int id = eventPtr.id; int deviceId = eventPtr.deviceId; eventPtr.deviceId = ApplyDeviceMapping(deviceId); m_OnEvent?.Invoke(eventPtr); try { InputSystem.QueueEvent(eventPtr); } finally { eventPtr.internalTime = internalTime; eventPtr.id = id; eventPtr.deviceId = deviceId; } } private bool MoveNext(bool skipFrameEvents, out InputEventPtr eventPtr) { eventPtr = default(InputEventPtr); if (m_AllEventsByTime != null) { if (m_AllEventsByTimeIndex + 1 >= m_AllEventsByTime.Count) { position = m_AllEventsByTime.Count; m_AllEventsByTimeIndex = m_AllEventsByTime.Count; return false; } if (m_AllEventsByTimeIndex < 0) { m_StartTimeAsPerFirstEvent = m_AllEventsByTime[0].internalTime; m_StartTimeAsPerRuntime = InputRuntime.s_Instance.currentTime; } else if (m_AllEventsByTimeIndex < m_AllEventsByTime.Count - 1 && m_AllEventsByTime[m_AllEventsByTimeIndex + 1].internalTime > m_StartTimeAsPerFirstEvent + (InputRuntime.s_Instance.currentTime - m_StartTimeAsPerRuntime)) { return false; } m_AllEventsByTimeIndex++; int num = position + 1; position = num; eventPtr = m_AllEventsByTime[m_AllEventsByTimeIndex]; } else { if (m_Enumerator == null) { m_Enumerator = new Enumerator(m_EventTrace); } do { if (!m_Enumerator.MoveNext()) { return false; } int num = position + 1; position = num; eventPtr = m_Enumerator.Current; } while (skipFrameEvents && eventPtr.type == FrameMarkerEvent); } return true; } private int ApplyDeviceMapping(int originalDeviceId) { for (int i = 0; i < m_DeviceIDMappings.length; i++) { KeyValuePair keyValuePair = m_DeviceIDMappings[i]; if (keyValuePair.Key == originalDeviceId) { return keyValuePair.Value; } } if (m_CreateNewDevices) { try { int num = m_EventTrace.deviceInfos.IndexOf((DeviceInfo x) => x.deviceId == originalDeviceId); if (num != -1) { DeviceInfo deviceInfo = m_EventTrace.deviceInfos[num]; InternedString internedString = new InternedString(deviceInfo.layout); if (!InputControlLayout.s_Layouts.HasLayout(internedString)) { if (string.IsNullOrEmpty(deviceInfo.m_FullLayoutJson)) { return originalDeviceId; } InputSystem.RegisterLayout(deviceInfo.m_FullLayoutJson); } InputDevice inputDevice = InputSystem.AddDevice(internedString); WithDeviceMappedFromTo(originalDeviceId, inputDevice.deviceId); m_CreatedDevices.AppendWithCapacity(inputDevice); return inputDevice.deviceId; } } catch { } } return originalDeviceId; } } [Serializable] public struct DeviceInfo { [SerializeField] internal int m_DeviceId; [SerializeField] internal string m_Layout; [SerializeField] internal FourCC m_StateFormat; [SerializeField] internal int m_StateSizeInBytes; [SerializeField] internal string m_FullLayoutJson; public int deviceId { get { return m_DeviceId; } set { m_DeviceId = value; } } public string layout { get { return m_Layout; } set { m_Layout = value; } } public FourCC stateFormat { get { return m_StateFormat; } set { m_StateFormat = value; } } public int stateSizeInBytes { get { return m_StateSizeInBytes; } set { m_StateSizeInBytes = value; } } } private const int kDefaultBufferSize = 1048576; [NonSerialized] private int m_ChangeCounter; [NonSerialized] private bool m_Enabled; [NonSerialized] private Func m_OnFilterEvent; [SerializeField] private int m_DeviceId; [NonSerialized] private CallbackArray> m_EventListeners; [SerializeField] private long m_EventBufferSize; [SerializeField] private long m_MaxEventBufferSize; [SerializeField] private long m_GrowIncrementSize; [SerializeField] private long m_EventCount; [SerializeField] private long m_EventSizeInBytes; [SerializeField] private ulong m_EventBufferStorage; [SerializeField] private ulong m_EventBufferHeadStorage; [SerializeField] private ulong m_EventBufferTailStorage; [SerializeField] private bool m_HasWrapped; [SerializeField] private bool m_RecordFrameMarkers; [SerializeField] private DeviceInfo[] m_DeviceInfos; private static int kFileVersion = 1; public static FourCC FrameMarkerEvent => new FourCC('F', 'R', 'M', 'E'); public int deviceId { get { return m_DeviceId; } set { m_DeviceId = value; } } public bool enabled => m_Enabled; public bool recordFrameMarkers { get { return m_RecordFrameMarkers; } set { if (m_RecordFrameMarkers == value) { return; } m_RecordFrameMarkers = value; if (m_Enabled) { if (value) { InputSystem.onBeforeUpdate += OnBeforeUpdate; } else { InputSystem.onBeforeUpdate -= OnBeforeUpdate; } } } } public long eventCount => m_EventCount; public long totalEventSizeInBytes => m_EventSizeInBytes; public unsafe long allocatedSizeInBytes { get { if (m_EventBuffer == null) { return 0L; } return m_EventBufferSize; } } public long maxSizeInBytes => m_MaxEventBufferSize; public ReadOnlyArray deviceInfos => m_DeviceInfos; public Func onFilterEvent { get { return m_OnFilterEvent; } set { m_OnFilterEvent = value; } } private unsafe byte* m_EventBuffer { get { return (byte*)m_EventBufferStorage; } set { m_EventBufferStorage = (ulong)value; } } private unsafe byte* m_EventBufferHead { get { return (byte*)m_EventBufferHeadStorage; } set { m_EventBufferHeadStorage = (ulong)value; } } private unsafe byte* m_EventBufferTail { get { return (byte*)m_EventBufferTailStorage; } set { m_EventBufferTailStorage = (ulong)value; } } private static FourCC kFileFormat => new FourCC('I', 'E', 'V', 'T'); public event Action onEvent { add { m_EventListeners.AddCallback(value); } remove { m_EventListeners.RemoveCallback(value); } } public InputEventTrace(InputDevice device, long bufferSizeInBytes = 1048576L, bool growBuffer = false, long maxBufferSizeInBytes = -1L, long growIncrementSizeInBytes = -1L) : this(bufferSizeInBytes, growBuffer, maxBufferSizeInBytes, growIncrementSizeInBytes) { if (device == null) { throw new ArgumentNullException("device"); } m_DeviceId = device.deviceId; } public InputEventTrace(long bufferSizeInBytes = 1048576L, bool growBuffer = false, long maxBufferSizeInBytes = -1L, long growIncrementSizeInBytes = -1L) { m_EventBufferSize = (uint)bufferSizeInBytes; if (growBuffer) { if (maxBufferSizeInBytes < 0) { m_MaxEventBufferSize = 268435456L; } else { m_MaxEventBufferSize = maxBufferSizeInBytes; } if (growIncrementSizeInBytes < 0) { m_GrowIncrementSize = 1048576L; } else { m_GrowIncrementSize = growIncrementSizeInBytes; } } else { m_MaxEventBufferSize = m_EventBufferSize; } } public void WriteTo(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } using FileStream stream = File.OpenWrite(filePath); WriteTo(stream); } public unsafe void WriteTo(Stream stream) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected I4, but got Unknown if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanSeek) { throw new ArgumentException("Stream does not support seeking", "stream"); } BinaryWriter binaryWriter = new BinaryWriter(stream); FileFlags fileFlags = (FileFlags)0; if (InputSystem.settings.updateMode == InputSettings.UpdateMode.ProcessEventsInFixedUpdate) { fileFlags |= FileFlags.FixedUpdate; } binaryWriter.Write(kFileFormat); binaryWriter.Write(kFileVersion); binaryWriter.Write((int)fileFlags); binaryWriter.Write((int)Application.platform); binaryWriter.Write((ulong)m_EventCount); binaryWriter.Write((ulong)m_EventSizeInBytes); using (IEnumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { InputEventPtr current = enumerator.Current; uint sizeInBytes = current.sizeInBytes; byte[] array = new byte[sizeInBytes]; fixed (byte* ptr = array) { UnsafeUtility.MemCpy((void*)ptr, (void*)current.data, (long)sizeInBytes); binaryWriter.Write(array); } } } binaryWriter.Flush(); long position = stream.Position; int num = m_DeviceInfos.LengthSafe(); binaryWriter.Write(num); for (int i = 0; i < num; i++) { ref DeviceInfo reference = ref m_DeviceInfos[i]; binaryWriter.Write(reference.deviceId); binaryWriter.Write(reference.layout); binaryWriter.Write(reference.stateFormat); binaryWriter.Write(reference.stateSizeInBytes); binaryWriter.Write(reference.m_FullLayoutJson ?? string.Empty); } binaryWriter.Flush(); long value = stream.Position - position; binaryWriter.Write(value); } public void ReadFrom(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } using FileStream stream = File.OpenRead(filePath); ReadFrom(stream); } public unsafe void ReadFrom(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException("Stream does not support reading", "stream"); } BinaryReader binaryReader = new BinaryReader(stream); if (binaryReader.ReadInt32() != kFileFormat) { throw new IOException($"Stream does not appear to be an InputEventTrace (no '{kFileFormat}' code)"); } if (binaryReader.ReadInt32() > kFileVersion) { throw new IOException($"Stream is an InputEventTrace but a newer version (expected version {kFileVersion} or below)"); } binaryReader.ReadInt32(); binaryReader.ReadInt32(); ulong num = binaryReader.ReadUInt64(); ulong num2 = binaryReader.ReadUInt64(); byte* eventBuffer = m_EventBuffer; if (num != 0 && num2 != 0) { byte* ptr; if (m_EventBuffer != null && m_EventBufferSize >= (long)num2) { ptr = m_EventBuffer; } else { ptr = (byte*)UnsafeUtility.Malloc((long)num2, 4, (Allocator)4); m_EventBufferSize = (long)num2; } try { byte* ptr2 = ptr; byte* ptr3 = ptr2 + num2; long num3 = 0L; for (ulong num4 = 0uL; num4 < num; num4++) { int num5 = binaryReader.ReadInt32(); uint num6 = binaryReader.ReadUInt16(); uint num7 = binaryReader.ReadUInt16(); if (num6 > ptr3 - ptr2) { break; } *(int*)ptr2 = num5; ptr2 += 4; *(ushort*)ptr2 = (ushort)num6; ptr2 += 2; *(ushort*)ptr2 = (ushort)num7; ptr2 += 2; int num8 = (int)(num6 - 4 - 2 - 2); byte[] array = binaryReader.ReadBytes(num8); fixed (byte* ptr4 = array) { UnsafeUtility.MemCpy((void*)ptr2, (void*)ptr4, (long)num8); } ptr2 += num8.AlignToMultipleOf(4); num3 += num6.AlignToMultipleOf(4u); if (ptr2 >= ptr3) { break; } } int num9 = binaryReader.ReadInt32(); DeviceInfo[] array2 = new DeviceInfo[num9]; for (int i = 0; i < num9; i++) { array2[i] = new DeviceInfo { deviceId = binaryReader.ReadInt32(), layout = binaryReader.ReadString(), stateFormat = binaryReader.ReadInt32(), stateSizeInBytes = binaryReader.ReadInt32(), m_FullLayoutJson = binaryReader.ReadString() }; } m_EventBuffer = ptr; m_EventBufferHead = m_EventBuffer; m_EventBufferTail = ptr3; m_EventCount = (long)num; m_EventSizeInBytes = num3; m_DeviceInfos = array2; } catch { if (ptr != eventBuffer) { UnsafeUtility.Free((void*)ptr, (Allocator)4); } throw; } } else { m_EventBuffer = null; m_EventBufferHead = null; m_EventBufferTail = null; } if (m_EventBuffer != eventBuffer && eventBuffer != null) { UnsafeUtility.Free((void*)eventBuffer, (Allocator)4); } m_ChangeCounter++; } public static InputEventTrace LoadFrom(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } using FileStream stream = File.OpenRead(filePath); return LoadFrom(stream); } public static InputEventTrace LoadFrom(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException("Stream must be readable", "stream"); } InputEventTrace inputEventTrace = new InputEventTrace(1048576L, growBuffer: false, -1L, -1L); inputEventTrace.ReadFrom(stream); return inputEventTrace; } public ReplayController Replay() { Disable(); return new ReplayController(this); } public unsafe bool Resize(long newBufferSize, long newMaxBufferSize = -1L) { if (newBufferSize <= 0) { throw new ArgumentException("Size must be positive", "newBufferSize"); } if (m_EventBufferSize == newBufferSize) { return true; } if (newMaxBufferSize < newBufferSize) { newMaxBufferSize = newBufferSize; } byte* ptr = (byte*)UnsafeUtility.Malloc(newBufferSize, 4, (Allocator)4); if (ptr == null) { return false; } if (m_EventCount > 0) { if (newBufferSize < m_EventBufferSize || m_HasWrapped) { InputEventPtr current = new InputEventPtr((InputEvent*)m_EventBufferHead); InputEvent* ptr2 = (InputEvent*)ptr; int num = 0; int num2 = 0; long num3 = m_EventSizeInBytes; for (int i = 0; i < m_EventCount; i++) { uint sizeInBytes = current.sizeInBytes; uint num4 = sizeInBytes.AlignToMultipleOf(4u); if (num3 <= newBufferSize) { UnsafeUtility.MemCpy((void*)ptr2, (void*)current.ToPointer(), (long)sizeInBytes); ptr2 = InputEvent.GetNextInMemory(ptr2); num2 += (int)num4; num++; } num3 -= num4; if (!GetNextEvent(ref current)) { break; } } m_HasWrapped = false; m_EventCount = num; m_EventSizeInBytes = num2; } else { UnsafeUtility.MemCpy((void*)ptr, (void*)m_EventBufferHead, m_EventSizeInBytes); } } if (m_EventBuffer != null) { UnsafeUtility.Free((void*)m_EventBuffer, (Allocator)4); } m_EventBufferSize = newBufferSize; m_EventBuffer = ptr; m_EventBufferHead = ptr; m_EventBufferTail = m_EventBuffer + m_EventSizeInBytes; m_MaxEventBufferSize = newMaxBufferSize; m_ChangeCounter++; return true; } public unsafe void Clear() { byte* eventBufferHead = (m_EventBufferTail = default(byte*)); m_EventBufferHead = eventBufferHead; m_EventCount = 0L; m_EventSizeInBytes = 0L; m_ChangeCounter++; m_DeviceInfos = null; } public unsafe void Enable() { if (!m_Enabled) { if (m_EventBuffer == null) { Allocate(); } InputSystem.onEvent += new Action(OnInputEvent); if (m_RecordFrameMarkers) { InputSystem.onBeforeUpdate += OnBeforeUpdate; } m_Enabled = true; } } public void Disable() { if (m_Enabled) { InputSystem.onEvent -= new Action(OnInputEvent); InputSystem.onBeforeUpdate -= OnBeforeUpdate; m_Enabled = false; } } public unsafe bool GetNextEvent(ref InputEventPtr current) { if (m_EventBuffer == null) { return false; } if (m_EventBufferHead == null) { return false; } if (!current.valid) { current = new InputEventPtr((InputEvent*)m_EventBufferHead); return true; } byte* ptr = (byte*)current.Next().data; byte* ptr2 = m_EventBuffer + m_EventBufferSize; if (ptr == m_EventBufferTail) { return false; } if (ptr2 - ptr < 20 || ((InputEvent*)ptr)->sizeInBytes == 0) { ptr = m_EventBuffer; if (ptr == current.ToPointer()) { return false; } } current = new InputEventPtr((InputEvent*)ptr); return true; } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { Disable(); Release(); } private unsafe void Allocate() { m_EventBuffer = (byte*)UnsafeUtility.Malloc(m_EventBufferSize, 4, (Allocator)4); } private unsafe void Release() { Clear(); if (m_EventBuffer != null) { UnsafeUtility.Free((void*)m_EventBuffer, (Allocator)4); m_EventBuffer = null; } } private unsafe void OnBeforeUpdate() { if (m_RecordFrameMarkers) { InputEvent inputEvent = new InputEvent { type = FrameMarkerEvent, internalTime = InputRuntime.s_Instance.currentTime, sizeInBytes = (uint)UnsafeUtility.SizeOf() }; OnInputEvent(new InputEventPtr((InputEvent*)UnsafeUtility.AddressOf(ref inputEvent)), null); } } private unsafe void OnInputEvent(InputEventPtr inputEvent, InputDevice device) { if (inputEvent.handled || (m_DeviceId != 0 && inputEvent.deviceId != m_DeviceId && inputEvent.type != FrameMarkerEvent) || (m_OnFilterEvent != null && !m_OnFilterEvent(inputEvent, device)) || m_EventBuffer == null) { return; } uint num = inputEvent.sizeInBytes.AlignToMultipleOf(4u); if (num > m_MaxEventBufferSize) { return; } if (m_EventBufferTail == null) { m_EventBufferHead = m_EventBuffer; m_EventBufferTail = m_EventBuffer; } byte* ptr = m_EventBufferTail + num; bool flag = ptr > m_EventBufferHead && m_EventBufferHead != m_EventBuffer; if (ptr > m_EventBuffer + m_EventBufferSize) { if (m_EventBufferSize < m_MaxEventBufferSize && !m_HasWrapped) { long num2 = Math.Max(m_GrowIncrementSize, num.AlignToMultipleOf(4u)); long num3 = m_EventBufferSize + num2; if (num3 > m_MaxEventBufferSize) { num3 = m_MaxEventBufferSize; } if (num3 < num) { return; } Resize(num3, -1L); ptr = m_EventBufferTail + num; } long num4 = m_EventBufferSize - (m_EventBufferTail - m_EventBuffer); if (num4 < num) { m_HasWrapped = true; if (num4 >= 20) { UnsafeUtility.MemClear((void*)m_EventBufferTail, 20L); } m_EventBufferTail = m_EventBuffer; ptr = m_EventBuffer + num; if (flag) { m_EventBufferHead = m_EventBuffer; } flag = ptr > m_EventBufferHead; } } if (flag) { byte* ptr2 = m_EventBufferHead; byte* ptr3 = m_EventBuffer + m_EventBufferSize - 20; while (ptr2 < ptr) { uint sizeInBytes = ((InputEvent*)ptr2)->sizeInBytes; ptr2 += sizeInBytes; m_EventCount--; m_EventSizeInBytes -= sizeInBytes; if (ptr2 > ptr3 || ((InputEvent*)ptr2)->sizeInBytes == 0) { ptr2 = m_EventBuffer; break; } } m_EventBufferHead = ptr2; } byte* eventBufferTail = m_EventBufferTail; m_EventBufferTail = ptr; UnsafeUtility.MemCpy((void*)eventBufferTail, (void*)inputEvent.data, (long)inputEvent.sizeInBytes); m_ChangeCounter++; m_EventCount++; m_EventSizeInBytes += num; if (device != null) { bool flag2 = false; if (m_DeviceInfos != null) { for (int i = 0; i < m_DeviceInfos.Length; i++) { if (m_DeviceInfos[i].deviceId == device.deviceId) { flag2 = true; break; } } } if (!flag2) { ArrayHelpers.Append(ref m_DeviceInfos, new DeviceInfo { m_DeviceId = device.deviceId, m_Layout = device.layout, m_StateFormat = device.stateBlock.format, m_StateSizeInBytes = (int)device.stateBlock.alignedSizeInBytes, m_FullLayoutJson = (InputControlLayout.s_Layouts.IsGeneratedLayout(device.m_Layout) ? InputSystem.LoadLayout(device.layout).ToJson() : null) }); } } if (m_EventListeners.length > 0) { DelegateHelpers.InvokeCallbacksSafe(ref m_EventListeners, new InputEventPtr((InputEvent*)eventBufferTail), "InputEventTrace.onEvent"); } } } [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 25)] public struct StateEvent : IInputEventTypeInfo { public const int Type = 1398030676; internal const int kStateDataSizeToSubtract = 1; [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(20)] public FourCC stateFormat; [FieldOffset(24)] internal unsafe fixed byte stateData[1]; public uint stateSizeInBytes => baseEvent.sizeInBytes - 24; public unsafe void* state { get { fixed (byte* result = stateData) { return result; } } } public FourCC typeStatic => 1398030676; public unsafe InputEventPtr ToEventPtr() { fixed (StateEvent* eventPtr = &this) { return new InputEventPtr((InputEvent*)eventPtr); } } public unsafe TState GetState() where TState : struct, IInputStateTypeInfo { TState result = default(TState); if (stateFormat != result.format) { throw new InvalidOperationException($"Expected state format '{result.format}' but got '{stateFormat}' instead"); } UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref result), state, Math.Min(stateSizeInBytes, UnsafeUtility.SizeOf())); return result; } public unsafe static TState GetState(InputEventPtr ptr) where TState : struct, IInputStateTypeInfo { return From(ptr)->GetState(); } public static int GetEventSizeWithPayload() where TState : struct { return UnsafeUtility.SizeOf() + 20 + 4; } public unsafe static StateEvent* From(InputEventPtr ptr) { if (!ptr.valid) { throw new ArgumentNullException("ptr"); } if (!ptr.IsA()) { throw new InvalidCastException($"Cannot cast event with type '{ptr.type}' into StateEvent"); } return FromUnchecked(ptr); } internal unsafe static StateEvent* FromUnchecked(InputEventPtr ptr) { return (StateEvent*)ptr.data; } public static NativeArray From(InputDevice device, out InputEventPtr eventPtr, Allocator allocator = (Allocator)2) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) return From(device, out eventPtr, allocator, useDefaultState: false); } public static NativeArray FromDefaultStateFor(InputDevice device, out InputEventPtr eventPtr, Allocator allocator = (Allocator)2) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) return From(device, out eventPtr, allocator, useDefaultState: true); } private unsafe static NativeArray From(InputDevice device, out InputEventPtr eventPtr, Allocator allocator, bool useDefaultState) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (device == null) { throw new ArgumentNullException("device"); } if (!device.added) { throw new ArgumentException($"Device '{device}' has not been added to system", "device"); } FourCC format = device.m_StateBlock.format; uint alignedSizeInBytes = device.m_StateBlock.alignedSizeInBytes; uint byteOffset = device.m_StateBlock.byteOffset; byte* ptr = (byte*)(useDefaultState ? device.defaultStatePtr : device.currentStatePtr) + (int)byteOffset; uint num = 24 + alignedSizeInBytes; NativeArray val = new NativeArray((int)num.AlignToMultipleOf(4u), allocator, (NativeArrayOptions)1); StateEvent* unsafePtr = (StateEvent*)NativeArrayUnsafeUtility.GetUnsafePtr(val); Unsafe.Write(&unsafePtr->baseEvent, new InputEvent(1398030676, (int)num, device.deviceId, InputRuntime.s_Instance.currentTime)); unsafePtr->stateFormat = format; UnsafeUtility.MemCpy(unsafePtr->state, (void*)ptr, (long)alignedSizeInBytes); eventPtr = unsafePtr->ToEventPtr(); return val; } } [StructLayout(LayoutKind.Explicit, Size = 24)] public struct TextEvent : IInputEventTypeInfo { public const int Type = 1413830740; [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(20)] public int character; public FourCC typeStatic => 1413830740; public unsafe static TextEvent* From(InputEventPtr eventPtr) { if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } if (!eventPtr.IsA()) { throw new InvalidCastException($"Cannot cast event with type '{eventPtr.type}' into TextEvent"); } return (TextEvent*)eventPtr.data; } public static TextEvent Create(int deviceId, char character, double time = -1.0) { return new TextEvent { baseEvent = new InputEvent(1413830740, 24, deviceId, time), character = character }; } public static TextEvent Create(int deviceId, int character, double time = -1.0) { return new TextEvent { baseEvent = new InputEvent(1413830740, 24, deviceId, time), character = character }; } } internal delegate void InputUpdateDelegate(InputUpdateType updateType, ref InputEventBuffer eventBuffer); internal interface IInputRuntime { InputUpdateDelegate onUpdate { get; set; } Action onBeforeUpdate { get; set; } Func onShouldRunUpdate { get; set; } Action onDeviceDiscovered { get; set; } Action onPlayerFocusChanged { get; set; } bool isPlayerFocused { get; } Action onShutdown { get; set; } float pollingFrequency { get; set; } double currentTime { get; } double currentTimeForFixedUpdate { get; } float unscaledGameTime { get; } double currentTimeOffsetToRealtimeSinceStartup { get; } bool runInBackground { get; set; } Vector2 screenSize { get; } ScreenOrientation screenOrientation { get; } bool isInBatchMode { get; } int AllocateDeviceId(); void Update(InputUpdateType type); unsafe void QueueEvent(InputEvent* ptr); unsafe long DeviceCommand(int deviceId, InputDeviceCommand* commandPtr); void RegisterAnalyticsEvent(string name, int maxPerHour, int maxPropertiesPerEvent); void SendAnalyticsEvent(string name, object data); } internal static class InputRuntime { public static IInputRuntime s_Instance; public static double s_CurrentTimeOffsetToRealtimeSinceStartup; } internal static class InputRuntimeExtensions { public unsafe static long DeviceCommand(this IInputRuntime runtime, int deviceId, ref TCommand command) where TCommand : struct, IInputDeviceCommandInfo { if (runtime == null) { throw new ArgumentNullException("runtime"); } return runtime.DeviceCommand(deviceId, (InputDeviceCommand*)UnsafeUtility.AddressOf(ref command)); } } [Serializable] public struct InputMetrics { public int maxNumDevices { get; set; } public int currentNumDevices { get; set; } public int maxStateSizeInBytes { get; set; } public int currentStateSizeInBytes { get; set; } public int currentControlCount { get; set; } public int currentLayoutCount { get; set; } public int totalEventBytes { get; set; } public int totalEventCount { get; set; } public int totalUpdateCount { get; set; } public double totalEventProcessingTime { get; set; } public double totalEventLagTime { get; set; } public float averageEventBytesPerFrame => (float)totalEventBytes / (float)totalUpdateCount; public double averageProcessingTimePerEvent => totalEventProcessingTime / (double)totalEventCount; public double averageLagTimePerEvent => totalEventLagTime / (double)totalEventCount; } [Flags] public enum InputUpdateType { None = 0, Dynamic = 1, Fixed = 2, BeforeRender = 4, Editor = 8, Manual = 0x10, Default = 0xB } internal static class InputUpdate { [Serializable] public struct UpdateStepCount { private bool m_WasUpdated; public uint value { get; private set; } public void OnBeforeUpdate() { m_WasUpdated = true; value++; } public void OnUpdate() { if (!m_WasUpdated) { value++; } m_WasUpdated = false; } } [Serializable] public struct SerializedState { public InputUpdateType lastUpdateType; public UpdateStepCount playerUpdateStepCount; } public static uint s_UpdateStepCount; public static InputUpdateType s_LatestUpdateType; public static UpdateStepCount s_PlayerUpdateStepCount; internal static void OnBeforeUpdate(InputUpdateType type) { s_LatestUpdateType = type; if ((uint)(type - 1) <= 1u || type == InputUpdateType.Manual) { s_PlayerUpdateStepCount.OnBeforeUpdate(); s_UpdateStepCount = s_PlayerUpdateStepCount.value; } } internal static void OnUpdate(InputUpdateType type) { s_LatestUpdateType = type; if ((uint)(type - 1) <= 1u || type == InputUpdateType.Manual) { s_PlayerUpdateStepCount.OnUpdate(); s_UpdateStepCount = s_PlayerUpdateStepCount.value; } } public static SerializedState Save() { return new SerializedState { lastUpdateType = s_LatestUpdateType, playerUpdateStepCount = s_PlayerUpdateStepCount }; } public static void Restore(SerializedState state) { s_LatestUpdateType = state.lastUpdateType; s_PlayerUpdateStepCount = state.playerUpdateStepCount; InputUpdateType inputUpdateType = s_LatestUpdateType; if ((uint)(inputUpdateType - 1) <= 1u || inputUpdateType == InputUpdateType.Manual) { s_UpdateStepCount = s_PlayerUpdateStepCount.value; } else { s_UpdateStepCount = 0u; } } public static InputUpdateType GetUpdateTypeForPlayer(this InputUpdateType mask) { if ((mask & InputUpdateType.Manual) != InputUpdateType.None) { return InputUpdateType.Manual; } if ((mask & InputUpdateType.Dynamic) != InputUpdateType.None) { return InputUpdateType.Dynamic; } if ((mask & InputUpdateType.Fixed) != InputUpdateType.None) { return InputUpdateType.Fixed; } return InputUpdateType.None; } public static bool IsPlayerUpdate(this InputUpdateType updateType) { if (updateType == InputUpdateType.Editor) { return false; } return updateType != InputUpdateType.None; } } internal class NativeInputRuntime : IInputRuntime { public static readonly NativeInputRuntime instance = new NativeInputRuntime(); private bool m_RunInBackground; private Action m_ShutdownMethod; private InputUpdateDelegate m_OnUpdate; private Action m_OnBeforeUpdate; private Func m_OnShouldRunUpdate; private float m_PollingFrequency = 60f; private bool m_DidCallOnShutdown; private Action m_FocusChangedMethod; public unsafe InputUpdateDelegate onUpdate { get { return m_OnUpdate; } set { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (value != null) { NativeInputSystem.onUpdate = (NativeUpdateCallback)delegate(NativeInputUpdateType updateType, NativeInputEventBuffer* eventBufferPtr) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected I4, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) InputEventBuffer eventBuffer = new InputEventBuffer((InputEvent*)((NativeInputEventBuffer)eventBufferPtr).eventBuffer, ((NativeInputEventBuffer)eventBufferPtr).eventCount, ((NativeInputEventBuffer)eventBufferPtr).sizeInBytes, ((NativeInputEventBuffer)eventBufferPtr).capacityInBytes); try { value((InputUpdateType)updateType, ref eventBuffer); } catch (Exception ex) { Debug.LogException(ex); Debug.LogError((object)$"{ex.GetType().Name} during event processing of {updateType} update; resetting event buffer"); eventBuffer.Reset(); } if (eventBuffer.eventCount > 0) { ((NativeInputEventBuffer)eventBufferPtr).eventCount = eventBuffer.eventCount; ((NativeInputEventBuffer)eventBufferPtr).sizeInBytes = (int)eventBuffer.sizeInBytes; ((NativeInputEventBuffer)eventBufferPtr).capacityInBytes = (int)eventBuffer.capacityInBytes; ((NativeInputEventBuffer)eventBufferPtr).eventBuffer = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(eventBuffer.data); } else { ((NativeInputEventBuffer)eventBufferPtr).eventCount = 0; ((NativeInputEventBuffer)eventBufferPtr).sizeInBytes = 0; } }; } else { NativeInputSystem.onUpdate = null; } m_OnUpdate = value; } } public Action onBeforeUpdate { get { return m_OnBeforeUpdate; } set { if (value != null) { NativeInputSystem.onBeforeUpdate = delegate(NativeInputUpdateType updateType) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected I4, but got Unknown value((InputUpdateType)updateType); }; } else { NativeInputSystem.onBeforeUpdate = null; } m_OnBeforeUpdate = value; } } public Func onShouldRunUpdate { get { return m_OnShouldRunUpdate; } set { if (value != null) { NativeInputSystem.onShouldRunUpdate = (NativeInputUpdateType updateType) => value((InputUpdateType)updateType); } else { NativeInputSystem.onShouldRunUpdate = null; } m_OnShouldRunUpdate = value; } } public Action onDeviceDiscovered { get { return NativeInputSystem.onDeviceDiscovered; } set { NativeInputSystem.onDeviceDiscovered = value; } } public Action onShutdown { get { return m_ShutdownMethod; } set { if (value == null) { Application.quitting -= OnShutdown; } else if (m_ShutdownMethod == null) { Application.quitting += OnShutdown; } m_ShutdownMethod = value; } } public Action onPlayerFocusChanged { get { return m_FocusChangedMethod; } set { if (value == null) { Application.focusChanged -= OnFocusChanged; } else if (m_FocusChangedMethod == null) { Application.focusChanged += OnFocusChanged; } m_FocusChangedMethod = value; } } public bool isPlayerFocused => Application.isFocused; public float pollingFrequency { get { return m_PollingFrequency; } set { m_PollingFrequency = value; NativeInputSystem.SetPollingFrequency(value); } } public double currentTime => NativeInputSystem.currentTime; public double currentTimeForFixedUpdate => (double)Time.fixedUnscaledTime + currentTimeOffsetToRealtimeSinceStartup; public double currentTimeOffsetToRealtimeSinceStartup => NativeInputSystem.currentTimeOffsetToRealtimeSinceStartup; public float unscaledGameTime => Time.unscaledTime; public bool runInBackground { get { if (!Application.runInBackground) { return m_RunInBackground; } return true; } set { m_RunInBackground = value; } } public Vector2 screenSize => new Vector2((float)Screen.width, (float)Screen.height); public ScreenOrientation screenOrientation => Screen.orientation; public bool isInBatchMode => Application.isBatchMode; public int AllocateDeviceId() { return NativeInputSystem.AllocateDeviceId(); } public void Update(InputUpdateType updateType) { NativeInputSystem.Update((NativeInputUpdateType)updateType); } public unsafe void QueueEvent(InputEvent* ptr) { NativeInputSystem.QueueInputEvent((IntPtr)ptr); } public unsafe long DeviceCommand(int deviceId, InputDeviceCommand* commandPtr) { if (commandPtr == null) { throw new ArgumentNullException("commandPtr"); } return NativeInputSystem.IOCTL(deviceId, (int)commandPtr->type, new IntPtr(commandPtr->payloadPtr), commandPtr->payloadSizeInBytes); } private void OnShutdown() { m_ShutdownMethod(); } private bool OnWantsToShutdown() { if (!m_DidCallOnShutdown) { OnShutdown(); m_DidCallOnShutdown = true; } return true; } private void OnFocusChanged(bool focus) { m_FocusChangedMethod(focus); } public void RegisterAnalyticsEvent(string name, int maxPerHour, int maxPropertiesPerEvent) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) Analytics.RegisterEvent(name, maxPerHour, maxPropertiesPerEvent, "unity.input", ""); } public void SendAnalyticsEvent(string name, object data) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Analytics.SendEvent(name, data, 1, ""); } } public interface IInputStateCallbackReceiver { void OnNextUpdate(); void OnStateEvent(InputEventPtr eventPtr); bool GetStateOffsetForEvent(InputControl control, InputEventPtr eventPtr, ref uint offset); } public interface IInputStateChangeMonitor { void NotifyControlStateChanged(InputControl control, double time, InputEventPtr eventPtr, long monitorIndex); void NotifyTimerExpired(InputControl control, double time, long monitorIndex, int timerIndex); } public interface IInputStateTypeInfo { FourCC format { get; } } public static class InputState { private class StateChangeMonitorDelegate : IInputStateChangeMonitor { public Action valueChangeCallback; public Action timerExpiredCallback; public void NotifyControlStateChanged(InputControl control, double time, InputEventPtr eventPtr, long monitorIndex) { valueChangeCallback(control, time, eventPtr, monitorIndex); } public void NotifyTimerExpired(InputControl control, double time, long monitorIndex, int timerIndex) { timerExpiredCallback?.Invoke(control, time, monitorIndex, timerIndex); } } public static InputUpdateType currentUpdateType => InputUpdate.s_LatestUpdateType; public static uint updateCount => InputUpdate.s_UpdateStepCount; public static double currentTime => InputRuntime.s_Instance.currentTime - InputRuntime.s_CurrentTimeOffsetToRealtimeSinceStartup; public static event Action onChange { add { InputSystem.s_Manager.onDeviceStateChange += value; } remove { InputSystem.s_Manager.onDeviceStateChange -= value; } } public unsafe static void Change(InputDevice device, InputEventPtr eventPtr, InputUpdateType updateType = InputUpdateType.None) { if (device == null) { throw new ArgumentNullException("device"); } if (!eventPtr.valid) { throw new ArgumentNullException("eventPtr"); } FourCC type = eventPtr.type; FourCC stateFormat; if (type == 1398030676) { stateFormat = StateEvent.FromUnchecked(eventPtr)->stateFormat; } else { if (!(type == 1145852993)) { return; } stateFormat = DeltaStateEvent.FromUnchecked(eventPtr)->stateFormat; } if (stateFormat != device.stateBlock.format) { throw new ArgumentException($"State format {stateFormat} from event does not match state format {device.stateBlock.format} of device {device}", "eventPtr"); } InputSystem.s_Manager.UpdateState(device, eventPtr, (updateType != InputUpdateType.None) ? updateType : InputSystem.s_Manager.defaultUpdateType); } public static void Change(InputControl control, TState state, InputUpdateType updateType = InputUpdateType.None, InputEventPtr eventPtr = default(InputEventPtr)) where TState : struct { Change(control, ref state, updateType, eventPtr); } public unsafe static void Change(InputControl control, ref TState state, InputUpdateType updateType = InputUpdateType.None, InputEventPtr eventPtr = default(InputEventPtr)) where TState : struct { if (control == null) { throw new ArgumentNullException("control"); } if (control.stateBlock.bitOffset != 0 || control.stateBlock.sizeInBits % 8 != 0) { throw new ArgumentException($"Cannot change state of bitfield control '{control}' using this method", "control"); } InputDevice device = control.device; long num = Math.Min(UnsafeUtility.SizeOf(), control.m_StateBlock.alignedSizeInBytes); void* statePtr = UnsafeUtility.AddressOf(ref state); uint stateOffsetInDevice = control.stateBlock.byteOffset - device.stateBlock.byteOffset; InputSystem.s_Manager.UpdateState(device, (updateType != InputUpdateType.None) ? updateType : InputSystem.s_Manager.defaultUpdateType, statePtr, stateOffsetInDevice, (uint)num, eventPtr.valid ? eventPtr.internalTime : InputRuntime.s_Instance.currentTime, eventPtr); } public static bool IsIntegerFormat(this FourCC format) { if (!(format == InputStateBlock.FormatBit) && !(format == InputStateBlock.FormatInt) && !(format == InputStateBlock.FormatByte) && !(format == InputStateBlock.FormatShort) && !(format == InputStateBlock.FormatSBit) && !(format == InputStateBlock.FormatUInt) && !(format == InputStateBlock.FormatUShort) && !(format == InputStateBlock.FormatLong)) { return format == InputStateBlock.FormatULong; } return true; } public static void AddChangeMonitor(InputControl control, IInputStateChangeMonitor monitor, long monitorIndex = -1L, uint groupIndex = 0u) { if (control == null) { throw new ArgumentNullException("control"); } if (monitor == null) { throw new ArgumentNullException("monitor"); } if (!control.device.added) { throw new ArgumentException($"Device for control '{control}' has not been added to system"); } InputSystem.s_Manager.AddStateChangeMonitor(control, monitor, monitorIndex, groupIndex); } public static IInputStateChangeMonitor AddChangeMonitor(InputControl control, Action valueChangeCallback, int monitorIndex = -1, Action timerExpiredCallback = null) { if (valueChangeCallback == null) { throw new ArgumentNullException("valueChangeCallback"); } StateChangeMonitorDelegate stateChangeMonitorDelegate = new StateChangeMonitorDelegate { valueChangeCallback = valueChangeCallback, timerExpiredCallback = timerExpiredCallback }; AddChangeMonitor(control, stateChangeMonitorDelegate, monitorIndex); return stateChangeMonitorDelegate; } public static void RemoveChangeMonitor(InputControl control, IInputStateChangeMonitor monitor, long monitorIndex = -1L) { if (control == null) { throw new ArgumentNullException("control"); } if (monitor == null) { throw new ArgumentNullException("monitor"); } InputSystem.s_Manager.RemoveStateChangeMonitor(control, monitor, monitorIndex); } public static void AddChangeMonitorTimeout(InputControl control, IInputStateChangeMonitor monitor, double time, long monitorIndex = -1L, int timerIndex = -1) { if (monitor == null) { throw new ArgumentNullException("monitor"); } InputSystem.s_Manager.AddStateChangeMonitorTimeout(control, monitor, time, monitorIndex, timerIndex); } public static void RemoveChangeMonitorTimeout(IInputStateChangeMonitor monitor, long monitorIndex = -1L, int timerIndex = -1) { if (monitor == null) { throw new ArgumentNullException("monitor"); } InputSystem.s_Manager.RemoveStateChangeMonitorTimeout(monitor, monitorIndex, timerIndex); } } public struct InputStateBlock { public const uint InvalidOffset = uint.MaxValue; public const uint AutomaticOffset = 4294967294u; public static readonly FourCC FormatInvalid = new FourCC(0); internal const int kFormatInvalid = 0; public static readonly FourCC FormatBit = new FourCC('B', 'I', 'T'); internal const int kFormatBit = 1112101920; public static readonly FourCC FormatSBit = new FourCC('S', 'B', 'I', 'T'); internal const int kFormatSBit = 1396853076; public static readonly FourCC FormatInt = new FourCC('I', 'N', 'T'); internal const int kFormatInt = 1229870112; public static readonly FourCC FormatUInt = new FourCC('U', 'I', 'N', 'T'); internal const int kFormatUInt = 1430867540; public static readonly FourCC FormatShort = new FourCC('S', 'H', 'R', 'T'); internal const int kFormatShort = 1397248596; public static readonly FourCC FormatUShort = new FourCC('U', 'S', 'H', 'T'); internal const int kFormatUShort = 1431521364; public static readonly FourCC FormatByte = new FourCC('B', 'Y', 'T', 'E'); internal const int kFormatByte = 1113150533; public static readonly FourCC FormatSByte = new FourCC('S', 'B', 'Y', 'T'); internal const int kFormatSByte = 1396857172; public static readonly FourCC FormatLong = new FourCC('L', 'N', 'G'); internal const int kFormatLong = 1280198432; public static readonly FourCC FormatULong = new FourCC('U', 'L', 'N', 'G'); internal const int kFormatULong = 1431064135; public static readonly FourCC FormatFloat = new FourCC('F', 'L', 'T'); internal const int kFormatFloat = 1179407392; public static readonly FourCC FormatDouble = new FourCC('D', 'B', 'L'); internal const int kFormatDouble = 1145195552; public static readonly FourCC FormatVector2 = new FourCC('V', 'E', 'C', '2'); internal const int kFormatVector2 = 1447379762; public static readonly FourCC FormatVector3 = new FourCC('V', 'E', 'C', '3'); internal const int kFormatVector3 = 1447379763; public static readonly FourCC FormatQuaternion = new FourCC('Q', 'U', 'A', 'T'); internal const int kFormatQuaternion = 1364541780; public static readonly FourCC FormatVector2Short = new FourCC('V', 'C', '2', 'S'); public static readonly FourCC FormatVector3Short = new FourCC('V', 'C', '3', 'S'); public static readonly FourCC FormatVector2Byte = new FourCC('V', 'C', '2', 'B'); public static readonly FourCC FormatVector3Byte = new FourCC('V', 'C', '3', 'B'); public static readonly FourCC FormatPose = new FourCC('P', 'o', 's', 'e'); internal const int kFormatPose = 1349481317; internal uint m_ByteOffset; public FourCC format { get; set; } public uint byteOffset { get { return m_ByteOffset; } set { m_ByteOffset = value; } } public uint bitOffset { get; set; } public uint sizeInBits { get; set; } internal uint alignedSizeInBytes => sizeInBits + 7 >> 3; internal uint effectiveByteOffset => byteOffset + (bitOffset >> 3); internal uint effectiveBitOffset => byteOffset * 8 + bitOffset; public static int GetSizeOfPrimitiveFormatInBits(FourCC type) { if (type == FormatBit || type == FormatSBit) { return 1; } if (type == FormatInt || type == FormatUInt) { return 32; } if (type == FormatShort || type == FormatUShort) { return 16; } if (type == FormatByte || type == FormatSByte) { return 8; } if (type == FormatLong || type == FormatULong) { return 64; } if (type == FormatFloat) { return 32; } if (type == FormatDouble) { return 64; } if (type == FormatVector2) { return 64; } if (type == FormatVector3) { return 96; } if (type == FormatQuaternion) { return 128; } if (type == FormatVector2Short) { return 32; } if (type == FormatVector3Short) { return 48; } if (type == FormatVector2Byte) { return 16; } if (type == FormatVector3Byte) { return 24; } return -1; } public static FourCC GetPrimitiveFormatFromType(Type type) { if ((object)type == typeof(int)) { return FormatInt; } if ((object)type == typeof(uint)) { return FormatUInt; } if ((object)type == typeof(short)) { return FormatShort; } if ((object)type == typeof(ushort)) { return FormatUShort; } if ((object)type == typeof(byte)) { return FormatByte; } if ((object)type == typeof(sbyte)) { return FormatSByte; } if ((object)type == typeof(long)) { return FormatLong; } if ((object)type == typeof(ulong)) { return FormatULong; } if ((object)type == typeof(float)) { return FormatFloat; } if ((object)type == typeof(double)) { return FormatDouble; } if ((object)type == typeof(Vector2)) { return FormatVector2; } if ((object)type == typeof(Vector3)) { return FormatVector3; } if ((object)type == typeof(Quaternion)) { return FormatQuaternion; } return default(FourCC); } public unsafe int ReadInt(void* statePtr) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { return MemoryHelpers.ReadSingleBit(ptr, bitOffset) ? 1 : 0; } return (int)MemoryHelpers.ReadMultipleBitsAsUInt(ptr, bitOffset, sizeInBits); case 1396853076: if (sizeInBits == 1) { if (!MemoryHelpers.ReadSingleBit(ptr, bitOffset)) { return -1; } return 1; } return MemoryHelpers.ReadExcessKMultipleBitsAsInt(ptr, bitOffset, sizeInBits); case 1229870112: case 1430867540: _ = 1430867540; return *(int*)ptr; case 1397248596: return *(short*)ptr; case 1431521364: return *(ushort*)ptr; case 1113150533: return *ptr; case 1396857172: return *ptr; default: throw new InvalidOperationException($"State format '{format}' is not supported as integer format"); } } public unsafe void WriteInt(void* statePtr, int value) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value != 0); } else { MemoryHelpers.WriteUIntAsMultipleBits(ptr, bitOffset, sizeInBits, (uint)value); } break; case 1396853076: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value > 0); } else { MemoryHelpers.WriteIntAsExcessKMultipleBits(ptr, bitOffset, sizeInBits, value); } break; case 1229870112: case 1430867540: *(int*)ptr = value; break; case 1397248596: *(short*)ptr = (short)value; break; case 1431521364: *(ushort*)ptr = (ushort)value; break; case 1113150533: *ptr = (byte)value; break; case 1396857172: *ptr = (byte)(sbyte)value; break; default: throw new Exception($"State format '{format}' is not supported as integer format"); } } public unsafe float ReadFloat(void* statePtr) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { if (!MemoryHelpers.ReadSingleBit(ptr, bitOffset)) { return 0f; } return 1f; } return MemoryHelpers.ReadMultipleBitsAsNormalizedUInt(ptr, bitOffset, sizeInBits); case 1396853076: if (sizeInBits == 1) { if (!MemoryHelpers.ReadSingleBit(ptr, bitOffset)) { return -1f; } return 1f; } return MemoryHelpers.ReadMultipleBitsAsNormalizedUInt(ptr, bitOffset, sizeInBits) * 2f - 1f; case 1229870112: return NumberHelpers.IntToNormalizedFloat(*(int*)ptr, int.MinValue, int.MaxValue) * 2f - 1f; case 1430867540: return NumberHelpers.UIntToNormalizedFloat(*(uint*)ptr, 0u, uint.MaxValue); case 1397248596: return NumberHelpers.IntToNormalizedFloat(*(short*)ptr, -32768, 32767) * 2f - 1f; case 1431521364: return NumberHelpers.UIntToNormalizedFloat(*(ushort*)ptr, 0u, 65535u); case 1113150533: return NumberHelpers.UIntToNormalizedFloat(*ptr, 0u, 255u); case 1396857172: return NumberHelpers.IntToNormalizedFloat(*ptr, -128, 127) * 2f - 1f; case 1179407392: return *(float*)ptr; case 1145195552: return (float)(*(double*)ptr); default: throw new InvalidOperationException($"State format '{format}' is not supported as floating-point format"); } } public unsafe void WriteFloat(void* statePtr, float value) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value >= 0.5f); } else { MemoryHelpers.WriteNormalizedUIntAsMultipleBits(ptr, bitOffset, sizeInBits, value); } break; case 1396853076: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value >= 0f); } else { MemoryHelpers.WriteNormalizedUIntAsMultipleBits(ptr, bitOffset, sizeInBits, value * 0.5f + 0.5f); } break; case 1229870112: *(int*)ptr = NumberHelpers.NormalizedFloatToInt(value * 0.5f + 0.5f, int.MinValue, int.MaxValue); break; case 1430867540: *(uint*)ptr = NumberHelpers.NormalizedFloatToUInt(value, 0u, uint.MaxValue); break; case 1397248596: *(short*)ptr = (short)NumberHelpers.NormalizedFloatToInt(value * 0.5f + 0.5f, -32768, 32767); break; case 1431521364: *(ushort*)ptr = (ushort)NumberHelpers.NormalizedFloatToUInt(value, 0u, 65535u); break; case 1113150533: *ptr = (byte)NumberHelpers.NormalizedFloatToUInt(value, 0u, 255u); break; case 1396857172: *ptr = (byte)(sbyte)NumberHelpers.NormalizedFloatToInt(value * 0.5f + 0.5f, -128, 127); break; case 1179407392: *(float*)ptr = value; break; case 1145195552: *(double*)ptr = value; break; default: throw new Exception($"State format '{format}' is not supported as floating-point format"); } } internal PrimitiveValue FloatToPrimitiveValue(float value) { switch (format) { case 1112101920: if (sizeInBits == 1) { return value >= 0.5f; } return (int)NumberHelpers.NormalizedFloatToUInt(value, 0u, (uint)((1L << (int)sizeInBits) - 1)); case 1396853076: { if (sizeInBits == 1) { return value >= 0f; } int intMinValue = (int)(-(1L << (int)(sizeInBits - 1))); int intMaxValue = (int)((1L << (int)(sizeInBits - 1)) - 1); return NumberHelpers.NormalizedFloatToInt(value, intMinValue, intMaxValue); } case 1229870112: return NumberHelpers.NormalizedFloatToInt(value * 0.5f + 0.5f, int.MinValue, int.MaxValue); case 1430867540: return NumberHelpers.NormalizedFloatToUInt(value, 0u, uint.MaxValue); case 1397248596: return (short)NumberHelpers.NormalizedFloatToInt(value * 0.5f + 0.5f, -32768, 32767); case 1431521364: return (ushort)NumberHelpers.NormalizedFloatToUInt(value, 0u, 65535u); case 1113150533: return (byte)NumberHelpers.NormalizedFloatToUInt(value, 0u, 255u); case 1396857172: return (sbyte)NumberHelpers.NormalizedFloatToInt(value * 0.5f + 0.5f, -128, 127); case 1179407392: return value; case 1145195552: return value; default: throw new Exception($"State format '{format}' is not supported as floating-point format"); } } public unsafe double ReadDouble(void* statePtr) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { return MemoryHelpers.ReadSingleBit(ptr, bitOffset) ? 1f : 0f; } return MemoryHelpers.ReadMultipleBitsAsNormalizedUInt(ptr, bitOffset, sizeInBits); case 1396853076: if (sizeInBits == 1) { return MemoryHelpers.ReadSingleBit(ptr, bitOffset) ? 1f : (-1f); } return MemoryHelpers.ReadMultipleBitsAsNormalizedUInt(ptr, bitOffset, sizeInBits) * 2f - 1f; case 1229870112: return NumberHelpers.IntToNormalizedFloat(*(int*)ptr, int.MinValue, int.MaxValue) * 2f - 1f; case 1430867540: return NumberHelpers.UIntToNormalizedFloat(*(uint*)ptr, 0u, uint.MaxValue); case 1397248596: return NumberHelpers.IntToNormalizedFloat(*(short*)ptr, -32768, 32767) * 2f - 1f; case 1431521364: return NumberHelpers.UIntToNormalizedFloat(*(ushort*)ptr, 0u, 65535u); case 1113150533: return NumberHelpers.UIntToNormalizedFloat(*ptr, 0u, 255u); case 1396857172: return NumberHelpers.IntToNormalizedFloat(*ptr, -128, 127) * 2f - 1f; case 1179407392: return *(float*)ptr; case 1145195552: return *(double*)ptr; default: throw new Exception($"State format '{format}' is not supported as floating-point format"); } } public unsafe void WriteDouble(void* statePtr, double value) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value >= 0.5); } else { MemoryHelpers.WriteNormalizedUIntAsMultipleBits(ptr, bitOffset, sizeInBits, (float)value); } break; case 1396853076: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value >= 0.0); } else { MemoryHelpers.WriteNormalizedUIntAsMultipleBits(ptr, bitOffset, sizeInBits, (float)value * 0.5f + 0.5f); } break; case 1229870112: *(int*)ptr = NumberHelpers.NormalizedFloatToInt((float)value * 0.5f + 0.5f, int.MinValue, int.MaxValue); break; case 1430867540: *(uint*)ptr = NumberHelpers.NormalizedFloatToUInt((float)value, 0u, uint.MaxValue); break; case 1397248596: *(short*)ptr = (short)NumberHelpers.NormalizedFloatToInt((float)value * 0.5f + 0.5f, -32768, 32767); break; case 1431521364: *(ushort*)ptr = (ushort)NumberHelpers.NormalizedFloatToUInt((float)value, 0u, 65535u); break; case 1113150533: *ptr = (byte)NumberHelpers.NormalizedFloatToUInt((float)value, 0u, 255u); break; case 1396857172: *ptr = (byte)(sbyte)NumberHelpers.NormalizedFloatToInt((float)value * 0.5f + 0.5f, -128, 127); break; case 1179407392: *(float*)ptr = (float)value; break; case 1145195552: *(double*)ptr = value; break; default: throw new InvalidOperationException($"State format '{format}' is not supported as floating-point format"); } } public unsafe void Write(void* statePtr, PrimitiveValue value) { byte* ptr = (byte*)statePtr + (int)byteOffset; switch (format) { case 1112101920: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value.ToBoolean()); } else { MemoryHelpers.WriteUIntAsMultipleBits(ptr, bitOffset, sizeInBits, value.ToUInt32()); } break; case 1396853076: if (sizeInBits == 1) { MemoryHelpers.WriteSingleBit(ptr, bitOffset, value.ToBoolean()); } else { MemoryHelpers.WriteIntAsExcessKMultipleBits(ptr, bitOffset, sizeInBits, value.ToInt32()); } break; case 1229870112: *(int*)ptr = value.ToInt32(); break; case 1430867540: *(uint*)ptr = value.ToUInt32(); break; case 1397248596: *(short*)ptr = value.ToInt16(); break; case 1431521364: *(ushort*)ptr = value.ToUInt16(); break; case 1113150533: *ptr = value.ToByte(); break; case 1396857172: *ptr = (byte)value.ToSByte(); break; case 1179407392: *(float*)ptr = value.ToSingle(); break; default: throw new NotImplementedException($"Writing primitive value of type '{value.type}' into state block with format '{format}'"); } } public unsafe void CopyToFrom(void* toStatePtr, void* fromStatePtr) { if (bitOffset != 0 || sizeInBits % 8 != 0) { throw new NotImplementedException("Copying bitfields"); } byte* ptr = (byte*)fromStatePtr + byteOffset; UnsafeUtility.MemCpy((void*)((byte*)toStatePtr + byteOffset), (void*)ptr, (long)alignedSizeInBytes); } } internal struct InputStateBuffers { [Serializable] internal struct DoubleBuffers { public unsafe void** deviceToBufferMapping; public unsafe bool valid => deviceToBufferMapping != null; public unsafe void SetFrontBuffer(int deviceIndex, void* ptr) { deviceToBufferMapping[deviceIndex * 2] = ptr; } public unsafe void SetBackBuffer(int deviceIndex, void* ptr) { deviceToBufferMapping[deviceIndex * 2 + 1] = ptr; } public unsafe void* GetFrontBuffer(int deviceIndex) { return deviceToBufferMapping[deviceIndex * 2]; } public unsafe void* GetBackBuffer(int deviceIndex) { return deviceToBufferMapping[deviceIndex * 2 + 1]; } public unsafe void SwapBuffers(int deviceIndex) { if (valid) { void* frontBuffer = GetFrontBuffer(deviceIndex); void* backBuffer = GetBackBuffer(deviceIndex); SetFrontBuffer(deviceIndex, backBuffer); SetBackBuffer(deviceIndex, frontBuffer); } } } public uint sizePerBuffer; public uint totalSize; public unsafe void* defaultStateBuffer; public unsafe void* noiseMaskBuffer; public unsafe void* resetMaskBuffer; private unsafe void* m_AllBuffers; internal DoubleBuffers m_PlayerStateBuffers; internal unsafe static void* s_DefaultStateBuffer; internal unsafe static void* s_NoiseMaskBuffer; internal unsafe static void* s_ResetMaskBuffer; internal static DoubleBuffers s_CurrentBuffers; public DoubleBuffers GetDoubleBuffersFor(InputUpdateType updateType) { if ((uint)(updateType - 1) <= 1u || updateType == InputUpdateType.BeforeRender || updateType == InputUpdateType.Manual) { return m_PlayerStateBuffers; } throw new ArgumentException("Unrecognized InputUpdateType: " + updateType, "updateType"); } public unsafe static void* GetFrontBufferForDevice(int deviceIndex) { return s_CurrentBuffers.GetFrontBuffer(deviceIndex); } public unsafe static void* GetBackBufferForDevice(int deviceIndex) { return s_CurrentBuffers.GetBackBuffer(deviceIndex); } public static void SwitchTo(InputStateBuffers buffers, InputUpdateType update) { s_CurrentBuffers = buffers.GetDoubleBuffersFor(update); } public unsafe void AllocateAll(InputDevice[] devices, int deviceCount) { sizePerBuffer = ComputeSizeOfSingleStateBuffer(devices, deviceCount); if (sizePerBuffer != 0) { sizePerBuffer = sizePerBuffer.AlignToMultipleOf(4u); uint num = (uint)(deviceCount * sizeof(void*) * 2); totalSize = 0u; totalSize += sizePerBuffer * 2; totalSize += num; totalSize += sizePerBuffer * 3; m_AllBuffers = UnsafeUtility.Malloc((long)totalSize, 4, (Allocator)4); UnsafeUtility.MemClear(m_AllBuffers, (long)totalSize); byte* bufferPtr = (byte*)m_AllBuffers; m_PlayerStateBuffers = SetUpDeviceToBufferMappings(deviceCount, ref bufferPtr, sizePerBuffer, num); defaultStateBuffer = bufferPtr; noiseMaskBuffer = bufferPtr + sizePerBuffer; resetMaskBuffer = bufferPtr + sizePerBuffer * 2; } } private unsafe static DoubleBuffers SetUpDeviceToBufferMappings(int deviceCount, ref byte* bufferPtr, uint sizePerBuffer, uint mappingTableSizePerBuffer) { byte* ptr = bufferPtr; byte* ptr2 = bufferPtr + sizePerBuffer; void** deviceToBufferMapping = (void**)(bufferPtr + sizePerBuffer * 2); bufferPtr += sizePerBuffer * 2 + mappingTableSizePerBuffer; DoubleBuffers result = new DoubleBuffers { deviceToBufferMapping = deviceToBufferMapping }; for (int i = 0; i < deviceCount; i++) { int deviceIndex = i; result.SetFrontBuffer(deviceIndex, ptr); result.SetBackBuffer(deviceIndex, ptr2); } return result; } public unsafe void FreeAll() { if (m_AllBuffers != null) { UnsafeUtility.Free(m_AllBuffers, (Allocator)4); m_AllBuffers = null; } m_PlayerStateBuffers = default(DoubleBuffers); s_CurrentBuffers = default(DoubleBuffers); if (s_DefaultStateBuffer == defaultStateBuffer) { s_DefaultStateBuffer = null; } defaultStateBuffer = null; if (s_NoiseMaskBuffer == noiseMaskBuffer) { s_NoiseMaskBuffer = null; } if (s_ResetMaskBuffer == resetMaskBuffer) { s_ResetMaskBuffer = null; } noiseMaskBuffer = null; resetMaskBuffer = null; totalSize = 0u; sizePerBuffer = 0u; } public unsafe void MigrateAll(InputDevice[] devices, int deviceCount, InputStateBuffers oldBuffers) { if (oldBuffers.totalSize != 0) { MigrateDoubleBuffer(m_PlayerStateBuffers, devices, deviceCount, oldBuffers.m_PlayerStateBuffers); MigrateSingleBuffer(defaultStateBuffer, devices, deviceCount, oldBuffers.defaultStateBuffer); MigrateSingleBuffer(noiseMaskBuffer, devices, deviceCount, oldBuffers.noiseMaskBuffer); MigrateSingleBuffer(resetMaskBuffer, devices, deviceCount, oldBuffers.resetMaskBuffer); } uint num = 0u; for (int i = 0; i < deviceCount; i++) { InputDevice inputDevice = devices[i]; uint byteOffset = inputDevice.m_StateBlock.byteOffset; if (byteOffset == uint.MaxValue) { inputDevice.m_StateBlock.byteOffset = 0u; if (num != 0) { inputDevice.BakeOffsetIntoStateBlockRecursive(num); } } else { uint num2 = num - byteOffset; if (num2 != 0) { inputDevice.BakeOffsetIntoStateBlockRecursive(num2); } } num = NextDeviceOffset(num, inputDevice); } } private unsafe static void MigrateDoubleBuffer(DoubleBuffers newBuffer, InputDevice[] devices, int deviceCount, DoubleBuffers oldBuffer) { if (!newBuffer.valid || !oldBuffer.valid) { return; } uint num = 0u; for (int i = 0; i < deviceCount; i++) { InputDevice inputDevice = devices[i]; if (inputDevice.m_StateBlock.byteOffset != uint.MaxValue) { int deviceIndex = inputDevice.m_DeviceIndex; int deviceIndex2 = i; uint alignedSizeInBytes = inputDevice.m_StateBlock.alignedSizeInBytes; byte* ptr = (byte*)oldBuffer.GetFrontBuffer(deviceIndex) + (int)inputDevice.m_StateBlock.byteOffset; byte* ptr2 = (byte*)oldBuffer.GetBackBuffer(deviceIndex) + (int)inputDevice.m_StateBlock.byteOffset; byte* ptr3 = (byte*)newBuffer.GetFrontBuffer(deviceIndex2) + (int)num; byte* num2 = (byte*)newBuffer.GetBackBuffer(deviceIndex2) + (int)num; UnsafeUtility.MemCpy((void*)ptr3, (void*)ptr, (long)alignedSizeInBytes); UnsafeUtility.MemCpy((void*)num2, (void*)ptr2, (long)alignedSizeInBytes); num = NextDeviceOffset(num, inputDevice); continue; } break; } } private unsafe static void MigrateSingleBuffer(void* newBuffer, InputDevice[] devices, int deviceCount, void* oldBuffer) { uint num = 0u; for (int i = 0; i < deviceCount; i++) { InputDevice inputDevice = devices[i]; if (inputDevice.m_StateBlock.byteOffset != uint.MaxValue) { uint alignedSizeInBytes = inputDevice.m_StateBlock.alignedSizeInBytes; byte* ptr = (byte*)oldBuffer + (int)inputDevice.m_StateBlock.byteOffset; UnsafeUtility.MemCpy((void*)((byte*)newBuffer + (int)num), (void*)ptr, (long)alignedSizeInBytes); num = NextDeviceOffset(num, inputDevice); continue; } break; } } private static uint ComputeSizeOfSingleStateBuffer(InputDevice[] devices, int deviceCount) { uint num = 0u; for (int i = 0; i < deviceCount; i++) { num = NextDeviceOffset(num, devices[i]); } return num; } private static uint NextDeviceOffset(uint currentOffset, InputDevice device) { uint alignedSizeInBytes = device.m_StateBlock.alignedSizeInBytes; if (alignedSizeInBytes == 0) { throw new ArgumentException($"Device '{device}' has a zero-size state buffer", "device"); } return currentOffset + alignedSizeInBytes.AlignToMultipleOf(4u); } } public class InputStateHistory : IDisposable, IEnumerable, IEnumerable, IInputStateChangeMonitor { private struct Enumerator : IEnumerator, IDisposable, IEnumerator { private readonly InputStateHistory m_History; private int m_Index; public Record Current => m_History[m_Index]; object IEnumerator.Current => Current; public Enumerator(InputStateHistory history) { m_History = history; m_Index = -1; } public bool MoveNext() { if (m_Index + 1 >= m_History.Count) { return false; } m_Index++; return true; } public void Reset() { m_Index = -1; } public void Dispose() { } } [StructLayout(LayoutKind.Explicit)] protected internal struct RecordHeader { [FieldOffset(0)] public double time; [FieldOffset(8)] public uint version; [FieldOffset(12)] public int controlIndex; [FieldOffset(12)] private unsafe fixed byte m_StateWithoutControlIndex[1]; [FieldOffset(16)] private unsafe fixed byte m_StateWithControlIndex[1]; public const int kSizeWithControlIndex = 16; public const int kSizeWithoutControlIndex = 12; public unsafe byte* statePtrWithControlIndex { get { fixed (byte* stateWithControlIndex = m_StateWithControlIndex) { return stateWithControlIndex; } } } public unsafe byte* statePtrWithoutControlIndex { get { fixed (byte* stateWithoutControlIndex = m_StateWithoutControlIndex) { return stateWithoutControlIndex; } } } } public struct Record : IEquatable { private readonly InputStateHistory m_Owner; private readonly int m_IndexPlusOne; private uint m_Version; internal unsafe RecordHeader* header => m_Owner.GetRecord(recordIndex); internal int recordIndex => m_IndexPlusOne - 1; internal uint version => m_Version; public unsafe bool valid { get { if (m_Owner != null && m_IndexPlusOne != 0) { return header->version == m_Version; } return false; } } public InputStateHistory owner => m_Owner; public int index { get { CheckValid(); return m_Owner.RecordIndexToUserIndex(recordIndex); } } public unsafe double time { get { CheckValid(); return header->time; } } public unsafe InputControl control { get { CheckValid(); ReadOnlyArray controls = m_Owner.controls; if (controls.Count == 1 && !m_Owner.m_AddNewControls) { return controls[0]; } return controls[header->controlIndex]; } } public unsafe Record next { get { CheckValid(); int num = m_Owner.RecordIndexToUserIndex(recordIndex); if (num + 1 >= m_Owner.Count) { return default(Record); } int num2 = m_Owner.UserIndexToRecordIndex(num + 1); return new Record(m_Owner, num2, m_Owner.GetRecord(num2)); } } public unsafe Record previous { get { CheckValid(); int num = m_Owner.RecordIndexToUserIndex(recordIndex); if (num - 1 < 0) { return default(Record); } int num2 = m_Owner.UserIndexToRecordIndex(num - 1); return new Record(m_Owner, num2, m_Owner.GetRecord(num2)); } } internal unsafe Record(InputStateHistory owner, int index, RecordHeader* header) { m_Owner = owner; m_IndexPlusOne = index + 1; m_Version = header->version; } public unsafe TValue ReadValue() where TValue : struct { CheckValid(); return m_Owner.ReadValue(header); } public unsafe object ReadValueAsObject() { CheckValid(); return m_Owner.ReadValueAsObject(header); } public unsafe void* GetUnsafeMemoryPtr() { CheckValid(); return GetUnsafeMemoryPtrUnchecked(); } internal unsafe void* GetUnsafeMemoryPtrUnchecked() { if (m_Owner.controls.Count == 1 && !m_Owner.m_AddNewControls) { return header->statePtrWithoutControlIndex; } return header->statePtrWithControlIndex; } public unsafe void* GetUnsafeExtraMemoryPtr() { CheckValid(); return GetUnsafeExtraMemoryPtrUnchecked(); } internal unsafe void* GetUnsafeExtraMemoryPtrUnchecked() { if (m_Owner.extraMemoryPerRecord == 0) { throw new InvalidOperationException("No extra memory has been set up for history records; set extraMemoryPerRecord"); } return (byte*)header + m_Owner.bytesPerRecord - m_Owner.extraMemoryPerRecord; } public unsafe void CopyFrom(Record record) { if (!record.valid) { throw new ArgumentException("Given history record is not valid", "record"); } CheckValid(); InputControl value = record.control; int num = m_Owner.controls.IndexOfReference(value); if (num == -1) { if (!m_Owner.m_AddNewControls) { throw new InvalidOperationException($"Control '{record.control}' is not tracked by target history"); } num = ArrayHelpers.AppendWithCapacity(ref m_Owner.m_Controls, ref m_Owner.m_ControlCount, value); } int stateSizeInBytes = m_Owner.m_StateSizeInBytes; if (stateSizeInBytes != record.m_Owner.m_StateSizeInBytes) { throw new InvalidOperationException($"Cannot copy record from owner with state size '{record.m_Owner.m_StateSizeInBytes}' to owner with state size '{stateSizeInBytes}'"); } RecordHeader* ptr = header; RecordHeader* ptr2 = record.header; UnsafeUtility.MemCpy((void*)ptr, (void*)ptr2, 12L); ptr->version = ++m_Owner.m_CurrentVersion; m_Version = ptr->version; byte* ptr3 = ptr->statePtrWithoutControlIndex; if (m_Owner.controls.Count > 1 || m_Owner.m_AddNewControls) { ptr->controlIndex = num; ptr3 = ptr->statePtrWithControlIndex; } byte* ptr4 = ((record.m_Owner.m_ControlCount > 1 || record.m_Owner.m_AddNewControls) ? ptr2->statePtrWithControlIndex : ptr2->statePtrWithoutControlIndex); UnsafeUtility.MemCpy((void*)ptr3, (void*)ptr4, (long)stateSizeInBytes); int extraMemoryPerRecord = m_Owner.m_ExtraMemoryPerRecord; if (extraMemoryPerRecord > 0 && extraMemoryPerRecord == record.m_Owner.m_ExtraMemoryPerRecord) { UnsafeUtility.MemCpy(GetUnsafeExtraMemoryPtr(), record.GetUnsafeExtraMemoryPtr(), (long)extraMemoryPerRecord); } m_Owner.onRecordAdded?.Invoke(this); } internal unsafe void CheckValid() { if (m_Owner == null || m_IndexPlusOne == 0) { throw new InvalidOperationException("Value not initialized"); } if (header->version != m_Version) { throw new InvalidOperationException("Record is no longer valid"); } } public bool Equals(Record other) { if (m_Owner == other.m_Owner && m_IndexPlusOne == other.m_IndexPlusOne) { return m_Version == other.m_Version; } return false; } public override bool Equals(object obj) { if (obj is Record other) { return Equals(other); } return false; } public override int GetHashCode() { return (((((m_Owner != null) ? m_Owner.GetHashCode() : 0) * 397) ^ m_IndexPlusOne) * 397) ^ (int)m_Version; } public override string ToString() { if (!valid) { return ""; } return $"{{ control={control} value={ReadValueAsObject()} time={time} }}"; } } private const int kDefaultHistorySize = 128; internal InputControl[] m_Controls; internal int m_ControlCount; private NativeArray m_RecordBuffer; private int m_StateSizeInBytes; private int m_RecordCount; private int m_HistoryDepth = 128; private int m_ExtraMemoryPerRecord; internal int m_HeadIndex; internal uint m_CurrentVersion; private InputUpdateType? m_UpdateMask; internal readonly bool m_AddNewControls; public int Count => m_RecordCount; public uint version => m_CurrentVersion; public int historyDepth { get { return m_HistoryDepth; } set { if (value < 0) { throw new ArgumentException("History depth cannot be negative", "value"); } if (m_RecordBuffer.IsCreated) { throw new NotImplementedException(); } m_HistoryDepth = value; } } public int extraMemoryPerRecord { get { return m_ExtraMemoryPerRecord; } set { if (value < 0) { throw new ArgumentException("Memory size cannot be negative", "value"); } if (m_RecordBuffer.IsCreated) { throw new NotImplementedException(); } m_ExtraMemoryPerRecord = value; } } public InputUpdateType updateMask { get { return m_UpdateMask ?? (InputSystem.s_Manager.updateMask & ~InputUpdateType.Editor); } set { if (value == InputUpdateType.None) { throw new ArgumentException("'InputUpdateType.None' is not a valid update mask", "value"); } m_UpdateMask = value; } } public ReadOnlyArray controls => new ReadOnlyArray(m_Controls, 0, m_ControlCount); public unsafe Record this[int index] { get { if (index < 0 || index >= m_RecordCount) { throw new ArgumentOutOfRangeException($"Index {index} is out of range for history with {m_RecordCount} entries", "index"); } int index2 = UserIndexToRecordIndex(index); return new Record(this, index2, GetRecord(index2)); } set { if (index < 0 || index >= m_RecordCount) { throw new ArgumentOutOfRangeException($"Index {index} is out of range for history with {m_RecordCount} entries", "index"); } int index2 = UserIndexToRecordIndex(index); new Record(this, index2, GetRecord(index2)).CopyFrom(value); } } public Action onRecordAdded { get; set; } public Func onShouldRecordStateChange { get; set; } internal int bytesPerRecord => (m_StateSizeInBytes + m_ExtraMemoryPerRecord + ((m_ControlCount == 1 && !m_AddNewControls) ? 12 : 16)).AlignToMultipleOf(4); public InputStateHistory(int maxStateSizeInBytes) { if (maxStateSizeInBytes <= 0) { throw new ArgumentException("State size must be >= 0", "maxStateSizeInBytes"); } m_AddNewControls = true; m_StateSizeInBytes = maxStateSizeInBytes.AlignToMultipleOf(4); } public InputStateHistory(string path) { using InputControlList inputControlList = InputSystem.FindControls(path); m_Controls = inputControlList.ToArray(); m_ControlCount = m_Controls.Length; } public InputStateHistory(InputControl control) { if (control == null) { throw new ArgumentNullException("control"); } m_Controls = new InputControl[1] { control }; m_ControlCount = 1; } public InputStateHistory(IEnumerable controls) { if (controls != null) { m_Controls = controls.ToArray(); m_ControlCount = m_Controls.Length; } } ~InputStateHistory() { Dispose(); } public void Clear() { m_HeadIndex = 0; m_RecordCount = 0; m_CurrentVersion++; } public unsafe Record AddRecord(Record record) { int index; RecordHeader* header = AllocateRecord(out index); Record result = new Record(this, index, header); result.CopyFrom(record); return result; } public void StartRecording() { foreach (InputControl control in controls) { InputState.AddChangeMonitor(control, this, -1L); } } public void StopRecording() { foreach (InputControl control in controls) { InputState.RemoveChangeMonitor(control, this, -1L); } } public unsafe Record RecordStateChange(InputControl control, InputEventPtr eventPtr) { if (eventPtr.IsA()) { throw new NotImplementedException(); } if (!eventPtr.IsA()) { throw new ArgumentException($"Event must be a state event but is '{eventPtr}' instead", "eventPtr"); } byte* statePtr = (byte*)StateEvent.From(eventPtr)->state - control.device.stateBlock.byteOffset; return RecordStateChange(control, statePtr, eventPtr.time); } public unsafe Record RecordStateChange(InputControl control, void* statePtr, double time) { int num = m_Controls.IndexOfReference(control, m_ControlCount); if (num == -1) { if (!m_AddNewControls) { throw new ArgumentException($"Control '{control}' is not part of InputStateHistory", "control"); } if (control.stateBlock.alignedSizeInBytes > m_StateSizeInBytes) { throw new InvalidOperationException($"Cannot add control '{control}' with state larger than {m_StateSizeInBytes} bytes"); } num = ArrayHelpers.AppendWithCapacity(ref m_Controls, ref m_ControlCount, control); } int index; RecordHeader* ptr = AllocateRecord(out index); ptr->time = time; ptr->version = ++m_CurrentVersion; byte* ptr2 = ptr->statePtrWithoutControlIndex; if (m_ControlCount > 1 || m_AddNewControls) { ptr->controlIndex = num; ptr2 = ptr->statePtrWithControlIndex; } uint alignedSizeInBytes = control.stateBlock.alignedSizeInBytes; uint byteOffset = control.stateBlock.byteOffset; UnsafeUtility.MemCpy((void*)ptr2, (void*)((byte*)statePtr + byteOffset), (long)alignedSizeInBytes); Record record = new Record(this, index, ptr); onRecordAdded?.Invoke(record); return record; } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { StopRecording(); Destroy(); GC.SuppressFinalize(this); } protected void Destroy() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (m_RecordBuffer.IsCreated) { m_RecordBuffer.Dispose(); m_RecordBuffer = default(NativeArray); } } private void Allocate() { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (!m_AddNewControls) { m_StateSizeInBytes = 0; foreach (InputControl control in controls) { m_StateSizeInBytes = (int)Math.Max((uint)m_StateSizeInBytes, control.stateBlock.alignedSizeInBytes); } } int num = bytesPerRecord * m_HistoryDepth; m_RecordBuffer = new NativeArray(num, (Allocator)4, (NativeArrayOptions)0); } protected internal int RecordIndexToUserIndex(int index) { if (index < m_HeadIndex) { return m_HistoryDepth - m_HeadIndex + index; } return index - m_HeadIndex; } protected internal int UserIndexToRecordIndex(int index) { return (m_HeadIndex + index) % m_HistoryDepth; } protected internal unsafe RecordHeader* GetRecord(int index) { if (!m_RecordBuffer.IsCreated) { throw new InvalidOperationException("History buffer has been disposed"); } if (index < 0 || index >= m_HistoryDepth) { throw new ArgumentOutOfRangeException("index"); } return GetRecordUnchecked(index); } internal unsafe RecordHeader* GetRecordUnchecked(int index) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return (RecordHeader*)((byte*)NativeArrayUnsafeUtility.GetUnsafePtr(m_RecordBuffer) + index * bytesPerRecord); } protected internal unsafe RecordHeader* AllocateRecord(out int index) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (!m_RecordBuffer.IsCreated) { Allocate(); } index = (m_HeadIndex + m_RecordCount) % m_HistoryDepth; if (m_RecordCount == m_HistoryDepth) { m_HeadIndex = (m_HeadIndex + 1) % m_HistoryDepth; } else { m_RecordCount++; } return (RecordHeader*)((byte*)NativeArrayUnsafeUtility.GetUnsafePtr(m_RecordBuffer) + bytesPerRecord * index); } protected unsafe TValue ReadValue(RecordHeader* data) where TValue : struct { int num; InputControl inputControl; if (m_ControlCount == 1) { num = ((!m_AddNewControls) ? 1 : 0); if (num != 0) { inputControl = controls[0]; goto IL_003d; } } else { num = 0; } inputControl = controls[data->controlIndex]; goto IL_003d; IL_003d: InputControl inputControl2 = inputControl; if (!(inputControl2 is InputControl inputControl3)) { throw new InvalidOperationException($"Cannot read value of type '{typeof(TValue).GetNiceTypeName()}' from control '{inputControl2}' with value type '{inputControl2.valueType.GetNiceTypeName()}'"); } byte* ptr = ((num != 0) ? data->statePtrWithoutControlIndex : data->statePtrWithControlIndex); ptr -= inputControl2.stateBlock.byteOffset; return inputControl3.ReadValueFromState(ptr); } protected unsafe object ReadValueAsObject(RecordHeader* data) { int num; InputControl inputControl; if (m_ControlCount == 1) { num = ((!m_AddNewControls) ? 1 : 0); if (num != 0) { inputControl = controls[0]; goto IL_003d; } } else { num = 0; } inputControl = controls[data->controlIndex]; goto IL_003d; IL_003d: InputControl inputControl2 = inputControl; byte* ptr = ((num != 0) ? data->statePtrWithoutControlIndex : data->statePtrWithControlIndex); ptr -= inputControl2.stateBlock.byteOffset; return inputControl2.ReadValueFromStateAsObject(ptr); } unsafe void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time, InputEventPtr eventPtr, long monitorIndex) { InputUpdateType currentUpdateType = InputState.currentUpdateType; InputUpdateType inputUpdateType = updateMask; if ((currentUpdateType & inputUpdateType) != InputUpdateType.None && (onShouldRecordStateChange == null || onShouldRecordStateChange(control, time, eventPtr))) { RecordStateChange(control, control.currentStatePtr, time); } } void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time, long monitorIndex, int timerIndex) { } } public class InputStateHistory : InputStateHistory, IReadOnlyList.Record>, IReadOnlyCollection.Record>, IEnumerable.Record>, IEnumerable where TValue : struct { private struct Enumerator : IEnumerator, IDisposable, IEnumerator { private readonly InputStateHistory m_History; private int m_Index; public Record Current => m_History[m_Index]; object IEnumerator.Current => Current; public Enumerator(InputStateHistory history) { m_History = history; m_Index = -1; } public bool MoveNext() { if (m_Index + 1 >= m_History.Count) { return false; } m_Index++; return true; } public void Reset() { m_Index = -1; } public void Dispose() { } } public new struct Record : IEquatable { private readonly InputStateHistory m_Owner; private readonly int m_IndexPlusOne; private uint m_Version; internal unsafe RecordHeader* header => m_Owner.GetRecord(recordIndex); internal int recordIndex => m_IndexPlusOne - 1; public unsafe bool valid { get { if (m_Owner != null && m_IndexPlusOne != 0) { return header->version == m_Version; } return false; } } public InputStateHistory owner => m_Owner; public int index { get { CheckValid(); return m_Owner.RecordIndexToUserIndex(recordIndex); } } public unsafe double time { get { CheckValid(); return header->time; } } public unsafe InputControl control { get { CheckValid(); ReadOnlyArray controls = m_Owner.controls; if (controls.Count == 1 && !m_Owner.m_AddNewControls) { return (InputControl)controls[0]; } return (InputControl)controls[header->controlIndex]; } } public unsafe Record next { get { CheckValid(); int num = m_Owner.RecordIndexToUserIndex(recordIndex); if (num + 1 >= m_Owner.Count) { return default(Record); } int num2 = m_Owner.UserIndexToRecordIndex(num + 1); return new Record(m_Owner, num2, m_Owner.GetRecord(num2)); } } public unsafe Record previous { get { CheckValid(); int num = m_Owner.RecordIndexToUserIndex(recordIndex); if (num - 1 < 0) { return default(Record); } int num2 = m_Owner.UserIndexToRecordIndex(num - 1); return new Record(m_Owner, num2, m_Owner.GetRecord(num2)); } } internal unsafe Record(InputStateHistory owner, int index, RecordHeader* header) { m_Owner = owner; m_IndexPlusOne = index + 1; m_Version = header->version; } internal Record(InputStateHistory owner, int index) { m_Owner = owner; m_IndexPlusOne = index + 1; m_Version = 0u; } public unsafe TValue ReadValue() { CheckValid(); return m_Owner.ReadValue(header); } public unsafe void* GetUnsafeMemoryPtr() { CheckValid(); return GetUnsafeMemoryPtrUnchecked(); } internal unsafe void* GetUnsafeMemoryPtrUnchecked() { if (m_Owner.controls.Count == 1 && !m_Owner.m_AddNewControls) { return header->statePtrWithoutControlIndex; } return header->statePtrWithControlIndex; } public unsafe void* GetUnsafeExtraMemoryPtr() { CheckValid(); return GetUnsafeExtraMemoryPtrUnchecked(); } internal unsafe void* GetUnsafeExtraMemoryPtrUnchecked() { if (m_Owner.extraMemoryPerRecord == 0) { throw new InvalidOperationException("No extra memory has been set up for history records; set extraMemoryPerRecord"); } return (byte*)header + m_Owner.bytesPerRecord - m_Owner.extraMemoryPerRecord; } public unsafe void CopyFrom(Record record) { CheckValid(); if (!record.valid) { throw new ArgumentException("Given history record is not valid", "record"); } InputStateHistory.Record record2 = new InputStateHistory.Record(m_Owner, recordIndex, header); record2.CopyFrom(new InputStateHistory.Record(record.m_Owner, record.recordIndex, record.header)); m_Version = record2.version; } private unsafe void CheckValid() { if (m_Owner == null || m_IndexPlusOne == 0) { throw new InvalidOperationException("Value not initialized"); } if (header->version != m_Version) { throw new InvalidOperationException("Record is no longer valid"); } } public bool Equals(Record other) { if (m_Owner == other.m_Owner && m_IndexPlusOne == other.m_IndexPlusOne) { return m_Version == other.m_Version; } return false; } public override bool Equals(object obj) { if (obj is Record other) { return Equals(other); } return false; } public override int GetHashCode() { return (((((m_Owner != null) ? m_Owner.GetHashCode() : 0) * 397) ^ m_IndexPlusOne) * 397) ^ (int)m_Version; } public override string ToString() { if (!valid) { return ""; } return $"{{ control={control} value={ReadValue()} time={time} }}"; } } public new unsafe Record this[int index] { get { if (index < 0 || index >= base.Count) { throw new ArgumentOutOfRangeException($"Index {index} is out of range for history with {base.Count} entries", "index"); } int index2 = UserIndexToRecordIndex(index); return new Record(this, index2, GetRecord(index2)); } set { if (index < 0 || index >= base.Count) { throw new ArgumentOutOfRangeException($"Index {index} is out of range for history with {base.Count} entries", "index"); } int index2 = UserIndexToRecordIndex(index); new Record(this, index2, GetRecord(index2)).CopyFrom(value); } } public InputStateHistory(int? maxStateSizeInBytes = null) : base(maxStateSizeInBytes ?? UnsafeUtility.SizeOf()) { if (maxStateSizeInBytes < UnsafeUtility.SizeOf()) { throw new ArgumentException("Max state size cannot be smaller than sizeof(TValue)", "maxStateSizeInBytes"); } } public InputStateHistory(InputControl control) : base(control) { } public InputStateHistory(string path) : base(path) { foreach (InputControl control in base.controls) { if (!typeof(TValue).IsAssignableFrom(control.valueType)) { throw new ArgumentException($"Control '{control}' matched by '{path}' has value type '{control.valueType.GetNiceTypeName()}' which is incompatible with '{typeof(TValue).GetNiceTypeName()}'"); } } } ~InputStateHistory() { Destroy(); } public unsafe Record AddRecord(Record record) { int index; RecordHeader* header = AllocateRecord(out index); Record result = new Record(this, index, header); result.CopyFrom(record); return result; } public unsafe Record RecordStateChange(InputControl control, TValue value, double time = -1.0) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) InputEventPtr eventPtr; NativeArray val = StateEvent.From(control.device, out eventPtr, (Allocator)2); try { byte* statePtr = (byte*)StateEvent.From(eventPtr)->state - control.device.stateBlock.byteOffset; control.WriteValueIntoState(value, statePtr); if (time >= 0.0) { eventPtr.time = time; } InputStateHistory.Record record = RecordStateChange(control, eventPtr); return new Record(this, record.recordIndex, record.header); } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } public new IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal class SelectObservable : IObservable { private class Select : IObserver { private SelectObservable m_Observable; private readonly IObserver m_Observer; public Select(SelectObservable observable, IObserver observer) { m_Observable = observable; m_Observer = observer; } public void OnCompleted() { } public void OnError(Exception error) { Debug.LogException(error); } public void OnNext(TSource evt) { TResult value = m_Observable.m_Filter(evt); m_Observer.OnNext(value); } } private readonly IObservable m_Source; private readonly Func m_Filter; public SelectObservable(IObservable source, Func filter) { m_Source = source; m_Filter = filter; } public IDisposable Subscribe(IObserver observer) { return m_Source.Subscribe(new Select(this, observer)); } } } namespace UnityEngine.InputSystem.Processors { public class AxisDeadzoneProcessor : InputProcessor { public float min; public float max; private float minOrDefault { get { if (min != 0f) { return min; } return InputSystem.settings.defaultDeadzoneMin; } } private float maxOrDefault { get { if (max != 0f) { return max; } return InputSystem.settings.defaultDeadzoneMax; } } public override float Process(float value, InputControl control = null) { float num = minOrDefault; float num2 = maxOrDefault; float num3 = Mathf.Abs(value); if (num3 < num) { return 0f; } if (num3 > num2) { return Mathf.Sign(value); } return Mathf.Sign(value) * ((num3 - num) / (num2 - num)); } public override string ToString() { return $"AxisDeadzone(min={minOrDefault},max={maxOrDefault})"; } } public class ClampProcessor : InputProcessor { public float min; public float max; public override float Process(float value, InputControl control) { return Mathf.Clamp(value, min, max); } public override string ToString() { return $"Clamp(min={min},max={max})"; } } [DesignTimeVisible(false)] internal class CompensateDirectionProcessor : InputProcessor { public override CachingPolicy cachingPolicy => CachingPolicy.EvaluateOnEveryRead; public override Vector3 Process(Vector3 value, InputControl control) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected I4, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) if (!InputSystem.settings.compensateForScreenOrientation) { return value; } Quaternion val = Quaternion.identity; ScreenOrientation screenOrientation = InputRuntime.s_Instance.screenOrientation; switch (screenOrientation - 2) { case 0: val = Quaternion.Euler(0f, 0f, 180f); break; case 1: val = Quaternion.Euler(0f, 0f, 90f); break; case 2: val = Quaternion.Euler(0f, 0f, 270f); break; } return val * value; } public override string ToString() { return "CompensateDirection()"; } } [DesignTimeVisible(false)] internal class CompensateRotationProcessor : InputProcessor { public override CachingPolicy cachingPolicy => CachingPolicy.EvaluateOnEveryRead; public override Quaternion Process(Quaternion value, InputControl control) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected I4, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) if (!InputSystem.settings.compensateForScreenOrientation) { return value; } Quaternion identity = Quaternion.identity; ScreenOrientation screenOrientation = InputRuntime.s_Instance.screenOrientation; switch (screenOrientation - 2) { case 0: ((Quaternion)(ref identity))..ctor(0f, 0f, 1f, 0f); break; case 1: ((Quaternion)(ref identity))..ctor(0f, 0f, 0.70710677f, -0.70710677f); break; case 2: ((Quaternion)(ref identity))..ctor(0f, 0f, -0.70710677f, -0.70710677f); break; } return value * identity; } public override string ToString() { return "CompensateRotation()"; } } public class InvertProcessor : InputProcessor { public override float Process(float value, InputControl control) { return value * -1f; } public override string ToString() { return "Invert()"; } } public class InvertVector2Processor : InputProcessor { public bool invertX = true; public bool invertY = true; public override Vector2 Process(Vector2 value, InputControl control) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (invertX) { value.x *= -1f; } if (invertY) { value.y *= -1f; } return value; } public override string ToString() { return $"InvertVector2(invertX={invertX},invertY={invertY})"; } } public class InvertVector3Processor : InputProcessor { public bool invertX = true; public bool invertY = true; public bool invertZ = true; public override Vector3 Process(Vector3 value, InputControl control) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (invertX) { value.x *= -1f; } if (invertY) { value.y *= -1f; } if (invertZ) { value.z *= -1f; } return value; } public override string ToString() { return $"InvertVector3(invertX={invertX},invertY={invertY},invertZ={invertZ})"; } } public class NormalizeProcessor : InputProcessor { public float min; public float max; public float zero; public override float Process(float value, InputControl control) { return Normalize(value, min, max, zero); } public static float Normalize(float value, float min, float max, float zero) { if (zero < min) { zero = min; } if (Mathf.Approximately(value, min)) { if (min < zero) { return -1f; } return 0f; } float num = (value - min) / (max - min); if (min < zero) { return 2f * num - 1f; } return num; } internal static float Denormalize(float value, float min, float max, float zero) { if (zero < min) { zero = min; } if (min < zero) { if (value < 0f) { return min + (zero - min) * (value * -1f); } return zero + (max - zero) * value; } return min + (max - min) * value; } public override string ToString() { return $"Normalize(min={min},max={max},zero={zero})"; } } public class NormalizeVector2Processor : InputProcessor { public override Vector2 Process(Vector2 value, InputControl control) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return ((Vector2)(ref value)).normalized; } public override string ToString() { return "NormalizeVector2()"; } } public class NormalizeVector3Processor : InputProcessor { public override Vector3 Process(Vector3 value, InputControl control) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return ((Vector3)(ref value)).normalized; } public override string ToString() { return "NormalizeVector3()"; } } public class ScaleProcessor : InputProcessor { [Tooltip("Scale factor to multiply incoming float values by.")] public float factor = 1f; public override float Process(float value, InputControl control) { return value * factor; } public override string ToString() { return $"Scale(factor={factor})"; } } public class ScaleVector2Processor : InputProcessor { [Tooltip("Scale factor to multiply the incoming Vector2's X component by.")] public float x = 1f; [Tooltip("Scale factor to multiply the incoming Vector2's Y component by.")] public float y = 1f; public override Vector2 Process(Vector2 value, InputControl control) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) return new Vector2(value.x * x, value.y * y); } public override string ToString() { return $"ScaleVector2(x={x},y={y})"; } } public class ScaleVector3Processor : InputProcessor { [Tooltip("Scale factor to multiply the incoming Vector3's X component by.")] public float x = 1f; [Tooltip("Scale factor to multiply the incoming Vector3's Y component by.")] public float y = 1f; [Tooltip("Scale factor to multiply the incoming Vector3's Z component by.")] public float z = 1f; public override Vector3 Process(Vector3 value, InputControl control) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) return new Vector3(value.x * x, value.y * y, value.z * z); } public override string ToString() { return $"ScaleVector3(x={x},y={y},z={z})"; } } public class StickDeadzoneProcessor : InputProcessor { public float min; public float max; private float minOrDefault { get { if (min != 0f) { return min; } return InputSystem.settings.defaultDeadzoneMin; } } private float maxOrDefault { get { if (max != 0f) { return max; } return InputSystem.settings.defaultDeadzoneMax; } } public override Vector2 Process(Vector2 value, InputControl control = null) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) float magnitude = ((Vector2)(ref value)).magnitude; float deadZoneAdjustedValue = GetDeadZoneAdjustedValue(magnitude); value = ((deadZoneAdjustedValue != 0f) ? (value * (deadZoneAdjustedValue / magnitude)) : Vector2.zero); return value; } private float GetDeadZoneAdjustedValue(float value) { float num = minOrDefault; float num2 = maxOrDefault; float num3 = Mathf.Abs(value); if (num3 < num) { return 0f; } if (num3 > num2) { return Mathf.Sign(value); } return Mathf.Sign(value) * ((num3 - num) / (num2 - num)); } public override string ToString() { return $"StickDeadzone(min={minOrDefault},max={maxOrDefault})"; } } } namespace UnityEngine.InputSystem.Layouts { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] public sealed class InputControlAttribute : PropertyAttribute { public string layout { get; set; } public string variants { get; set; } public string name { get; set; } public string format { get; set; } public string usage { get; set; } public string[] usages { get; set; } public string parameters { get; set; } public string processors { get; set; } public string alias { get; set; } public string[] aliases { get; set; } public string useStateFrom { get; set; } public uint bit { get; set; } = uint.MaxValue; public uint offset { get; set; } = uint.MaxValue; public uint sizeInBits { get; set; } public int arraySize { get; set; } public string displayName { get; set; } public string shortDisplayName { get; set; } public bool noisy { get; set; } public bool synthetic { get; set; } public bool dontReset { get; set; } public object defaultState { get; set; } public object minValue { get; set; } public object maxValue { get; set; } } public delegate string InputDeviceFindControlLayoutDelegate(ref InputDeviceDescription description, string matchedLayout, InputDeviceExecuteCommandDelegate executeDeviceCommand); public class InputControlLayout { public struct ControlItem { [Flags] private enum Flags { isModifyingExistingControl = 1, IsNoisy = 2, IsSynthetic = 4, IsFirstDefinedInThisLayout = 8, DontReset = 0x10 } public InternedString name { get; internal set; } public InternedString layout { get; internal set; } public InternedString variants { get; internal set; } public string useStateFrom { get; internal set; } public string displayName { get; internal set; } public string shortDisplayName { get; internal set; } public ReadOnlyArray usages { get; internal set; } public ReadOnlyArray aliases { get; internal set; } public ReadOnlyArray parameters { get; internal set; } public ReadOnlyArray processors { get; internal set; } public uint offset { get; internal set; } public uint bit { get; internal set; } public uint sizeInBits { get; internal set; } public FourCC format { get; internal set; } private Flags flags { get; set; } public int arraySize { get; internal set; } public PrimitiveValue defaultState { get; internal set; } public PrimitiveValue minValue { get; internal set; } public PrimitiveValue maxValue { get; internal set; } public bool isModifyingExistingControl { get { return (flags & Flags.isModifyingExistingControl) == Flags.isModifyingExistingControl; } internal set { if (value) { flags |= Flags.isModifyingExistingControl; } else { flags &= ~Flags.isModifyingExistingControl; } } } public bool isNoisy { get { return (flags & Flags.IsNoisy) == Flags.IsNoisy; } internal set { if (value) { flags |= Flags.IsNoisy; } else { flags &= ~Flags.IsNoisy; } } } public bool isSynthetic { get { return (flags & Flags.IsSynthetic) == Flags.IsSynthetic; } internal set { if (value) { flags |= Flags.IsSynthetic; } else { flags &= ~Flags.IsSynthetic; } } } public bool dontReset { get { return (flags & Flags.DontReset) == Flags.DontReset; } internal set { if (value) { flags |= Flags.DontReset; } else { flags &= ~Flags.DontReset; } } } public bool isFirstDefinedInThisLayout { get { return (flags & Flags.IsFirstDefinedInThisLayout) != 0; } internal set { if (value) { flags |= Flags.IsFirstDefinedInThisLayout; } else { flags &= ~Flags.IsFirstDefinedInThisLayout; } } } public bool isArray => arraySize != 0; public ControlItem Merge(ControlItem other) { ControlItem result = new ControlItem { name = name, isModifyingExistingControl = isModifyingExistingControl, displayName = (string.IsNullOrEmpty(displayName) ? other.displayName : displayName), shortDisplayName = (string.IsNullOrEmpty(shortDisplayName) ? other.shortDisplayName : shortDisplayName), layout = (layout.IsEmpty() ? other.layout : layout), variants = (variants.IsEmpty() ? other.variants : variants), useStateFrom = (useStateFrom ?? other.useStateFrom), arraySize = ((!isArray) ? other.arraySize : arraySize), isNoisy = (isNoisy || other.isNoisy), dontReset = (dontReset || other.dontReset), isSynthetic = (isSynthetic || other.isSynthetic), isFirstDefinedInThisLayout = false }; if (offset != uint.MaxValue) { result.offset = offset; } else { result.offset = other.offset; } if (bit != uint.MaxValue) { result.bit = bit; } else { result.bit = other.bit; } if (format != 0) { result.format = format; } else { result.format = other.format; } if (sizeInBits != 0) { result.sizeInBits = sizeInBits; } else { result.sizeInBits = other.sizeInBits; } if (aliases.Count > 0) { result.aliases = aliases; } else { result.aliases = other.aliases; } if (usages.Count > 0) { result.usages = usages; } else { result.usages = other.usages; } if (parameters.Count == 0) { result.parameters = other.parameters; } else { result.parameters = parameters; } if (processors.Count == 0) { result.processors = other.processors; } else { result.processors = processors; } if (!string.IsNullOrEmpty(displayName)) { result.displayName = displayName; } else { result.displayName = other.displayName; } if (!defaultState.isEmpty) { result.defaultState = defaultState; } else { result.defaultState = other.defaultState; } if (!minValue.isEmpty) { result.minValue = minValue; } else { result.minValue = other.minValue; } if (!maxValue.isEmpty) { result.maxValue = maxValue; } else { result.maxValue = other.maxValue; } return result; } } public class Builder { public struct ControlBuilder { internal Builder builder; internal int index; public ControlBuilder WithDisplayName(string displayName) { builder.m_Controls[index].displayName = displayName; return this; } public ControlBuilder WithLayout(string layout) { if (string.IsNullOrEmpty(layout)) { throw new ArgumentException("Layout name cannot be null or empty", "layout"); } builder.m_Controls[index].layout = new InternedString(layout); return this; } public ControlBuilder WithFormat(FourCC format) { builder.m_Controls[index].format = format; return this; } public ControlBuilder WithFormat(string format) { return WithFormat(new FourCC(format)); } public ControlBuilder WithByteOffset(uint offset) { builder.m_Controls[index].offset = offset; return this; } public ControlBuilder WithBitOffset(uint bit) { builder.m_Controls[index].bit = bit; return this; } public ControlBuilder IsSynthetic(bool value) { builder.m_Controls[index].isSynthetic = value; return this; } public ControlBuilder IsNoisy(bool value) { builder.m_Controls[index].isNoisy = value; return this; } public ControlBuilder DontReset(bool value) { builder.m_Controls[index].dontReset = value; return this; } public ControlBuilder WithSizeInBits(uint sizeInBits) { builder.m_Controls[index].sizeInBits = sizeInBits; return this; } public ControlBuilder WithRange(float minValue, float maxValue) { builder.m_Controls[index].minValue = minValue; builder.m_Controls[index].maxValue = maxValue; return this; } public ControlBuilder WithUsages(params InternedString[] usages) { if (usages == null || usages.Length == 0) { return this; } for (int i = 0; i < usages.Length; i++) { if (usages[i].IsEmpty()) { throw new ArgumentException($"Empty usage entry at index {i} for control '{builder.m_Controls[index].name}' in layout '{builder.name}'", "usages"); } } builder.m_Controls[index].usages = new ReadOnlyArray(usages); return this; } public ControlBuilder WithUsages(IEnumerable usages) { InternedString[] usages2 = usages.Select((string x) => new InternedString(x)).ToArray(); return WithUsages(usages2); } public ControlBuilder WithUsages(params string[] usages) { return WithUsages((IEnumerable)usages); } public ControlBuilder WithParameters(string parameters) { if (string.IsNullOrEmpty(parameters)) { return this; } NamedValue[] array = NamedValue.ParseMultiple(parameters); builder.m_Controls[index].parameters = new ReadOnlyArray(array); return this; } public ControlBuilder WithProcessors(string processors) { if (string.IsNullOrEmpty(processors)) { return this; } NameAndParameters[] array = NameAndParameters.ParseMultiple(processors).ToArray(); builder.m_Controls[index].processors = new ReadOnlyArray(array); return this; } public ControlBuilder WithDefaultState(PrimitiveValue value) { builder.m_Controls[index].defaultState = value; return this; } public ControlBuilder UsingStateFrom(string path) { if (string.IsNullOrEmpty(path)) { return this; } builder.m_Controls[index].useStateFrom = path; return this; } public ControlBuilder AsArrayOfControlsWithSize(int arraySize) { builder.m_Controls[index].arraySize = arraySize; return this; } } private string m_ExtendsLayout; private int m_ControlCount; private ControlItem[] m_Controls; public string name { get; set; } public string displayName { get; set; } public Type type { get; set; } public FourCC stateFormat { get; set; } public int stateSizeInBytes { get; set; } public string extendsLayout { get { return m_ExtendsLayout; } set { if (!string.IsNullOrEmpty(value)) { m_ExtendsLayout = value; } else { m_ExtendsLayout = null; } } } public bool? updateBeforeRender { get; set; } public ReadOnlyArray controls => new ReadOnlyArray(m_Controls, 0, m_ControlCount); public ControlBuilder AddControl(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(name); } int index = ArrayHelpers.AppendWithCapacity(ref m_Controls, ref m_ControlCount, new ControlItem { name = new InternedString(name), isModifyingExistingControl = (name.IndexOf('/') != -1), offset = uint.MaxValue, bit = uint.MaxValue }); return new ControlBuilder { builder = this, index = index }; } public Builder WithName(string name) { this.name = name; return this; } public Builder WithDisplayName(string displayName) { this.displayName = displayName; return this; } public Builder WithType() where T : InputControl { type = typeof(T); return this; } public Builder WithFormat(FourCC format) { stateFormat = format; return this; } public Builder WithFormat(string format) { return WithFormat(new FourCC(format)); } public Builder WithSizeInBytes(int sizeInBytes) { stateSizeInBytes = sizeInBytes; return this; } public Builder Extend(string baseLayoutName) { extendsLayout = baseLayoutName; return this; } public InputControlLayout Build() { ControlItem[] destinationArray = null; if (m_ControlCount > 0) { destinationArray = new ControlItem[m_ControlCount]; Array.Copy(m_Controls, destinationArray, m_ControlCount); } return new InputControlLayout(new InternedString(name), (type == null && string.IsNullOrEmpty(extendsLayout)) ? typeof(InputDevice) : type) { m_DisplayName = displayName, m_StateFormat = stateFormat, m_StateSizeInBytes = stateSizeInBytes, m_BaseLayouts = ((!string.IsNullOrEmpty(extendsLayout)) ? new InlinedArray(new InternedString(extendsLayout)) : default(InlinedArray)), m_Controls = destinationArray, m_UpdateBeforeRender = updateBeforeRender }; } } [Flags] private enum Flags { IsGenericTypeOfDevice = 1, HideInUI = 2, IsOverride = 4, CanRunInBackground = 8, CanRunInBackgroundIsSet = 0x10, IsNoisy = 0x20 } [Serializable] internal struct LayoutJsonNameAndDescriptorOnly { public string name; public string extend; public string[] extendMultiple; public InputDeviceMatcher.MatcherJson device; } [Serializable] private struct LayoutJson { public string name; public string extend; public string[] extendMultiple; public string format; public string beforeRender; public string runInBackground; public string[] commonUsages; public string displayName; public string description; public string type; public string variant; public bool isGenericTypeOfDevice; public bool hideInUI; public ControlItemJson[] controls; public InputControlLayout ToLayout() { Type type = null; if (!string.IsNullOrEmpty(this.type)) { type = Type.GetType(this.type, throwOnError: false); if (type == null) { Debug.Log((object)("Cannot find type '" + this.type + "' used by layout '" + name + "'; falling back to using InputDevice")); type = typeof(InputDevice); } else if (!typeof(InputControl).IsAssignableFrom(type)) { throw new InvalidOperationException("'" + this.type + "' used by layout '" + name + "' is not an InputControl"); } } else if (string.IsNullOrEmpty(extend)) { type = typeof(InputDevice); } InputControlLayout inputControlLayout = new InputControlLayout(name, type) { m_DisplayName = displayName, m_Description = description, isGenericTypeOfDevice = isGenericTypeOfDevice, hideInUI = hideInUI, m_Variants = new InternedString(variant), m_CommonUsages = ArrayHelpers.Select(commonUsages, (string x) => new InternedString(x)) }; if (!string.IsNullOrEmpty(format)) { inputControlLayout.m_StateFormat = new FourCC(format); } if (!string.IsNullOrEmpty(extend)) { inputControlLayout.m_BaseLayouts.Append(new InternedString(extend)); } if (extendMultiple != null) { string[] array = extendMultiple; foreach (string text in array) { inputControlLayout.m_BaseLayouts.Append(new InternedString(text)); } } if (!string.IsNullOrEmpty(beforeRender)) { string text2 = beforeRender.ToLower(); if (text2 == "ignore") { inputControlLayout.m_UpdateBeforeRender = false; } else { if (!(text2 == "update")) { throw new InvalidOperationException("Invalid beforeRender setting '" + beforeRender + "' (should be 'ignore' or 'update')"); } inputControlLayout.m_UpdateBeforeRender = true; } } if (!string.IsNullOrEmpty(runInBackground)) { string text3 = runInBackground.ToLower(); if (text3 == "enabled") { inputControlLayout.canRunInBackground = true; } else { if (!(text3 == "disabled")) { throw new InvalidOperationException("Invalid runInBackground setting '" + beforeRender + "' (should be 'enabled' or 'disabled')"); } inputControlLayout.canRunInBackground = false; } } if (controls != null) { List list = new List(); ControlItemJson[] array2 = controls; foreach (ControlItemJson obj in array2) { if (string.IsNullOrEmpty(obj.name)) { throw new InvalidOperationException("Control with no name in layout '" + name); } ControlItem item = obj.ToLayout(); list.Add(item); } inputControlLayout.m_Controls = list.ToArray(); } return inputControlLayout; } public static LayoutJson FromLayout(InputControlLayout layout) { return new LayoutJson { name = layout.m_Name, type = layout.type?.AssemblyQualifiedName, variant = layout.m_Variants, displayName = layout.m_DisplayName, description = layout.m_Description, isGenericTypeOfDevice = layout.isGenericTypeOfDevice, hideInUI = layout.hideInUI, extend = ((layout.m_BaseLayouts.length == 1) ? layout.m_BaseLayouts[0].ToString() : null), extendMultiple = ((layout.m_BaseLayouts.length > 1) ? layout.m_BaseLayouts.ToArray((InternedString x) => x.ToString()) : null), format = layout.stateFormat.ToString(), commonUsages = ArrayHelpers.Select(layout.m_CommonUsages, (InternedString x) => x.ToString()), controls = ControlItemJson.FromControlItems(layout.m_Controls), beforeRender = ((!layout.m_UpdateBeforeRender.HasValue) ? null : (layout.m_UpdateBeforeRender.Value ? "Update" : "Ignore")) }; } } [Serializable] private class ControlItemJson { public string name; public string layout; public string variants; public string usage; public string alias; public string useStateFrom; public uint offset; public uint bit; public uint sizeInBits; public string format; public int arraySize; public string[] usages; public string[] aliases; public string parameters; public string processors; public string displayName; public string shortDisplayName; public bool noisy; public bool dontReset; public bool synthetic; public string defaultState; public string minValue; public string maxValue; public ControlItemJson() { offset = uint.MaxValue; bit = uint.MaxValue; } public ControlItem ToLayout() { ControlItem result = new ControlItem { name = new InternedString(name), layout = new InternedString(layout), variants = new InternedString(variants), displayName = displayName, shortDisplayName = shortDisplayName, offset = offset, useStateFrom = useStateFrom, bit = bit, sizeInBits = sizeInBits, isModifyingExistingControl = (name.IndexOf('/') != -1), isNoisy = noisy, dontReset = dontReset, isSynthetic = synthetic, isFirstDefinedInThisLayout = true, arraySize = arraySize }; if (!string.IsNullOrEmpty(format)) { result.format = new FourCC(format); } if (!string.IsNullOrEmpty(usage) || usages != null) { List list = new List(); if (!string.IsNullOrEmpty(usage)) { list.Add(usage); } if (usages != null) { list.AddRange(usages); } result.usages = new ReadOnlyArray(list.Select((string x) => new InternedString(x)).ToArray()); } if (!string.IsNullOrEmpty(alias) || aliases != null) { List list2 = new List(); if (!string.IsNullOrEmpty(alias)) { list2.Add(alias); } if (aliases != null) { list2.AddRange(aliases); } result.aliases = new ReadOnlyArray(list2.Select((string x) => new InternedString(x)).ToArray()); } if (!string.IsNullOrEmpty(parameters)) { result.parameters = new ReadOnlyArray(NamedValue.ParseMultiple(parameters)); } if (!string.IsNullOrEmpty(processors)) { result.processors = new ReadOnlyArray(NameAndParameters.ParseMultiple(processors).ToArray()); } if (defaultState != null) { result.defaultState = PrimitiveValue.FromObject(defaultState); } if (minValue != null) { result.minValue = PrimitiveValue.FromObject(minValue); } if (maxValue != null) { result.maxValue = PrimitiveValue.FromObject(maxValue); } return result; } public static ControlItemJson[] FromControlItems(ControlItem[] items) { if (items == null) { return null; } int num = items.Length; ControlItemJson[] array = new ControlItemJson[num]; for (int i = 0; i < num; i++) { ControlItem controlItem = items[i]; array[i] = new ControlItemJson { name = controlItem.name, layout = controlItem.layout, variants = controlItem.variants, displayName = controlItem.displayName, shortDisplayName = controlItem.shortDisplayName, bit = controlItem.bit, offset = controlItem.offset, sizeInBits = controlItem.sizeInBits, format = controlItem.format.ToString(), parameters = string.Join(",", controlItem.parameters.Select((NamedValue x) => x.ToString()).ToArray()), processors = string.Join(",", controlItem.processors.Select((NameAndParameters x) => x.ToString()).ToArray()), usages = controlItem.usages.Select((InternedString x) => x.ToString()).ToArray(), aliases = controlItem.aliases.Select((InternedString x) => x.ToString()).ToArray(), noisy = controlItem.isNoisy, dontReset = controlItem.dontReset, synthetic = controlItem.isSynthetic, arraySize = controlItem.arraySize, defaultState = controlItem.defaultState.ToString(), minValue = controlItem.minValue.ToString(), maxValue = controlItem.maxValue.ToString() }; } return array; } } internal struct Collection { public struct LayoutMatcher { public InternedString layoutName; public InputDeviceMatcher deviceMatcher; } public struct PrecompiledLayout { public Func factoryMethod; public string metadata; } public const float kBaseScoreForNonGeneratedLayouts = 1f; public Dictionary layoutTypes; public Dictionary layoutStrings; public Dictionary> layoutBuilders; public Dictionary baseLayoutTable; public Dictionary layoutOverrides; public HashSet layoutOverrideNames; public Dictionary precompiledLayouts; public List layoutMatchers; public void Allocate() { layoutTypes = new Dictionary(); layoutStrings = new Dictionary(); layoutBuilders = new Dictionary>(); baseLayoutTable = new Dictionary(); layoutOverrides = new Dictionary(); layoutOverrideNames = new HashSet(); layoutMatchers = new List(); precompiledLayouts = new Dictionary(); } public InternedString TryFindLayoutForType(Type layoutType) { foreach (KeyValuePair layoutType2 in layoutTypes) { if (layoutType2.Value == layoutType) { return layoutType2.Key; } } return default(InternedString); } public InternedString TryFindMatchingLayout(InputDeviceDescription deviceDescription) { float num = 0f; InternedString result = default(InternedString); int count = layoutMatchers.Count; for (int i = 0; i < count; i++) { float num2 = layoutMatchers[i].deviceMatcher.MatchPercentage(deviceDescription); if (num2 > 0f && !layoutBuilders.ContainsKey(layoutMatchers[i].layoutName)) { num2 += 1f; } if (num2 > num) { num = num2; result = layoutMatchers[i].layoutName; } } return result; } public bool HasLayout(InternedString name) { if (!layoutTypes.ContainsKey(name) && !layoutStrings.ContainsKey(name)) { return layoutBuilders.ContainsKey(name); } return true; } private InputControlLayout TryLoadLayoutInternal(InternedString name) { if (layoutStrings.TryGetValue(name, out var value)) { return FromJson(value); } if (layoutTypes.TryGetValue(name, out var value2)) { return FromType(name, value2); } if (layoutBuilders.TryGetValue(name, out var value3)) { return value3() ?? throw new InvalidOperationException($"Layout builder '{name}' returned null when invoked"); } return null; } public InputControlLayout TryLoadLayout(InternedString name, Dictionary table = null) { if (table != null && table.TryGetValue(name, out var value)) { return value; } value = TryLoadLayoutInternal(name); if (value != null) { value.m_Name = name; if (layoutOverrideNames.Contains(name)) { value.isOverride = true; } InternedString value2 = default(InternedString); if (!value.isOverride && baseLayoutTable.TryGetValue(name, out value2)) { InputControlLayout inputControlLayout = TryLoadLayout(value2, table); if (inputControlLayout == null) { throw new LayoutNotFoundException($"Cannot find base layout '{value2}' of layout '{name}'"); } value.MergeLayout(inputControlLayout); if (value.m_BaseLayouts.length == 0) { value.m_BaseLayouts.Append(value2); } } if (layoutOverrides.TryGetValue(name, out var value3)) { foreach (InternedString internedString in value3) { InputControlLayout inputControlLayout2 = TryLoadLayout(internedString); inputControlLayout2.MergeLayout(value); inputControlLayout2.m_BaseLayouts.Clear(); inputControlLayout2.isOverride = false; inputControlLayout2.isGenericTypeOfDevice = value.isGenericTypeOfDevice; inputControlLayout2.m_Name = value.name; inputControlLayout2.m_BaseLayouts = value.m_BaseLayouts; value = inputControlLayout2; value.m_AppliedOverrides.Append(internedString); } } if (table != null) { table[name] = value; } } return value; } public InternedString GetBaseLayoutName(InternedString layoutName) { if (baseLayoutTable.TryGetValue(layoutName, out var value)) { return value; } return default(InternedString); } public InternedString GetRootLayoutName(InternedString layoutName) { InternedString value; while (baseLayoutTable.TryGetValue(layoutName, out value)) { layoutName = value; } return layoutName; } public bool ComputeDistanceInInheritanceHierarchy(InternedString firstLayout, InternedString secondLayout, out int distance) { distance = 0; int num = 0; InternedString internedString = secondLayout; while (!internedString.IsEmpty() && internedString != firstLayout) { internedString = GetBaseLayoutName(internedString); num++; } if (internedString == firstLayout) { distance = num; return true; } int num2 = 0; internedString = firstLayout; while (!internedString.IsEmpty() && internedString != secondLayout) { internedString = GetBaseLayoutName(internedString); num2++; } if (internedString == secondLayout) { distance = num2; return true; } return false; } public InternedString FindLayoutThatIntroducesControl(InputControl control, Cache cache) { InputControl inputControl = control; while (inputControl.parent != control.device) { inputControl = inputControl.parent; } InternedString internedString = control.device.m_Layout; InternedString value = internedString; while (baseLayoutTable.TryGetValue(value, out value)) { if (cache.FindOrLoadLayout(value).FindControl(inputControl.m_Name).HasValue) { internedString = value; } } return internedString; } public Type GetControlTypeForLayout(InternedString layoutName) { while (layoutStrings.ContainsKey(layoutName)) { if (baseLayoutTable.TryGetValue(layoutName, out var value)) { layoutName = value; continue; } return typeof(InputDevice); } layoutTypes.TryGetValue(layoutName, out var value2); return value2; } public bool ValueTypeIsAssignableFrom(InternedString layoutName, Type valueType) { Type controlTypeForLayout = GetControlTypeForLayout(layoutName); if (controlTypeForLayout == null) { return false; } Type genericTypeArgumentFromHierarchy = TypeHelpers.GetGenericTypeArgumentFromHierarchy(controlTypeForLayout, typeof(InputControl<>), 0); if (genericTypeArgumentFromHierarchy == null) { return false; } return valueType.IsAssignableFrom(genericTypeArgumentFromHierarchy); } public bool IsGeneratedLayout(InternedString layout) { return layoutBuilders.ContainsKey(layout); } public IEnumerable GetBaseLayouts(InternedString layout, bool includeSelf = true) { if (includeSelf) { yield return layout; } while (baseLayoutTable.TryGetValue(layout, out layout)) { yield return layout; } } public bool IsBasedOn(InternedString parentLayout, InternedString childLayout) { InternedString value = childLayout; while (baseLayoutTable.TryGetValue(value, out value)) { if (value == parentLayout) { return true; } } return false; } public void AddMatcher(InternedString layout, InputDeviceMatcher matcher) { int count = layoutMatchers.Count; for (int i = 0; i < count; i++) { if (layoutMatchers[i].deviceMatcher == matcher) { return; } } layoutMatchers.Add(new LayoutMatcher { layoutName = layout, deviceMatcher = matcher }); } } public class LayoutNotFoundException : Exception { public string layout { get; } public LayoutNotFoundException() { } public LayoutNotFoundException(string name, string message) : base(message) { layout = name; } public LayoutNotFoundException(string name) : base("Cannot find control layout '" + name + "'") { layout = name; } public LayoutNotFoundException(string message, Exception innerException) : base(message, innerException) { } protected LayoutNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal struct Cache { public Dictionary table; public void Clear() { table = null; } public InputControlLayout FindOrLoadLayout(string name, bool throwIfNotFound = true) { InternedString name2 = new InternedString(name); if (table == null) { table = new Dictionary(); } InputControlLayout inputControlLayout = s_Layouts.TryLoadLayout(name2, table); if (inputControlLayout != null) { return inputControlLayout; } if (throwIfNotFound) { throw new LayoutNotFoundException(name); } return null; } } internal struct CacheRefInstance : IDisposable { public bool valid; public void Dispose() { if (valid) { s_CacheInstanceRef--; if (s_CacheInstanceRef <= 0) { s_CacheInstance = default(Cache); s_CacheInstanceRef = 0; } valid = false; } } } private static InternedString s_DefaultVariant = new InternedString("Default"); public const string VariantSeparator = ";"; private InternedString m_Name; private Type m_Type; private InternedString m_Variants; private FourCC m_StateFormat; internal int m_StateSizeInBytes; internal bool? m_UpdateBeforeRender; internal InlinedArray m_BaseLayouts; private InlinedArray m_AppliedOverrides; private InternedString[] m_CommonUsages; internal ControlItem[] m_Controls; internal string m_DisplayName; private string m_Description; private Flags m_Flags; internal static Collection s_Layouts; internal static Cache s_CacheInstance; internal static int s_CacheInstanceRef; public static InternedString DefaultVariant => s_DefaultVariant; public InternedString name => m_Name; public string displayName => m_DisplayName ?? ((string)m_Name); public Type type => m_Type; public InternedString variants => m_Variants; public FourCC stateFormat => m_StateFormat; public int stateSizeInBytes => m_StateSizeInBytes; public IEnumerable baseLayouts => m_BaseLayouts; public IEnumerable appliedOverrides => m_AppliedOverrides; public ReadOnlyArray commonUsages => new ReadOnlyArray(m_CommonUsages); public ReadOnlyArray controls => new ReadOnlyArray(m_Controls); public bool updateBeforeRender => m_UpdateBeforeRender == true; public bool isDeviceLayout => typeof(InputDevice).IsAssignableFrom(m_Type); public bool isControlLayout => !isDeviceLayout; public bool isOverride { get { return (m_Flags & Flags.IsOverride) != 0; } internal set { if (value) { m_Flags |= Flags.IsOverride; } else { m_Flags &= ~Flags.IsOverride; } } } public bool isGenericTypeOfDevice { get { return (m_Flags & Flags.IsGenericTypeOfDevice) != 0; } internal set { if (value) { m_Flags |= Flags.IsGenericTypeOfDevice; } else { m_Flags &= ~Flags.IsGenericTypeOfDevice; } } } public bool hideInUI { get { return (m_Flags & Flags.HideInUI) != 0; } internal set { if (value) { m_Flags |= Flags.HideInUI; } else { m_Flags &= ~Flags.HideInUI; } } } public bool isNoisy { get { return (m_Flags & Flags.IsNoisy) != 0; } internal set { if (value) { m_Flags |= Flags.IsNoisy; } else { m_Flags &= ~Flags.IsNoisy; } } } public bool? canRunInBackground { get { if ((m_Flags & Flags.CanRunInBackgroundIsSet) == 0) { return null; } return (m_Flags & Flags.CanRunInBackground) != 0; } internal set { if (!value.HasValue) { m_Flags &= ~Flags.CanRunInBackgroundIsSet; return; } m_Flags |= Flags.CanRunInBackgroundIsSet; if (value.Value) { m_Flags |= Flags.CanRunInBackground; } else { m_Flags &= ~Flags.CanRunInBackground; } } } public ControlItem this[string path] { get { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } if (m_Controls != null) { for (int i = 0; i < m_Controls.Length; i++) { if (m_Controls[i].name == path) { return m_Controls[i]; } } } throw new KeyNotFoundException($"Cannot find control '{path}' in layout '{name}'"); } } internal static ref Cache cache => ref s_CacheInstance; public ControlItem? FindControl(InternedString path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } if (m_Controls == null) { return null; } for (int i = 0; i < m_Controls.Length; i++) { if (m_Controls[i].name == path) { return m_Controls[i]; } } return null; } public ControlItem? FindControlIncludingArrayElements(string path, out int arrayIndex) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } arrayIndex = -1; if (m_Controls == null) { return null; } int num = 0; int num2 = path.Length; while (num2 > 0 && char.IsDigit(path[num2 - 1])) { num2--; num *= 10; num += path[num2] - 48; } int num3 = 0; if (num2 < path.Length && num2 > 0) { num3 = num2; } for (int i = 0; i < m_Controls.Length; i++) { ref ControlItem reference = ref m_Controls[i]; if (string.Compare(reference.name, path, StringComparison.InvariantCultureIgnoreCase) == 0) { return reference; } if (reference.isArray && num3 > 0 && num3 == reference.name.length && string.Compare(reference.name.ToString(), 0, path, 0, num3, StringComparison.InvariantCultureIgnoreCase) == 0) { arrayIndex = num; return reference; } } return null; } public Type GetValueType() { return TypeHelpers.GetGenericTypeArgumentFromHierarchy(type, typeof(InputControl<>), 0); } public static InputControlLayout FromType(string name, Type type) { List list = new List(); InputControlLayoutAttribute customAttribute = type.GetCustomAttribute(inherit: true); FourCC fourCC = default(FourCC); if (customAttribute != null && customAttribute.stateType != null) { AddControlItems(customAttribute.stateType, list, name); if (typeof(IInputStateTypeInfo).IsAssignableFrom(customAttribute.stateType)) { fourCC = ((IInputStateTypeInfo)Activator.CreateInstance(customAttribute.stateType)).format; } } else { AddControlItems(type, list, name); } if (customAttribute != null && !string.IsNullOrEmpty(customAttribute.stateFormat)) { fourCC = new FourCC(customAttribute.stateFormat); } InternedString internedString = default(InternedString); if (customAttribute != null) { internedString = new InternedString(customAttribute.variants); } InputControlLayout inputControlLayout = new InputControlLayout(name, type) { m_Controls = list.ToArray(), m_StateFormat = fourCC, m_Variants = internedString, m_UpdateBeforeRender = customAttribute?.updateBeforeRenderInternal, isGenericTypeOfDevice = (customAttribute?.isGenericTypeOfDevice ?? false), hideInUI = (customAttribute?.hideInUI ?? false), m_Description = customAttribute?.description, m_DisplayName = customAttribute?.displayName, canRunInBackground = customAttribute?.canRunInBackgroundInternal, isNoisy = (customAttribute?.isNoisy ?? false) }; if (customAttribute?.commonUsages != null) { inputControlLayout.m_CommonUsages = ArrayHelpers.Select(customAttribute.commonUsages, (string x) => new InternedString(x)); } return inputControlLayout; } public string ToJson() { return JsonUtility.ToJson((object)LayoutJson.FromLayout(this), true); } public static InputControlLayout FromJson(string json) { return JsonUtility.FromJson(json).ToLayout(); } private InputControlLayout(string name, Type type) { m_Name = new InternedString(name); m_Type = type; } private static void AddControlItems(Type type, List controlLayouts, string layoutName) { AddControlItemsFromFields(type, controlLayouts, layoutName); AddControlItemsFromProperties(type, controlLayouts, layoutName); } private static void AddControlItemsFromFields(Type type, List controlLayouts, string layoutName) { MemberInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); AddControlItemsFromMembers(fields, controlLayouts, layoutName); } private static void AddControlItemsFromProperties(Type type, List controlLayouts, string layoutName) { MemberInfo[] properties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); AddControlItemsFromMembers(properties, controlLayouts, layoutName); } private static void AddControlItemsFromMembers(MemberInfo[] members, List controlItems, string layoutName) { foreach (MemberInfo memberInfo in members) { if (memberInfo.DeclaringType == typeof(InputControl)) { continue; } Type valueType = TypeHelpers.GetValueType(memberInfo); if (valueType != null && valueType.IsValueType && typeof(IInputStateTypeInfo).IsAssignableFrom(valueType)) { int count = controlItems.Count; AddControlItems(valueType, controlItems, layoutName); if (memberInfo as FieldInfo != null) { int num = Marshal.OffsetOf(memberInfo.DeclaringType, memberInfo.Name).ToInt32(); int count2 = controlItems.Count; for (int j = count; j < count2; j++) { ControlItem value = controlItems[j]; if (controlItems[j].offset != uint.MaxValue) { value.offset += (uint)num; controlItems[j] = value; } } } } InputControlAttribute[] array = memberInfo.GetCustomAttributes(inherit: false).ToArray(); if (array.Length != 0 || (!(valueType == null) && typeof(InputControl).IsAssignableFrom(valueType) && !(memberInfo is PropertyInfo))) { AddControlItemsFromMember(memberInfo, array, controlItems); } } } private static void AddControlItemsFromMember(MemberInfo member, InputControlAttribute[] attributes, List controlItems) { if (attributes.Length == 0) { ControlItem item = CreateControlItemFromMember(member, null); controlItems.Add(item); return; } foreach (InputControlAttribute attribute in attributes) { ControlItem item2 = CreateControlItemFromMember(member, attribute); controlItems.Add(item2); } } private static ControlItem CreateControlItemFromMember(MemberInfo member, InputControlAttribute attribute) { string text = attribute?.name; if (string.IsNullOrEmpty(text)) { text = member.Name; } bool flag = text.IndexOf('/') != -1; string text2 = attribute?.displayName; string shortDisplayName = attribute?.shortDisplayName; string text3 = attribute?.layout; if (string.IsNullOrEmpty(text3) && !flag && (!(member is FieldInfo) || member.GetCustomAttribute(inherit: false) == null)) { text3 = InferLayoutFromValueType(TypeHelpers.GetValueType(member)); } string text4 = null; if (attribute != null && !string.IsNullOrEmpty(attribute.variants)) { text4 = attribute.variants; } uint offset = uint.MaxValue; if (attribute != null && attribute.offset != uint.MaxValue) { offset = attribute.offset; } else if (member is FieldInfo && !flag) { offset = (uint)Marshal.OffsetOf(member.DeclaringType, member.Name).ToInt32(); } uint num = uint.MaxValue; if (attribute != null) { num = attribute.bit; } uint sizeInBits = 0u; if (attribute != null) { sizeInBits = attribute.sizeInBits; } FourCC format = default(FourCC); if (attribute != null && !string.IsNullOrEmpty(attribute.format)) { format = new FourCC(attribute.format); } else if (!flag && num == uint.MaxValue) { format = InputStateBlock.GetPrimitiveFormatFromType(TypeHelpers.GetValueType(member)); } InternedString[] array = null; if (attribute != null) { string[] array2 = ArrayHelpers.Join(attribute.alias, attribute.aliases); if (array2 != null) { array = array2.Select((string x) => new InternedString(x)).ToArray(); } } InternedString[] array3 = null; if (attribute != null) { string[] array4 = ArrayHelpers.Join(attribute.usage, attribute.usages); if (array4 != null) { array3 = array4.Select((string x) => new InternedString(x)).ToArray(); } } NamedValue[] array5 = null; if (attribute != null && !string.IsNullOrEmpty(attribute.parameters)) { array5 = NamedValue.ParseMultiple(attribute.parameters); } NameAndParameters[] array6 = null; if (attribute != null && !string.IsNullOrEmpty(attribute.processors)) { array6 = NameAndParameters.ParseMultiple(attribute.processors).ToArray(); } string useStateFrom = null; if (attribute != null && !string.IsNullOrEmpty(attribute.useStateFrom)) { useStateFrom = attribute.useStateFrom; } bool flag2 = false; if (attribute != null) { flag2 = attribute.noisy; } bool dontReset = false; if (attribute != null) { dontReset = attribute.dontReset; } bool isSynthetic = false; if (attribute != null) { isSynthetic = attribute.synthetic; } int arraySize = 0; if (attribute != null) { arraySize = attribute.arraySize; } PrimitiveValue defaultState = default(PrimitiveValue); if (attribute != null) { defaultState = PrimitiveValue.FromObject(attribute.defaultState); } PrimitiveValue minValue = default(PrimitiveValue); PrimitiveValue maxValue = default(PrimitiveValue); if (attribute != null) { minValue = PrimitiveValue.FromObject(attribute.minValue); maxValue = PrimitiveValue.FromObject(attribute.maxValue); } return new ControlItem { name = new InternedString(text), displayName = text2, shortDisplayName = shortDisplayName, layout = new InternedString(text3), variants = new InternedString(text4), useStateFrom = useStateFrom, format = format, offset = offset, bit = num, sizeInBits = sizeInBits, parameters = new ReadOnlyArray(array5), processors = new ReadOnlyArray(array6), usages = new ReadOnlyArray(array3), aliases = new ReadOnlyArray(array), isModifyingExistingControl = flag, isFirstDefinedInThisLayout = true, isNoisy = flag2, dontReset = dontReset, isSynthetic = isSynthetic, arraySize = arraySize, defaultState = defaultState, minValue = minValue, maxValue = maxValue }; } private static string InferLayoutFromValueType(Type type) { InternedString internedString = s_Layouts.TryFindLayoutForType(type); if (internedString.IsEmpty()) { InternedString internedString2 = new InternedString(type.Name); if (s_Layouts.HasLayout(internedString2)) { internedString = internedString2; } else if (type.Name.EndsWith("Control")) { internedString2 = new InternedString(type.Name.Substring(0, type.Name.Length - "Control".Length)); if (s_Layouts.HasLayout(internedString2)) { internedString = internedString2; } } } return internedString; } public void MergeLayout(InputControlLayout other) { if (other == null) { throw new ArgumentNullException("other"); } m_UpdateBeforeRender = m_UpdateBeforeRender ?? other.m_UpdateBeforeRender; if (m_Variants.IsEmpty()) { m_Variants = other.m_Variants; } if (m_Type == null) { m_Type = other.m_Type; } else if (m_Type.IsAssignableFrom(other.m_Type)) { m_Type = other.m_Type; } bool flag = !m_Variants.IsEmpty(); if (m_StateFormat == default(FourCC)) { m_StateFormat = other.m_StateFormat; } m_CommonUsages = ArrayHelpers.Merge(other.m_CommonUsages, m_CommonUsages); m_AppliedOverrides.Merge(other.m_AppliedOverrides); if (string.IsNullOrEmpty(m_DisplayName)) { m_DisplayName = other.m_DisplayName; } if (m_Controls == null) { m_Controls = other.m_Controls; } else { if (other.m_Controls == null) { return; } ControlItem[] controlItems = other.m_Controls; List list = new List(); List list2 = new List(); Dictionary dictionary = CreateLookupTableForControls(controlItems, list2); foreach (KeyValuePair item5 in CreateLookupTableForControls(m_Controls)) { if (dictionary.TryGetValue(item5.Key, out var value)) { ControlItem item = item5.Value.Merge(value); list.Add(item); dictionary.Remove(item5.Key); } else if (item5.Value.variants.IsEmpty() || item5.Value.variants == DefaultVariant) { bool flag2 = false; if (flag) { for (int i = 0; i < list2.Count; i++) { if (VariantsMatch(m_Variants.ToLower(), list2[i])) { string key = item5.Key + "@" + list2[i]; if (dictionary.TryGetValue(key, out value)) { ControlItem item2 = item5.Value.Merge(value); list.Add(item2); dictionary.Remove(key); flag2 = true; } } } } else { foreach (string item6 in list2) { string key2 = item5.Key + "@" + item6; if (dictionary.TryGetValue(key2, out value)) { ControlItem item3 = item5.Value.Merge(value); list.Add(item3); dictionary.Remove(key2); flag2 = true; } } } if (!flag2) { list.Add(item5.Value); } } else if (dictionary.TryGetValue(item5.Value.name.ToLower(), out value)) { ControlItem item4 = item5.Value.Merge(value); list.Add(item4); dictionary.Remove(item5.Value.name.ToLower()); } else if (VariantsMatch(m_Variants, item5.Value.variants)) { list.Add(item5.Value); } } if (!flag) { int count = list.Count; list.AddRange(dictionary.Values); for (int j = count; j < list.Count; j++) { ControlItem value2 = list[j]; value2.isFirstDefinedInThisLayout = false; list[j] = value2; } } else { int count2 = list.Count; list.AddRange(dictionary.Values.Where((ControlItem x) => VariantsMatch(m_Variants, x.variants))); for (int num = count2; num < list.Count; num++) { ControlItem value3 = list[num]; value3.isFirstDefinedInThisLayout = false; list[num] = value3; } } m_Controls = list.ToArray(); } } private static Dictionary CreateLookupTableForControls(ControlItem[] controlItems, List variants = null) { Dictionary dictionary = new Dictionary(); for (int i = 0; i < controlItems.Length; i++) { string text = controlItems[i].name.ToLower(); InternedString internedString = controlItems[i].variants; if (!internedString.IsEmpty() && internedString != DefaultVariant) { if (internedString.ToString().IndexOf(";"[0]) != -1) { string[] array = internedString.ToLower().Split(";"[0]); foreach (string text2 in array) { variants?.Add(text2); text = text + "@" + text2; dictionary[text] = controlItems[i]; } continue; } text = text + "@" + internedString.ToLower(); variants?.Add(internedString.ToLower()); } dictionary[text] = controlItems[i]; } return dictionary; } internal static bool VariantsMatch(InternedString expected, InternedString actual) { return VariantsMatch(expected.ToLower(), actual.ToLower()); } internal static bool VariantsMatch(string expected, string actual) { if (actual != null && StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(DefaultVariant, actual, ";"[0])) { return true; } if (expected == null) { return true; } if (actual == null) { return true; } return StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(expected, actual, ";"[0]); } internal static void ParseHeaderFieldsFromJson(string json, out InternedString name, out InlinedArray baseLayouts, out InputDeviceMatcher deviceMatcher) { LayoutJsonNameAndDescriptorOnly layoutJsonNameAndDescriptorOnly = JsonUtility.FromJson(json); name = new InternedString(layoutJsonNameAndDescriptorOnly.name); baseLayouts = default(InlinedArray); if (!string.IsNullOrEmpty(layoutJsonNameAndDescriptorOnly.extend)) { baseLayouts.Append(new InternedString(layoutJsonNameAndDescriptorOnly.extend)); } if (layoutJsonNameAndDescriptorOnly.extendMultiple != null) { string[] extendMultiple = layoutJsonNameAndDescriptorOnly.extendMultiple; foreach (string text in extendMultiple) { baseLayouts.Append(new InternedString(text)); } } deviceMatcher = layoutJsonNameAndDescriptorOnly.device.ToMatcher(); } internal static CacheRefInstance CacheRef() { s_CacheInstanceRef++; return new CacheRefInstance { valid = true }; } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class InputControlLayoutAttribute : Attribute { internal bool? canRunInBackgroundInternal; internal bool? updateBeforeRenderInternal; public Type stateType { get; set; } public string stateFormat { get; set; } public string[] commonUsages { get; set; } public string variants { get; set; } public bool isNoisy { get; set; } public bool canRunInBackground { get { return canRunInBackgroundInternal.Value; } set { canRunInBackgroundInternal = value; } } public bool updateBeforeRender { get { return updateBeforeRenderInternal.Value; } set { updateBeforeRenderInternal = value; } } public bool isGenericTypeOfDevice { get; set; } public string displayName { get; set; } public string description { get; set; } public bool hideInUI { get; set; } } internal struct InputDeviceBuilder : IDisposable { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct RefInstance : IDisposable { public void Dispose() { s_InstanceRef--; if (s_InstanceRef <= 0) { s_Instance.Dispose(); s_Instance = default(InputDeviceBuilder); s_InstanceRef = 0; } else { s_Instance.Reset(); } } } private InputDevice m_Device; private InputControlLayout.CacheRefInstance m_LayoutCacheRef; private Dictionary m_ChildControlOverrides; private List m_StateOffsetToControlMap; private StringBuilder m_StringBuilder; private const uint kSizeForControlUsingStateFromOtherControl = uint.MaxValue; private static InputDeviceBuilder s_Instance; private static int s_InstanceRef; internal static ref InputDeviceBuilder instance => ref s_Instance; public void Setup(InternedString layout, InternedString variants, InputDeviceDescription deviceDescription = default(InputDeviceDescription)) { m_LayoutCacheRef = InputControlLayout.CacheRef(); InstantiateLayout(layout, variants, default(InternedString), null); FinalizeControlHierarchy(); m_StateOffsetToControlMap.Sort(); m_Device.m_Description = deviceDescription; m_Device.m_StateOffsetToControlMap = m_StateOffsetToControlMap.ToArray(); m_Device.CallFinishSetupRecursive(); } public InputDevice Finish() { InputDevice device = m_Device; Reset(); return device; } public void Dispose() { m_LayoutCacheRef.Dispose(); } private void Reset() { m_Device = null; m_ChildControlOverrides?.Clear(); m_StateOffsetToControlMap?.Clear(); } private InputControl InstantiateLayout(InternedString layout, InternedString variants, InternedString name, InputControl parent) { InputControlLayout layout2 = FindOrLoadLayout(layout); return InstantiateLayout(layout2, variants, name, parent); } private InputControl InstantiateLayout(InputControlLayout layout, InternedString variants, InternedString name, InputControl parent) { if (!(Activator.CreateInstance(layout.type) is InputControl inputControl)) { throw new InvalidOperationException($"Type '{layout.type.Name}' referenced by layout '{layout.name}' is not an InputControl"); } if (inputControl is InputDevice device) { if (parent != null) { throw new InvalidOperationException($"Cannot instantiate device layout '{layout.name}' as child of '{parent.path}'; devices must be added at root"); } m_Device = device; m_Device.m_StateBlock.byteOffset = 0u; m_Device.m_StateBlock.bitOffset = 0u; m_Device.m_StateBlock.format = layout.stateFormat; m_Device.m_AliasesForEachControl = null; m_Device.m_ChildrenForEachControl = null; m_Device.m_UsagesForEachControl = null; m_Device.m_UsageToControl = null; if (layout.m_UpdateBeforeRender == true) { m_Device.m_DeviceFlags |= InputDevice.DeviceFlags.UpdateBeforeRender; } if (layout.canRunInBackground.HasValue) { m_Device.m_DeviceFlags |= InputDevice.DeviceFlags.CanRunInBackgroundHasBeenQueried; if (layout.canRunInBackground == true) { m_Device.m_DeviceFlags |= InputDevice.DeviceFlags.CanRunInBackground; } } } else if (parent == null) { throw new InvalidOperationException($"Toplevel layout used with InputDeviceBuilder must be a device layout; '{layout.name}' is a control layout"); } if (name.IsEmpty()) { name = layout.name; int num = name.ToString().LastIndexOf(':'); if (num != -1) { name = new InternedString(name.ToString().Substring(num + 1)); } } if (name.ToString().IndexOf('/') != -1) { name = new InternedString(name.ToString().CleanSlashes()); } if (variants.IsEmpty()) { variants = layout.variants; if (variants.IsEmpty()) { variants = InputControlLayout.DefaultVariant; } } inputControl.m_Name = name; inputControl.m_DisplayNameFromLayout = layout.m_DisplayName; inputControl.m_Layout = layout.name; inputControl.m_Variants = variants; inputControl.m_Parent = parent; inputControl.m_Device = m_Device; if (inputControl is InputDevice) { inputControl.noisy = layout.isNoisy; } bool haveChildrenUsingStateFromOtherControls = false; try { AddChildControls(layout, variants, inputControl, ref haveChildrenUsingStateFromOtherControls); } catch { throw; } ComputeStateLayout(inputControl); if (haveChildrenUsingStateFromOtherControls) { InputControlLayout.ControlItem[] controls = layout.m_Controls; for (int i = 0; i < controls.Length; i++) { ref InputControlLayout.ControlItem reference = ref controls[i]; if (!string.IsNullOrEmpty(reference.useStateFrom)) { ApplyUseStateFrom(inputControl, ref reference, layout); } } } return inputControl; } private void AddChildControls(InputControlLayout layout, InternedString variants, InputControl parent, ref bool haveChildrenUsingStateFromOtherControls) { InputControlLayout.ControlItem[] controls = layout.m_Controls; if (controls == null) { return; } int num = 0; bool flag = false; for (int i = 0; i < controls.Length; i++) { if (!controls[i].variants.IsEmpty() && !StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(controls[i].variants, variants, ";"[0])) { continue; } if (controls[i].isModifyingExistingControl) { if (controls[i].isArray) { throw new NotSupportedException($"Control '{controls[i].name}' in layout '{layout.name}' is modifying the child of another control but is marked as an array"); } flag = true; InsertChildControlOverride(parent, ref controls[i]); } else { num = ((!controls[i].isArray) ? (num + 1) : (num + controls[i].arraySize)); } } if (num == 0) { parent.m_ChildCount = 0; parent.m_ChildStartIndex = 0; haveChildrenUsingStateFromOtherControls = false; return; } int num2 = ArrayHelpers.GrowBy(ref m_Device.m_ChildrenForEachControl, num); int num3 = num2; for (int j = 0; j < controls.Length; j++) { InputControlLayout.ControlItem controlItem = controls[j]; if (controlItem.isModifyingExistingControl || (!controlItem.variants.IsEmpty() && !StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(controlItem.variants, variants, ";"[0]))) { continue; } if (controlItem.isArray) { for (int k = 0; k < controlItem.arraySize; k++) { string nameOverride = string.Concat(controlItem.name, k.ToString()); InputControl inputControl = AddChildControl(layout, variants, parent, ref haveChildrenUsingStateFromOtherControls, controlItem, num3, nameOverride); num3++; if (inputControl.m_StateBlock.byteOffset != uint.MaxValue) { inputControl.m_StateBlock.byteOffset += (uint)(k * (int)inputControl.m_StateBlock.alignedSizeInBytes); } } } else { AddChildControl(layout, variants, parent, ref haveChildrenUsingStateFromOtherControls, controlItem, num3); num3++; } } parent.m_ChildCount = num; parent.m_ChildStartIndex = num2; if (!flag) { return; } for (int l = 0; l < controls.Length; l++) { InputControlLayout.ControlItem controlItem2 = controls[l]; if (controlItem2.isModifyingExistingControl && (controlItem2.variants.IsEmpty() || StringHelpers.CharacterSeparatedListsHaveAtLeastOneCommonElement(controls[l].variants, variants, ";"[0]))) { AddChildControlIfMissing(layout, variants, parent, ref haveChildrenUsingStateFromOtherControls, ref controlItem2); } } } private InputControl AddChildControl(InputControlLayout layout, InternedString variants, InputControl parent, ref bool haveChildrenUsingStateFromOtherControls, InputControlLayout.ControlItem controlItem, int childIndex, string nameOverride = null) { InternedString internedString = ((nameOverride != null) ? new InternedString(nameOverride) : controlItem.name); if (string.IsNullOrEmpty(controlItem.layout)) { throw new InvalidOperationException($"Layout has not been set on control '{controlItem.name}' in '{layout.name}'"); } if (m_ChildControlOverrides != null) { string key = ChildControlOverridePath(parent, internedString); if (m_ChildControlOverrides.TryGetValue(key, out var value)) { controlItem = value.Merge(controlItem); } } InternedString layout2 = controlItem.layout; InputControl inputControl; try { inputControl = InstantiateLayout(layout2, variants, internedString, parent); } catch (InputControlLayout.LayoutNotFoundException ex) { throw new InputControlLayout.LayoutNotFoundException($"Cannot find layout '{ex.layout}' used in control '{internedString}' of layout '{layout.name}'", ex); } m_Device.m_ChildrenForEachControl[childIndex] = inputControl; inputControl.noisy = controlItem.isNoisy; inputControl.synthetic = controlItem.isSynthetic; inputControl.usesStateFromOtherControl = !string.IsNullOrEmpty(controlItem.useStateFrom); inputControl.dontReset = (inputControl.noisy || controlItem.dontReset) && !inputControl.usesStateFromOtherControl; if (inputControl.noisy) { m_Device.noisy = true; } inputControl.isButton = inputControl is ButtonControl; if (inputControl.dontReset) { m_Device.hasDontResetControls = true; } inputControl.m_DisplayNameFromLayout = controlItem.displayName; inputControl.m_ShortDisplayNameFromLayout = controlItem.shortDisplayName; inputControl.m_DefaultState = controlItem.defaultState; if (!inputControl.m_DefaultState.isEmpty) { m_Device.hasControlsWithDefaultState = true; } if (!controlItem.minValue.isEmpty) { inputControl.m_MinValue = controlItem.minValue; } if (!controlItem.maxValue.isEmpty) { inputControl.m_MaxValue = controlItem.maxValue; } if (!inputControl.usesStateFromOtherControl) { inputControl.m_StateBlock.byteOffset = controlItem.offset; inputControl.m_StateBlock.bitOffset = controlItem.bit; if (controlItem.sizeInBits != 0) { inputControl.m_StateBlock.sizeInBits = controlItem.sizeInBits; } if (controlItem.format != 0) { SetFormat(inputControl, controlItem); } } else { inputControl.m_StateBlock.sizeInBits = uint.MaxValue; haveChildrenUsingStateFromOtherControls = true; } ReadOnlyArray usages = controlItem.usages; if (usages.Count > 0) { int count = usages.Count; int num = (inputControl.m_UsageStartIndex = ArrayHelpers.AppendToImmutable(ref m_Device.m_UsagesForEachControl, usages.m_Array)); inputControl.m_UsageCount = count; ArrayHelpers.GrowBy(ref m_Device.m_UsageToControl, count); for (int i = 0; i < count; i++) { m_Device.m_UsageToControl[num + i] = inputControl; } } if (controlItem.aliases.Count > 0) { int count2 = controlItem.aliases.Count; int aliasStartIndex = ArrayHelpers.AppendToImmutable(ref m_Device.m_AliasesForEachControl, controlItem.aliases.m_Array); inputControl.m_AliasStartIndex = aliasStartIndex; inputControl.m_AliasCount = count2; } if (controlItem.parameters.Count > 0) { NamedValue.ApplyAllToObject(inputControl, controlItem.parameters); } if (controlItem.processors.Count > 0) { AddProcessors(inputControl, ref controlItem, layout.name); } return inputControl; } private void InsertChildControlOverride(InputControl parent, ref InputControlLayout.ControlItem controlItem) { if (m_ChildControlOverrides == null) { m_ChildControlOverrides = new Dictionary(); } string key = ChildControlOverridePath(parent, controlItem.name); if (!m_ChildControlOverrides.TryGetValue(key, out var value)) { m_ChildControlOverrides[key] = controlItem; return; } value = value.Merge(controlItem); m_ChildControlOverrides[key] = value; } private string ChildControlOverridePath(InputControl parent, InternedString controlName) { string text = controlName.ToLower(); for (InputControl inputControl = parent; inputControl != m_Device; inputControl = inputControl.m_Parent) { text = inputControl.m_Name.ToLower() + "/" + text; } return text; } private void AddChildControlIfMissing(InputControlLayout layout, InternedString variants, InputControl parent, ref bool haveChildrenUsingStateFromOtherControls, ref InputControlLayout.ControlItem controlItem) { InputControl inputControl = InputControlPath.TryFindChild(parent, controlItem.name); if (inputControl == null) { inputControl = InsertChildControl(layout, variants, parent, ref haveChildrenUsingStateFromOtherControls, ref controlItem); if (inputControl.parent != parent) { ComputeStateLayout(inputControl.parent); } } } private InputControl InsertChildControl(InputControlLayout layout, InternedString variant, InputControl parent, ref bool haveChildrenUsingStateFromOtherControls, ref InputControlLayout.ControlItem controlItem) { string text = controlItem.name.ToString(); int num = text.LastIndexOf('/'); if (num == -1) { throw new InvalidOperationException("InsertChildControl has to be called with a slash-separated path"); } string text2 = text.Substring(0, num); InputControl inputControl = InputControlPath.TryFindChild(parent, text2); if (inputControl == null) { throw new InvalidOperationException($"Cannot find parent '{text2}' of control '{controlItem.name}' in layout '{layout.name}'"); } string text3 = text.Substring(num + 1); if (text3.Length == 0) { throw new InvalidOperationException($"Path cannot end in '/' (control '{controlItem.name}' in layout '{layout.name}')"); } int num2 = inputControl.m_ChildStartIndex; if (num2 == 0) { num2 = (inputControl.m_ChildStartIndex = m_Device.m_ChildrenForEachControl.LengthSafe()); } int num3 = num2 + inputControl.m_ChildCount; ShiftChildIndicesInHierarchyOneUp(m_Device, num3, inputControl); ArrayHelpers.InsertAt(ref m_Device.m_ChildrenForEachControl, num3, null); inputControl.m_ChildCount++; return AddChildControl(layout, variant, inputControl, ref haveChildrenUsingStateFromOtherControls, controlItem, num3, text3); } private static void ApplyUseStateFrom(InputControl parent, ref InputControlLayout.ControlItem controlItem, InputControlLayout layout) { InputControl inputControl = InputControlPath.TryFindChild(parent, controlItem.name); InputControl inputControl2 = InputControlPath.TryFindChild(parent, controlItem.useStateFrom); if (inputControl2 == null) { throw new InvalidOperationException($"Cannot find control '{controlItem.useStateFrom}' referenced in 'useStateFrom' of control '{controlItem.name}' in layout '{layout.name}'"); } inputControl.m_StateBlock = inputControl2.m_StateBlock; inputControl.usesStateFromOtherControl = true; inputControl.dontReset = inputControl2.dontReset; if (inputControl.parent != inputControl2.parent) { for (InputControl parent2 = inputControl2.parent; parent2 != parent; parent2 = parent2.parent) { inputControl.m_StateBlock.byteOffset += parent2.m_StateBlock.byteOffset; } } } private static void ShiftChildIndicesInHierarchyOneUp(InputDevice device, int startIndex, InputControl exceptControl) { InputControl[] childrenForEachControl = device.m_ChildrenForEachControl; int num = childrenForEachControl.Length; for (int i = 0; i < num; i++) { InputControl inputControl = childrenForEachControl[i]; if (inputControl != null && inputControl != exceptControl && inputControl.m_ChildStartIndex >= startIndex) { inputControl.m_ChildStartIndex++; } } } private void SetDisplayName(InputControl control, string longDisplayNameFromLayout, string shortDisplayNameFromLayout, bool shortName) { string text = (shortName ? shortDisplayNameFromLayout : longDisplayNameFromLayout); if (string.IsNullOrEmpty(text)) { if (shortName) { if (control.parent != null && control.parent != control.device) { if (m_StringBuilder == null) { m_StringBuilder = new StringBuilder(); } m_StringBuilder.Length = 0; AddParentDisplayNameRecursive(control.parent, m_StringBuilder, shortName: true); if (m_StringBuilder.Length == 0) { control.m_ShortDisplayNameFromLayout = null; return; } if (!string.IsNullOrEmpty(longDisplayNameFromLayout)) { m_StringBuilder.Append(longDisplayNameFromLayout); } else { m_StringBuilder.Append(control.name); } control.m_ShortDisplayNameFromLayout = m_StringBuilder.ToString(); } else { control.m_ShortDisplayNameFromLayout = null; } return; } text = control.name; } if (control.parent != null && control.parent != control.device) { if (m_StringBuilder == null) { m_StringBuilder = new StringBuilder(); } m_StringBuilder.Length = 0; AddParentDisplayNameRecursive(control.parent, m_StringBuilder, shortName); m_StringBuilder.Append(text); text = m_StringBuilder.ToString(); } if (shortName) { control.m_ShortDisplayNameFromLayout = text; } else { control.m_DisplayNameFromLayout = text; } } private static void AddParentDisplayNameRecursive(InputControl control, StringBuilder stringBuilder, bool shortName) { if (control.parent != null && control.parent != control.device) { AddParentDisplayNameRecursive(control.parent, stringBuilder, shortName); } if (shortName) { string value = control.shortDisplayName; if (string.IsNullOrEmpty(value)) { value = control.displayName; } stringBuilder.Append(value); } else { stringBuilder.Append(control.displayName); } stringBuilder.Append(' '); } private static void AddProcessors(InputControl control, ref InputControlLayout.ControlItem controlItem, string layoutName) { int count = controlItem.processors.Count; for (int i = 0; i < count; i++) { string name = controlItem.processors[i].name; Type type = InputProcessor.s_Processors.LookupTypeRegistration(name); if (type == null) { throw new InvalidOperationException($"Cannot find processor '{name}' referenced by control '{controlItem.name}' in layout '{layoutName}'"); } object first = Activator.CreateInstance(type); ReadOnlyArray parameters = controlItem.processors[i].parameters; if (parameters.Count > 0) { NamedValue.ApplyAllToObject(first, parameters); } control.AddProcessor(first); } } private static void SetFormat(InputControl control, InputControlLayout.ControlItem controlItem) { control.m_StateBlock.format = controlItem.format; if (controlItem.sizeInBits == 0) { int sizeOfPrimitiveFormatInBits = InputStateBlock.GetSizeOfPrimitiveFormatInBits(controlItem.format); if (sizeOfPrimitiveFormatInBits != -1) { control.m_StateBlock.sizeInBits = (uint)sizeOfPrimitiveFormatInBits; } } } private static InputControlLayout FindOrLoadLayout(string name) { return InputControlLayout.cache.FindOrLoadLayout(name); } private static void ComputeStateLayout(InputControl control) { ReadOnlyArray children = control.children; if (control.m_StateBlock.sizeInBits == 0 && control.m_StateBlock.format != 0) { int sizeOfPrimitiveFormatInBits = InputStateBlock.GetSizeOfPrimitiveFormatInBits(control.m_StateBlock.format); if (sizeOfPrimitiveFormatInBits != -1) { control.m_StateBlock.sizeInBits = (uint)sizeOfPrimitiveFormatInBits; } } if (control.m_StateBlock.sizeInBits == 0 && children.Count == 0) { throw new InvalidOperationException("Control '" + control.path + "' with layout '" + control.layout + "' has no size set and has no children to compute size from"); } if (children.Count == 0) { return; } uint num = 0u; foreach (InputControl item in children) { if (item.m_StateBlock.sizeInBits == uint.MaxValue) { continue; } uint sizeInBits = item.m_StateBlock.sizeInBits; if (sizeInBits == 0 || sizeInBits == uint.MaxValue) { throw new InvalidOperationException("Child '" + item.name + "' of '" + control.name + "' has no size set!"); } if (item.m_StateBlock.byteOffset != uint.MaxValue && item.m_StateBlock.byteOffset != 4294967294u) { if (item.m_StateBlock.bitOffset == uint.MaxValue) { item.m_StateBlock.bitOffset = 0u; } uint num2 = MemoryHelpers.ComputeFollowingByteOffset(item.m_StateBlock.byteOffset, item.m_StateBlock.bitOffset + sizeInBits); if (num2 > num) { num = num2; } } } uint num3 = num; InputControl inputControl = null; uint num4 = 0u; foreach (InputControl item2 in children) { if ((item2.m_StateBlock.byteOffset != uint.MaxValue && item2.m_StateBlock.byteOffset != 4294967294u) || item2.m_StateBlock.sizeInBits == uint.MaxValue) { continue; } bool num5 = item2.m_StateBlock.sizeInBits % 8 != 0; if (num5) { if (inputControl == null) { inputControl = item2; } if (item2.m_StateBlock.bitOffset == uint.MaxValue || item2.m_StateBlock.bitOffset == 4294967294u) { item2.m_StateBlock.bitOffset = num4; num4 += item2.m_StateBlock.sizeInBits; } else { uint num6 = item2.m_StateBlock.bitOffset + item2.m_StateBlock.sizeInBits; if (num6 > num4) { num4 = num6; } } } else { if (inputControl != null) { num3 = MemoryHelpers.ComputeFollowingByteOffset(num3, num4); inputControl = null; } if (item2.m_StateBlock.bitOffset == uint.MaxValue) { item2.m_StateBlock.bitOffset = 0u; } num3 = MemoryHelpers.AlignNatural(num3, item2.m_StateBlock.alignedSizeInBytes); } item2.m_StateBlock.byteOffset = num3; if (!num5) { num3 = MemoryHelpers.ComputeFollowingByteOffset(num3, item2.m_StateBlock.sizeInBits); } } if (inputControl != null) { num3 = MemoryHelpers.ComputeFollowingByteOffset(num3, num4); } uint num7 = num3; control.m_StateBlock.sizeInBits = num7 * 8; } private void FinalizeControlHierarchy() { if (m_StateOffsetToControlMap == null) { m_StateOffsetToControlMap = new List(); } if ((long)m_Device.allControls.Count > 1024L) { throw new NotSupportedException($"Device '{m_Device}' exceeds maximum supported control count of {1024u} (has {m_Device.allControls.Count} controls)"); } InputDevice.ControlBitRangeNode controlBitRangeNode = new InputDevice.ControlBitRangeNode((ushort)(m_Device.m_StateBlock.sizeInBits - 1)); m_Device.m_ControlTreeNodes = new InputDevice.ControlBitRangeNode[1]; m_Device.m_ControlTreeNodes[0] = controlBitRangeNode; int controlIndiciesNextFreeIndex = 0; FinalizeControlHierarchyRecursive(m_Device, -1, m_Device.m_ChildrenForEachControl, noisy: false, dontReset: false, ref controlIndiciesNextFreeIndex); } private void FinalizeControlHierarchyRecursive(InputControl control, int controlIndex, InputControl[] allControls, bool noisy, bool dontReset, ref int controlIndiciesNextFreeIndex) { if (control.m_ChildCount == 0) { if (control.m_StateBlock.effectiveBitOffset >= 8192) { throw new NotSupportedException($"Control '{control}' exceeds maximum supported state bit offset of {8191u} (bit offset {control.stateBlock.effectiveBitOffset})"); } if (control.m_StateBlock.sizeInBits >= 512) { throw new NotSupportedException($"Control '{control}' exceeds maximum supported state bit size of {511u} (bit offset {control.stateBlock.sizeInBits})"); } } if (control != m_Device) { InsertControlBitRangeNode(ref m_Device.m_ControlTreeNodes[0], control, ref controlIndiciesNextFreeIndex, 0); } if (control.m_ChildCount == 0) { m_StateOffsetToControlMap.Add(InputDevice.EncodeStateOffsetToControlMapEntry((uint)controlIndex, control.m_StateBlock.effectiveBitOffset, control.m_StateBlock.sizeInBits)); } string displayNameFromLayout = control.m_DisplayNameFromLayout; string shortDisplayNameFromLayout = control.m_ShortDisplayNameFromLayout; SetDisplayName(control, displayNameFromLayout, shortDisplayNameFromLayout, shortName: false); SetDisplayName(control, displayNameFromLayout, shortDisplayNameFromLayout, shortName: true); if (control != control.device) { if (noisy) { control.noisy = true; } else { noisy = control.noisy; } if (dontReset) { control.dontReset = true; } else { dontReset = control.dontReset; } } uint byteOffset = control.m_StateBlock.byteOffset; int childCount = control.m_ChildCount; int childStartIndex = control.m_ChildStartIndex; for (int i = 0; i < childCount; i++) { int num = childStartIndex + i; InputControl inputControl = allControls[num]; inputControl.m_StateBlock.byteOffset += byteOffset; FinalizeControlHierarchyRecursive(inputControl, num, allControls, noisy, dontReset, ref controlIndiciesNextFreeIndex); } control.isSetupFinished = true; } private void InsertControlBitRangeNode(ref InputDevice.ControlBitRangeNode parent, InputControl control, ref int controlIndiciesNextFreeIndex, ushort startOffset) { InputDevice.ControlBitRangeNode left; InputDevice.ControlBitRangeNode right; if (parent.leftChildIndex == -1) { ushort bestMidPoint = GetBestMidPoint(parent, startOffset); left = new InputDevice.ControlBitRangeNode(bestMidPoint); right = new InputDevice.ControlBitRangeNode(parent.endBitOffset); AddChildren(ref parent, left, right); } else { left = m_Device.m_ControlTreeNodes[parent.leftChildIndex]; right = m_Device.m_ControlTreeNodes[parent.leftChildIndex + 1]; } if (control.m_StateBlock.effectiveBitOffset < left.endBitOffset && control.m_StateBlock.effectiveBitOffset + control.m_StateBlock.sizeInBits > left.endBitOffset) { AddControlToNode(control, ref controlIndiciesNextFreeIndex, parent.leftChildIndex); AddControlToNode(control, ref controlIndiciesNextFreeIndex, parent.leftChildIndex + 1); } else if (control.m_StateBlock.effectiveBitOffset == startOffset && control.m_StateBlock.effectiveBitOffset + control.m_StateBlock.sizeInBits == left.endBitOffset) { AddControlToNode(control, ref controlIndiciesNextFreeIndex, parent.leftChildIndex); } else if (control.m_StateBlock.effectiveBitOffset == left.endBitOffset && control.m_StateBlock.effectiveBitOffset + control.m_StateBlock.sizeInBits == right.endBitOffset) { AddControlToNode(control, ref controlIndiciesNextFreeIndex, parent.leftChildIndex + 1); } else if (control.m_StateBlock.effectiveBitOffset < left.endBitOffset) { InsertControlBitRangeNode(ref m_Device.m_ControlTreeNodes[parent.leftChildIndex], control, ref controlIndiciesNextFreeIndex, startOffset); } else { InsertControlBitRangeNode(ref m_Device.m_ControlTreeNodes[parent.leftChildIndex + 1], control, ref controlIndiciesNextFreeIndex, left.endBitOffset); } } private ushort GetBestMidPoint(InputDevice.ControlBitRangeNode parent, ushort startOffset) { ushort num = (ushort)(startOffset + ((parent.endBitOffset - startOffset - 1) / 2 + 1)); ushort num2 = ushort.MaxValue; ushort num3 = ushort.MaxValue; InputControl[] childrenForEachControl = m_Device.m_ChildrenForEachControl; for (int i = 0; i < childrenForEachControl.Length; i++) { InputStateBlock stateBlock = childrenForEachControl[i].m_StateBlock; if (stateBlock.effectiveBitOffset + stateBlock.sizeInBits - 1 >= startOffset && stateBlock.effectiveBitOffset < parent.endBitOffset && stateBlock.sizeInBits <= parent.endBitOffset - startOffset && stateBlock.effectiveBitOffset != startOffset && stateBlock.effectiveBitOffset + stateBlock.sizeInBits != parent.endBitOffset) { if (Math.Abs(stateBlock.effectiveBitOffset + stateBlock.sizeInBits - (int)num) < Math.Abs(num2 - num) && stateBlock.effectiveBitOffset + stateBlock.sizeInBits < parent.endBitOffset) { num2 = (ushort)(stateBlock.effectiveBitOffset + stateBlock.sizeInBits); } if (Math.Abs(stateBlock.effectiveBitOffset - (int)num) < Math.Abs(num3 - num) && stateBlock.effectiveBitOffset >= startOffset) { num3 = (ushort)stateBlock.effectiveBitOffset; } } } int num4 = 0; int num5 = 0; int num6 = 0; childrenForEachControl = m_Device.m_ChildrenForEachControl; foreach (InputControl inputControl in childrenForEachControl) { if (num3 != ushort.MaxValue && num3 > inputControl.m_StateBlock.effectiveBitOffset && num3 < inputControl.m_StateBlock.effectiveBitOffset + inputControl.m_StateBlock.sizeInBits) { num5++; } if (num2 != ushort.MaxValue && num2 > inputControl.m_StateBlock.effectiveBitOffset && num2 < inputControl.m_StateBlock.effectiveBitOffset + inputControl.m_StateBlock.sizeInBits) { num6++; } if (num > inputControl.m_StateBlock.effectiveBitOffset && num < inputControl.m_StateBlock.effectiveBitOffset + inputControl.m_StateBlock.sizeInBits) { num4++; } } if (num2 != ushort.MaxValue && num6 <= num5 && num6 <= num4) { return num2; } if (num3 != ushort.MaxValue && num5 <= num6 && num5 <= num4) { return num3; } return num; } private void AddControlToNode(InputControl control, ref int controlIndiciesNextFreeIndex, int nodeIndex) { ref InputDevice.ControlBitRangeNode reference = ref m_Device.m_ControlTreeNodes[nodeIndex]; ushort controlStartIndex = reference.controlStartIndex; if (reference.controlCount == 0) { reference.controlStartIndex = (ushort)controlIndiciesNextFreeIndex; controlStartIndex = reference.controlStartIndex; } ArrayHelpers.InsertAt(ref m_Device.m_ControlTreeIndices, reference.controlStartIndex + reference.controlCount, GetControlIndex(control)); reference.controlCount++; controlIndiciesNextFreeIndex++; for (int i = 0; i < m_Device.m_ControlTreeNodes.Length; i++) { if (m_Device.m_ControlTreeNodes[i].controlCount != 0 && m_Device.m_ControlTreeNodes[i].controlStartIndex > controlStartIndex) { m_Device.m_ControlTreeNodes[i].controlStartIndex++; } } } private void AddChildren(ref InputDevice.ControlBitRangeNode parent, InputDevice.ControlBitRangeNode left, InputDevice.ControlBitRangeNode right) { if (parent.leftChildIndex == -1) { int num = m_Device.m_ControlTreeNodes.Length; parent.leftChildIndex = (short)num; Array.Resize(ref m_Device.m_ControlTreeNodes, num + 2); m_Device.m_ControlTreeNodes[num] = left; m_Device.m_ControlTreeNodes[num + 1] = right; } } private ushort GetControlIndex(InputControl control) { for (int i = 0; i < m_Device.m_ChildrenForEachControl.Length; i++) { if (control == m_Device.m_ChildrenForEachControl[i]) { return (ushort)i; } } throw new InvalidOperationException($"InputDeviceBuilder error. Couldn't find control {control}."); } internal static RefInstance Ref() { s_InstanceRef++; return default(RefInstance); } } [Serializable] public struct InputDeviceDescription : IEquatable { private struct DeviceDescriptionJson { public string @interface; public string type; public string product; public string serial; public string version; public string manufacturer; public string capabilities; } [SerializeField] private string m_InterfaceName; [SerializeField] private string m_DeviceClass; [SerializeField] private string m_Manufacturer; [SerializeField] private string m_Product; [SerializeField] private string m_Serial; [SerializeField] private string m_Version; [SerializeField] private string m_Capabilities; public string interfaceName { get { return m_InterfaceName; } set { m_InterfaceName = value; } } public string deviceClass { get { return m_DeviceClass; } set { m_DeviceClass = value; } } public string manufacturer { get { return m_Manufacturer; } set { m_Manufacturer = value; } } public string product { get { return m_Product; } set { m_Product = value; } } public string serial { get { return m_Serial; } set { m_Serial = value; } } public string version { get { return m_Version; } set { m_Version = value; } } public string capabilities { get { return m_Capabilities; } set { m_Capabilities = value; } } public bool empty { get { if (string.IsNullOrEmpty(m_InterfaceName) && string.IsNullOrEmpty(m_DeviceClass) && string.IsNullOrEmpty(m_Manufacturer) && string.IsNullOrEmpty(m_Product) && string.IsNullOrEmpty(m_Serial) && string.IsNullOrEmpty(m_Version)) { return string.IsNullOrEmpty(m_Capabilities); } return false; } } public override string ToString() { bool flag = !string.IsNullOrEmpty(product); bool flag2 = !string.IsNullOrEmpty(manufacturer); bool flag3 = !string.IsNullOrEmpty(interfaceName); if (flag && flag2) { if (flag3) { return manufacturer + " " + product + " (" + interfaceName + ")"; } return manufacturer + " " + product; } if (flag) { if (flag3) { return product + " (" + interfaceName + ")"; } return product; } if (!string.IsNullOrEmpty(deviceClass)) { if (flag3) { return deviceClass + " (" + interfaceName + ")"; } return deviceClass; } if (!string.IsNullOrEmpty(capabilities)) { string text = capabilities; if (capabilities.Length > 40) { text = text.Substring(0, 40) + "..."; } if (flag3) { return text + " (" + interfaceName + ")"; } return text; } if (flag3) { return interfaceName; } return ""; } public bool Equals(InputDeviceDescription other) { if (m_InterfaceName.InvariantEqualsIgnoreCase(other.m_InterfaceName) && m_DeviceClass.InvariantEqualsIgnoreCase(other.m_DeviceClass) && m_Manufacturer.InvariantEqualsIgnoreCase(other.m_Manufacturer) && m_Product.InvariantEqualsIgnoreCase(other.m_Product) && m_Serial.InvariantEqualsIgnoreCase(other.m_Serial) && m_Version.InvariantEqualsIgnoreCase(other.m_Version)) { return m_Capabilities.InvariantEqualsIgnoreCase(other.m_Capabilities); } return false; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputDeviceDescription other) { return Equals(other); } return false; } public override int GetHashCode() { return (((((((((((((m_InterfaceName != null) ? m_InterfaceName.GetHashCode() : 0) * 397) ^ ((m_DeviceClass != null) ? m_DeviceClass.GetHashCode() : 0)) * 397) ^ ((m_Manufacturer != null) ? m_Manufacturer.GetHashCode() : 0)) * 397) ^ ((m_Product != null) ? m_Product.GetHashCode() : 0)) * 397) ^ ((m_Serial != null) ? m_Serial.GetHashCode() : 0)) * 397) ^ ((m_Version != null) ? m_Version.GetHashCode() : 0)) * 397) ^ ((m_Capabilities != null) ? m_Capabilities.GetHashCode() : 0); } public static bool operator ==(InputDeviceDescription left, InputDeviceDescription right) { return left.Equals(right); } public static bool operator !=(InputDeviceDescription left, InputDeviceDescription right) { return !left.Equals(right); } public string ToJson() { return JsonUtility.ToJson((object)new DeviceDescriptionJson { @interface = interfaceName, type = deviceClass, product = product, manufacturer = manufacturer, serial = serial, version = version, capabilities = capabilities }, true); } public static InputDeviceDescription FromJson(string json) { if (json == null) { throw new ArgumentNullException("json"); } DeviceDescriptionJson deviceDescriptionJson = JsonUtility.FromJson(json); return new InputDeviceDescription { interfaceName = deviceDescriptionJson.@interface, deviceClass = deviceDescriptionJson.type, product = deviceDescriptionJson.product, manufacturer = deviceDescriptionJson.manufacturer, serial = deviceDescriptionJson.serial, version = deviceDescriptionJson.version, capabilities = deviceDescriptionJson.capabilities }; } internal static bool ComparePropertyToDeviceDescriptor(string propertyName, string propertyValue, string deviceDescriptor) { JsonParser jsonParser = new JsonParser(deviceDescriptor); if (!jsonParser.NavigateToProperty(propertyName)) { if (string.IsNullOrEmpty(propertyValue)) { return true; } return false; } return jsonParser.CurrentPropertyHasValueEqualTo(propertyValue); } } public struct InputDeviceMatcher : IEquatable { [Serializable] internal struct MatcherJson { public struct Capability { public string path; public string value; } public string @interface; public string[] interfaces; public string deviceClass; public string[] deviceClasses; public string manufacturer; public string[] manufacturers; public string product; public string[] products; public string version; public string[] versions; public Capability[] capabilities; public static MatcherJson FromMatcher(InputDeviceMatcher matcher) { if (matcher.empty) { return default(MatcherJson); } MatcherJson result = default(MatcherJson); KeyValuePair[] patterns = matcher.m_Patterns; for (int i = 0; i < patterns.Length; i++) { KeyValuePair keyValuePair = patterns[i]; InternedString key = keyValuePair.Key; string text = keyValuePair.Value.ToString(); if (key == kInterfaceKey) { if (result.@interface == null) { result.@interface = text; } else { ArrayHelpers.Append(ref result.interfaces, text); } } else if (key == kDeviceClassKey) { if (result.deviceClass == null) { result.deviceClass = text; } else { ArrayHelpers.Append(ref result.deviceClasses, text); } } else if (key == kManufacturerKey) { if (result.manufacturer == null) { result.manufacturer = text; } else { ArrayHelpers.Append(ref result.manufacturers, text); } } else if (key == kProductKey) { if (result.product == null) { result.product = text; } else { ArrayHelpers.Append(ref result.products, text); } } else if (key == kVersionKey) { if (result.version == null) { result.version = text; } else { ArrayHelpers.Append(ref result.versions, text); } } else { ArrayHelpers.Append(ref result.capabilities, new Capability { path = key, value = text }); } } return result; } public InputDeviceMatcher ToMatcher() { InputDeviceMatcher result = default(InputDeviceMatcher); if (!string.IsNullOrEmpty(@interface)) { result = result.WithInterface(@interface); } if (interfaces != null) { string[] array = interfaces; foreach (string pattern in array) { result = result.WithInterface(pattern); } } if (!string.IsNullOrEmpty(deviceClass)) { result = result.WithDeviceClass(deviceClass); } if (deviceClasses != null) { string[] array = deviceClasses; foreach (string pattern2 in array) { result = result.WithDeviceClass(pattern2); } } if (!string.IsNullOrEmpty(manufacturer)) { result = result.WithManufacturer(manufacturer); } if (manufacturers != null) { string[] array = manufacturers; foreach (string pattern3 in array) { result = result.WithManufacturer(pattern3); } } if (!string.IsNullOrEmpty(product)) { result = result.WithProduct(product); } if (products != null) { string[] array = products; foreach (string pattern4 in array) { result = result.WithProduct(pattern4); } } if (!string.IsNullOrEmpty(version)) { result = result.WithVersion(version); } if (versions != null) { string[] array = versions; foreach (string pattern5 in array) { result = result.WithVersion(pattern5); } } if (capabilities != null) { Capability[] array2 = capabilities; for (int i = 0; i < array2.Length; i++) { Capability capability = array2[i]; result = result.WithCapability(capability.path, capability.value); } } return result; } } private KeyValuePair[] m_Patterns; private static readonly InternedString kInterfaceKey = new InternedString("interface"); private static readonly InternedString kDeviceClassKey = new InternedString("deviceClass"); private static readonly InternedString kManufacturerKey = new InternedString("manufacturer"); private static readonly InternedString kProductKey = new InternedString("product"); private static readonly InternedString kVersionKey = new InternedString("version"); public bool empty => m_Patterns == null; public IEnumerable> patterns { get { if (m_Patterns != null) { int count = m_Patterns.Length; int i = 0; while (i < count) { yield return new KeyValuePair(m_Patterns[i].Key.ToString(), m_Patterns[i].Value); int num = i + 1; i = num; } } } } public InputDeviceMatcher WithInterface(string pattern, bool supportRegex = true) { return With(kInterfaceKey, pattern, supportRegex); } public InputDeviceMatcher WithDeviceClass(string pattern, bool supportRegex = true) { return With(kDeviceClassKey, pattern, supportRegex); } public InputDeviceMatcher WithManufacturer(string pattern, bool supportRegex = true) { return With(kManufacturerKey, pattern, supportRegex); } public InputDeviceMatcher WithProduct(string pattern, bool supportRegex = true) { return With(kProductKey, pattern, supportRegex); } public InputDeviceMatcher WithVersion(string pattern, bool supportRegex = true) { return With(kVersionKey, pattern, supportRegex); } public InputDeviceMatcher WithCapability(string path, TValue value) { return With(new InternedString(path), value); } private InputDeviceMatcher With(InternedString key, object value, bool supportRegex = true) { if (supportRegex && value is string text && !text.All((char ch) => char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)) && !double.TryParse(text, out var _)) { value = new Regex(text, RegexOptions.IgnoreCase); } InputDeviceMatcher result2 = this; ArrayHelpers.Append(ref result2.m_Patterns, new KeyValuePair(key, value)); return result2; } public float MatchPercentage(InputDeviceDescription deviceDescription) { if (empty) { return 0f; } int num = m_Patterns.Length; for (int i = 0; i < num; i++) { InternedString key = m_Patterns[i].Key; object value = m_Patterns[i].Value; if (key == kInterfaceKey) { if (string.IsNullOrEmpty(deviceDescription.interfaceName) || !MatchSingleProperty(value, deviceDescription.interfaceName)) { return 0f; } continue; } if (key == kDeviceClassKey) { if (string.IsNullOrEmpty(deviceDescription.deviceClass) || !MatchSingleProperty(value, deviceDescription.deviceClass)) { return 0f; } continue; } if (key == kManufacturerKey) { if (string.IsNullOrEmpty(deviceDescription.manufacturer) || !MatchSingleProperty(value, deviceDescription.manufacturer)) { return 0f; } continue; } if (key == kProductKey) { if (string.IsNullOrEmpty(deviceDescription.product) || !MatchSingleProperty(value, deviceDescription.product)) { return 0f; } continue; } if (key == kVersionKey) { if (string.IsNullOrEmpty(deviceDescription.version) || !MatchSingleProperty(value, deviceDescription.version)) { return 0f; } continue; } if (string.IsNullOrEmpty(deviceDescription.capabilities)) { return 0f; } JsonParser jsonParser = new JsonParser(deviceDescription.capabilities); if (!jsonParser.NavigateToProperty(key.ToString()) || !jsonParser.CurrentPropertyHasValueEqualTo(new JsonParser.JsonValue { type = JsonParser.JsonValueType.Any, anyValue = value })) { return 0f; } } int numPropertiesIn = GetNumPropertiesIn(deviceDescription); float num2 = 1f / (float)numPropertiesIn; return (float)num * num2; } private static bool MatchSingleProperty(object pattern, string value) { if (pattern is string strA) { return string.Compare(strA, value, StringComparison.OrdinalIgnoreCase) == 0; } if (pattern is Regex regex) { return regex.IsMatch(value); } return false; } private static int GetNumPropertiesIn(InputDeviceDescription description) { int num = 0; if (!string.IsNullOrEmpty(description.interfaceName)) { num++; } if (!string.IsNullOrEmpty(description.deviceClass)) { num++; } if (!string.IsNullOrEmpty(description.manufacturer)) { num++; } if (!string.IsNullOrEmpty(description.product)) { num++; } if (!string.IsNullOrEmpty(description.version)) { num++; } if (!string.IsNullOrEmpty(description.capabilities)) { num++; } return num; } public static InputDeviceMatcher FromDeviceDescription(InputDeviceDescription deviceDescription) { InputDeviceMatcher result = default(InputDeviceMatcher); if (!string.IsNullOrEmpty(deviceDescription.interfaceName)) { result = result.WithInterface(deviceDescription.interfaceName, supportRegex: false); } if (!string.IsNullOrEmpty(deviceDescription.deviceClass)) { result = result.WithDeviceClass(deviceDescription.deviceClass, supportRegex: false); } if (!string.IsNullOrEmpty(deviceDescription.manufacturer)) { result = result.WithManufacturer(deviceDescription.manufacturer, supportRegex: false); } if (!string.IsNullOrEmpty(deviceDescription.product)) { result = result.WithProduct(deviceDescription.product, supportRegex: false); } if (!string.IsNullOrEmpty(deviceDescription.version)) { result = result.WithVersion(deviceDescription.version, supportRegex: false); } return result; } public override string ToString() { if (empty) { return ""; } string text = string.Empty; KeyValuePair[] array = m_Patterns; for (int i = 0; i < array.Length; i++) { KeyValuePair keyValuePair = array[i]; text = ((text.Length <= 0) ? (text + $"{keyValuePair.Key}={keyValuePair.Value}") : (text + $",{keyValuePair.Key}={keyValuePair.Value}")); } return text; } public bool Equals(InputDeviceMatcher other) { if (m_Patterns == other.m_Patterns) { return true; } if (m_Patterns == null || other.m_Patterns == null) { return false; } if (m_Patterns.Length != other.m_Patterns.Length) { return false; } for (int i = 0; i < m_Patterns.Length; i++) { KeyValuePair keyValuePair = m_Patterns[i]; bool flag = false; for (int j = 0; j < m_Patterns.Length; j++) { KeyValuePair keyValuePair2 = other.m_Patterns[j]; if (!(keyValuePair.Key != keyValuePair2.Key)) { if (!keyValuePair.Value.Equals(keyValuePair2.Value)) { return false; } flag = true; break; } } if (!flag) { return false; } } return true; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InputDeviceMatcher other) { return Equals(other); } return false; } public static bool operator ==(InputDeviceMatcher left, InputDeviceMatcher right) { return left.Equals(right); } public static bool operator !=(InputDeviceMatcher left, InputDeviceMatcher right) { return !(left == right); } public override int GetHashCode() { if (m_Patterns == null) { return 0; } return m_Patterns.GetHashCode(); } } } namespace UnityEngine.InputSystem.Controls { [InputControlLayout(hideInUI = true)] public class AnyKeyControl : ButtonControl { public AnyKeyControl() { m_StateBlock.sizeInBits = 1u; m_StateBlock.format = InputStateBlock.FormatBit; } public unsafe override float ReadUnprocessedValueFromState(void* statePtr) { if (!this.CheckStateIsAtDefault(statePtr, null)) { return 1f; } return 0f; } } public class AxisControl : InputControl { public enum Clamp { None, BeforeNormalize, AfterNormalize, ToConstantBeforeNormalize } public Clamp clamp; public float clampMin; public float clampMax; public float clampConstant; public bool invert; public bool normalize; public float normalizeMin; public float normalizeMax; public float normalizeZero; public bool scale; public float scaleFactor; [MethodImpl(MethodImplOptions.AggressiveInlining)] protected float Preprocess(float value) { if (scale) { value *= scaleFactor; } if (clamp == Clamp.ToConstantBeforeNormalize) { if (value < clampMin || value > clampMax) { value = clampConstant; } } else if (clamp == Clamp.BeforeNormalize) { value = Mathf.Clamp(value, clampMin, clampMax); } if (normalize) { value = NormalizeProcessor.Normalize(value, normalizeMin, normalizeMax, normalizeZero); } if (clamp == Clamp.AfterNormalize) { value = Mathf.Clamp(value, clampMin, clampMax); } if (invert) { value *= -1f; } return value; } private float Unpreprocess(float value) { if (invert) { value *= -1f; } if (normalize) { value = NormalizeProcessor.Denormalize(value, normalizeMin, normalizeMax, normalizeZero); } if (scale) { value /= scaleFactor; } return value; } public AxisControl() { m_StateBlock.format = InputStateBlock.FormatFloat; } protected override void FinishSetup() { base.FinishSetup(); if (!base.hasDefaultState && normalize && Mathf.Abs(normalizeZero) > Mathf.Epsilon) { m_DefaultState = base.stateBlock.FloatToPrimitiveValue(normalizeZero); } } public unsafe override float ReadUnprocessedValueFromState(void* statePtr) { switch (m_OptimizedControlDataType) { case 1179407392: return *(float*)((byte*)statePtr + m_StateBlock.m_ByteOffset); case 1113150533: if (((byte*)statePtr)[m_StateBlock.m_ByteOffset] == 0) { return 0f; } return 1f; default: { float num = base.stateBlock.ReadFloat(statePtr); return Preprocess(num); } } } public unsafe override void WriteValueIntoState(float value, void* statePtr) { switch (m_OptimizedControlDataType) { case 1179407392: *(float*)((byte*)statePtr + m_StateBlock.m_ByteOffset) = value; break; case 1113150533: ((sbyte*)statePtr)[m_StateBlock.m_ByteOffset] = ((value >= 0.5f) ? ((sbyte)1) : ((sbyte)0)); break; default: value = Unpreprocess(value); base.stateBlock.WriteFloat(statePtr, value); break; } } public unsafe override bool CompareValue(void* firstStatePtr, void* secondStatePtr) { float num = ReadValueFromState(firstStatePtr); float num2 = ReadValueFromState(secondStatePtr); return !Mathf.Approximately(num, num2); } public unsafe override float EvaluateMagnitude(void* statePtr) { return EvaluateMagnitude(ReadValueFromStateWithCaching(statePtr)); } private float EvaluateMagnitude(float value) { if (m_MinValue.isEmpty || m_MaxValue.isEmpty) { return Mathf.Abs(value); } float num = m_MinValue.ToSingle(); float num2 = m_MaxValue.ToSingle(); float num3 = Mathf.Clamp(value, num, num2); if (num < 0f) { if (num3 < 0f) { return NormalizeProcessor.Normalize(Mathf.Abs(num3), 0f, Mathf.Abs(num), 0f); } return NormalizeProcessor.Normalize(num3, 0f, num2, 0f); } return NormalizeProcessor.Normalize(num3, num, num2, 0f); } protected override FourCC CalculateOptimizedControlDataType() { bool flag = clamp == Clamp.None && !invert && !normalize && !scale; if (flag && m_StateBlock.format == InputStateBlock.FormatFloat && m_StateBlock.sizeInBits == 32 && m_StateBlock.bitOffset == 0) { return InputStateBlock.FormatFloat; } if (flag && m_StateBlock.format == InputStateBlock.FormatBit && m_StateBlock.sizeInBits == 8 && m_StateBlock.bitOffset == 0) { return InputStateBlock.FormatByte; } return InputStateBlock.FormatInvalid; } } public class ButtonControl : AxisControl { public float pressPoint = -1f; internal static float s_GlobalDefaultButtonPressPoint; internal static float s_GlobalDefaultButtonReleaseThreshold; internal const float kMinButtonPressPoint = 0.0001f; public float pressPointOrDefault { get { if (!(pressPoint > 0f)) { return s_GlobalDefaultButtonPressPoint; } return pressPoint; } } public bool isPressed => IsValueConsideredPressed(base.value); public bool wasPressedThisFrame { get { if (base.device.wasUpdatedThisFrame && IsValueConsideredPressed(base.value)) { return !IsValueConsideredPressed(ReadValueFromPreviousFrame()); } return false; } } public bool wasReleasedThisFrame { get { if (base.device.wasUpdatedThisFrame && !IsValueConsideredPressed(base.value)) { return IsValueConsideredPressed(ReadValueFromPreviousFrame()); } return false; } } public ButtonControl() { m_StateBlock.format = InputStateBlock.FormatBit; m_MinValue = 0f; m_MaxValue = 1f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public new bool IsValueConsideredPressed(float value) { return value >= pressPointOrDefault; } } [Preserve] public class DeltaControl : Vector2Control { [InputControl(useStateFrom = "y", parameters = "clamp=1,clampMin=0,clampMax=3.402823E+38", synthetic = true, displayName = "Up")] [Preserve] public AxisControl up { get; set; } [InputControl(useStateFrom = "y", parameters = "clamp=1,clampMin=-3.402823E+38,clampMax=0,invert", synthetic = true, displayName = "Down")] [Preserve] public AxisControl down { get; set; } [InputControl(useStateFrom = "x", parameters = "clamp=1,clampMin=-3.402823E+38,clampMax=0,invert", synthetic = true, displayName = "Left")] [Preserve] public AxisControl left { get; set; } [InputControl(useStateFrom = "x", parameters = "clamp=1,clampMin=0,clampMax=3.402823E+38", synthetic = true, displayName = "Right")] [Preserve] public AxisControl right { get; set; } protected override void FinishSetup() { base.FinishSetup(); up = GetChildControl("up"); down = GetChildControl("down"); left = GetChildControl("left"); right = GetChildControl("right"); } } public class DiscreteButtonControl : ButtonControl { public enum WriteMode { WriteDisabled, WriteNullAndMaxValue } public int minValue; public int maxValue; public int wrapAtValue; public int nullValue; public WriteMode writeMode; protected override void FinishSetup() { base.FinishSetup(); if (!base.stateBlock.format.IsIntegerFormat()) { throw new NotSupportedException($"Non-integer format '{base.stateBlock.format}' is not supported for DiscreteButtonControl '{this}'"); } } public unsafe override float ReadUnprocessedValueFromState(void* statePtr) { int num = MemoryHelpers.ReadTwosComplementMultipleBitsAsInt((byte*)statePtr + (int)m_StateBlock.byteOffset, m_StateBlock.bitOffset, m_StateBlock.sizeInBits); float num2 = 0f; if (minValue > maxValue) { if (wrapAtValue == nullValue) { wrapAtValue = minValue; } if ((num >= minValue && num <= wrapAtValue) || (num != nullValue && num <= maxValue)) { num2 = 1f; } } else { num2 = ((num >= minValue && num <= maxValue) ? 1f : 0f); } return Preprocess(num2); } public unsafe override void WriteValueIntoState(float value, void* statePtr) { if (writeMode == WriteMode.WriteNullAndMaxValue) { MemoryHelpers.WriteIntAsTwosComplementMultipleBits((byte*)statePtr + (int)m_StateBlock.byteOffset, value: (value >= base.pressPointOrDefault) ? maxValue : nullValue, bitOffset: m_StateBlock.bitOffset, bitCount: m_StateBlock.sizeInBits); return; } throw new NotSupportedException("Writing value states for DiscreteButtonControl is not supported as a single value may correspond to multiple states"); } } public class DoubleControl : InputControl { public DoubleControl() { m_StateBlock.format = InputStateBlock.FormatDouble; } public unsafe override double ReadUnprocessedValueFromState(void* statePtr) { return m_StateBlock.ReadDouble(statePtr); } public unsafe override void WriteValueIntoState(double value, void* statePtr) { m_StateBlock.WriteDouble(statePtr, value); } } public class DpadControl : Vector2Control { [InputControlLayout(hideInUI = true)] public class DpadAxisControl : AxisControl { public int component { get; set; } protected override void FinishSetup() { base.FinishSetup(); component = ((!(base.name == "x")) ? 1 : 0); m_StateBlock = m_Parent.m_StateBlock; } public unsafe override float ReadUnprocessedValueFromState(void* statePtr) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) Vector2 val = ((DpadControl)m_Parent).ReadUnprocessedValueFromState(statePtr); return ((Vector2)(ref val))[component]; } } internal enum ButtonBits { Up, Down, Left, Right } [InputControl(name = "x", layout = "DpadAxis", useStateFrom = "right", synthetic = true)] [InputControl(name = "y", layout = "DpadAxis", useStateFrom = "up", synthetic = true)] [InputControl(bit = 0u, displayName = "Up")] public ButtonControl up { get; set; } [InputControl(bit = 1u, displayName = "Down")] public ButtonControl down { get; set; } [InputControl(bit = 2u, displayName = "Left")] public ButtonControl left { get; set; } [InputControl(bit = 3u, displayName = "Right")] public ButtonControl right { get; set; } public DpadControl() { m_StateBlock.sizeInBits = 4u; m_StateBlock.format = InputStateBlock.FormatBit; } protected override void FinishSetup() { up = GetChildControl("up"); down = GetChildControl("down"); left = GetChildControl("left"); right = GetChildControl("right"); base.FinishSetup(); } public unsafe override Vector2 ReadUnprocessedValueFromState(void* statePtr) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) bool num = up.ReadValueFromStateWithCaching(statePtr) >= up.pressPointOrDefault; bool flag = down.ReadValueFromStateWithCaching(statePtr) >= down.pressPointOrDefault; bool flag2 = left.ReadValueFromStateWithCaching(statePtr) >= left.pressPointOrDefault; bool flag3 = right.ReadValueFromStateWithCaching(statePtr) >= right.pressPointOrDefault; return MakeDpadVector(num, flag, flag2, flag3); } public unsafe override void WriteValueIntoState(Vector2 value, void* statePtr) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) bool flag = up.IsValueConsideredPressed(value.y); bool flag2 = down.IsValueConsideredPressed(value.y * -1f); bool flag3 = left.IsValueConsideredPressed(value.x * -1f); bool flag4 = right.IsValueConsideredPressed(value.x); up.WriteValueIntoState((flag && !flag2) ? value.y : 0f, statePtr); down.WriteValueIntoState((flag2 && !flag) ? (value.y * -1f) : 0f, statePtr); left.WriteValueIntoState((flag3 && !flag4) ? (value.x * -1f) : 0f, statePtr); right.WriteValueIntoState((flag4 && !flag3) ? value.x : 0f, statePtr); } public static Vector2 MakeDpadVector(bool up, bool down, bool left, bool right, bool normalize = true) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) float num = (up ? 1f : 0f); float num2 = (down ? (-1f) : 0f); float num3 = (left ? (-1f) : 0f); float num4 = (right ? 1f : 0f); Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(num3 + num4, num + num2); if (normalize && val.x != 0f && val.y != 0f) { ((Vector2)(ref val))..ctor(val.x * 0.707107f, val.y * 0.707107f); } return val; } public static Vector2 MakeDpadVector(float up, float down, float left, float right) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return new Vector2(0f - left + right, up - down); } } public class IntegerControl : InputControl { public IntegerControl() { m_StateBlock.format = InputStateBlock.FormatInt; } public unsafe override int ReadUnprocessedValueFromState(void* statePtr) { if ((int)m_OptimizedControlDataType == 1229870112) { return *(int*)((byte*)statePtr + (int)m_StateBlock.byteOffset); } return m_StateBlock.ReadInt(statePtr); } public unsafe override void WriteValueIntoState(int value, void* statePtr) { if ((int)m_OptimizedControlDataType == 1229870112) { *(int*)((byte*)statePtr + (int)m_StateBlock.byteOffset) = value; } else { m_StateBlock.WriteInt(statePtr, value); } } protected override FourCC CalculateOptimizedControlDataType() { if (m_StateBlock.format == InputStateBlock.FormatInt && m_StateBlock.sizeInBits == 32 && m_StateBlock.bitOffset == 0) { return InputStateBlock.FormatInt; } return InputStateBlock.FormatInvalid; } } public class KeyControl : ButtonControl { private int m_ScanCode; public Key keyCode { get; set; } public int scanCode { get { RefreshConfigurationIfNeeded(); return m_ScanCode; } } protected override void RefreshConfiguration() { base.displayName = null; m_ScanCode = 0; QueryKeyNameCommand command = QueryKeyNameCommand.Create(keyCode); if (base.device.ExecuteCommand(ref command) <= 0) { return; } m_ScanCode = command.scanOrKeyCode; string str = command.ReadKeyName(); if (string.IsNullOrEmpty(str)) { base.displayName = str; return; } TextInfo textInfo = CultureInfo.InvariantCulture.TextInfo; string str2 = textInfo.ToLower(str); if (string.IsNullOrEmpty(str2)) { base.displayName = str; } else { base.displayName = textInfo.ToTitleCase(str2); } } } public class QuaternionControl : InputControl { [InputControl(displayName = "X")] public AxisControl x { get; private set; } [InputControl(displayName = "Y")] public AxisControl y { get; private set; } [InputControl(displayName = "Z")] public AxisControl z { get; private set; } [InputControl(displayName = "W")] public AxisControl w { get; private set; } public QuaternionControl() { m_StateBlock.sizeInBits = 128u; m_StateBlock.format = InputStateBlock.FormatQuaternion; } protected override void FinishSetup() { x = GetChildControl("x"); y = GetChildControl("y"); z = GetChildControl("z"); w = GetChildControl("w"); base.FinishSetup(); } public unsafe override Quaternion ReadUnprocessedValueFromState(void* statePtr) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1364541780) { return (Quaternion)((byte*)statePtr)[(int)m_StateBlock.byteOffset]; } return new Quaternion(x.ReadValueFromStateWithCaching(statePtr), y.ReadValueFromStateWithCaching(statePtr), z.ReadValueFromStateWithCaching(statePtr), w.ReadUnprocessedValueFromStateWithCaching(statePtr)); } public unsafe override void WriteValueIntoState(Quaternion value, void* statePtr) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1364541780) { Unsafe.Write((byte*)statePtr + (int)m_StateBlock.byteOffset, value); return; } x.WriteValueIntoState(value.x, statePtr); y.WriteValueIntoState(value.y, statePtr); z.WriteValueIntoState(value.z, statePtr); w.WriteValueIntoState(value.w, statePtr); } protected override FourCC CalculateOptimizedControlDataType() { if (m_StateBlock.sizeInBits == 128 && m_StateBlock.bitOffset == 0 && x.optimizedControlDataType == InputStateBlock.FormatFloat && y.optimizedControlDataType == InputStateBlock.FormatFloat && z.optimizedControlDataType == InputStateBlock.FormatFloat && w.optimizedControlDataType == InputStateBlock.FormatFloat && y.m_StateBlock.byteOffset == x.m_StateBlock.byteOffset + 4 && z.m_StateBlock.byteOffset == x.m_StateBlock.byteOffset + 8 && w.m_StateBlock.byteOffset == x.m_StateBlock.byteOffset + 12 && x.m_ProcessorStack.length == 0 && y.m_ProcessorStack.length == 0 && z.m_ProcessorStack.length == 0) { return InputStateBlock.FormatQuaternion; } return InputStateBlock.FormatInvalid; } } public class StickControl : Vector2Control { [InputControl(useStateFrom = "y", processors = "axisDeadzone", parameters = "clamp=2,clampMin=0,clampMax=1", synthetic = true, displayName = "Up")] [InputControl(name = "x", minValue = -1f, maxValue = 1f, layout = "Axis", processors = "axisDeadzone")] [InputControl(name = "y", minValue = -1f, maxValue = 1f, layout = "Axis", processors = "axisDeadzone")] public ButtonControl up { get; set; } [InputControl(useStateFrom = "y", processors = "axisDeadzone", parameters = "clamp=2,clampMin=-1,clampMax=0,invert", synthetic = true, displayName = "Down")] public ButtonControl down { get; set; } [InputControl(useStateFrom = "x", processors = "axisDeadzone", parameters = "clamp=2,clampMin=-1,clampMax=0,invert", synthetic = true, displayName = "Left")] public ButtonControl left { get; set; } [InputControl(useStateFrom = "x", processors = "axisDeadzone", parameters = "clamp=2,clampMin=0,clampMax=1", synthetic = true, displayName = "Right")] public ButtonControl right { get; set; } protected override void FinishSetup() { base.FinishSetup(); up = GetChildControl("up"); down = GetChildControl("down"); left = GetChildControl("left"); right = GetChildControl("right"); } } [InputControlLayout(stateType = typeof(TouchState))] public class TouchControl : InputControl { public TouchPressControl press { get; set; } public IntegerControl displayIndex { get; set; } public IntegerControl touchId { get; set; } public Vector2Control position { get; set; } public DeltaControl delta { get; set; } public AxisControl pressure { get; set; } public Vector2Control radius { get; set; } public TouchPhaseControl phase { get; set; } public ButtonControl indirectTouch { get; set; } public ButtonControl tap { get; set; } public IntegerControl tapCount { get; set; } public DoubleControl startTime { get; set; } public Vector2Control startPosition { get; set; } public bool isInProgress { get { TouchPhase touchPhase = phase.value; if ((uint)(touchPhase - 1) <= 1u || touchPhase == TouchPhase.Stationary) { return true; } return false; } } public TouchControl() { m_StateBlock.format = new FourCC('T', 'O', 'U', 'C'); } protected override void FinishSetup() { press = GetChildControl("press"); displayIndex = GetChildControl("displayIndex"); touchId = GetChildControl("touchId"); position = GetChildControl("position"); delta = GetChildControl("delta"); pressure = GetChildControl("pressure"); radius = GetChildControl("radius"); phase = GetChildControl("phase"); indirectTouch = GetChildControl("indirectTouch"); tap = GetChildControl("tap"); tapCount = GetChildControl("tapCount"); startTime = GetChildControl("startTime"); startPosition = GetChildControl("startPosition"); base.FinishSetup(); } public unsafe override TouchState ReadUnprocessedValueFromState(void* statePtr) { TouchState* ptr = (TouchState*)((byte*)statePtr + (int)m_StateBlock.byteOffset); return *ptr; } public unsafe override void WriteValueIntoState(TouchState value, void* statePtr) { TouchState* ptr = (TouchState*)((byte*)statePtr + (int)m_StateBlock.byteOffset); UnsafeUtility.MemCpy((void*)ptr, UnsafeUtility.AddressOf(ref value), (long)UnsafeUtility.SizeOf()); } } [InputControlLayout(hideInUI = true)] public class TouchPhaseControl : InputControl { public TouchPhaseControl() { m_StateBlock.format = InputStateBlock.FormatInt; } public unsafe override TouchPhase ReadUnprocessedValueFromState(void* statePtr) { return (TouchPhase)base.stateBlock.ReadInt(statePtr); } public unsafe override void WriteValueIntoState(TouchPhase value, void* statePtr) { *(TouchPhase*)((byte*)statePtr + (int)m_StateBlock.byteOffset) = value; } } [InputControlLayout(hideInUI = true)] public class TouchPressControl : ButtonControl { protected override void FinishSetup() { base.FinishSetup(); if (!base.stateBlock.format.IsIntegerFormat()) { throw new NotSupportedException($"Non-integer format '{base.stateBlock.format}' is not supported for TouchButtonControl '{this}'"); } } public unsafe override float ReadUnprocessedValueFromState(void* statePtr) { TouchPhase touchPhase = (TouchPhase)MemoryHelpers.ReadMultipleBitsAsUInt((byte*)statePtr + (int)m_StateBlock.byteOffset, m_StateBlock.bitOffset, m_StateBlock.sizeInBits); float num = 0f; if (touchPhase == TouchPhase.Began || touchPhase == TouchPhase.Stationary || touchPhase == TouchPhase.Moved) { num = 1f; } return Preprocess(num); } public unsafe override void WriteValueIntoState(float value, void* statePtr) { throw new NotSupportedException(); } } public class Vector2Control : InputControl { [InputControl(offset = 0u, displayName = "X")] public AxisControl x { get; set; } [InputControl(offset = 4u, displayName = "Y")] public AxisControl y { get; set; } public Vector2Control() { m_StateBlock.format = InputStateBlock.FormatVector2; } protected override void FinishSetup() { x = GetChildControl("x"); y = GetChildControl("y"); base.FinishSetup(); } public unsafe override Vector2 ReadUnprocessedValueFromState(void* statePtr) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1447379762) { return (Vector2)((byte*)statePtr)[(int)m_StateBlock.byteOffset]; } return new Vector2(x.ReadUnprocessedValueFromStateWithCaching(statePtr), y.ReadUnprocessedValueFromStateWithCaching(statePtr)); } public unsafe override void WriteValueIntoState(Vector2 value, void* statePtr) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1447379762) { Unsafe.Write((byte*)statePtr + (int)m_StateBlock.byteOffset, value); return; } x.WriteValueIntoState(value.x, statePtr); y.WriteValueIntoState(value.y, statePtr); } public unsafe override float EvaluateMagnitude(void* statePtr) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) Vector2 val = ReadValueFromStateWithCaching(statePtr); return ((Vector2)(ref val)).magnitude; } protected override FourCC CalculateOptimizedControlDataType() { if (m_StateBlock.sizeInBits == 64 && m_StateBlock.bitOffset == 0 && x.optimizedControlDataType == InputStateBlock.FormatFloat && y.optimizedControlDataType == InputStateBlock.FormatFloat && y.m_StateBlock.byteOffset == x.m_StateBlock.byteOffset + 4) { return InputStateBlock.FormatVector2; } return InputStateBlock.FormatInvalid; } } public class Vector3Control : InputControl { [InputControl(offset = 0u, displayName = "X")] public AxisControl x { get; set; } [InputControl(offset = 4u, displayName = "Y")] public AxisControl y { get; set; } [InputControl(offset = 8u, displayName = "Z")] public AxisControl z { get; set; } public Vector3Control() { m_StateBlock.format = InputStateBlock.FormatVector3; } protected override void FinishSetup() { x = GetChildControl("x"); y = GetChildControl("y"); z = GetChildControl("z"); base.FinishSetup(); } public unsafe override Vector3 ReadUnprocessedValueFromState(void* statePtr) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1447379763) { return (Vector3)((byte*)statePtr)[(int)m_StateBlock.byteOffset]; } return new Vector3(x.ReadUnprocessedValueFromStateWithCaching(statePtr), y.ReadUnprocessedValueFromStateWithCaching(statePtr), z.ReadUnprocessedValueFromStateWithCaching(statePtr)); } public unsafe override void WriteValueIntoState(Vector3 value, void* statePtr) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if ((int)m_OptimizedControlDataType == 1447379763) { Unsafe.Write((byte*)statePtr + (int)m_StateBlock.byteOffset, value); return; } x.WriteValueIntoState(value.x, statePtr); y.WriteValueIntoState(value.y, statePtr); z.WriteValueIntoState(value.z, statePtr); } public unsafe override float EvaluateMagnitude(void* statePtr) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ReadValueFromStateWithCaching(statePtr); return ((Vector3)(ref val)).magnitude; } protected override FourCC CalculateOptimizedControlDataType() { if (m_StateBlock.sizeInBits == 96 && m_StateBlock.bitOffset == 0 && x.optimizedControlDataType == InputStateBlock.FormatFloat && y.optimizedControlDataType == InputStateBlock.FormatFloat && z.optimizedControlDataType == InputStateBlock.FormatFloat && y.m_StateBlock.byteOffset == x.m_StateBlock.byteOffset + 4 && z.m_StateBlock.byteOffset == x.m_StateBlock.byteOffset + 8) { return InputStateBlock.FormatVector3; } return InputStateBlock.FormatInvalid; } } } namespace UnityEngine.InputSystem.Interactions { [DisplayName("Hold")] public class HoldInteraction : IInputInteraction { public float duration; public float pressPoint; private double m_TimePressed; private float durationOrDefault { get { if (!((double)duration > 0.0)) { return InputSystem.settings.defaultHoldTime; } return duration; } } private float pressPointOrDefault { get { if (!((double)pressPoint > 0.0)) { return ButtonControl.s_GlobalDefaultButtonPressPoint; } return pressPoint; } } public void Process(ref InputInteractionContext context) { if (context.timerHasExpired) { context.PerformedAndStayPerformed(); return; } switch (context.phase) { case InputActionPhase.Waiting: if (context.ControlIsActuated(pressPointOrDefault)) { m_TimePressed = context.time; context.Started(); context.SetTimeout(durationOrDefault); } break; case InputActionPhase.Started: if (context.time - m_TimePressed >= (double)durationOrDefault) { context.PerformedAndStayPerformed(); } if (!context.ControlIsActuated()) { context.Canceled(); } break; case InputActionPhase.Performed: if (!context.ControlIsActuated(pressPointOrDefault)) { context.Canceled(); } break; } } public void Reset() { m_TimePressed = 0.0; } } public class MultiTapInteraction : IInputInteraction, IInputInteraction { private enum TapPhase { None, WaitingForNextRelease, WaitingForNextPress } [Tooltip("The maximum time (in seconds) allowed to elapse between pressing and releasing a control for it to register as a tap.")] public float tapTime; [Tooltip("The maximum delay (in seconds) allowed between each tap. If this time is exceeded, the multi-tap is canceled.")] public float tapDelay; [Tooltip("How many taps need to be performed in succession. Two means double-tap, three means triple-tap, and so on.")] public int tapCount = 2; public float pressPoint; private TapPhase m_CurrentTapPhase; private int m_CurrentTapCount; private double m_CurrentTapStartTime; private double m_LastTapReleaseTime; private float tapTimeOrDefault { get { if (!((double)tapTime > 0.0)) { return InputSystem.settings.defaultTapTime; } return tapTime; } } internal float tapDelayOrDefault { get { if (!((double)tapDelay > 0.0)) { return InputSystem.settings.multiTapDelayTime; } return tapDelay; } } private float pressPointOrDefault { get { if (!(pressPoint > 0f)) { return ButtonControl.s_GlobalDefaultButtonPressPoint; } return pressPoint; } } private float releasePointOrDefault => pressPointOrDefault * ButtonControl.s_GlobalDefaultButtonReleaseThreshold; public void Process(ref InputInteractionContext context) { if (context.timerHasExpired) { context.Canceled(); return; } switch (m_CurrentTapPhase) { case TapPhase.None: if (context.ControlIsActuated(pressPointOrDefault)) { m_CurrentTapPhase = TapPhase.WaitingForNextRelease; m_CurrentTapStartTime = context.time; context.Started(); float num = tapTimeOrDefault; float num2 = tapDelayOrDefault; context.SetTimeout(num); context.SetTotalTimeoutCompletionTime(num * (float)tapCount + (float)(tapCount - 1) * num2); } break; case TapPhase.WaitingForNextRelease: if (context.ControlIsActuated(releasePointOrDefault)) { break; } if (context.time - m_CurrentTapStartTime <= (double)tapTimeOrDefault) { m_CurrentTapCount++; if (m_CurrentTapCount >= tapCount) { context.Performed(); break; } m_CurrentTapPhase = TapPhase.WaitingForNextPress; m_LastTapReleaseTime = context.time; context.SetTimeout(tapDelayOrDefault); } else { context.Canceled(); } break; case TapPhase.WaitingForNextPress: if (context.ControlIsActuated(pressPointOrDefault)) { if (context.time - m_LastTapReleaseTime <= (double)tapDelayOrDefault) { m_CurrentTapPhase = TapPhase.WaitingForNextRelease; m_CurrentTapStartTime = context.time; context.SetTimeout(tapTimeOrDefault); } else { context.Canceled(); } } break; } } public void Reset() { m_CurrentTapPhase = TapPhase.None; m_CurrentTapCount = 0; m_CurrentTapStartTime = 0.0; m_LastTapReleaseTime = 0.0; } } [DisplayName("Press")] public class PressInteraction : IInputInteraction { [Tooltip("The amount of actuation a control requires before being considered pressed. If not set, default to 'Default Press Point' in the global input settings.")] public float pressPoint; [Tooltip("Determines how button presses trigger the action. By default (PressOnly), the action is performed on press. With ReleaseOnly, the action is performed on release. With PressAndRelease, the action is performed on press and release.")] public PressBehavior behavior; private bool m_WaitingForRelease; private float pressPointOrDefault { get { if (!(pressPoint > 0f)) { return ButtonControl.s_GlobalDefaultButtonPressPoint; } return pressPoint; } } private float releasePointOrDefault => pressPointOrDefault * ButtonControl.s_GlobalDefaultButtonReleaseThreshold; public void Process(ref InputInteractionContext context) { float num = context.ComputeMagnitude(); switch (behavior) { case PressBehavior.PressOnly: if (m_WaitingForRelease) { if (num <= releasePointOrDefault) { m_WaitingForRelease = false; if (Mathf.Approximately(0f, num)) { context.Canceled(); } else { context.Started(); } } } else if (num >= pressPointOrDefault) { m_WaitingForRelease = true; context.PerformedAndStayPerformed(); } else if (num > 0f && !context.isStarted) { context.Started(); } else if (Mathf.Approximately(0f, num) && context.isStarted) { context.Canceled(); } break; case PressBehavior.ReleaseOnly: { if (m_WaitingForRelease) { if (num <= releasePointOrDefault) { m_WaitingForRelease = false; context.Performed(); context.Canceled(); } break; } if (num >= pressPointOrDefault) { m_WaitingForRelease = true; if (!context.isStarted) { context.Started(); } break; } bool isStarted2 = context.isStarted; if (num > 0f && !isStarted2) { context.Started(); } else if (Mathf.Approximately(0f, num) && isStarted2) { context.Canceled(); } break; } case PressBehavior.PressAndRelease: if (m_WaitingForRelease) { if (num <= releasePointOrDefault) { m_WaitingForRelease = false; context.Performed(); if (Mathf.Approximately(0f, num)) { context.Canceled(); } } } else if (num >= pressPointOrDefault) { m_WaitingForRelease = true; context.PerformedAndStayPerformed(); } else { bool isStarted = context.isStarted; if (num > 0f && !isStarted) { context.Started(); } else if (Mathf.Approximately(0f, num) && isStarted) { context.Canceled(); } } break; } } public void Reset() { m_WaitingForRelease = false; } } public enum PressBehavior { PressOnly, ReleaseOnly, PressAndRelease } [DisplayName("Long Tap")] public class SlowTapInteraction : IInputInteraction { public float duration; public float pressPoint; private double m_SlowTapStartTime; private float durationOrDefault { get { if (!(duration > 0f)) { return InputSystem.settings.defaultSlowTapTime; } return duration; } } private float pressPointOrDefault { get { if (!(pressPoint > 0f)) { return ButtonControl.s_GlobalDefaultButtonPressPoint; } return pressPoint; } } public void Process(ref InputInteractionContext context) { if (context.isWaiting && context.ControlIsActuated(pressPointOrDefault)) { m_SlowTapStartTime = context.time; context.Started(); } else if (context.isStarted && !context.ControlIsActuated(pressPointOrDefault)) { if (context.time - m_SlowTapStartTime >= (double)durationOrDefault) { context.Performed(); } else { context.Canceled(); } } } public void Reset() { m_SlowTapStartTime = 0.0; } } [DisplayName("Tap")] public class TapInteraction : IInputInteraction { public float duration; public float pressPoint; private double m_TapStartTime; private float durationOrDefault { get { if (!((double)duration > 0.0)) { return InputSystem.settings.defaultTapTime; } return duration; } } private float pressPointOrDefault { get { if (!(pressPoint > 0f)) { return ButtonControl.s_GlobalDefaultButtonPressPoint; } return pressPoint; } } private float releasePointOrDefault => pressPointOrDefault * ButtonControl.s_GlobalDefaultButtonReleaseThreshold; public void Process(ref InputInteractionContext context) { if (context.timerHasExpired) { context.Canceled(); } else if (context.isWaiting && context.ControlIsActuated(pressPointOrDefault)) { m_TapStartTime = context.time; context.Started(); context.SetTimeout(durationOrDefault + 1E-05f); } else if (context.isStarted && !context.ControlIsActuated(releasePointOrDefault)) { if (context.time - m_TapStartTime <= (double)durationOrDefault) { context.Performed(); } else { context.Canceled(); } } } public void Reset() { m_TapStartTime = 0.0; } } } namespace UnityEngine.InputSystem.Utilities { public sealed class InputActionTrace : IEnumerable, IEnumerable, IDisposable { public struct ActionEventPtr { internal InputActionState m_State; internal unsafe ActionEvent* m_Ptr; public unsafe InputAction action => m_State.GetActionOrNull(m_Ptr->bindingIndex); public unsafe InputActionPhase phase => m_Ptr->phase; public unsafe InputControl control => m_State.controls[m_Ptr->controlIndex]; public unsafe IInputInteraction interaction { get { int interactionIndex = m_Ptr->interactionIndex; if (interactionIndex == -1) { return null; } return m_State.interactions[interactionIndex]; } } public unsafe double time => m_Ptr->baseEvent.time; public unsafe double startTime => m_Ptr->startTime; public double duration => time - startTime; public unsafe int valueSizeInBytes => m_Ptr->valueSizeInBytes; public unsafe object ReadValueAsObject() { if (m_Ptr == null) { throw new InvalidOperationException("ActionEventPtr is invalid"); } byte* valueData = m_Ptr->valueData; int bindingIndex = m_Ptr->bindingIndex; if (m_State.bindingStates[bindingIndex].isPartOfComposite) { int compositeOrCompositeBindingIndex = m_State.bindingStates[bindingIndex].compositeOrCompositeBindingIndex; int compositeOrCompositeBindingIndex2 = m_State.bindingStates[compositeOrCompositeBindingIndex].compositeOrCompositeBindingIndex; InputBindingComposite inputBindingComposite = m_State.composites[compositeOrCompositeBindingIndex2]; Type valueType = inputBindingComposite.valueType; if (valueType == null) { throw new InvalidOperationException($"Cannot read value from Composite '{inputBindingComposite}' which does not have a valueType set"); } return Marshal.PtrToStructure(new IntPtr(valueData), valueType); } int bufferSize = m_Ptr->valueSizeInBytes; return control.ReadValueFromBufferAsObject(valueData, bufferSize); } public unsafe void ReadValue(void* buffer, int bufferSize) { int num = m_Ptr->valueSizeInBytes; if (bufferSize < num) { throw new ArgumentException($"Expected buffer of at least {num} bytes but got buffer of just {bufferSize} bytes instead", "bufferSize"); } UnsafeUtility.MemCpy(buffer, (void*)m_Ptr->valueData, (long)num); } public unsafe TValue ReadValue() where TValue : struct { int num = m_Ptr->valueSizeInBytes; if (UnsafeUtility.SizeOf() != num) { throw new InvalidOperationException($"Cannot read a value of type '{typeof(TValue).Name}' with size {UnsafeUtility.SizeOf()} from event on action '{action}' with value size {num}"); } TValue result = new TValue(); UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref result), (void*)m_Ptr->valueData, (long)num); return result; } public unsafe override string ToString() { if (m_Ptr == null) { return ""; } string text = ((action.actionMap != null) ? (action.actionMap.name + "/" + action.name) : action.name); return $"{{ action={text} phase={phase} time={time} control={control} value={ReadValueAsObject()} interaction={interaction} duration={duration} }}"; } } private struct Enumerator : IEnumerator, IDisposable, IEnumerator { private readonly InputActionTrace m_Trace; private unsafe readonly ActionEvent* m_Buffer; private readonly int m_EventCount; private unsafe ActionEvent* m_CurrentEvent; private int m_CurrentIndex; public unsafe ActionEventPtr Current { get { InputActionState state = m_Trace.m_ActionMapStates[m_CurrentEvent->stateIndex]; return new ActionEventPtr { m_State = state, m_Ptr = m_CurrentEvent }; } } object IEnumerator.Current => Current; public unsafe Enumerator(InputActionTrace trace) { m_Trace = trace; m_Buffer = (ActionEvent*)trace.m_EventBuffer.bufferPtr.data; m_EventCount = trace.m_EventBuffer.eventCount; m_CurrentEvent = null; m_CurrentIndex = 0; } public unsafe bool MoveNext() { if (m_CurrentIndex == m_EventCount) { return false; } if (m_CurrentEvent == null) { m_CurrentEvent = m_Buffer; return m_CurrentEvent != null; } m_CurrentIndex++; if (m_CurrentIndex == m_EventCount) { return false; } m_CurrentEvent = (ActionEvent*)InputEvent.GetNextInMemory((InputEvent*)m_CurrentEvent); return true; } public unsafe void Reset() { m_CurrentEvent = null; m_CurrentIndex = 0; } public void Dispose() { } } private bool m_SubscribedToAll; private bool m_OnActionChangeHooked; private InlinedArray m_SubscribedActions; private InlinedArray m_SubscribedActionMaps; private InputEventBuffer m_EventBuffer; private InlinedArray m_ActionMapStates; private InlinedArray m_ActionMapStateClones; private Action m_CallbackDelegate; private Action m_ActionChangeDelegate; public InputEventBuffer buffer => m_EventBuffer; public int count => m_EventBuffer.eventCount; public InputActionTrace() { } public InputActionTrace(InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } SubscribeTo(action); } public InputActionTrace(InputActionMap actionMap) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } SubscribeTo(actionMap); } public void SubscribeToAll() { if (!m_SubscribedToAll) { HookOnActionChange(); m_SubscribedToAll = true; while (m_SubscribedActions.length > 0) { UnsubscribeFrom(m_SubscribedActions[m_SubscribedActions.length - 1]); } while (m_SubscribedActionMaps.length > 0) { UnsubscribeFrom(m_SubscribedActionMaps[m_SubscribedActionMaps.length - 1]); } } } public void UnsubscribeFromAll() { if (count == 0) { UnhookOnActionChange(); } m_SubscribedToAll = false; while (m_SubscribedActions.length > 0) { UnsubscribeFrom(m_SubscribedActions[m_SubscribedActions.length - 1]); } while (m_SubscribedActionMaps.length > 0) { UnsubscribeFrom(m_SubscribedActionMaps[m_SubscribedActionMaps.length - 1]); } } public void SubscribeTo(InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } if (m_CallbackDelegate == null) { m_CallbackDelegate = RecordAction; } action.performed += m_CallbackDelegate; action.started += m_CallbackDelegate; action.canceled += m_CallbackDelegate; m_SubscribedActions.AppendWithCapacity(action); } public void SubscribeTo(InputActionMap actionMap) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (m_CallbackDelegate == null) { m_CallbackDelegate = RecordAction; } actionMap.actionTriggered += m_CallbackDelegate; m_SubscribedActionMaps.AppendWithCapacity(actionMap); } public void UnsubscribeFrom(InputAction action) { if (action == null) { throw new ArgumentNullException("action"); } if (m_CallbackDelegate != null) { action.performed -= m_CallbackDelegate; action.started -= m_CallbackDelegate; action.canceled -= m_CallbackDelegate; int num = m_SubscribedActions.IndexOfReference(action); if (num != -1) { m_SubscribedActions.RemoveAtWithCapacity(num); } } } public void UnsubscribeFrom(InputActionMap actionMap) { if (actionMap == null) { throw new ArgumentNullException("actionMap"); } if (m_CallbackDelegate != null) { actionMap.actionTriggered -= m_CallbackDelegate; int num = m_SubscribedActionMaps.IndexOfReference(actionMap); if (num != -1) { m_SubscribedActionMaps.RemoveAtWithCapacity(num); } } } public unsafe void RecordAction(InputAction.CallbackContext context) { int num = m_ActionMapStates.IndexOfReference(context.m_State); if (num == -1) { num = m_ActionMapStates.AppendWithCapacity(context.m_State); } HookOnActionChange(); int valueSizeInBytes = context.valueSizeInBytes; ActionEvent* ptr = (ActionEvent*)m_EventBuffer.AllocateEvent(ActionEvent.GetEventSizeWithValueSize(valueSizeInBytes), 2048, (Allocator)4); ref InputActionState.TriggerState reference = ref context.m_State.actionStates[context.m_ActionIndex]; ptr->baseEvent.type = ActionEvent.Type; ptr->baseEvent.time = reference.time; ptr->stateIndex = num; ptr->controlIndex = reference.controlIndex; ptr->bindingIndex = reference.bindingIndex; ptr->interactionIndex = reference.interactionIndex; ptr->startTime = reference.startTime; ptr->phase = reference.phase; byte* valueData = ptr->valueData; context.ReadValue(valueData, valueSizeInBytes); } public void Clear() { m_EventBuffer.Reset(); m_ActionMapStates.ClearWithCapacity(); } ~InputActionTrace() { DisposeInternal(); } public override string ToString() { if (count == 0) { return "[]"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); bool flag = true; using (IEnumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { ActionEventPtr current = enumerator.Current; if (!flag) { stringBuilder.Append(",\n"); } stringBuilder.Append(current.ToString()); flag = false; } } stringBuilder.Append(']'); return stringBuilder.ToString(); } public void Dispose() { UnsubscribeFromAll(); DisposeInternal(); } private void DisposeInternal() { for (int i = 0; i < m_ActionMapStateClones.length; i++) { m_ActionMapStateClones[i].Dispose(); } m_EventBuffer.Dispose(); m_ActionMapStates.Clear(); m_ActionMapStateClones.Clear(); if (m_ActionChangeDelegate != null) { InputSystem.onActionChange -= m_ActionChangeDelegate; m_ActionChangeDelegate = null; } } public IEnumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void HookOnActionChange() { if (!m_OnActionChangeHooked) { if (m_ActionChangeDelegate == null) { m_ActionChangeDelegate = OnActionChange; } InputSystem.onActionChange += m_ActionChangeDelegate; m_OnActionChangeHooked = true; } } private void UnhookOnActionChange() { if (m_OnActionChangeHooked) { InputSystem.onActionChange -= m_ActionChangeDelegate; m_OnActionChangeHooked = false; } } private void OnActionChange(object actionOrMapOrAsset, InputActionChange change) { if (m_SubscribedToAll && (uint)(change - 4) <= 2u) { InputAction obj = (InputAction)actionOrMapOrAsset; int actionIndexInState = obj.m_ActionIndexInState; InputActionState state = obj.m_ActionMap.m_State; InputAction.CallbackContext context = new InputAction.CallbackContext { m_State = state, m_ActionIndex = actionIndexInState }; RecordAction(context); } else { if (change != InputActionChange.BoundControlsAboutToChange) { return; } if (actionOrMapOrAsset is InputAction inputAction) { CloneActionStateBeforeBindingsChange(inputAction.m_ActionMap); } else if (actionOrMapOrAsset is InputActionMap actionMap) { CloneActionStateBeforeBindingsChange(actionMap); } else { if (!(actionOrMapOrAsset is InputActionAsset { actionMaps: var actionMaps })) { return; } foreach (InputActionMap item in actionMaps) { CloneActionStateBeforeBindingsChange(item); } } } } private void CloneActionStateBeforeBindingsChange(InputActionMap actionMap) { InputActionState state = actionMap.m_State; if (state != null) { int num = m_ActionMapStates.IndexOfReference(state); if (num != -1) { InputActionState value = state.Clone(); m_ActionMapStateClones.Append(value); m_ActionMapStates[num] = value; } } } } internal static class ArrayHelpers { public static int LengthSafe(this TValue[] array) { if (array == null) { return 0; } return array.Length; } public static void Clear(this TValue[] array) { if (array != null) { Array.Clear(array, 0, array.Length); } } public static void Clear(this TValue[] array, int count) { if (array != null) { Array.Clear(array, 0, count); } } public static void Clear(this TValue[] array, ref int count) { if (array != null) { Array.Clear(array, 0, count); count = 0; } } public static void EnsureCapacity(ref TValue[] array, int count, int capacity, int capacityIncrement = 10) { if (capacity != 0) { if (array == null) { array = new TValue[Math.Max(capacity, capacityIncrement)]; } else if (array.Length - count < capacity) { DuplicateWithCapacity(ref array, count, capacity, capacityIncrement); } } } public static void DuplicateWithCapacity(ref TValue[] array, int count, int capacity, int capacityIncrement = 10) { if (array == null) { array = new TValue[Math.Max(capacity, capacityIncrement)]; return; } TValue[] array2 = new TValue[count + Math.Max(capacity, capacityIncrement)]; Array.Copy(array, array2, count); array = array2; } public static bool Contains(TValue[] array, TValue value) { if (array == null) { return false; } EqualityComparer equalityComparer = EqualityComparer.Default; for (int i = 0; i < array.Length; i++) { if (equalityComparer.Equals(array[i], value)) { return true; } } return false; } public static bool ContainsReference(this TValue[] array, TValue value) where TValue : class { return array?.ContainsReference(array.Length, value) ?? false; } public static bool ContainsReference(this TFirst[] array, int count, TSecond value) where TFirst : TSecond where TSecond : class { return array.IndexOfReference(value, count) != -1; } public static bool ContainsReference(this TFirst[] array, int startIndex, int count, TSecond value) where TFirst : TSecond where TSecond : class { return array.IndexOfReference(value, startIndex, count) != -1; } public static bool HaveDuplicateReferences(this TFirst[] first, int index, int count) { for (int i = 0; i < count; i++) { TFirst val = first[i]; for (int j = i + 1; j < count - i; j++) { if ((object)val == (object)first[j]) { return true; } } } return false; } public static bool HaveEqualElements(TValue[] first, TValue[] second, int count = int.MaxValue) { if (first == null || second == null) { return second == first; } int num = Math.Min(count, first.Length); int num2 = Math.Min(count, second.Length); if (num != num2) { return false; } EqualityComparer equalityComparer = EqualityComparer.Default; for (int i = 0; i < num; i++) { if (!equalityComparer.Equals(first[i], second[i])) { return false; } } return true; } public static int IndexOf(TValue[] array, TValue value, int startIndex = 0, int count = -1) { if (array == null) { return -1; } if (count < 0) { count = array.Length - startIndex; } EqualityComparer equalityComparer = EqualityComparer.Default; for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(array[i], value)) { return i; } } return -1; } public static int IndexOf(this TValue[] array, Predicate predicate) { if (array == null) { return -1; } int num = array.Length; for (int i = 0; i < num; i++) { if (predicate(array[i])) { return i; } } return -1; } public static int IndexOf(this TValue[] array, Predicate predicate, int startIndex = 0, int count = -1) { if (array == null) { return -1; } int num = startIndex + ((count < 0) ? (array.Length - startIndex) : count); for (int i = startIndex; i < num; i++) { if (predicate(array[i])) { return i; } } return -1; } public static int IndexOfReference(this TFirst[] array, TSecond value, int count = -1) where TFirst : TSecond where TSecond : class { return array.IndexOfReference(value, 0, count); } public static int IndexOfReference(this TFirst[] array, TSecond value, int startIndex, int count) where TFirst : TSecond where TSecond : class { if (array == null) { return -1; } if (count < 0) { count = array.Length - startIndex; } for (int i = startIndex; i < startIndex + count; i++) { if ((object)array[i] == value) { return i; } } return -1; } public static int IndexOfValue(this TValue[] array, TValue value, int startIndex = 0, int count = -1) where TValue : struct, IEquatable { if (array == null) { return -1; } if (count < 0) { count = array.Length - startIndex; } for (int i = startIndex; i < startIndex + count; i++) { if (value.Equals(array[i])) { return i; } } return -1; } public unsafe static void Resize(ref NativeArray array, int newSize, Allocator allocator) where TValue : struct { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) int length = array.Length; if (length == newSize) { return; } if (newSize == 0) { if (array.IsCreated) { array.Dispose(); } array = default(NativeArray); return; } NativeArray val = default(NativeArray); val..ctor(newSize, allocator, (NativeArrayOptions)1); if (length != 0) { UnsafeUtility.MemCpy(NativeArrayUnsafeUtility.GetUnsafePtr(val), NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(array), (long)(UnsafeUtility.SizeOf() * ((newSize < length) ? newSize : length))); array.Dispose(); } array = val; } public static int Append(ref TValue[] array, TValue value) { if (array == null) { array = new TValue[1]; array[0] = value; return 0; } int num = array.Length; Array.Resize(ref array, num + 1); array[num] = value; return num; } public static int Append(ref TValue[] array, IEnumerable values) { if (array == null) { array = values.ToArray(); return 0; } int num = array.Length; int num2 = values.Count(); Array.Resize(ref array, num + num2); int num3 = num; foreach (TValue value in values) { array[num3++] = value; } return num; } public static int AppendToImmutable(ref TValue[] array, TValue[] values) { if (array == null) { array = values; return 0; } if (values != null && values.Length != 0) { int num = array.Length; int num2 = values.Length; Array.Resize(ref array, num + num2); Array.Copy(values, 0, array, num, num2); return num; } return array.Length; } public static int AppendWithCapacity(ref TValue[] array, ref int count, TValue value, int capacityIncrement = 10) { if (array == null) { array = new TValue[capacityIncrement]; array[0] = value; count++; return 0; } int num = array.Length; if (num == count) { num += capacityIncrement; Array.Resize(ref array, num); } int num2 = count; array[num2] = value; count++; return num2; } public static int AppendListWithCapacity(ref TValue[] array, ref int length, TValues values, int capacityIncrement = 10) where TValues : IReadOnlyList { int count = values.Count; if (array == null) { int num = Math.Max(count, capacityIncrement); array = new TValue[num]; for (int i = 0; i < count; i++) { array[i] = values[i]; } length += count; return 0; } int num2 = array.Length; if (num2 < length + count) { num2 += Math.Max(length + count, capacityIncrement); Array.Resize(ref array, num2); } int num3 = length; for (int j = 0; j < count; j++) { array[num3 + j] = values[j]; } length += count; return num3; } public static int AppendWithCapacity(ref NativeArray array, ref int count, TValue value, int capacityIncrement = 10, Allocator allocator = (Allocator)4) where TValue : struct { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (array.Length == count) { GrowBy(ref array, (capacityIncrement <= 1) ? 1 : capacityIncrement, allocator); } int num = count; array[num] = value; count++; return num; } public static void InsertAt(ref TValue[] array, int index, TValue value) { if (array == null) { if (index != 0) { throw new ArgumentOutOfRangeException("index"); } array = new TValue[1]; array[0] = value; return; } int num = array.Length; Array.Resize(ref array, num + 1); if (index != num) { Array.Copy(array, index, array, index + 1, num - index); } array[index] = value; } public static void InsertAtWithCapacity(ref TValue[] array, ref int count, int index, TValue value, int capacityIncrement = 10) { EnsureCapacity(ref array, count, count + 1, capacityIncrement); if (index != count) { Array.Copy(array, index, array, index + 1, count - index); } array[index] = value; count++; } public static void PutAtIfNotSet(ref TValue[] array, int index, Func valueFn) { if (array.LengthSafe() < index + 1) { Array.Resize(ref array, index + 1); } if (EqualityComparer.Default.Equals(array[index], default(TValue))) { array[index] = valueFn(); } } public static int GrowBy(ref TValue[] array, int count) { if (array == null) { array = new TValue[count]; return 0; } int num = array.Length; Array.Resize(ref array, num + count); return num; } public unsafe static int GrowBy(ref NativeArray array, int count, Allocator allocator = (Allocator)4) where TValue : struct { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) int length = array.Length; if (length == 0) { array = new NativeArray(count, allocator, (NativeArrayOptions)1); return 0; } NativeArray val = default(NativeArray); val..ctor(length + count, allocator, (NativeArrayOptions)1); UnsafeUtility.MemCpy(NativeArrayUnsafeUtility.GetUnsafePtr(val), NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(array), (long)length * (long)UnsafeUtility.SizeOf()); array.Dispose(); array = val; return length; } public static int GrowWithCapacity(ref TValue[] array, ref int count, int growBy, int capacityIncrement = 10) { if (((array != null) ? array.Length : 0) < count + growBy) { if (capacityIncrement < growBy) { capacityIncrement = growBy; } GrowBy(ref array, capacityIncrement); } int result = count; count += growBy; return result; } public static int GrowWithCapacity(ref NativeArray array, ref int count, int growBy, int capacityIncrement = 10, Allocator allocator = (Allocator)4) where TValue : struct { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (array.Length < count + growBy) { if (capacityIncrement < growBy) { capacityIncrement = growBy; } GrowBy(ref array, capacityIncrement, allocator); } int result = count; count += growBy; return result; } public static TValue[] Join(TValue value, params TValue[] values) { int num = 0; if (value != null) { num++; } if (values != null) { num += values.Length; } if (num == 0) { return null; } TValue[] array = new TValue[num]; int destinationIndex = 0; if (value != null) { array[destinationIndex++] = value; } if (values != null) { Array.Copy(values, 0, array, destinationIndex, values.Length); } return array; } public static TValue[] Merge(TValue[] first, TValue[] second) where TValue : IEquatable { if (first == null) { return second; } if (second == null) { return first; } List list = new List(); list.AddRange(first); foreach (TValue secondValue in second) { if (!list.Exists((TValue x) => x.Equals(secondValue))) { list.Add(secondValue); } } return list.ToArray(); } public static TValue[] Merge(TValue[] first, TValue[] second, IEqualityComparer comparer) { if (first == null) { return second; } if (second == null) { return null; } List list = new List(); list.AddRange(first); foreach (TValue secondValue in second) { if (!list.Exists((TValue x) => comparer.Equals(secondValue))) { list.Add(secondValue); } } return list.ToArray(); } public static void EraseAt(ref TValue[] array, int index) { int num = array.Length; if (index == 0 && num == 1) { array = null; return; } if (index < num - 1) { Array.Copy(array, index + 1, array, index, num - index - 1); } Array.Resize(ref array, num - 1); } public static void EraseAtWithCapacity(this TValue[] array, ref int count, int index) { if (index < count - 1) { Array.Copy(array, index + 1, array, index, count - index - 1); } array[count - 1] = default(TValue); count--; } public unsafe static void EraseAtWithCapacity(NativeArray array, ref int count, int index) where TValue : struct { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (index < count - 1) { int num = UnsafeUtility.SizeOf(); byte* unsafePtr = (byte*)NativeArrayUnsafeUtility.GetUnsafePtr(array); UnsafeUtility.MemCpy((void*)(unsafePtr + num * index), (void*)(unsafePtr + num * (index + 1)), (long)((count - index - 1) * num)); } count--; } public static bool Erase(ref TValue[] array, TValue value) { int num = IndexOf(array, value); if (num != -1) { EraseAt(ref array, num); return true; } return false; } public static void EraseAtByMovingTail(TValue[] array, ref int count, int index) { if (index != count - 1) { array[index] = array[count - 1]; } if (count >= 1) { array[count - 1] = default(TValue); } count--; } public static TValue[] Copy(TValue[] array) { if (array == null) { return null; } int num = array.Length; TValue[] array2 = new TValue[num]; Array.Copy(array, array2, num); return array2; } public static TValue[] Clone(TValue[] array) where TValue : ICloneable { if (array == null) { return null; } int num = array.Length; TValue[] array2 = new TValue[num]; for (int i = 0; i < num; i++) { array2[i] = (TValue)array[i].Clone(); } return array2; } public static TNew[] Select(TOld[] array, Func converter) { if (array == null) { return null; } int num = array.Length; TNew[] array2 = new TNew[num]; for (int i = 0; i < num; i++) { array2[i] = converter(array[i]); } return array2; } private static void Swap(ref TValue first, ref TValue second) { TValue val = first; first = second; second = val; } public static void MoveSlice(TValue[] array, int sourceIndex, int destinationIndex, int count) { if (count <= 0 || sourceIndex == destinationIndex) { return; } int num = ((destinationIndex <= sourceIndex) ? (sourceIndex + count - destinationIndex) : (destinationIndex + count - sourceIndex)); if (num == count * 2) { for (int i = 0; i < count; i++) { Swap(ref array[sourceIndex + i], ref array[destinationIndex + i]); } return; } int num2 = num - 1; int num3 = destinationIndex; for (int j = 0; j < num2; j++) { Swap(ref array[num3], ref array[sourceIndex]); if (destinationIndex > sourceIndex) { num3 -= count; if (num3 < sourceIndex) { num3 = destinationIndex + count - Math.Abs(sourceIndex - num3); } } else { num3 += count; if (num3 >= sourceIndex + count) { num3 = destinationIndex + (num3 - (sourceIndex + count)); } } } } public static void EraseSliceWithCapacity(ref TValue[] array, ref int length, int index, int count) { if (count < length) { Array.Copy(array, index + count, array, index, length - index - count); } for (int i = 0; i < count; i++) { array[length - i - 1] = default(TValue); } length -= count; } public static void SwapElements(this TValue[] array, int index1, int index2) { MemoryHelpers.Swap(ref array[index1], ref array[index2]); } public static void SwapElements(this NativeArray array, int index1, int index2) where TValue : struct { TValue val = array[index1]; array[index1] = array[index2]; array[index2] = val; } } internal static class CSharpCodeHelpers { public static bool IsProperIdentifier(string name) { if (string.IsNullOrEmpty(name)) { return false; } if (char.IsDigit(name[0])) { return false; } foreach (char c in name) { if (!char.IsLetterOrDigit(c) && c != '_') { return false; } } return true; } public static bool IsEmptyOrProperIdentifier(string name) { if (string.IsNullOrEmpty(name)) { return true; } return IsProperIdentifier(name); } public static bool IsEmptyOrProperNamespaceName(string name) { if (string.IsNullOrEmpty(name)) { return true; } return name.Split('.').All(IsProperIdentifier); } public static string MakeIdentifier(string name, string suffix = "") { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (char.IsDigit(name[0])) { name = "_" + name; } bool flag = false; foreach (char c in name) { if (!char.IsLetterOrDigit(c) && c != '_') { flag = true; break; } } if (flag) { StringBuilder stringBuilder = new StringBuilder(); foreach (char c2 in name) { if (char.IsLetterOrDigit(c2) || c2 == '_') { stringBuilder.Append(c2); } } name = stringBuilder.ToString(); } return name + suffix; } public static string MakeTypeName(string name, string suffix = "") { string text = MakeIdentifier(name, suffix); if (char.IsLower(text[0])) { text = char.ToUpper(text[0]) + text.Substring(1); } return text; } } internal struct CallbackArray where TDelegate : Delegate { private bool m_CannotMutateCallbacksArray; private InlinedArray m_Callbacks; private InlinedArray m_CallbacksToAdd; private InlinedArray m_CallbacksToRemove; public int length => m_Callbacks.length; public TDelegate this[int index] => m_Callbacks[index]; public void Clear() { m_Callbacks.Clear(); m_CallbacksToAdd.Clear(); m_CallbacksToRemove.Clear(); } public void AddCallback(TDelegate dlg) { if (m_CannotMutateCallbacksArray) { if (!m_CallbacksToAdd.Contains(dlg)) { int num = m_CallbacksToRemove.IndexOf(dlg); if (num != -1) { m_CallbacksToRemove.RemoveAtByMovingTailWithCapacity(num); } m_CallbacksToAdd.AppendWithCapacity(dlg); } } else if (!m_Callbacks.Contains(dlg)) { m_Callbacks.AppendWithCapacity(dlg, 4); } } public void RemoveCallback(TDelegate dlg) { if (m_CannotMutateCallbacksArray) { if (!m_CallbacksToRemove.Contains(dlg)) { int num = m_CallbacksToAdd.IndexOf(dlg); if (num != -1) { m_CallbacksToAdd.RemoveAtByMovingTailWithCapacity(num); } m_CallbacksToRemove.AppendWithCapacity(dlg); } } else { int num2 = m_Callbacks.IndexOf(dlg); if (num2 >= 0) { m_Callbacks.RemoveAtWithCapacity(num2); } } } public void LockForChanges() { m_CannotMutateCallbacksArray = true; } public void UnlockForChanges() { m_CannotMutateCallbacksArray = false; for (int i = 0; i < m_CallbacksToRemove.length; i++) { RemoveCallback(m_CallbacksToRemove[i]); } for (int j = 0; j < m_CallbacksToAdd.length; j++) { AddCallback(m_CallbacksToAdd[j]); } m_CallbacksToAdd.Clear(); m_CallbacksToRemove.Clear(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct Vector2MagnitudeComparer : IComparer { public int Compare(Vector2 x, Vector2 y) { float sqrMagnitude = ((Vector2)(ref x)).sqrMagnitude; float sqrMagnitude2 = ((Vector2)(ref y)).sqrMagnitude; if (sqrMagnitude < sqrMagnitude2) { return -1; } if (sqrMagnitude > sqrMagnitude2) { return 1; } return 0; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct Vector3MagnitudeComparer : IComparer { public int Compare(Vector3 x, Vector3 y) { float sqrMagnitude = ((Vector3)(ref x)).sqrMagnitude; float sqrMagnitude2 = ((Vector3)(ref y)).sqrMagnitude; if (sqrMagnitude < sqrMagnitude2) { return -1; } if (sqrMagnitude > sqrMagnitude2) { return 1; } return 0; } } internal static class DelegateHelpers { public static void InvokeCallbacksSafe(ref CallbackArray callbacks, string callbackName, object context = null) { if (callbacks.length == 0) { return; } callbacks.LockForChanges(); for (int i = 0; i < callbacks.length; i++) { try { callbacks[i](); } catch (Exception ex) { Debug.LogException(ex); if (context != null) { Debug.LogError((object)$"{ex.GetType().Name} while executing '{callbackName}' callbacks of '{context}'"); } else { Debug.LogError((object)(ex.GetType().Name + " while executing '" + callbackName + "' callbacks")); } } } callbacks.UnlockForChanges(); } public static void InvokeCallbacksSafe(ref CallbackArray> callbacks, TValue argument, string callbackName, object context = null) { if (callbacks.length == 0) { return; } callbacks.LockForChanges(); for (int i = 0; i < callbacks.length; i++) { try { callbacks[i](argument); } catch (Exception ex) { Debug.LogException(ex); if (context != null) { Debug.LogError((object)$"{ex.GetType().Name} while executing '{callbackName}' callbacks of '{context}'"); } else { Debug.LogError((object)(ex.GetType().Name + " while executing '" + callbackName + "' callbacks")); } } } callbacks.UnlockForChanges(); } public static void InvokeCallbacksSafe(ref CallbackArray> callbacks, TValue1 argument1, TValue2 argument2, string callbackName, object context = null) { if (callbacks.length == 0) { return; } callbacks.LockForChanges(); for (int i = 0; i < callbacks.length; i++) { try { callbacks[i](argument1, argument2); } catch (Exception ex) { Debug.LogException(ex); if (context != null) { Debug.LogError((object)$"{ex.GetType().Name} while executing '{callbackName}' callbacks of '{context}'"); } else { Debug.LogError((object)(ex.GetType().Name + " while executing '" + callbackName + "' callbacks")); } } } callbacks.UnlockForChanges(); } public static bool InvokeCallbacksSafe_AnyCallbackReturnsTrue(ref CallbackArray> callbacks, TValue1 argument1, TValue2 argument2, string callbackName, object context = null) { if (callbacks.length == 0) { return true; } callbacks.LockForChanges(); for (int i = 0; i < callbacks.length; i++) { try { if (callbacks[i](argument1, argument2)) { callbacks.UnlockForChanges(); return true; } } catch (Exception ex) { Debug.LogException(ex); if (context != null) { Debug.LogError((object)$"{ex.GetType().Name} while executing '{callbackName}' callbacks of '{context}'"); } else { Debug.LogError((object)(ex.GetType().Name + " while executing '" + callbackName + "' callbacks")); } } } callbacks.UnlockForChanges(); return false; } public static void InvokeCallbacksSafe_AndInvokeReturnedActions(ref CallbackArray> callbacks, TValue argument, string callbackName, object context = null) { if (callbacks.length == 0) { return; } callbacks.LockForChanges(); for (int i = 0; i < callbacks.length; i++) { try { callbacks[i](argument)?.Invoke(); } catch (Exception ex) { Debug.LogException(ex); if (context != null) { Debug.LogError((object)$"{ex.GetType().Name} while executing '{callbackName}' callbacks of '{context}'"); } else { Debug.LogError((object)(ex.GetType().Name + " while executing '" + callbackName + "' callbacks")); } } } callbacks.UnlockForChanges(); } public static bool InvokeCallbacksSafe_AnyCallbackReturnsObject(ref CallbackArray> callbacks, TValue argument, string callbackName, object context = null) { if (callbacks.length == 0) { return false; } callbacks.LockForChanges(); for (int i = 0; i < callbacks.length; i++) { try { if (callbacks[i](argument) != null) { callbacks.UnlockForChanges(); return true; } } catch (Exception ex) { Debug.LogException(ex); if (context != null) { Debug.LogError((object)$"{ex.GetType().Name} while executing '{callbackName}' callbacks of '{context}'"); } else { Debug.LogError((object)(ex.GetType().Name + " while executing '" + callbackName + "' callbacks")); } } } callbacks.UnlockForChanges(); return false; } } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public class DisplayStringFormatAttribute : Attribute { public string formatString { get; set; } public DisplayStringFormatAttribute(string formatString) { this.formatString = formatString; } } internal static class ExceptionHelpers { public static bool IsExceptionIndicatingBugInCode(this Exception exception) { if (!(exception is NullReferenceException) && !(exception is IndexOutOfRangeException)) { return exception is ArgumentException; } return true; } } public struct FourCC : IEquatable { private int m_Code; public FourCC(int code) { m_Code = code; } public FourCC(char a, char b = ' ', char c = ' ', char d = ' ') { m_Code = (int)(((uint)a << 24) | ((uint)b << 16) | ((uint)c << 8) | d); } public FourCC(string str) { this = default(FourCC); if (str == null) { throw new ArgumentNullException("str"); } int length = str.Length; if (length < 1 || length > 4) { throw new ArgumentException("FourCC string must be one to four characters long!", "str"); } char c = str[0]; char c2 = ((length > 1) ? str[1] : ' '); char c3 = ((length > 2) ? str[2] : ' '); char c4 = ((length > 3) ? str[3] : ' '); m_Code = (int)(((uint)c << 24) | ((uint)c2 << 16) | ((uint)c3 << 8) | c4); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator int(FourCC fourCC) { return fourCC.m_Code; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator FourCC(int i) { return new FourCC(i); } public override string ToString() { return $"{(char)(m_Code >> 24)}{(char)((m_Code & 0xFF0000) >> 16)}{(char)((m_Code & 0xFF00) >> 8)}{(char)(m_Code & 0xFF)}"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(FourCC other) { return m_Code == other.m_Code; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is FourCC other) { return Equals(other); } return false; } public override int GetHashCode() { return m_Code; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(FourCC left, FourCC right) { return left.m_Code == right.m_Code; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(FourCC left, FourCC right) { return left.m_Code != right.m_Code; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FourCC FromInt32(int i) { return i; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ToInt32(FourCC fourCC) { return fourCC.m_Code; } } internal struct InlinedArray : IEnumerable, IEnumerable { private struct Enumerator : IEnumerator, IDisposable, IEnumerator { public InlinedArray array; public int index; public TValue Current => array[index]; object IEnumerator.Current => Current; public bool MoveNext() { if (index >= array.length) { return false; } index++; return index < array.length; } public void Reset() { index = -1; } public void Dispose() { } } public int length; public TValue firstValue; public TValue[] additionalValues; public int Capacity { get { TValue[] array = additionalValues; if (array == null) { return 1; } return array.Length + 1; } } public TValue this[int index] { get { if (index < 0 || index >= length) { throw new ArgumentOutOfRangeException("index"); } if (index == 0) { return firstValue; } return additionalValues[index - 1]; } set { if (index < 0 || index >= length) { throw new ArgumentOutOfRangeException("index"); } if (index == 0) { firstValue = value; } else { additionalValues[index - 1] = value; } } } public InlinedArray(TValue value) { length = 1; firstValue = value; additionalValues = null; } public InlinedArray(TValue firstValue, params TValue[] additionalValues) { length = 1 + additionalValues.Length; this.firstValue = firstValue; this.additionalValues = additionalValues; } public InlinedArray(IEnumerable values) { this = default(InlinedArray); length = values.Count(); if (length > 1) { additionalValues = new TValue[length - 1]; } else { additionalValues = null; } int num = 0; foreach (TValue value in values) { if (num == 0) { firstValue = value; } else { additionalValues[num - 1] = value; } num++; } } public void Clear() { length = 0; firstValue = default(TValue); additionalValues = null; } public void ClearWithCapacity() { firstValue = default(TValue); for (int i = 0; i < length - 1; i++) { additionalValues[i] = default(TValue); } length = 0; } public InlinedArray Clone() { return new InlinedArray { length = length, firstValue = firstValue, additionalValues = ((additionalValues != null) ? ArrayHelpers.Copy(additionalValues) : null) }; } public void SetLength(int size) { if (size < length) { for (int i = size; i < length; i++) { this[i] = default(TValue); } } length = size; if (size > 1 && (additionalValues == null || additionalValues.Length < size - 1)) { Array.Resize(ref additionalValues, size - 1); } } public TValue[] ToArray() { return ArrayHelpers.Join(firstValue, additionalValues); } public TOther[] ToArray(Func mapFunction) { if (length == 0) { return null; } TOther[] array = new TOther[length]; for (int i = 0; i < length; i++) { array[i] = mapFunction(this[i]); } return array; } public int IndexOf(TValue value) { EqualityComparer equalityComparer = EqualityComparer.Default; if (length > 0) { if (equalityComparer.Equals(firstValue, value)) { return 0; } if (additionalValues != null) { for (int i = 0; i < length - 1; i++) { if (equalityComparer.Equals(additionalValues[i], value)) { return i + 1; } } } } return -1; } public int Append(TValue value) { if (length == 0) { firstValue = value; } else if (additionalValues == null) { additionalValues = new TValue[1]; additionalValues[0] = value; } else { Array.Resize(ref additionalValues, length); additionalValues[length - 1] = value; } int result = length; length++; return result; } public int AppendWithCapacity(TValue value, int capacityIncrement = 10) { if (length == 0) { firstValue = value; } else { int count = length - 1; ArrayHelpers.AppendWithCapacity(ref additionalValues, ref count, value, capacityIncrement); } int result = length; length++; return result; } public void AssignWithCapacity(InlinedArray values) { if (Capacity < values.length && values.length > 1) { additionalValues = new TValue[values.length - 1]; } length = values.length; if (length > 0) { firstValue = values.firstValue; } if (length > 1) { Array.Copy(values.additionalValues, additionalValues, length - 1); } } public void Append(IEnumerable values) { foreach (TValue value in values) { Append(value); } } public void Remove(TValue value) { if (length < 1) { return; } if (EqualityComparer.Default.Equals(firstValue, value)) { RemoveAt(0); } else { if (additionalValues == null) { return; } for (int i = 0; i < length - 1; i++) { if (EqualityComparer.Default.Equals(additionalValues[i], value)) { RemoveAt(i + 1); break; } } } } public void RemoveAtWithCapacity(int index) { if (index < 0 || index >= length) { throw new ArgumentOutOfRangeException("index"); } if (index == 0) { if (length == 1) { firstValue = default(TValue); } else if (length == 2) { firstValue = additionalValues[0]; additionalValues[0] = default(TValue); } else { firstValue = additionalValues[0]; int count = length - 1; additionalValues.EraseAtWithCapacity(ref count, 0); } } else { int count2 = length - 1; additionalValues.EraseAtWithCapacity(ref count2, index - 1); } length--; } public void RemoveAt(int index) { if (index < 0 || index >= length) { throw new ArgumentOutOfRangeException("index"); } if (index == 0) { if (additionalValues != null) { firstValue = additionalValues[0]; if (additionalValues.Length == 1) { additionalValues = null; } else { Array.Copy(additionalValues, 1, additionalValues, 0, additionalValues.Length - 1); Array.Resize(ref additionalValues, additionalValues.Length - 1); } } else { firstValue = default(TValue); } } else { int num = length - 1; if (num == 1) { additionalValues = null; } else if (index == length - 1) { Array.Resize(ref additionalValues, num - 1); } else { TValue[] destinationArray = new TValue[num - 1]; if (index >= 2) { Array.Copy(additionalValues, 0, destinationArray, 0, index - 1); } Array.Copy(additionalValues, index + 1 - 1, destinationArray, index - 1, length - index - 1); additionalValues = destinationArray; } } length--; } public void RemoveAtByMovingTailWithCapacity(int index) { if (index < 0 || index >= length) { throw new ArgumentOutOfRangeException("index"); } int count = length - 1; if (index == 0) { if (length > 1) { firstValue = additionalValues[count - 1]; additionalValues[count - 1] = default(TValue); } else { firstValue = default(TValue); } } else { ArrayHelpers.EraseAtByMovingTail(additionalValues, ref count, index - 1); } length--; } public bool RemoveByMovingTailWithCapacity(TValue value) { int num = IndexOf(value); if (num == -1) { return false; } RemoveAtByMovingTailWithCapacity(num); return true; } public bool Contains(TValue value, IEqualityComparer comparer) { for (int i = 0; i < length; i++) { if (comparer.Equals(this[i], value)) { return true; } } return false; } public void Merge(InlinedArray other) { EqualityComparer comparer = EqualityComparer.Default; for (int i = 0; i < other.length; i++) { TValue value = other[i]; if (!Contains(value, comparer)) { Append(value); } } } public IEnumerator GetEnumerator() { return new Enumerator { array = this, index = -1 }; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal static class InputArrayExtensions { public static int IndexOfReference(this InlinedArray array, TValue value) where TValue : class { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return -1; } public static bool Contains(this InlinedArray array, TValue value) { for (int i = 0; i < array.length; i++) { if (array[i].Equals(value)) { return true; } } return false; } public static bool ContainsReference(this InlinedArray array, TValue value) where TValue : class { return array.IndexOfReference(value) != -1; } } public struct InternedString : IEquatable, IComparable { private readonly string m_StringOriginalCase; private readonly string m_StringLowerCase; public int length => m_StringLowerCase?.Length ?? 0; public InternedString(string text) { if (string.IsNullOrEmpty(text)) { m_StringOriginalCase = null; m_StringLowerCase = null; } else { m_StringOriginalCase = string.Intern(text); m_StringLowerCase = string.Intern(text.ToLower(CultureInfo.InvariantCulture)); } } public bool IsEmpty() { return m_StringLowerCase == null; } public string ToLower() { return m_StringLowerCase; } public override bool Equals(object obj) { if (obj is InternedString other) { return Equals(other); } if (obj is string text) { if (m_StringLowerCase == null) { return string.IsNullOrEmpty(text); } return string.Equals(m_StringLowerCase, text.ToLower(CultureInfo.InvariantCulture)); } return false; } public bool Equals(InternedString other) { return (object)m_StringLowerCase == other.m_StringLowerCase; } public int CompareTo(InternedString other) { return string.Compare(m_StringLowerCase, other.m_StringLowerCase, StringComparison.InvariantCultureIgnoreCase); } public override int GetHashCode() { if (m_StringLowerCase == null) { return 0; } return m_StringLowerCase.GetHashCode(); } public override string ToString() { return m_StringOriginalCase ?? string.Empty; } public static bool operator ==(InternedString a, InternedString b) { return a.Equals(b); } public static bool operator !=(InternedString a, InternedString b) { return !a.Equals(b); } public static bool operator ==(InternedString a, string b) { return string.Compare(a.m_StringLowerCase, b.ToLower(CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase) == 0; } public static bool operator !=(InternedString a, string b) { return string.Compare(a.m_StringLowerCase, b.ToLower(CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase) != 0; } public static bool operator ==(string a, InternedString b) { return string.Compare(a.ToLower(CultureInfo.InvariantCulture), b.m_StringLowerCase, StringComparison.InvariantCultureIgnoreCase) == 0; } public static bool operator !=(string a, InternedString b) { return string.Compare(a.ToLower(CultureInfo.InvariantCulture), b.m_StringLowerCase, StringComparison.InvariantCultureIgnoreCase) != 0; } public static bool operator <(InternedString left, InternedString right) { return string.Compare(left.m_StringLowerCase, right.m_StringLowerCase, StringComparison.InvariantCultureIgnoreCase) < 0; } public static bool operator >(InternedString left, InternedString right) { return string.Compare(left.m_StringLowerCase, right.m_StringLowerCase, StringComparison.InvariantCultureIgnoreCase) > 0; } public static implicit operator string(InternedString str) { return str.ToString(); } } internal struct JsonParser { public enum JsonValueType { None, Bool, Real, Integer, String, Array, Object, Any } public struct JsonString : IEquatable { public Substring text; public bool hasEscapes; public override string ToString() { if (!hasEscapes) { return text.ToString(); } StringBuilder stringBuilder = new StringBuilder(); int length = text.length; for (int i = 0; i < length; i++) { char c = text[i]; if (c == '\\') { i++; if (i == length) { break; } c = text[i]; } stringBuilder.Append(c); } return stringBuilder.ToString(); } public bool Equals(JsonString other) { if (hasEscapes == other.hasEscapes) { return Substring.Compare(text, other.text, StringComparison.InvariantCultureIgnoreCase) == 0; } int length = text.length; int length2 = other.text.length; int num = 0; int num2 = 0; while (num < length && num2 < length2) { char c = text[num]; char c2 = other.text[num2]; if (c == '\\') { num++; if (num == length) { return false; } c = text[num]; } if (c2 == '\\') { num2++; if (num2 == length2) { return false; } c2 = other.text[num2]; } if (char.ToUpperInvariant(c) != char.ToUpperInvariant(c2)) { return false; } num++; num2++; } if (num == length) { return num2 == length2; } return false; } public override bool Equals(object obj) { if (obj is JsonString other) { return Equals(other); } return false; } public override int GetHashCode() { return (text.GetHashCode() * 397) ^ hasEscapes.GetHashCode(); } public static bool operator ==(JsonString left, JsonString right) { return left.Equals(right); } public static bool operator !=(JsonString left, JsonString right) { return !left.Equals(right); } public static implicit operator JsonString(string str) { return new JsonString { text = str }; } } public struct JsonValue : IEquatable { public JsonValueType type; public bool boolValue; public double realValue; public long integerValue; public JsonString stringValue; public List arrayValue; public Dictionary objectValue; public object anyValue; public bool ToBoolean() { return type switch { JsonValueType.Bool => boolValue, JsonValueType.Integer => integerValue != 0, JsonValueType.Real => NumberHelpers.Approximately(0.0, realValue), JsonValueType.String => Convert.ToBoolean(ToString()), _ => false, }; } public long ToInteger() { return type switch { JsonValueType.Bool => boolValue ? 1 : 0, JsonValueType.Integer => integerValue, JsonValueType.Real => (long)realValue, JsonValueType.String => Convert.ToInt64(ToString()), _ => 0L, }; } public double ToDouble() { return type switch { JsonValueType.Bool => boolValue ? 1 : 0, JsonValueType.Integer => integerValue, JsonValueType.Real => realValue, JsonValueType.String => Convert.ToSingle(ToString()), _ => 0.0, }; } public override string ToString() { switch (type) { case JsonValueType.None: return "null"; case JsonValueType.Bool: return boolValue.ToString(); case JsonValueType.Integer: return integerValue.ToString(CultureInfo.InvariantCulture); case JsonValueType.Real: return realValue.ToString(CultureInfo.InvariantCulture); case JsonValueType.String: return stringValue.ToString(); case JsonValueType.Array: if (arrayValue == null) { return "[]"; } return "[" + string.Join(",", arrayValue.Select((JsonValue x) => x.ToString())) + "]"; case JsonValueType.Object: { if (objectValue == null) { return "{}"; } IEnumerable values = objectValue.Select((KeyValuePair pair) => $"\"{pair.Key}\" : \"{pair.Value}\""); return "{" + string.Join(",", values) + "}"; } case JsonValueType.Any: return anyValue.ToString(); default: return base.ToString(); } } public static implicit operator JsonValue(bool val) { return new JsonValue { type = JsonValueType.Bool, boolValue = val }; } public static implicit operator JsonValue(long val) { return new JsonValue { type = JsonValueType.Integer, integerValue = val }; } public static implicit operator JsonValue(double val) { return new JsonValue { type = JsonValueType.Real, realValue = val }; } public static implicit operator JsonValue(string str) { return new JsonValue { type = JsonValueType.String, stringValue = new JsonString { text = str } }; } public static implicit operator JsonValue(JsonString str) { return new JsonValue { type = JsonValueType.String, stringValue = str }; } public static implicit operator JsonValue(List array) { return new JsonValue { type = JsonValueType.Array, arrayValue = array }; } public static implicit operator JsonValue(Dictionary obj) { return new JsonValue { type = JsonValueType.Object, objectValue = obj }; } public static implicit operator JsonValue(Enum val) { return new JsonValue { type = JsonValueType.Any, anyValue = val }; } public bool Equals(JsonValue other) { if (type == other.type) { return type switch { JsonValueType.None => true, JsonValueType.Bool => boolValue == other.boolValue, JsonValueType.Integer => integerValue == other.integerValue, JsonValueType.Real => NumberHelpers.Approximately(realValue, other.realValue), JsonValueType.String => stringValue == other.stringValue, JsonValueType.Object => throw new NotImplementedException(), JsonValueType.Array => throw new NotImplementedException(), JsonValueType.Any => anyValue.Equals(other.anyValue), _ => false, }; } if (anyValue != null) { return Equals(anyValue, other); } if (other.anyValue != null) { return Equals(other.anyValue, this); } return false; } private static bool Equals(object obj, JsonValue value) { if (obj == null) { return false; } if (obj is Regex regex) { return regex.IsMatch(value.ToString()); } if (obj is string text) { switch (value.type) { case JsonValueType.String: return value.stringValue == text; case JsonValueType.Integer: { if (long.TryParse(text, out var result)) { return result == value.integerValue; } return false; } case JsonValueType.Real: { if (double.TryParse(text, out var result2)) { return NumberHelpers.Approximately(result2, value.realValue); } return false; } case JsonValueType.Bool: if (value.boolValue) { if (!(text == "True") && !(text == "true")) { return text == "1"; } return true; } if (!(text == "False") && !(text == "false")) { return text == "0"; } return true; } } if (obj is float num) { if (value.type == JsonValueType.Real) { return NumberHelpers.Approximately(num, value.realValue); } if (value.type == JsonValueType.String) { if (float.TryParse(value.ToString(), out var result3)) { return Mathf.Approximately(num, result3); } return false; } } if (obj is double a) { if (value.type == JsonValueType.Real) { return NumberHelpers.Approximately(a, value.realValue); } if (value.type == JsonValueType.String) { if (double.TryParse(value.ToString(), out var result4)) { return NumberHelpers.Approximately(a, result4); } return false; } } if (obj is int num2) { if (value.type == JsonValueType.Integer) { return num2 == value.integerValue; } if (value.type == JsonValueType.String) { if (int.TryParse(value.ToString(), out var result5)) { return num2 == result5; } return false; } } if (obj is long num3) { if (value.type == JsonValueType.Integer) { return num3 == value.integerValue; } if (value.type == JsonValueType.String) { if (long.TryParse(value.ToString(), out var result6)) { return num3 == result6; } return false; } } if (obj is bool flag) { if (value.type == JsonValueType.Bool) { return flag == value.boolValue; } if (value.type == JsonValueType.String) { if (flag) { if (!(value.stringValue == "true") && !(value.stringValue == "True")) { return value.stringValue == "1"; } return true; } if (!(value.stringValue == "false") && !(value.stringValue == "False")) { return value.stringValue == "0"; } return true; } } if (obj is Enum) { if (value.type == JsonValueType.Integer) { return Convert.ToInt64(obj) == value.integerValue; } if (value.type == JsonValueType.String) { return value.stringValue == Enum.GetName(obj.GetType(), obj); } } return false; } public override bool Equals(object obj) { if (obj is JsonValue other) { return Equals(other); } return false; } public override int GetHashCode() { return ((((((((((((((int)type * 397) ^ boolValue.GetHashCode()) * 397) ^ realValue.GetHashCode()) * 397) ^ integerValue.GetHashCode()) * 397) ^ stringValue.GetHashCode()) * 397) ^ ((arrayValue != null) ? arrayValue.GetHashCode() : 0)) * 397) ^ ((objectValue != null) ? objectValue.GetHashCode() : 0)) * 397) ^ ((anyValue != null) ? anyValue.GetHashCode() : 0); } public static bool operator ==(JsonValue left, JsonValue right) { return left.Equals(right); } public static bool operator !=(JsonValue left, JsonValue right) { return !left.Equals(right); } } private readonly string m_Text; private readonly int m_Length; private int m_Position; private bool m_MatchAnyElementInArray; private bool m_DryRun; public bool isAtEnd => m_Position >= m_Length; public JsonParser(string json) { this = default(JsonParser); if (json == null) { throw new ArgumentNullException("json"); } m_Text = json; m_Length = json.Length; } public void Reset() { m_Position = 0; m_MatchAnyElementInArray = false; m_DryRun = false; } public override string ToString() { if (m_Text != null) { return $"{m_Position}: {m_Text.Substring(m_Position)}"; } return base.ToString(); } public bool NavigateToProperty(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } int length = path.Length; int i = 0; m_DryRun = true; if (!ParseToken('{')) { return false; } while (m_Position < m_Length && i < length) { SkipWhitespace(); if (m_Position == m_Length) { return false; } if (m_Text[m_Position] != '"') { return false; } m_Position++; int num = i; for (; i < length; i++) { char c = path[i]; if (c == '/' || c == '[' || m_Text[m_Position] != c) { break; } m_Position++; } if (m_Position < m_Length && m_Text[m_Position] == '"' && (i >= length || path[i] == '/' || path[i] == '[')) { m_Position++; if (!SkipToValue()) { return false; } if (i >= length) { return true; } if (path[i] == '/') { i++; if (!ParseToken('{')) { return false; } } else if (path[i] == '[') { i++; if (i == length) { throw new ArgumentException("Malformed JSON property path: " + path, "path"); } if (path[i] != ']') { throw new NotImplementedException("Navigating to specific array element"); } m_MatchAnyElementInArray = true; i++; if (i == length) { return true; } } } else { i = num; while (m_Position < m_Length && m_Text[m_Position] != '"') { m_Position++; } if (m_Position == m_Length || m_Text[m_Position] != '"') { return false; } m_Position++; if (!SkipToValue() || !ParseValue()) { return false; } SkipWhitespace(); if (m_Position == m_Length || m_Text[m_Position] == '}' || m_Text[m_Position] != ',') { return false; } m_Position++; } } return false; } public bool CurrentPropertyHasValueEqualTo(JsonValue expectedValue) { int position = m_Position; m_DryRun = false; if (!ParseValue(out var result)) { m_Position = position; return false; } m_Position = position; bool flag = false; if (result.type == JsonValueType.Array && m_MatchAnyElementInArray) { List arrayValue = result.arrayValue; int num = 0; while (!flag && num < arrayValue.Count) { flag = arrayValue[num] == expectedValue; num++; } } else { flag = result == expectedValue; } return flag; } public bool ParseToken(char token) { SkipWhitespace(); if (m_Position == m_Length) { return false; } if (m_Text[m_Position] != token) { return false; } m_Position++; SkipWhitespace(); return m_Position < m_Length; } public bool ParseValue() { JsonValue result; return ParseValue(out result); } public bool ParseValue(out JsonValue result) { result = default(JsonValue); SkipWhitespace(); if (m_Position == m_Length) { return false; } switch (m_Text[m_Position]) { case '"': if (ParseStringValue(out result)) { return true; } break; case '[': if (ParseArrayValue(out result)) { return true; } break; case '{': if (ParseObjectValue(out result)) { return true; } break; case 'f': case 't': if (ParseBooleanValue(out result)) { return true; } break; case 'n': if (ParseNullValue(out result)) { return true; } break; default: if (ParseNumber(out result)) { return true; } break; } return false; } public bool ParseStringValue(out JsonValue result) { result = default(JsonValue); SkipWhitespace(); if (m_Position == m_Length || m_Text[m_Position] != '"') { return false; } m_Position++; int position = m_Position; bool hasEscapes = false; for (; m_Position < m_Length; m_Position++) { switch (m_Text[m_Position]) { case '\\': m_Position++; if (m_Position != m_Length) { hasEscapes = true; continue; } break; case '"': m_Position++; result = new JsonString { text = new Substring(m_Text, position, m_Position - position - 1), hasEscapes = hasEscapes }; return true; default: continue; } break; } return false; } public bool ParseArrayValue(out JsonValue result) { result = default(JsonValue); SkipWhitespace(); if (m_Position == m_Length || m_Text[m_Position] != '[') { return false; } m_Position++; if (m_Position == m_Length) { return false; } if (m_Text[m_Position] == ']') { result = new JsonValue { type = JsonValueType.Array }; m_Position++; return true; } List list = null; if (!m_DryRun) { list = new List(); } while (m_Position < m_Length) { if (!ParseValue(out var result2)) { return false; } if (!m_DryRun) { list.Add(result2); } SkipWhitespace(); if (m_Position == m_Length) { return false; } switch (m_Text[m_Position]) { case ']': m_Position++; if (!m_DryRun) { result = list; } return true; case ',': m_Position++; break; } } return false; } public bool ParseObjectValue(out JsonValue result) { result = default(JsonValue); if (!ParseToken('{')) { return false; } if (m_Position < m_Length && m_Text[m_Position] == '}') { result = new JsonValue { type = JsonValueType.Object }; m_Position++; return true; } while (m_Position < m_Length) { if (!ParseStringValue(out var _)) { return false; } if (!SkipToValue()) { return false; } if (!ParseValue(out var _)) { return false; } if (!m_DryRun) { throw new NotImplementedException(); } SkipWhitespace(); if (m_Position < m_Length && m_Text[m_Position] == '}') { if (!m_DryRun) { throw new NotImplementedException(); } m_Position++; return true; } } return false; } public bool ParseNumber(out JsonValue result) { result = default(JsonValue); SkipWhitespace(); if (m_Position == m_Length) { return false; } bool flag = false; bool flag2 = false; long num = 0L; double num2 = 0.0; double num3 = 10.0; int num4 = 0; if (m_Text[m_Position] == '-') { flag = true; m_Position++; } if (m_Position == m_Length || !char.IsDigit(m_Text[m_Position])) { return false; } while (m_Position < m_Length) { char c = m_Text[m_Position]; if (c == '.' || c < '0' || c > '9') { break; } num = num * 10 + c - 48; m_Position++; } if (m_Position < m_Length && m_Text[m_Position] == '.') { flag2 = true; m_Position++; if (m_Position == m_Length || !char.IsDigit(m_Text[m_Position])) { return false; } while (m_Position < m_Length) { char c2 = m_Text[m_Position]; if (c2 < '0' || c2 > '9') { break; } num2 = (double)(c2 - 48) / num3 + num2; num3 *= 10.0; m_Position++; } } if (m_Position < m_Length && (m_Text[m_Position] == 'e' || m_Text[m_Position] == 'E')) { m_Position++; bool flag3 = false; if (m_Position < m_Length && m_Text[m_Position] == '-') { flag3 = true; m_Position++; } else if (m_Position < m_Length && m_Text[m_Position] == '+') { m_Position++; } int num5 = 1; while (m_Position < m_Length && char.IsDigit(m_Text[m_Position])) { int num6 = m_Text[m_Position] - 48; num4 *= num5; num4 += num6; num5 *= 10; m_Position++; } if (flag3) { num4 *= -1; } } if (!m_DryRun) { if (!flag2 && num4 == 0) { if (flag) { result = -num; } else { result = num; } } else { float num7 = ((!flag) ? ((float)((double)num + num2)) : ((float)(0.0 - ((double)num + num2)))); if (num4 != 0) { num7 *= Mathf.Pow(10f, (float)num4); } result = num7; } } return true; } public bool ParseBooleanValue(out JsonValue result) { SkipWhitespace(); if (SkipString("true")) { result = true; return true; } if (SkipString("false")) { result = false; return true; } result = default(JsonValue); return false; } public bool ParseNullValue(out JsonValue result) { result = default(JsonValue); return SkipString("null"); } public bool SkipToValue() { SkipWhitespace(); if (m_Position == m_Length || m_Text[m_Position] != ':') { return false; } m_Position++; SkipWhitespace(); return true; } private bool SkipString(string text) { SkipWhitespace(); int length = text.Length; if (m_Position + length >= m_Length) { return false; } for (int i = 0; i < length; i++) { if (m_Text[m_Position + i] != text[i]) { return false; } } m_Position += length; return true; } private void SkipWhitespace() { while (m_Position < m_Length && char.IsWhiteSpace(m_Text[m_Position])) { m_Position++; } } } internal static class MemoryHelpers { public struct BitRegion { public uint bitOffset; public uint sizeInBits; public bool isEmpty => sizeInBits == 0; public BitRegion(uint bitOffset, uint sizeInBits) { this.bitOffset = bitOffset; this.sizeInBits = sizeInBits; } public BitRegion(uint byteOffset, uint bitOffset, uint sizeInBits) { this.bitOffset = byteOffset * 8 + bitOffset; this.sizeInBits = sizeInBits; } public BitRegion Overlap(BitRegion other) { uint num = bitOffset + sizeInBits; uint num2 = other.bitOffset + other.sizeInBits; if (num <= other.bitOffset || num2 <= bitOffset) { return default(BitRegion); } uint num3 = Math.Min(num, num2); uint num4 = Math.Max(bitOffset, other.bitOffset); return new BitRegion(num4, num3 - num4); } } public unsafe static bool Compare(void* ptr1, void* ptr2, BitRegion region) { if (region.sizeInBits == 1) { return ReadSingleBit(ptr1, region.bitOffset) == ReadSingleBit(ptr2, region.bitOffset); } return MemCmpBitRegion(ptr1, ptr2, region.bitOffset, region.sizeInBits, null); } public static uint ComputeFollowingByteOffset(uint byteOffset, uint sizeInBits) { return (uint)(byteOffset + sizeInBits / 8 + ((sizeInBits % 8 != 0) ? 1 : 0)); } public unsafe static void WriteSingleBit(void* ptr, uint bitOffset, bool value) { uint num = bitOffset >> 3; bitOffset &= 7; if (value) { byte* num2 = (byte*)ptr + num; *num2 |= (byte)(1 << (int)bitOffset); } else { byte* num3 = (byte*)ptr + num; *num3 &= (byte)(~(1 << (int)bitOffset)); } } public unsafe static bool ReadSingleBit(void* ptr, uint bitOffset) { uint num = bitOffset >> 3; bitOffset &= 7; return (((byte*)ptr)[num] & (1 << (int)bitOffset)) != 0; } public unsafe static void MemCpyBitRegion(void* destination, void* source, uint bitOffset, uint bitCount) { byte* ptr = (byte*)destination; byte* ptr2 = (byte*)source; if (bitOffset >= 8) { uint num = bitOffset / 8; ptr += num; ptr2 += num; bitOffset %= 8; } if (bitOffset != 0) { int num2 = 255 << (int)bitOffset; if (bitCount + bitOffset < 8) { num2 &= 255 >> (int)(8 - (bitCount + bitOffset)); } *ptr = (byte)(((*ptr & ~num2) | (*ptr2 & num2)) & 0xFF); if (bitCount + bitOffset <= 8) { return; } ptr++; ptr2++; bitCount -= 8 - bitOffset; } uint num3 = bitCount / 8; if (num3 >= 1) { UnsafeUtility.MemCpy((void*)ptr, (void*)ptr2, (long)num3); } uint num4 = bitCount % 8; if (num4 != 0) { ptr += num3; ptr2 += num3; int num5 = 255 >> (int)(8 - num4); *ptr = (byte)(((*ptr & ~num5) | (*ptr2 & num5)) & 0xFF); } } public unsafe static bool MemCmpBitRegion(void* ptr1, void* ptr2, uint bitOffset, uint bitCount, void* mask = null) { byte* ptr3 = (byte*)ptr1; byte* ptr4 = (byte*)ptr2; byte* ptr5 = (byte*)mask; if (bitOffset >= 8) { uint num = bitOffset / 8; ptr3 += num; ptr4 += num; if (ptr5 != null) { ptr5 += num; } bitOffset %= 8; } if (bitOffset != 0) { int num2 = 255 << (int)bitOffset; if (bitCount + bitOffset < 8) { num2 &= 255 >> (int)(8 - (bitCount + bitOffset)); } if (ptr5 != null) { num2 &= *ptr5; ptr5++; } int num3 = *ptr3 & num2; int num4 = *ptr4 & num2; if (num3 != num4) { return false; } if (bitCount + bitOffset <= 8) { return true; } ptr3++; ptr4++; bitCount -= 8 - bitOffset; } uint num5 = bitCount / 8; if (num5 >= 1) { if (ptr5 != null) { for (int i = 0; i < num5; i++) { byte num6 = ptr3[i]; byte b = ptr4[i]; byte b2 = ptr5[i]; if ((num6 & b2) != (b & b2)) { return false; } } } else if (UnsafeUtility.MemCmp((void*)ptr3, (void*)ptr4, (long)num5) != 0) { return false; } } uint num7 = bitCount % 8; if (num7 != 0) { ptr3 += num5; ptr4 += num5; int num8 = 255 >> (int)(8 - num7); if (ptr5 != null) { ptr5 += num5; num8 &= *ptr5; } int num9 = *ptr3 & num8; int num10 = *ptr4 & num8; if (num9 != num10) { return false; } } return true; } public unsafe static void MemSet(void* destination, int numBytes, byte value) { int num = 0; while (numBytes >= 8) { *(ulong*)((byte*)destination + num) = ((ulong)value << 56) | ((ulong)value << 48) | ((ulong)value << 40) | ((ulong)value << 32) | ((ulong)value << 24) | ((ulong)value << 16) | ((ulong)value << 8) | value; numBytes -= 8; num += 8; } while (numBytes >= 4) { *(int*)((byte*)destination + num) = (value << 24) | (value << 16) | (value << 8) | value; numBytes -= 4; num += 4; } while (numBytes > 0) { ((sbyte*)destination)[num] = (sbyte)value; numBytes--; num++; } } public unsafe static void MemCpyMasked(void* destination, void* source, int numBytes, void* mask) { int num = 0; while (numBytes >= 8) { *(long*)((byte*)destination + num) &= ~(*(long*)((byte*)mask + num)); *(long*)((byte*)destination + num) |= *(long*)((byte*)source + num) & *(long*)((byte*)mask + num); numBytes -= 8; num += 8; } while (numBytes >= 4) { *(int*)((byte*)destination + num) &= (int)(~(*(uint*)((byte*)mask + num))); *(int*)((byte*)destination + num) |= (int)(*(uint*)((byte*)source + num) & *(uint*)((byte*)mask + num)); numBytes -= 4; num += 4; } while (numBytes > 0) { byte* num2 = (byte*)destination + num; *num2 &= (byte)(~((byte*)mask)[num]); byte* num3 = (byte*)destination + num; *num3 |= (byte)(((byte*)source)[num] & ((byte*)mask)[num]); numBytes--; num++; } } public unsafe static uint ReadMultipleBitsAsUInt(void* ptr, uint bitOffset, uint bitCount) { if (ptr == null) { throw new ArgumentNullException("ptr"); } if (bitCount > 32) { throw new ArgumentException("Trying to read more than 32 bits as int", "bitCount"); } if (bitOffset > 32) { int num = (int)bitOffset % 32; int num2 = ((int)bitOffset - num) / 32; ptr = (byte*)ptr + num2 * 4; bitOffset = (uint)num; } if (bitOffset + bitCount <= 8) { byte num3 = (byte)(*(byte*)ptr >> (int)bitOffset); uint num4 = 255u >> (int)(8 - bitCount); return num3 & num4; } if (bitOffset + bitCount <= 16) { ushort num5 = (ushort)(*(ushort*)ptr >> (int)bitOffset); uint num6 = 65535u >> (int)(16 - bitCount); return num5 & num6; } if (bitOffset + bitCount <= 32) { uint num7 = *(uint*)ptr >> (int)bitOffset; uint num8 = uint.MaxValue >> (int)(32 - bitCount); return num7 & num8; } throw new NotImplementedException("Reading int straddling int boundary"); } public unsafe static void WriteUIntAsMultipleBits(void* ptr, uint bitOffset, uint bitCount, uint value) { if (ptr == null) { throw new ArgumentNullException("ptr"); } if (bitCount > 32) { throw new ArgumentException("Trying to write more than 32 bits as int", "bitCount"); } if (bitOffset > 32) { int num = (int)bitOffset % 32; int num2 = ((int)bitOffset - num) / 32; ptr = (byte*)ptr + num2 * 4; bitOffset = (uint)num; } if (bitOffset + bitCount <= 8) { byte b = (byte)value; b = (byte)(b << (int)bitOffset); uint num3 = (uint)(~(255 >>> (int)(8 - bitCount) << (int)bitOffset)); *(byte*)ptr = (byte)((*(byte*)ptr & num3) | b); return; } if (bitOffset + bitCount <= 16) { ushort num4 = (ushort)value; num4 = (ushort)(num4 << (int)bitOffset); uint num5 = (uint)(~(65535 >>> (int)(16 - bitCount) << (int)bitOffset)); *(ushort*)ptr = (ushort)((*(ushort*)ptr & num5) | num4); return; } if (bitOffset + bitCount <= 32) { uint num6 = value; num6 <<= (int)bitOffset; uint num7 = (uint)(~(-1 >>> (int)(32 - bitCount) << (int)bitOffset)); *(uint*)ptr = (*(uint*)ptr & num7) | num6; return; } throw new NotImplementedException("Writing int straddling int boundary"); } public unsafe static int ReadTwosComplementMultipleBitsAsInt(void* ptr, uint bitOffset, uint bitCount) { return (int)ReadMultipleBitsAsUInt(ptr, bitOffset, bitCount); } public unsafe static void WriteIntAsTwosComplementMultipleBits(void* ptr, uint bitOffset, uint bitCount, int value) { WriteUIntAsMultipleBits(ptr, bitOffset, bitCount, (uint)value); } public unsafe static int ReadExcessKMultipleBitsAsInt(void* ptr, uint bitOffset, uint bitCount) { long num = ReadMultipleBitsAsUInt(ptr, bitOffset, bitCount); long num2 = (long)((ulong)(1L << (int)bitCount) / 2uL); return (int)(num - num2); } public unsafe static void WriteIntAsExcessKMultipleBits(void* ptr, uint bitOffset, uint bitCount, int value) { long num = (long)((ulong)(1L << (int)bitCount) / 2uL) + (long)value; WriteUIntAsMultipleBits(ptr, bitOffset, bitCount, (uint)num); } public unsafe static float ReadMultipleBitsAsNormalizedUInt(void* ptr, uint bitOffset, uint bitCount) { uint value = ReadMultipleBitsAsUInt(ptr, bitOffset, bitCount); uint maxValue = (uint)((1L << (int)bitCount) - 1); return NumberHelpers.UIntToNormalizedFloat(value, 0u, maxValue); } public unsafe static void WriteNormalizedUIntAsMultipleBits(void* ptr, uint bitOffset, uint bitCount, float value) { uint uintMaxValue = (uint)((1L << (int)bitCount) - 1); uint value2 = NumberHelpers.NormalizedFloatToUInt(value, 0u, uintMaxValue); WriteUIntAsMultipleBits(ptr, bitOffset, bitCount, value2); } public unsafe static void SetBitsInBuffer(void* buffer, int byteOffset, int bitOffset, int sizeInBits, bool value) { if (buffer == null) { throw new ArgumentException("A buffer must be provided to apply the bitmask on", "buffer"); } if (sizeInBits < 0) { throw new ArgumentException("Negative sizeInBits", "sizeInBits"); } if (bitOffset < 0) { throw new ArgumentException("Negative bitOffset", "bitOffset"); } if (byteOffset < 0) { throw new ArgumentException("Negative byteOffset", "byteOffset"); } if (bitOffset >= 8) { int num = bitOffset / 8; byteOffset += num; bitOffset %= 8; } byte* ptr = (byte*)buffer + byteOffset; int num2 = sizeInBits; if (bitOffset != 0) { int num3 = 255 << bitOffset; if (num2 + bitOffset < 8) { num3 &= 255 >> 8 - (num2 + bitOffset); } if (value) { byte* intPtr = ptr; *intPtr |= (byte)num3; } else { byte* intPtr2 = ptr; *intPtr2 &= (byte)(~num3); } ptr++; num2 -= 8 - bitOffset; } while (num2 >= 8) { *ptr = (byte)(value ? byte.MaxValue : 0); ptr++; num2 -= 8; } if (num2 > 0) { byte b = (byte)(255 >> 8 - num2); if (value) { byte* intPtr3 = ptr; *intPtr3 |= b; } else { byte* intPtr4 = ptr; *intPtr4 &= (byte)(~b); } } } public static void Swap(ref TValue a, ref TValue b) { TValue val = a; a = b; b = val; } public static uint AlignNatural(uint offset, uint sizeInBytes) { uint alignment = Math.Min(8u, sizeInBytes); return offset.AlignToMultipleOf(alignment); } } internal static class MiscHelpers { public static TValue GetValueOrDefault(this Dictionary dictionary, TKey key) { if (!dictionary.TryGetValue(key, out var value)) { return default(TValue); } return value; } public static IEnumerable EveryNth(this IEnumerable enumerable, int n, int start = 0) { int index = 0; foreach (TValue item in enumerable) { int num; if (index < start) { num = index + 1; index = num; continue; } if ((index - start) % n == 0) { yield return item; } num = index + 1; index = num; } } public static int IndexOf(this IEnumerable enumerable, TValue value) { int num = 0; foreach (TValue item in enumerable) { if (EqualityComparer.Default.Equals(item, value)) { return num; } num++; } return -1; } } public struct NameAndParameters { public string name { get; set; } public ReadOnlyArray parameters { get; set; } public override string ToString() { if (parameters.Count == 0) { return name; } string text = string.Join(",", parameters.Select((NamedValue x) => x.ToString()).ToArray()); return name + "(" + text + ")"; } public static IEnumerable ParseMultiple(string text) { List list = null; if (!ParseMultiple(text, ref list)) { return Enumerable.Empty(); } return list; } internal static bool ParseMultiple(string text, ref List list) { text = text.Trim(); if (string.IsNullOrEmpty(text)) { return false; } if (list == null) { list = new List(); } else { list.Clear(); } int index = 0; int length = text.Length; while (index < length) { list.Add(ParseNameAndParameters(text, ref index)); } return true; } internal static string ParseName(string text) { if (text == null) { throw new ArgumentNullException("text"); } int index = 0; return ParseNameAndParameters(text, ref index, nameOnly: true).name; } public static NameAndParameters Parse(string text) { if (text == null) { throw new ArgumentNullException("text"); } int index = 0; return ParseNameAndParameters(text, ref index); } private static NameAndParameters ParseNameAndParameters(string text, ref int index, bool nameOnly = false) { int length = text.Length; while (index < length && char.IsWhiteSpace(text[index])) { index++; } int num = index; while (index < length) { char c = text[index]; if (c == '(' || c == ","[0] || char.IsWhiteSpace(c)) { break; } index++; } if (index - num == 0) { throw new ArgumentException($"Expecting name at position {num} in '{text}'", "text"); } string text2 = text.Substring(num, index - num); if (nameOnly) { return new NameAndParameters { name = text2 }; } while (index < length && char.IsWhiteSpace(text[index])) { index++; } NamedValue[] array = null; if (index < length && text[index] == '(') { index++; int num2 = text.IndexOf(')', index); if (num2 == -1) { throw new ArgumentException($"Expecting ')' after '(' at position {index} in '{text}'", "text"); } array = NamedValue.ParseMultiple(text.Substring(index, num2 - index)); index = num2 + 1; } if (index < length && (text[index] == ',' || text[index] == ';')) { index++; } return new NameAndParameters { name = text2, parameters = new ReadOnlyArray(array) }; } } public struct NamedValue : IEquatable { public const string Separator = ","; public string name { get; set; } public PrimitiveValue value { get; set; } public TypeCode type => value.type; public NamedValue ConvertTo(TypeCode type) { return new NamedValue { name = name, value = value.ConvertTo(type) }; } public static NamedValue From(string name, TValue value) where TValue : struct { return new NamedValue { name = name, value = PrimitiveValue.From(value) }; } public override string ToString() { return $"{name}={value}"; } public bool Equals(NamedValue other) { if (string.Equals(name, other.name, StringComparison.InvariantCultureIgnoreCase)) { return value == other.value; } return false; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is NamedValue other) { return Equals(other); } return false; } public override int GetHashCode() { return (((name != null) ? name.GetHashCode() : 0) * 397) ^ value.GetHashCode(); } public static bool operator ==(NamedValue left, NamedValue right) { return left.Equals(right); } public static bool operator !=(NamedValue left, NamedValue right) { return !left.Equals(right); } public static NamedValue[] ParseMultiple(string parameterString) { if (parameterString == null) { throw new ArgumentNullException("parameterString"); } parameterString = parameterString.Trim(); if (string.IsNullOrEmpty(parameterString)) { return null; } int num = parameterString.CountOccurrences(","[0]) + 1; NamedValue[] array = new NamedValue[num]; int index = 0; for (int i = 0; i < num; i++) { NamedValue namedValue = ParseParameter(parameterString, ref index); array[i] = namedValue; } return array; } public static NamedValue Parse(string str) { int index = 0; return ParseParameter(str, ref index); } private static NamedValue ParseParameter(string parameterString, ref int index) { NamedValue result = default(NamedValue); int length = parameterString.Length; while (index < length && char.IsWhiteSpace(parameterString[index])) { index++; } int num = index; while (index < length) { char c = parameterString[index]; if (c == '=' || c == ","[0] || char.IsWhiteSpace(c)) { break; } index++; } result.name = parameterString.Substring(num, index - num); while (index < length && char.IsWhiteSpace(parameterString[index])) { index++; } if (index == length || parameterString[index] != '=') { result.value = true; } else { index++; while (index < length && char.IsWhiteSpace(parameterString[index])) { index++; } int num2 = index; while (index < length && parameterString[index] != ","[0] && !char.IsWhiteSpace(parameterString[index])) { index++; } string text = parameterString.Substring(num2, index - num2); result.value = PrimitiveValue.FromString(text); } if (index < length && parameterString[index] == ","[0]) { index++; } return result; } public void ApplyToObject(object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } Type type = instance.GetType(); FieldInfo field = type.GetField(name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { throw new ArgumentException("Cannot find public field '" + name + "' in '" + type.Name + "' (while trying to apply parameter)", "instance"); } TypeCode typeCode = Type.GetTypeCode(field.FieldType); field.SetValue(instance, value.ConvertTo(typeCode).ToObject()); } public static void ApplyAllToObject(object instance, TParameterList parameters) where TParameterList : IEnumerable { foreach (NamedValue item in parameters) { item.ApplyToObject(instance); } } } internal static class NumberHelpers { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int AlignToMultipleOf(this int number, int alignment) { int num = number % alignment; if (num == 0) { return number; } return number + alignment - num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long AlignToMultipleOf(this long number, long alignment) { long num = number % alignment; if (num == 0L) { return number; } return number + alignment - num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint AlignToMultipleOf(this uint number, uint alignment) { uint num = number % alignment; if (num == 0) { return number; } return number + alignment - num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Approximately(double a, double b) { return Math.Abs(b - a) < Math.Max(1E-06 * Math.Max(Math.Abs(a), Math.Abs(b)), 4E-323); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IntToNormalizedFloat(int value, int minValue, int maxValue) { if (value <= minValue) { return 0f; } if (value >= maxValue) { return 1f; } return (float)(((double)value - (double)minValue) / ((double)maxValue - (double)minValue)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int NormalizedFloatToInt(float value, int intMinValue, int intMaxValue) { if (value <= 0f) { return intMinValue; } if (value >= 1f) { return intMaxValue; } return (int)((double)value * ((double)intMaxValue - (double)intMinValue) + (double)intMinValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float UIntToNormalizedFloat(uint value, uint minValue, uint maxValue) { if (value <= minValue) { return 0f; } if (value >= maxValue) { return 1f; } return (float)(((double)value - (double)minValue) / ((double)maxValue - (double)minValue)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint NormalizedFloatToUInt(float value, uint uintMinValue, uint uintMaxValue) { if (value <= 0f) { return uintMinValue; } if (value >= 1f) { return uintMaxValue; } return (uint)((double)value * ((double)uintMaxValue - (double)uintMinValue) + (double)uintMinValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RemapUIntBitsToNormalizeFloatToUIntBits(uint value, uint inBitSize, uint outBitSize) { uint maxValue = (uint)((1L << (int)inBitSize) - 1); uint uintMaxValue = (uint)((1L << (int)outBitSize) - 1); return NormalizedFloatToUInt(UIntToNormalizedFloat(value, 0u, maxValue), 0u, uintMaxValue); } } internal class ForDeviceEventObservable : IObservable { private class ForDevice : IObserver { private IObserver m_Observer; private InputDevice m_Device; private Type m_DeviceType; public ForDevice(Type deviceType, InputDevice device, IObserver observer) { m_Device = device; m_DeviceType = deviceType; m_Observer = observer; } public void OnCompleted() { } public void OnError(Exception error) { Debug.LogException(error); } public void OnNext(InputEventPtr value) { if (m_DeviceType != null) { InputDevice deviceById = InputSystem.GetDeviceById(value.deviceId); if (deviceById == null || !m_DeviceType.IsInstanceOfType(deviceById)) { return; } } if (m_Device == null || value.deviceId == m_Device.deviceId) { m_Observer.OnNext(value); } } } private IObservable m_Source; private InputDevice m_Device; private Type m_DeviceType; public ForDeviceEventObservable(IObservable source, Type deviceType, InputDevice device) { m_Source = source; m_DeviceType = deviceType; m_Device = device; } public IDisposable Subscribe(IObserver observer) { return m_Source.Subscribe(new ForDevice(m_DeviceType, m_Device, observer)); } } public static class Observable { public static IObservable Where(this IObservable source, Func predicate) { if (source == null) { throw new ArgumentNullException("source"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return new WhereObservable(source, predicate); } public static IObservable Select(this IObservable source, Func filter) { if (source == null) { throw new ArgumentNullException("source"); } if (filter == null) { throw new ArgumentNullException("filter"); } return new SelectObservable(source, filter); } public static IObservable SelectMany(this IObservable source, Func> filter) { if (source == null) { throw new ArgumentNullException("source"); } if (filter == null) { throw new ArgumentNullException("filter"); } return new SelectManyObservable(source, filter); } public static IObservable Take(this IObservable source, int count) { if (source == null) { throw new ArgumentNullException("source"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } return new TakeNObservable(source, count); } public static IObservable ForDevice(this IObservable source, InputDevice device) { if (source == null) { throw new ArgumentNullException("source"); } return new ForDeviceEventObservable(source, null, device); } public static IObservable ForDevice(this IObservable source) where TDevice : InputDevice { if (source == null) { throw new ArgumentNullException("source"); } return new ForDeviceEventObservable(source, typeof(TDevice), null); } public static IDisposable CallOnce(this IObservable source, Action action) { if (source == null) { throw new ArgumentNullException("source"); } if (action == null) { throw new ArgumentNullException("action"); } IDisposable subscription = null; subscription = source.Take(1).Subscribe(new Observer(action, delegate { subscription?.Dispose(); })); return subscription; } public static IDisposable Call(this IObservable source, Action action) { if (source == null) { throw new ArgumentNullException("source"); } if (action == null) { throw new ArgumentNullException("action"); } return source.Subscribe(new Observer(action)); } } internal class Observer : IObserver { private Action m_OnNext; private Action m_OnCompleted; public Observer(Action onNext, Action onCompleted = null) { m_OnNext = onNext; m_OnCompleted = onCompleted; } public void OnCompleted() { m_OnCompleted?.Invoke(); } public void OnError(Exception error) { Debug.LogException(error); } public void OnNext(TValue evt) { m_OnNext?.Invoke(evt); } } internal class SelectManyObservable : IObservable { private class Select : IObserver { private SelectManyObservable m_Observable; private readonly IObserver m_Observer; public Select(SelectManyObservable observable, IObserver observer) { m_Observable = observable; m_Observer = observer; } public void OnCompleted() { } public void OnError(Exception error) { Debug.LogException(error); } public void OnNext(TSource evt) { foreach (TResult item in m_Observable.m_Filter(evt)) { m_Observer.OnNext(item); } } } private readonly IObservable m_Source; private readonly Func> m_Filter; public SelectManyObservable(IObservable source, Func> filter) { m_Source = source; m_Filter = filter; } public IDisposable Subscribe(IObserver observer) { return m_Source.Subscribe(new Select(this, observer)); } } internal class TakeNObservable : IObservable { private class Take : IObserver { private IObserver m_Observer; private int m_Remaining; public Take(TakeNObservable observable, IObserver observer) { m_Observer = observer; m_Remaining = observable.m_Count; } public void OnCompleted() { } public void OnError(Exception error) { Debug.LogException(error); } public void OnNext(TValue evt) { if (m_Remaining > 0) { m_Remaining--; m_Observer.OnNext(evt); if (m_Remaining == 0) { m_Observer.OnCompleted(); m_Observer = null; } } } } private IObservable m_Source; private int m_Count; public TakeNObservable(IObservable source, int count) { m_Source = source; m_Count = count; } public IDisposable Subscribe(IObserver observer) { return m_Source.Subscribe(new Take(this, observer)); } } internal class WhereObservable : IObservable { private class Where : IObserver { private WhereObservable m_Observable; private readonly IObserver m_Observer; public Where(WhereObservable observable, IObserver observer) { m_Observable = observable; m_Observer = observer; } public void OnCompleted() { } public void OnError(Exception error) { Debug.LogException(error); } public void OnNext(TValue evt) { if (m_Observable.m_Predicate(evt)) { m_Observer.OnNext(evt); } } } private readonly IObservable m_Source; private readonly Func m_Predicate; public WhereObservable(IObservable source, Func predicate) { m_Source = source; m_Predicate = predicate; } public IDisposable Subscribe(IObserver observer) { return m_Source.Subscribe(new Where(this, observer)); } } internal struct OneOrMore : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable where TList : IReadOnlyList { private class Enumerator : IEnumerator, IDisposable, IEnumerator { internal int m_Index = -1; internal OneOrMore m_List; public TValue Current => m_List[m_Index]; object IEnumerator.Current => Current; public bool MoveNext() { m_Index++; if (m_Index >= m_List.Count) { return false; } return true; } public void Reset() { m_Index = -1; } public void Dispose() { } } private readonly bool m_IsSingle; private readonly TValue m_Single; private readonly TList m_Multiple; public int Count { get { if (!m_IsSingle) { return m_Multiple.Count; } return 1; } } public TValue this[int index] { get { if (!m_IsSingle) { return m_Multiple[index]; } if (index < 0 || index > 1) { throw new ArgumentOutOfRangeException("index"); } return m_Single; } } public OneOrMore(TValue single) { m_IsSingle = true; m_Single = single; m_Multiple = default(TList); } public OneOrMore(TList multiple) { m_IsSingle = false; m_Single = default(TValue); m_Multiple = multiple; } public static implicit operator OneOrMore(TValue single) { return new OneOrMore(single); } public static implicit operator OneOrMore(TList multiple) { return new OneOrMore(multiple); } public IEnumerator GetEnumerator() { return new Enumerator { m_List = this }; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal struct PredictiveParser { private int m_Position; public void ExpectSingleChar(ReadOnlySpan str, char c) { if (str[m_Position] != c) { throw new InvalidOperationException($"Expected a '{c}' character at position {m_Position} in : {str.ToString()}"); } m_Position++; } public int ExpectInt(ReadOnlySpan str) { int num = m_Position; int num2 = 1; if (str[num] == '-') { num2 = -1; num++; } int num3 = 0; while (true) { char c = str[num]; if (c < '0' || c > '9') { break; } num3 *= 10; num3 += c - 48; num++; } if (m_Position == num) { throw new InvalidOperationException($"Expected an int at position {m_Position} in {str.ToString()}"); } m_Position = num; return num3 * num2; } public ReadOnlySpan ExpectString(ReadOnlySpan str) { int position = m_Position; if (str[position] != '"') { throw new InvalidOperationException($"Expected a '\"' character at position {m_Position} in {str.ToString()}"); } m_Position++; while (true) { char c = str[m_Position]; c = (char)(c | 0x20); if (c < 'a' || c > 'z') { break; } m_Position++; } if (str[m_Position] != '"') { throw new InvalidOperationException($"Expected a closing '\"' character at position {m_Position} in string: {str.ToString()}"); } if (m_Position - position == 1) { return ReadOnlySpan.Empty; } ReadOnlySpan result = str.Slice(position + 1, m_Position - position - 1); m_Position++; return result; } public bool AcceptSingleChar(ReadOnlySpan str, char c) { if (str[m_Position] != c) { return false; } m_Position++; return true; } public bool AcceptString(ReadOnlySpan input, out ReadOnlySpan output) { output = default(ReadOnlySpan); int position = m_Position; int num = position; if (input[num] != '"') { return false; } num++; while (true) { char c = input[num]; c = (char)(c | 0x20); if (c < 'a' || c > 'z') { break; } num++; } if (input[num] != '"') { return false; } if (m_Position - position == 1) { output = ReadOnlySpan.Empty; } else { output = input.Slice(position + 1, num - position - 1); } m_Position = num + 1; return true; } public void AcceptInt(ReadOnlySpan str) { if (str[m_Position] == '-') { m_Position++; } while (true) { char c = str[m_Position]; if (c >= '0' && c <= '9') { m_Position++; continue; } break; } } } [StructLayout(LayoutKind.Explicit)] public struct PrimitiveValue : IEquatable, IConvertible { [FieldOffset(0)] private TypeCode m_Type; [FieldOffset(4)] private bool m_BoolValue; [FieldOffset(4)] private char m_CharValue; [FieldOffset(4)] private byte m_ByteValue; [FieldOffset(4)] private sbyte m_SByteValue; [FieldOffset(4)] private short m_ShortValue; [FieldOffset(4)] private ushort m_UShortValue; [FieldOffset(4)] private int m_IntValue; [FieldOffset(4)] private uint m_UIntValue; [FieldOffset(4)] private long m_LongValue; [FieldOffset(4)] private ulong m_ULongValue; [FieldOffset(4)] private float m_FloatValue; [FieldOffset(4)] private double m_DoubleValue; internal unsafe byte* valuePtr => (byte*)UnsafeUtility.AddressOf(ref this) + 4; public TypeCode type => m_Type; public bool isEmpty => type == TypeCode.Empty; public PrimitiveValue(bool value) { this = default(PrimitiveValue); m_Type = TypeCode.Boolean; m_BoolValue = value; } public PrimitiveValue(char value) { this = default(PrimitiveValue); m_Type = TypeCode.Char; m_CharValue = value; } public PrimitiveValue(byte value) { this = default(PrimitiveValue); m_Type = TypeCode.Byte; m_ByteValue = value; } public PrimitiveValue(sbyte value) { this = default(PrimitiveValue); m_Type = TypeCode.SByte; m_SByteValue = value; } public PrimitiveValue(short value) { this = default(PrimitiveValue); m_Type = TypeCode.Int16; m_ShortValue = value; } public PrimitiveValue(ushort value) { this = default(PrimitiveValue); m_Type = TypeCode.UInt16; m_UShortValue = value; } public PrimitiveValue(int value) { this = default(PrimitiveValue); m_Type = TypeCode.Int32; m_IntValue = value; } public PrimitiveValue(uint value) { this = default(PrimitiveValue); m_Type = TypeCode.UInt32; m_UIntValue = value; } public PrimitiveValue(long value) { this = default(PrimitiveValue); m_Type = TypeCode.Int64; m_LongValue = value; } public PrimitiveValue(ulong value) { this = default(PrimitiveValue); m_Type = TypeCode.UInt64; m_ULongValue = value; } public PrimitiveValue(float value) { this = default(PrimitiveValue); m_Type = TypeCode.Single; m_FloatValue = value; } public PrimitiveValue(double value) { this = default(PrimitiveValue); m_Type = TypeCode.Double; m_DoubleValue = value; } public PrimitiveValue ConvertTo(TypeCode type) { return type switch { TypeCode.Boolean => ToBoolean(), TypeCode.Char => ToChar(), TypeCode.Byte => ToByte(), TypeCode.SByte => ToSByte(), TypeCode.Int16 => ToInt16(), TypeCode.Int32 => ToInt32(), TypeCode.Int64 => ToInt64(), TypeCode.UInt16 => ToInt16(), TypeCode.UInt32 => ToInt32(), TypeCode.UInt64 => ToUInt64(), TypeCode.Single => ToSingle(), TypeCode.Double => ToDouble(), TypeCode.Empty => default(PrimitiveValue), _ => throw new ArgumentException($"Don't know how to convert PrimitiveValue to '{type}'", "type"), }; } public unsafe bool Equals(PrimitiveValue other) { if (m_Type != other.m_Type) { return false; } void* intPtr = UnsafeUtility.AddressOf(ref m_DoubleValue); void* ptr = UnsafeUtility.AddressOf(ref other.m_DoubleValue); return UnsafeUtility.MemCmp(intPtr, ptr, 8L) == 0; } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is PrimitiveValue other) { return Equals(other); } if (obj is bool || obj is char || obj is byte || obj is sbyte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is float || obj is double) { return Equals(FromObject(obj)); } return false; } public static bool operator ==(PrimitiveValue left, PrimitiveValue right) { return left.Equals(right); } public static bool operator !=(PrimitiveValue left, PrimitiveValue right) { return !left.Equals(right); } public unsafe override int GetHashCode() { fixed (double* doubleValue = &m_DoubleValue) { return (m_Type.GetHashCode() * 397) ^ doubleValue->GetHashCode(); } } public override string ToString() { switch (type) { case TypeCode.Boolean: if (!m_BoolValue) { return "false"; } return "true"; case TypeCode.Char: return "'" + m_CharValue + "'"; case TypeCode.Byte: return m_ByteValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.SByte: return m_SByteValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.Int16: return m_ShortValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.UInt16: return m_UShortValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.Int32: return m_IntValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.UInt32: return m_UIntValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.Int64: return m_LongValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.UInt64: return m_ULongValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.Single: return m_FloatValue.ToString(CultureInfo.InvariantCulture.NumberFormat); case TypeCode.Double: return m_DoubleValue.ToString(CultureInfo.InvariantCulture.NumberFormat); default: return string.Empty; } } public static PrimitiveValue FromString(string value) { if (string.IsNullOrEmpty(value)) { return default(PrimitiveValue); } if (value.Equals("true", StringComparison.InvariantCultureIgnoreCase)) { return new PrimitiveValue(value: true); } if (value.Equals("false", StringComparison.InvariantCultureIgnoreCase)) { return new PrimitiveValue(value: false); } if ((value.Contains('.') || value.Contains("e") || value.Contains("E") || value.Contains("infinity", StringComparison.InvariantCultureIgnoreCase)) && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return new PrimitiveValue(result); } if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2)) { return new PrimitiveValue(result2); } if (value.IndexOf("0x", StringComparison.InvariantCultureIgnoreCase) != -1) { string text = value.TrimStart(); if (text.StartsWith("0x")) { text = text.Substring(2); } if (long.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result3)) { return new PrimitiveValue(result3); } } throw new NotImplementedException(); } public TypeCode GetTypeCode() { return type; } public bool ToBoolean(IFormatProvider provider = null) { return type switch { TypeCode.Boolean => m_BoolValue, TypeCode.Char => m_CharValue != '\0', TypeCode.Byte => m_ByteValue != 0, TypeCode.SByte => m_SByteValue != 0, TypeCode.Int16 => m_ShortValue != 0, TypeCode.UInt16 => m_UShortValue != 0, TypeCode.Int32 => m_IntValue != 0, TypeCode.UInt32 => m_UIntValue != 0, TypeCode.Int64 => m_LongValue != 0, TypeCode.UInt64 => m_ULongValue != 0, TypeCode.Single => !Mathf.Approximately(m_FloatValue, 0f), TypeCode.Double => NumberHelpers.Approximately(m_DoubleValue, 0.0), _ => false, }; } public byte ToByte(IFormatProvider provider = null) { return (byte)ToInt64(provider); } public char ToChar(IFormatProvider provider = null) { switch (type) { case TypeCode.Char: return m_CharValue; case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return (char)ToInt64(provider); default: return '\0'; } } public DateTime ToDateTime(IFormatProvider provider = null) { throw new NotSupportedException("Converting PrimitiveValue to DateTime"); } public decimal ToDecimal(IFormatProvider provider = null) { return new decimal(ToDouble(provider)); } public double ToDouble(IFormatProvider provider = null) { switch (type) { case TypeCode.Boolean: if (m_BoolValue) { return 1.0; } return 0.0; case TypeCode.Char: return (int)m_CharValue; case TypeCode.Byte: return (int)m_ByteValue; case TypeCode.SByte: return m_SByteValue; case TypeCode.Int16: return m_ShortValue; case TypeCode.UInt16: return (int)m_UShortValue; case TypeCode.Int32: return m_IntValue; case TypeCode.UInt32: return m_UIntValue; case TypeCode.Int64: return m_LongValue; case TypeCode.UInt64: return m_ULongValue; case TypeCode.Single: return m_FloatValue; case TypeCode.Double: return m_DoubleValue; default: return 0.0; } } public short ToInt16(IFormatProvider provider = null) { return (short)ToInt64(provider); } public int ToInt32(IFormatProvider provider = null) { return (int)ToInt64(provider); } public long ToInt64(IFormatProvider provider = null) { switch (type) { case TypeCode.Boolean: if (m_BoolValue) { return 1L; } return 0L; case TypeCode.Char: return m_CharValue; case TypeCode.Byte: return m_ByteValue; case TypeCode.SByte: return m_SByteValue; case TypeCode.Int16: return m_ShortValue; case TypeCode.UInt16: return m_UShortValue; case TypeCode.Int32: return m_IntValue; case TypeCode.UInt32: return m_UIntValue; case TypeCode.Int64: return m_LongValue; case TypeCode.UInt64: return (long)m_ULongValue; case TypeCode.Single: return (long)m_FloatValue; case TypeCode.Double: return (long)m_DoubleValue; default: return 0L; } } public sbyte ToSByte(IFormatProvider provider = null) { return (sbyte)ToInt64(provider); } public float ToSingle(IFormatProvider provider = null) { return (float)ToDouble(provider); } public string ToString(IFormatProvider provider) { return ToString(); } public object ToType(Type conversionType, IFormatProvider provider) { throw new NotSupportedException(); } public ushort ToUInt16(IFormatProvider provider = null) { return (ushort)ToUInt64(); } public uint ToUInt32(IFormatProvider provider = null) { return (uint)ToUInt64(); } public ulong ToUInt64(IFormatProvider provider = null) { switch (type) { case TypeCode.Boolean: if (m_BoolValue) { return 1uL; } return 0uL; case TypeCode.Char: return m_CharValue; case TypeCode.Byte: return m_ByteValue; case TypeCode.SByte: return (ulong)m_SByteValue; case TypeCode.Int16: return (ulong)m_ShortValue; case TypeCode.UInt16: return m_UShortValue; case TypeCode.Int32: return (ulong)m_IntValue; case TypeCode.UInt32: return m_UIntValue; case TypeCode.Int64: return (ulong)m_LongValue; case TypeCode.UInt64: return m_ULongValue; case TypeCode.Single: return (ulong)m_FloatValue; case TypeCode.Double: return (ulong)m_DoubleValue; default: return 0uL; } } public object ToObject() { return m_Type switch { TypeCode.Boolean => m_BoolValue, TypeCode.Char => m_CharValue, TypeCode.Byte => m_ByteValue, TypeCode.SByte => m_SByteValue, TypeCode.Int16 => m_ShortValue, TypeCode.UInt16 => m_UShortValue, TypeCode.Int32 => m_IntValue, TypeCode.UInt32 => m_UIntValue, TypeCode.Int64 => m_LongValue, TypeCode.UInt64 => m_ULongValue, TypeCode.Single => m_FloatValue, TypeCode.Double => m_DoubleValue, _ => null, }; } public static PrimitiveValue From(TValue value) where TValue : struct { Type type = typeof(TValue); if (type.IsEnum) { type = type.GetEnumUnderlyingType(); } return Type.GetTypeCode(type) switch { TypeCode.Boolean => new PrimitiveValue(Convert.ToBoolean(value)), TypeCode.Char => new PrimitiveValue(Convert.ToChar(value)), TypeCode.Byte => new PrimitiveValue(Convert.ToByte(value)), TypeCode.SByte => new PrimitiveValue(Convert.ToSByte(value)), TypeCode.Int16 => new PrimitiveValue(Convert.ToInt16(value)), TypeCode.Int32 => new PrimitiveValue(Convert.ToInt32(value)), TypeCode.Int64 => new PrimitiveValue(Convert.ToInt64(value)), TypeCode.UInt16 => new PrimitiveValue(Convert.ToUInt16(value)), TypeCode.UInt32 => new PrimitiveValue(Convert.ToUInt32(value)), TypeCode.UInt64 => new PrimitiveValue(Convert.ToUInt64(value)), TypeCode.Single => new PrimitiveValue(Convert.ToSingle(value)), TypeCode.Double => new PrimitiveValue(Convert.ToDouble(value)), _ => throw new ArgumentException($"Cannot convert value '{value}' of type '{typeof(TValue).Name}' to PrimitiveValue", "value"), }; } public static PrimitiveValue FromObject(object value) { if (value == null) { return default(PrimitiveValue); } if (value is string value2) { return FromString(value2); } if (value is bool value3) { return new PrimitiveValue(value3); } if (value is char value4) { return new PrimitiveValue(value4); } if (value is byte value5) { return new PrimitiveValue(value5); } if (value is sbyte value6) { return new PrimitiveValue(value6); } if (value is short value7) { return new PrimitiveValue(value7); } if (value is ushort value8) { return new PrimitiveValue(value8); } if (value is int value9) { return new PrimitiveValue(value9); } if (value is uint value10) { return new PrimitiveValue(value10); } if (value is long value11) { return new PrimitiveValue(value11); } if (value is ulong value12) { return new PrimitiveValue(value12); } if (value is float value13) { return new PrimitiveValue(value13); } if (value is double value14) { return new PrimitiveValue(value14); } if (value is Enum) { switch (Type.GetTypeCode(value.GetType().GetEnumUnderlyingType())) { case TypeCode.Byte: return new PrimitiveValue((byte)value); case TypeCode.SByte: return new PrimitiveValue((sbyte)value); case TypeCode.Int16: return new PrimitiveValue((short)value); case TypeCode.Int32: return new PrimitiveValue((int)value); case TypeCode.Int64: return new PrimitiveValue((long)value); case TypeCode.UInt16: return new PrimitiveValue((ushort)value); case TypeCode.UInt32: return new PrimitiveValue((uint)value); case TypeCode.UInt64: return new PrimitiveValue((ulong)value); } } throw new ArgumentException($"Cannot convert '{value}' to primitive value", "value"); } public static implicit operator PrimitiveValue(bool value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(char value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(byte value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(sbyte value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(short value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(ushort value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(int value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(uint value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(long value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(ulong value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(float value) { return new PrimitiveValue(value); } public static implicit operator PrimitiveValue(double value) { return new PrimitiveValue(value); } public static PrimitiveValue FromBoolean(bool value) { return new PrimitiveValue(value); } public static PrimitiveValue FromChar(char value) { return new PrimitiveValue(value); } public static PrimitiveValue FromByte(byte value) { return new PrimitiveValue(value); } public static PrimitiveValue FromSByte(sbyte value) { return new PrimitiveValue(value); } public static PrimitiveValue FromInt16(short value) { return new PrimitiveValue(value); } public static PrimitiveValue FromUInt16(ushort value) { return new PrimitiveValue(value); } public static PrimitiveValue FromInt32(int value) { return new PrimitiveValue(value); } public static PrimitiveValue FromUInt32(uint value) { return new PrimitiveValue(value); } public static PrimitiveValue FromInt64(long value) { return new PrimitiveValue(value); } public static PrimitiveValue FromUInt64(ulong value) { return new PrimitiveValue(value); } public static PrimitiveValue FromSingle(float value) { return new PrimitiveValue(value); } public static PrimitiveValue FromDouble(double value) { return new PrimitiveValue(value); } } public struct ReadOnlyArray : IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable { public struct Enumerator : IEnumerator, IDisposable, IEnumerator { private readonly TValue[] m_Array; private readonly int m_IndexStart; private readonly int m_IndexEnd; private int m_Index; public TValue Current { get { if (m_Index == m_IndexEnd) { throw new InvalidOperationException("Iterated beyond end"); } return m_Array[m_Index]; } } object IEnumerator.Current => Current; internal Enumerator(TValue[] array, int index, int length) { m_Array = array; m_IndexStart = index - 1; m_IndexEnd = index + length; m_Index = m_IndexStart; } public void Dispose() { } public bool MoveNext() { if (m_Index < m_IndexEnd) { m_Index++; } return m_Index != m_IndexEnd; } public void Reset() { m_Index = m_IndexStart; } } internal TValue[] m_Array; internal int m_StartIndex; internal int m_Length; public int Count => m_Length; public TValue this[int index] { get { if (index < 0 || index >= m_Length) { throw new ArgumentOutOfRangeException("index"); } if (m_Array == null) { throw new InvalidOperationException(); } return m_Array[m_StartIndex + index]; } } public ReadOnlyArray(TValue[] array) { m_Array = array; m_StartIndex = 0; m_Length = ((array != null) ? array.Length : 0); } public ReadOnlyArray(TValue[] array, int index, int length) { m_Array = array; m_StartIndex = index; m_Length = length; } public TValue[] ToArray() { TValue[] array = new TValue[m_Length]; if (m_Length > 0) { Array.Copy(m_Array, m_StartIndex, array, 0, m_Length); } return array; } public int IndexOf(Predicate predicate) { if (predicate == null) { throw new ArgumentNullException("predicate"); } for (int i = 0; i < m_Length; i++) { if (predicate(m_Array[m_StartIndex + i])) { return i; } } return -1; } public Enumerator GetEnumerator() { return new Enumerator(m_Array, m_StartIndex, m_Length); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public static implicit operator ReadOnlyArray(TValue[] array) { return new ReadOnlyArray(array); } } public static class ReadOnlyArrayExtensions { public static bool Contains(this ReadOnlyArray array, TValue value) where TValue : IComparable { for (int i = 0; i < array.m_Length; i++) { if (array.m_Array[array.m_StartIndex + i].CompareTo(value) == 0) { return true; } } return false; } public static bool ContainsReference(this ReadOnlyArray array, TValue value) where TValue : class { return array.IndexOfReference(value) != -1; } public static int IndexOfReference(this ReadOnlyArray array, TValue value) where TValue : class { for (int i = 0; i < array.m_Length; i++) { if (array.m_Array[array.m_StartIndex + i] == value) { return i; } } return -1; } internal static bool HaveEqualReferences(this ReadOnlyArray array1, IReadOnlyList array2, int count = int.MaxValue) { int num = Math.Min(array1.Count, count); int num2 = Math.Min(array2.Count, count); if (num != num2) { return false; } for (int i = 0; i < num; i++) { if ((object)array1[i] != (object)array2[i]) { return false; } } return true; } } internal interface ISavedState { void StaticDisposeCurrentState(); void RestoreSavedState(); } internal sealed class SavedStructState : ISavedState where T : struct { public delegate void TypedRestore(ref T state); private T m_State; private TypedRestore m_RestoreAction; private Action m_StaticDisposeCurrentState; internal SavedStructState(ref T state, TypedRestore restoreAction, Action staticDisposeCurrentState = null) { m_State = state; m_RestoreAction = restoreAction; m_StaticDisposeCurrentState = staticDisposeCurrentState; } public void StaticDisposeCurrentState() { if (m_StaticDisposeCurrentState != null) { m_StaticDisposeCurrentState(); m_StaticDisposeCurrentState = null; } } public void RestoreSavedState() { m_RestoreAction(ref m_State); m_RestoreAction = null; } } internal static class SpriteUtilities { public unsafe static Sprite CreateCircleSprite(int radius, Color32 colour) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) int num = radius * 2; Texture2D val = new Texture2D(num, num, (DefaultFormat)0, (TextureCreationFlags)0); NativeArray rawTextureData = val.GetRawTextureData(); Color32* unsafePtr = (Color32*)NativeArrayUnsafeUtility.GetUnsafePtr(rawTextureData); UnsafeUtility.MemSet((void*)unsafePtr, (byte)0, (long)(rawTextureData.Length * UnsafeUtility.SizeOf())); uint* ptr = (uint*)UnsafeUtility.AddressOf(ref colour); ulong num2 = (ulong)((*(long*)ptr << 32) | *ptr); float num3 = radius * radius; for (int i = -radius; i < radius; i++) { int num4 = (int)Mathf.Sqrt(num3 - (float)(i * i)); Color32* ptr2 = (Color32*)((byte*)unsafePtr + (nint)((i + radius) * num) * (nint)Unsafe.SizeOf() + (nint)radius * (nint)Unsafe.SizeOf() - (nint)num4 * (nint)Unsafe.SizeOf()); for (int j = 0; j < num4; j++) { *ptr2 = (Color32)num2; ptr2 = (Color32*)((byte*)ptr2 + (nint)2 * (nint)Unsafe.SizeOf()); } } val.Apply(); return Sprite.Create(val, new Rect(0f, 0f, (float)num, (float)num), new Vector2((float)radius, (float)radius), 1f, 0u, (SpriteMeshType)0); } } internal static class StringHelpers { public static string Escape(this string str, string chars = "\n\t\r\\\"", string replacements = "ntr\\\"") { if (str == null) { return null; } bool flag = false; string text = str; foreach (char value in text) { if (chars.Contains(value)) { flag = true; break; } } if (!flag) { return str; } StringBuilder stringBuilder = new StringBuilder(); text = str; foreach (char value2 in text) { int num = chars.IndexOf(value2); if (num == -1) { stringBuilder.Append(value2); continue; } stringBuilder.Append('\\'); stringBuilder.Append(replacements[num]); } return stringBuilder.ToString(); } public static string Unescape(this string str, string chars = "ntr\\\"", string replacements = "\n\t\r\\\"") { if (str == null) { return str; } if (!str.Contains('\\')) { return str; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < str.Length; i++) { char c = str[i]; if (c == '\\' && i < str.Length - 2) { i++; c = str[i]; int num = chars.IndexOf(c); if (num != -1) { stringBuilder.Append(replacements[num]); } else { stringBuilder.Append(c); } } else { stringBuilder.Append(c); } } return stringBuilder.ToString(); } public static bool Contains(this string str, char ch) { if (str == null) { return false; } return str.IndexOf(ch) != -1; } public static bool Contains(this string str, string text, StringComparison comparison) { if (str == null) { return false; } return str.IndexOf(text, comparison) != -1; } public static string GetPlural(this string str) { if (str == null) { throw new ArgumentNullException("str"); } return str switch { "Mouse" => "Mice", "mouse" => "mice", "Axis" => "Axes", "axis" => "axes", _ => str + "s", }; } public static string NicifyMemorySize(long numBytes) { if (numBytes > 1073741824) { long num = numBytes / 1073741824; float num2 = (float)(numBytes % 1073741824) / 1f; return $"{(float)num + num2} GB"; } if (numBytes > 1048576) { long num3 = numBytes / 1048576; float num4 = (float)(numBytes % 1048576) / 1f; return $"{(float)num3 + num4} MB"; } if (numBytes > 1024) { long num5 = numBytes / 1024; float num6 = (float)(numBytes % 1024) / 1f; return $"{(float)num5 + num6} KB"; } return $"{numBytes} Bytes"; } public static bool FromNicifiedMemorySize(string text, out long result, long defaultMultiplier = 1L) { text = text.Trim(); long num = defaultMultiplier; if (text.EndsWith("MB", StringComparison.InvariantCultureIgnoreCase)) { num = 1048576L; text = text.Substring(0, text.Length - 2); } else if (text.EndsWith("GB", StringComparison.InvariantCultureIgnoreCase)) { num = 1073741824L; text = text.Substring(0, text.Length - 2); } else if (text.EndsWith("KB", StringComparison.InvariantCultureIgnoreCase)) { num = 1024L; text = text.Substring(0, text.Length - 2); } else if (text.EndsWith("Bytes", StringComparison.InvariantCultureIgnoreCase)) { num = 1L; text = text.Substring(0, text.Length - "Bytes".Length); } if (!long.TryParse(text, out var result2)) { result = 0L; return false; } result = result2 * num; return true; } public static int CountOccurrences(this string str, char ch) { if (str == null) { return 0; } int length = str.Length; int num = 0; int num2 = 0; while (num < length) { int num3 = str.IndexOf(ch, num); if (num3 == -1) { break; } num2++; num = num3 + 1; } return num2; } public static IEnumerable Tokenize(this string str) { int i = 0; int length = str.Length; while (i < length) { for (; i < length && char.IsWhiteSpace(str[i]); i++) { } if (i == length) { break; } if (str[i] == '"') { i++; int endPos = i; while (endPos < length && str[endPos] != '"') { int num; if (str[endPos] == '\\' && endPos < length - 1) { num = endPos + 1; endPos = num; } num = endPos + 1; endPos = num; } yield return new Substring(str, i, endPos - i); i = endPos + 1; } else { int endPos = i; while (endPos < length && !char.IsWhiteSpace(str[endPos])) { int num = endPos + 1; endPos = num; } yield return new Substring(str, i, endPos - i); i = endPos; } } } public static IEnumerable Split(this string str, Func predicate) { if (string.IsNullOrEmpty(str)) { yield break; } int length = str.Length; int position = 0; while (position < length) { char arg = str[position]; int num; if (predicate(arg)) { num = position + 1; position = num; continue; } int num2 = position; num = position + 1; for (position = num; position < length; position = num) { arg = str[position]; if (predicate(arg)) { break; } num = position + 1; } yield return str.Substring(num2, position - num2); } } public static string Join(string separator, params TValue[] values) { return Join(values, separator); } public static string Join(IEnumerable values, string separator) { string text = null; int num = 0; StringBuilder stringBuilder = null; foreach (TValue value in values) { if (value == null) { continue; } string text2 = value.ToString(); if (!string.IsNullOrEmpty(text2)) { num++; switch (num) { case 1: text = text2; continue; case 2: stringBuilder = new StringBuilder(); stringBuilder.Append(text); break; } stringBuilder.Append(separator); stringBuilder.Append(text2); } } return num switch { 0 => null, 1 => text, _ => stringBuilder.ToString(), }; } public static string MakeUniqueName(string baseName, IEnumerable existingSet, Func getNameFunc) { if (getNameFunc == null) { throw new ArgumentNullException("getNameFunc"); } if (existingSet == null) { return baseName; } string text = baseName; string text2 = text.ToLower(); bool flag = false; int num = 1; if (baseName.Length > 0) { int num2 = baseName.Length; while (num2 > 0 && char.IsDigit(baseName[num2 - 1])) { num2--; } if (num2 != baseName.Length) { num = int.Parse(baseName.Substring(num2)) + 1; baseName = baseName.Substring(0, num2); } } while (!flag) { flag = true; foreach (TExisting item in existingSet) { if (getNameFunc(item).ToLower() == text2) { text = $"{baseName}{num}"; text2 = text.ToLower(); flag = false; num++; break; } } } return text; } public static bool CharacterSeparatedListsHaveAtLeastOneCommonElement(string firstList, string secondList, char separator) { if (firstList == null) { throw new ArgumentNullException("firstList"); } if (secondList == null) { throw new ArgumentNullException("secondList"); } int num = 0; int length = firstList.Length; int length2 = secondList.Length; while (num < length) { if (firstList[num] == separator) { num++; } int i; for (i = num + 1; i < length && firstList[i] != separator; i++) { } int num2 = i - num; int num3 = 0; while (num3 < length2) { if (secondList[num3] == separator) { num3++; } int j; for (j = num3 + 1; j < length2 && secondList[j] != separator; j++) { } int num4 = j - num3; if (num2 == num4) { int num5 = num; int num6 = num3; bool flag = true; for (int k = 0; k < num2; k++) { char c = firstList[num5 + k]; char c2 = secondList[num6 + k]; if (char.ToLowerInvariant(c) != char.ToLowerInvariant(c2)) { flag = false; break; } } if (flag) { return true; } } num3 = j + 1; } num = i + 1; } return false; } public static int ParseInt(string str, int pos) { int num = 1; int num2 = 0; int length = str.Length; while (pos < length) { int num3 = str[pos] - 48; if (num3 < 0 || num3 > 9) { break; } num2 = num2 * num + num3; num *= 10; pos++; } return num2; } public static bool WriteStringToBuffer(string text, IntPtr buffer, int bufferSizeInCharacters) { uint offset = 0u; return WriteStringToBuffer(text, buffer, bufferSizeInCharacters, ref offset); } public unsafe static bool WriteStringToBuffer(string text, IntPtr buffer, int bufferSizeInCharacters, ref uint offset) { if (buffer == IntPtr.Zero) { throw new ArgumentNullException("buffer"); } int num = ((!string.IsNullOrEmpty(text)) ? text.Length : 0); if (num > 65535) { throw new ArgumentException($"String exceeds max size of {ushort.MaxValue} characters", "text"); } long num2 = offset + 2 * num + 4; if (num2 > bufferSizeInCharacters) { return false; } byte* ptr = (byte*)(void*)buffer + offset; *(ushort*)ptr = (ushort)num; ptr += 2; int num3 = 0; while (num3 < num) { *(char*)ptr = text[num3]; num3++; ptr += 2; } offset = (uint)num2; return true; } public static string ReadStringFromBuffer(IntPtr buffer, int bufferSize) { uint offset = 0u; return ReadStringFromBuffer(buffer, bufferSize, ref offset); } public unsafe static string ReadStringFromBuffer(IntPtr buffer, int bufferSize, ref uint offset) { if (buffer == IntPtr.Zero) { throw new ArgumentNullException("buffer"); } if (offset + 4 > bufferSize) { return null; } byte* ptr = (byte*)(void*)buffer + offset; ushort num = *(ushort*)ptr; ptr += 2; if (num == 0) { return null; } long num2 = offset + 2 * num + 4; if (num2 > bufferSize) { return null; } string result = Marshal.PtrToStringUni(new IntPtr(ptr), num); offset = (uint)num2; return result; } public static bool IsPrintable(this char ch) { if (!char.IsControl(ch)) { return !char.IsWhiteSpace(ch); } return false; } public static string WithAllWhitespaceStripped(this string str) { StringBuilder stringBuilder = new StringBuilder(); foreach (char c in str) { if (!char.IsWhiteSpace(c)) { stringBuilder.Append(c); } } return stringBuilder.ToString(); } public static bool InvariantEqualsIgnoreCase(this string left, string right) { if (string.IsNullOrEmpty(left)) { return string.IsNullOrEmpty(right); } return string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); } public static string ExpandTemplateString(string template, Func mapFunc) { if (string.IsNullOrEmpty(template)) { throw new ArgumentNullException("template"); } if (mapFunc == null) { throw new ArgumentNullException("mapFunc"); } StringBuilder stringBuilder = new StringBuilder(); int length = template.Length; for (int i = 0; i < length; i++) { char c = template[i]; if (c != '{') { stringBuilder.Append(c); continue; } i++; int num = i; for (; i < length && template[i] != '}'; i++) { } string arg = template.Substring(num, i - num); string value = mapFunc(arg); stringBuilder.Append(value); } return stringBuilder.ToString(); } } internal struct Substring : IComparable, IEquatable { private readonly string m_String; private readonly int m_Index; private readonly int m_Length; public bool isEmpty => m_Length == 0; public int length => m_Length; public int index => m_Index; public char this[int index] { get { if (index < 0 || index >= m_Length) { throw new ArgumentOutOfRangeException("index"); } return m_String[m_Index + index]; } } public Substring(string str) { m_String = str; m_Index = 0; if (str != null) { m_Length = str.Length; } else { m_Length = 0; } } public Substring(string str, int index, int length) { m_String = str; m_Index = index; m_Length = length; } public Substring(string str, int index) { m_String = str; m_Index = index; m_Length = str.Length - index; } public override bool Equals(object obj) { if (obj is Substring other) { return Equals(other); } if (obj is string other2) { return Equals(other2); } return false; } public bool Equals(string other) { if (string.IsNullOrEmpty(other)) { return m_Length == 0; } if (other.Length != m_Length) { return false; } for (int i = 0; i < m_Length; i++) { if (other[i] != m_String[m_Index + i]) { return false; } } return true; } public bool Equals(Substring other) { return CompareTo(other) == 0; } public bool Equals(InternedString other) { if (length != other.length) { return false; } return string.Compare(m_String, m_Index, other.ToString(), 0, length, StringComparison.OrdinalIgnoreCase) == 0; } public int CompareTo(Substring other) { return Compare(this, other, StringComparison.CurrentCulture); } public static int Compare(Substring left, Substring right, StringComparison comparison) { if (left.m_Length != right.m_Length) { if (left.m_Length < right.m_Length) { return -1; } return 1; } return string.Compare(left.m_String, left.m_Index, right.m_String, right.m_Index, left.m_Length, comparison); } public bool StartsWith(string str) { if (str.Length > length) { return false; } for (int i = 0; i < str.Length; i++) { if (m_String[m_Index + i] != str[i]) { return false; } } return true; } public string Substr(int index = 0, int length = -1) { if (length < 0) { length = this.length - index; } return m_String.Substring(m_Index + index, length); } public override string ToString() { if (m_String == null) { return string.Empty; } return m_String.Substring(m_Index, m_Length); } public override int GetHashCode() { if (m_String == null) { return 0; } if (m_Index == 0 && m_Length == m_String.Length) { return m_String.GetHashCode(); } return ToString().GetHashCode(); } public static bool operator ==(Substring a, Substring b) { return a.Equals(b); } public static bool operator !=(Substring a, Substring b) { return !a.Equals(b); } public static bool operator ==(Substring a, InternedString b) { return a.Equals(b); } public static bool operator !=(Substring a, InternedString b) { return !a.Equals(b); } public static bool operator ==(InternedString a, Substring b) { return b.Equals(a); } public static bool operator !=(InternedString a, Substring b) { return !b.Equals(a); } public static implicit operator Substring(string s) { return new Substring(s); } } internal static class TypeHelpers { public static TObject As(this object obj) { if (obj == null) { return default(TObject); } return (TObject)obj; } public static bool IsInt(this TypeCode type) { return type switch { TypeCode.Byte => true, TypeCode.SByte => true, TypeCode.Int16 => true, TypeCode.Int32 => true, TypeCode.Int64 => true, TypeCode.UInt16 => true, TypeCode.UInt32 => true, TypeCode.UInt64 => true, _ => false, }; } public static Type GetValueType(MemberInfo member) { FieldInfo fieldInfo = member as FieldInfo; if (fieldInfo != null) { return fieldInfo.FieldType; } PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) { return propertyInfo.PropertyType; } MethodInfo methodInfo = member as MethodInfo; if (methodInfo != null) { return methodInfo.ReturnType; } return null; } public static string GetNiceTypeName(this Type type) { if (type.IsPrimitive) { if (type == typeof(int)) { return "int"; } if (type == typeof(float)) { return "float"; } if (type == typeof(char)) { return "char"; } if (type == typeof(byte)) { return "byte"; } if (type == typeof(short)) { return "short"; } if (type == typeof(long)) { return "long"; } if (type == typeof(double)) { return "double"; } if (type == typeof(uint)) { return "uint"; } if (type == typeof(sbyte)) { return "sbyte"; } if (type == typeof(ushort)) { return "ushort"; } if (type == typeof(ulong)) { return "ulong"; } } return type.Name; } public static Type GetGenericTypeArgumentFromHierarchy(Type type, Type genericTypeDefinition, int argumentIndex) { if (type == null) { throw new ArgumentNullException("type"); } if (genericTypeDefinition == null) { throw new ArgumentNullException("genericTypeDefinition"); } if (argumentIndex < 0) { throw new ArgumentOutOfRangeException("argumentIndex"); } if (genericTypeDefinition.IsInterface) { while (true) { Type[] interfaces = type.GetInterfaces(); bool flag = false; Type[] array = interfaces; foreach (Type type2 in array) { if (type2.IsConstructedGenericType && type2.GetGenericTypeDefinition() == genericTypeDefinition) { type = type2; flag = true; break; } Type genericTypeArgumentFromHierarchy = GetGenericTypeArgumentFromHierarchy(type2, genericTypeDefinition, argumentIndex); if (genericTypeArgumentFromHierarchy != null) { return genericTypeArgumentFromHierarchy; } } if (flag) { break; } type = type.BaseType; if (type == null || type == typeof(object)) { return null; } } } else { while (!type.IsConstructedGenericType || type.GetGenericTypeDefinition() != genericTypeDefinition) { type = type.BaseType; if (type == typeof(object)) { return null; } } } return type.GenericTypeArguments[argumentIndex]; } } internal struct TypeTable { public Dictionary table; public IEnumerable names => table.Keys.Select((InternedString x) => x.ToString()); public IEnumerable internedNames => table.Keys; public void Initialize() { table = new Dictionary(); } public InternedString FindNameForType(Type type) { if (type == null) { throw new ArgumentNullException("type"); } foreach (KeyValuePair item in table) { if (item.Value == type) { return item.Key; } } return default(InternedString); } public void AddTypeRegistration(string name, Type type) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Name cannot be null or empty", "name"); } if (type == null) { throw new ArgumentNullException("type"); } InternedString key = new InternedString(name); table[key] = type; } public Type LookupTypeRegistration(string name) { if (string.IsNullOrEmpty(name)) { return null; } if (table == null) { throw new InvalidOperationException("Input System not yet initialized"); } InternedString key = new InternedString(name); if (table.TryGetValue(key, out var value)) { return value; } return null; } } } namespace UnityEngine.InputSystem.Composites { [DisplayStringFormat("{negative}/{positive}")] [DisplayName("Positive/Negative Binding")] public class AxisComposite : InputBindingComposite { public enum WhichSideWins { Neither, Positive, Negative } [InputControl(layout = "Axis")] public int negative; [InputControl(layout = "Axis")] public int positive; [Tooltip("Value to return when the negative side is fully actuated.")] public float minValue = -1f; [Tooltip("Value to return when the positive side is fully actuated.")] public float maxValue = 1f; [Tooltip("If both the positive and negative side are actuated, decides what value to return. 'Neither' (default) means that the resulting value is the midpoint between min and max. 'Positive' means that max will be returned. 'Negative' means that min will be returned.")] public WhichSideWins whichSideWins; public float midPoint => (maxValue + minValue) / 2f; public override float ReadValue(ref InputBindingCompositeContext context) { float num = Mathf.Abs(context.ReadValue(negative)); float num2 = Mathf.Abs(context.ReadValue(positive)); bool flag = num > Mathf.Epsilon; bool flag2 = num2 > Mathf.Epsilon; if (flag == flag2) { switch (whichSideWins) { case WhichSideWins.Negative: flag2 = false; break; case WhichSideWins.Positive: flag = false; break; case WhichSideWins.Neither: return midPoint; } } float num3 = midPoint; if (flag) { return num3 - (num3 - minValue) * num; } return num3 + (maxValue - num3) * num2; } public override float EvaluateMagnitude(ref InputBindingCompositeContext context) { float num = ReadValue(ref context); if (num < midPoint) { num = Mathf.Abs(num - midPoint); return NormalizeProcessor.Normalize(num, 0f, Mathf.Abs(minValue), 0f); } num = Mathf.Abs(num - midPoint); return NormalizeProcessor.Normalize(num, 0f, Mathf.Abs(maxValue), 0f); } } [DesignTimeVisible(false)] [DisplayStringFormat("{modifier}+{button}")] public class ButtonWithOneModifier : InputBindingComposite { [InputControl(layout = "Button")] public int modifier; [InputControl(layout = "Button")] public int button; public bool overrideModifiersNeedToBePressedFirst; public override float ReadValue(ref InputBindingCompositeContext context) { if (ModifierIsPressed(ref context)) { return context.ReadValue(button); } return 0f; } private bool ModifierIsPressed(ref InputBindingCompositeContext context) { bool flag = context.ReadValueAsButton(modifier); if (flag && !overrideModifiersNeedToBePressedFirst) { double pressTime = context.GetPressTime(button); return context.GetPressTime(modifier) <= pressTime; } return flag; } public override float EvaluateMagnitude(ref InputBindingCompositeContext context) { return ReadValue(ref context); } protected override void FinishSetup(ref InputBindingCompositeContext context) { if (!overrideModifiersNeedToBePressedFirst) { overrideModifiersNeedToBePressedFirst = !InputSystem.settings.shortcutKeysConsumeInput; } } } [DesignTimeVisible(false)] [DisplayStringFormat("{modifier1}+{modifier2}+{button}")] public class ButtonWithTwoModifiers : InputBindingComposite { [InputControl(layout = "Button")] public int modifier1; [InputControl(layout = "Button")] public int modifier2; [InputControl(layout = "Button")] public int button; public bool overrideModifiersNeedToBePressedFirst; public override float ReadValue(ref InputBindingCompositeContext context) { if (ModifiersArePressed(ref context)) { return context.ReadValue(button); } return 0f; } private bool ModifiersArePressed(ref InputBindingCompositeContext context) { bool flag = context.ReadValueAsButton(modifier1) && context.ReadValueAsButton(modifier2); if (flag && !overrideModifiersNeedToBePressedFirst) { double pressTime = context.GetPressTime(button); double pressTime2 = context.GetPressTime(modifier1); double pressTime3 = context.GetPressTime(modifier2); if (pressTime2 <= pressTime) { return pressTime3 <= pressTime; } return false; } return flag; } public override float EvaluateMagnitude(ref InputBindingCompositeContext context) { return ReadValue(ref context); } protected override void FinishSetup(ref InputBindingCompositeContext context) { if (!overrideModifiersNeedToBePressedFirst) { overrideModifiersNeedToBePressedFirst = !InputSystem.settings.shortcutKeysConsumeInput; } } } [DisplayStringFormat("{modifier}+{binding}")] [DisplayName("Binding With One Modifier")] public class OneModifierComposite : InputBindingComposite { [InputControl(layout = "Button")] public int modifier; [InputControl] public int binding; public bool overrideModifiersNeedToBePressedFirst; private int m_ValueSizeInBytes; private Type m_ValueType; private bool m_BindingIsButton; public override Type valueType => m_ValueType; public override int valueSizeInBytes => m_ValueSizeInBytes; public override float EvaluateMagnitude(ref InputBindingCompositeContext context) { if (ModifierIsPressed(ref context)) { return context.EvaluateMagnitude(binding); } return 0f; } public unsafe override void ReadValue(ref InputBindingCompositeContext context, void* buffer, int bufferSize) { if (ModifierIsPressed(ref context)) { context.ReadValue(binding, buffer, bufferSize); } else { UnsafeUtility.MemClear(buffer, (long)m_ValueSizeInBytes); } } private bool ModifierIsPressed(ref InputBindingCompositeContext context) { bool flag = context.ReadValueAsButton(modifier); if (flag && m_BindingIsButton && !overrideModifiersNeedToBePressedFirst) { double pressTime = context.GetPressTime(binding); return context.GetPressTime(modifier) <= pressTime; } return flag; } protected override void FinishSetup(ref InputBindingCompositeContext context) { DetermineValueTypeAndSize(ref context, binding, out m_ValueType, out m_ValueSizeInBytes, out m_BindingIsButton); if (!overrideModifiersNeedToBePressedFirst) { overrideModifiersNeedToBePressedFirst = !InputSystem.settings.shortcutKeysConsumeInput; } } public override object ReadValueAsObject(ref InputBindingCompositeContext context) { if (context.ReadValueAsButton(modifier)) { return context.ReadValueAsObject(binding); } return null; } internal static void DetermineValueTypeAndSize(ref InputBindingCompositeContext context, int part, out Type valueType, out int valueSizeInBytes, out bool isButton) { valueSizeInBytes = 0; isButton = true; Type type = null; foreach (InputBindingCompositeContext.PartBinding control in context.controls) { if (control.part == part) { Type type2 = control.control.valueType; if (type == null || type2.IsAssignableFrom(type)) { type = type2; } else if (!type.IsAssignableFrom(type2)) { type = typeof(Object); } valueSizeInBytes = Math.Max(control.control.valueSizeInBytes, valueSizeInBytes); isButton &= control.control.isButton; } } valueType = type; } } [DisplayStringFormat("{modifier1}+{modifier2}+{binding}")] [DisplayName("Binding With Two Modifiers")] public class TwoModifiersComposite : InputBindingComposite { [InputControl(layout = "Button")] public int modifier1; [InputControl(layout = "Button")] public int modifier2; [InputControl] public int binding; public bool overrideModifiersNeedToBePressedFirst; private int m_ValueSizeInBytes; private Type m_ValueType; private bool m_BindingIsButton; public override Type valueType => m_ValueType; public override int valueSizeInBytes => m_ValueSizeInBytes; public override float EvaluateMagnitude(ref InputBindingCompositeContext context) { if (ModifiersArePressed(ref context)) { return context.EvaluateMagnitude(binding); } return 0f; } public unsafe override void ReadValue(ref InputBindingCompositeContext context, void* buffer, int bufferSize) { if (ModifiersArePressed(ref context)) { context.ReadValue(binding, buffer, bufferSize); } else { UnsafeUtility.MemClear(buffer, (long)m_ValueSizeInBytes); } } private bool ModifiersArePressed(ref InputBindingCompositeContext context) { bool flag = context.ReadValueAsButton(modifier1) && context.ReadValueAsButton(modifier2); if (flag && m_BindingIsButton && !overrideModifiersNeedToBePressedFirst) { double pressTime = context.GetPressTime(binding); double pressTime2 = context.GetPressTime(modifier1); double pressTime3 = context.GetPressTime(modifier2); if (pressTime2 <= pressTime) { return pressTime3 <= pressTime; } return false; } return flag; } protected override void FinishSetup(ref InputBindingCompositeContext context) { OneModifierComposite.DetermineValueTypeAndSize(ref context, binding, out m_ValueType, out m_ValueSizeInBytes, out m_BindingIsButton); if (!overrideModifiersNeedToBePressedFirst) { overrideModifiersNeedToBePressedFirst = !InputSystem.settings.shortcutKeysConsumeInput; } } public override object ReadValueAsObject(ref InputBindingCompositeContext context) { if (context.ReadValueAsButton(modifier1) && context.ReadValueAsButton(modifier2)) { return context.ReadValueAsObject(binding); } return null; } } [DisplayStringFormat("{up}/{left}/{down}/{right}")] [DisplayName("Up/Down/Left/Right Composite")] public class Vector2Composite : InputBindingComposite { public enum Mode { Analog = 2, DigitalNormalized = 0, Digital = 1 } [InputControl(layout = "Axis")] public int up; [InputControl(layout = "Axis")] public int down; [InputControl(layout = "Axis")] public int left; [InputControl(layout = "Axis")] public int right; [Obsolete("Use Mode.DigitalNormalized with 'mode' instead")] public bool normalize = true; public Mode mode; public override Vector2 ReadValue(ref InputBindingCompositeContext context) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) Mode mode = this.mode; if (mode == Mode.Analog) { float num = context.ReadValue(up); float num2 = context.ReadValue(down); float num3 = context.ReadValue(left); float num4 = context.ReadValue(right); return DpadControl.MakeDpadVector(num, num2, num3, num4); } bool num5 = context.ReadValueAsButton(up); bool flag = context.ReadValueAsButton(down); bool flag2 = context.ReadValueAsButton(left); bool flag3 = context.ReadValueAsButton(right); if (!normalize) { mode = Mode.Digital; } return DpadControl.MakeDpadVector(num5, flag, flag2, flag3, mode == Mode.DigitalNormalized); } public override float EvaluateMagnitude(ref InputBindingCompositeContext context) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) Vector2 val = ReadValue(ref context); return ((Vector2)(ref val)).magnitude; } } [DisplayStringFormat("{up}+{down}/{left}+{right}/{forward}+{backward}")] [DisplayName("Up/Down/Left/Right/Forward/Backward Composite")] public class Vector3Composite : InputBindingComposite { public enum Mode { Analog, DigitalNormalized, Digital } [InputControl(layout = "Axis")] public int up; [InputControl(layout = "Axis")] public int down; [InputControl(layout = "Axis")] public int left; [InputControl(layout = "Axis")] public int right; [InputControl(layout = "Axis")] public int forward; [InputControl(layout = "Axis")] public int backward; public Mode mode; public override Vector3 ReadValue(ref InputBindingCompositeContext context) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) if (mode == Mode.Analog) { float num = context.ReadValue(up); float num2 = context.ReadValue(down); float num3 = context.ReadValue(left); float num4 = context.ReadValue(right); float num5 = context.ReadValue(forward); float num6 = context.ReadValue(backward); return new Vector3(num4 - num3, num - num2, num5 - num6); } float num7 = (context.ReadValueAsButton(up) ? 1f : 0f); float num8 = (context.ReadValueAsButton(down) ? (-1f) : 0f); float num9 = (context.ReadValueAsButton(left) ? (-1f) : 0f); float num10 = (context.ReadValueAsButton(right) ? 1f : 0f); float num11 = (context.ReadValueAsButton(forward) ? 1f : 0f); float num12 = (context.ReadValueAsButton(backward) ? (-1f) : 0f); Vector3 normalized = default(Vector3); ((Vector3)(ref normalized))..ctor(num9 + num10, num7 + num8, num11 + num12); if (mode == Mode.DigitalNormalized) { normalized = ((Vector3)(ref normalized)).normalized; return normalized; } return normalized; } } }