Example #1
0
 // Add all overrides that have been applied to this action to the given list.
 // Returns the number of overrides found.
 public static int GetBindingOverrides(this InputAction action, List <InputBinding> overrides)
 {
     throw new NotImplementedException();
 }
Example #2
0
 public ActionConstraint Canceled <TValue>(InputAction action, InputControl <TValue> control, TValue value, double?time = null)
     where TValue : struct
 {
     return(new ActionConstraint(InputActionPhase.Canceled, action, control, value, time: time));
 }
Example #3
0
 public void Trigger <TValue>(InputAction action, InputControl <TValue> control, TValue value)
     where TValue : struct
 {
     throw new NotImplementedException();
 }
 public static BindingSyntax ChangeBindingWithPath(this InputAction action, string path)
 {
     return(action.ChangeBinding(new InputBinding {
         path = path
     }));
 }
 internal CompositeSyntax(InputActionMap map, InputAction action, int compositeIndex)
 {
     m_Action         = action;
     m_ActionMap      = map;
     m_CompositeIndex = compositeIndex;
 }
Example #6
0
 private static void BindAxis(UnityEngine.InputSystem.InputAction action, AxisClosure prop)
 {
     action.performed += context => prop(context.ReadValue <Vector2>());
     action.canceled  += context => prop(Vector2.zero);
 }
 public static BindingSyntax ChangeBindingWithId(this InputAction action, Guid id)
 {
     return(action.ChangeBinding(new InputBinding {
         id = id
     }));
 }
        public unsafe void AddActionMap(InputActionMap map)
        {
            Debug.Assert(map != null, "Received null map");

            var actionsInThisMap      = map.m_Actions;
            var bindingsInThisMap     = map.m_Bindings;
            var bindingCountInThisMap = bindingsInThisMap?.Length ?? 0;
            var actionCountInThisMap  = actionsInThisMap?.Length ?? 0;
            var mapIndex = totalMapCount;

            // Keep track of indices for this map.
            var actionStartIndex      = totalActionCount;
            var bindingStartIndex     = totalBindingCount;
            var controlStartIndex     = totalControlCount;
            var interactionStartIndex = totalInteractionCount;
            var processorStartIndex   = totalProcessorCount;
            var compositeStartIndex   = totalCompositeCount;

            // Allocate an initial block of memory. We probably will have to re-allocate once
            // at the end to accommodate interactions and controls added from the map.
            var newMemory = new InputActionState.UnmanagedMemory();

            newMemory.Allocate(
                mapCount: totalMapCount + 1,
                actionCount: totalActionCount + actionCountInThisMap,
                bindingCount: totalBindingCount + bindingCountInThisMap,
                // We reallocate for the following once we know the final count.
                interactionCount: totalInteractionCount,
                compositeCount: totalCompositeCount,
                controlCount: totalControlCount);
            if (memory.isAllocated)
            {
                newMemory.CopyDataFrom(memory);
            }

            ////TODO: make sure composite objects get all the bindings they need
            ////TODO: handle case where we have bindings resolving to the same control
            ////      (not so clear cut what to do there; each binding may have a different interaction setup, for example)
            var         currentCompositeBindingIndex     = InputActionState.kInvalidIndex;
            var         currentCompositeIndex            = InputActionState.kInvalidIndex;
            var         currentCompositePartCount        = 0;
            var         currentCompositeActionIndexInMap = InputActionState.kInvalidIndex;
            InputAction currentCompositeAction           = null;
            var         bindingMaskOnThisMap             = map.m_BindingMask;
            var         devicesForThisMap = map.devices;

            // Can't use `using` as we need to use it with `ref`.
            var resolvedControls = new InputControlList <InputControl>(Allocator.Temp);

            // We gather all controls in temporary memory and then move them over into newMemory once
            // we're done resolving.
            try
            {
                for (var n = 0; n < bindingCountInThisMap; ++n)
                {
                    var     bindingStatesPtr  = newMemory.bindingStates;
                    ref var unresolvedBinding = ref bindingsInThisMap[n];
                    var     bindingIndex      = bindingStartIndex + n;
                    var     isComposite       = unresolvedBinding.isComposite;
                    var     isPartOfComposite = !isComposite && unresolvedBinding.isPartOfComposite;
                    var     bindingState      = &bindingStatesPtr[bindingIndex];

                    try
                    {
                        ////TODO: if it's a composite, check if any of the children matches our binding masks (if any) and skip composite if none do

                        var firstControlIndex     = 0; // numControls dictates whether this is a valid index or not.
                        var firstInteractionIndex = InputActionState.kInvalidIndex;
                        var firstProcessorIndex   = InputActionState.kInvalidIndex;
                        var actionIndexForBinding = InputActionState.kInvalidIndex;
                        var partIndex             = InputActionState.kInvalidIndex;

                        var numControls     = 0;
                        var numInteractions = 0;
                        var numProcessors   = 0;

                        // Make sure that if it's part of a composite, we are actually part of a composite.
                        if (isPartOfComposite && currentCompositeBindingIndex == InputActionState.kInvalidIndex)
                        {
                            throw new InvalidOperationException(
                                      $"Binding '{unresolvedBinding}' is marked as being part of a composite but the preceding binding is not a composite");
                        }

                        // Try to find action.
                        //
                        // NOTE: We ignore actions on bindings that are part of composites. We only allow
                        //       actions to be triggered from the composite itself.
                        var         actionIndexInMap = InputActionState.kInvalidIndex;
                        var         actionName       = unresolvedBinding.action;
                        InputAction action           = null;
                        if (!isPartOfComposite)
                        {
                            if (!string.IsNullOrEmpty(actionName))
                            {
                                ////REVIEW: should we fail here if we don't manage to find the action
                                actionIndexInMap = map.FindActionIndex(actionName);
                            }
                            else if (map.m_SingletonAction != null)
                            {
                                // Special-case for singleton actions that don't have names.
                                actionIndexInMap = 0;
                            }

                            if (actionIndexInMap != InputActionState.kInvalidIndex)
                            {
                                action = actionsInThisMap[actionIndexInMap];
                            }
                        }
                        else
                        {
                            actionIndexInMap = currentCompositeActionIndexInMap;
                            action           = currentCompositeAction;
                        }

                        // If it's a composite, start a chain.
                        if (isComposite)
                        {
                            currentCompositeBindingIndex     = bindingIndex;
                            currentCompositeAction           = action;
                            currentCompositeActionIndexInMap = actionIndexInMap;
                        }

                        // Determine if the binding is disabled.
                        // Disabled if path is empty.
                        var path = unresolvedBinding.effectivePath;
                        var bindingIsDisabled = string.IsNullOrEmpty(path)

                                                // Also, if we can't find the action to trigger for the binding, we just go and disable
                                                // the binding.
                                                || action == null

                                                // Also, disabled if binding doesn't match with our binding mask (might be empty).
                                                || (!isComposite && bindingMask != null &&
                                                    !bindingMask.Value.Matches(ref unresolvedBinding,
                                                                               InputBinding.MatchOptions.EmptyGroupMatchesAny))

                                                // Also, disabled if binding doesn't match the binding mask on the map (might be empty).
                                                || (!isComposite && bindingMaskOnThisMap != null &&
                                                    !bindingMaskOnThisMap.Value.Matches(ref unresolvedBinding,
                                                                                        InputBinding.MatchOptions.EmptyGroupMatchesAny))

                                                // Finally, also disabled if binding doesn't match the binding mask on the action (might be empty).
                                                || (!isComposite && action?.m_BindingMask != null &&
                                                    !action.m_BindingMask.Value.Matches(ref unresolvedBinding,
                                                                                        InputBinding.MatchOptions.EmptyGroupMatchesAny));

                        // If the binding isn't disabled, look up controls now. We do this first as we may still disable the
                        // binding if it doesn't resolve to any controls or resolves only to controls already bound to by
                        // other bindings.
                        //
                        // NOTE: We continuously add controls here to `resolvedControls`. Once we've completed our
                        //       pass over the bindings in the map, `resolvedControls` will have all the controls for
                        //       the current map.
                        if (!bindingIsDisabled && !isComposite)
                        {
                            firstControlIndex = memory.controlCount + resolvedControls.Count;
                            if (devicesForThisMap != null)
                            {
                                // Search in devices for only this map.
                                var list = devicesForThisMap.Value;
                                for (var i = 0; i < list.Count; ++i)
                                {
                                    var device = list[i];
                                    if (!device.added)
                                    {
                                        continue; // Skip devices that have been removed.
                                    }
                                    numControls += InputControlPath.TryFindControls(device, path, 0, ref resolvedControls);
                                }
                            }
                            else
                            {
                                // Search globally.
                                numControls = InputSystem.FindControls(path, ref resolvedControls);
                            }

                            // Check for controls that are already bound to the action through other
                            // bindings. The first binding that grabs a specific control gets to "own" it.
                            if (numControls > 0)
                            {
                                for (var i = 0; i < n; ++i)
                                {
                                    ref var otherBindingState = ref bindingStatesPtr[bindingStartIndex + i];

                                    // Skip if binding has no controls.
                                    if (otherBindingState.controlCount == 0)
                                    {
                                        continue;
                                    }

                                    // Skip if binding isn't from same action.
                                    if (otherBindingState.actionIndex != actionStartIndex + actionIndexInMap)
                                    {
                                        continue;
                                    }

                                    // Check for controls in the set that we just resolved that are also on the other
                                    // binding. Each such control we find, we kick out of the list.
                                    for (var k = 0; k < numControls; ++k)
                                    {
                                        var controlOnCurrentBinding    = resolvedControls[firstControlIndex + k - memory.controlCount];
                                        var controlIndexOnOtherBinding = resolvedControls.IndexOf(controlOnCurrentBinding,
                                                                                                  otherBindingState.controlStartIndex - memory.controlCount, otherBindingState.controlCount);
                                        if (controlIndexOnOtherBinding != -1)
                                        {
                                            // Control is bound to a previous binding. Remove it from the current binding.
                                            resolvedControls.RemoveAt(firstControlIndex + k - memory.controlCount);
                                            --numControls;
                                            --k;
                                        }
                                    }
                                }
                            }

                            // Disable binding if it doesn't resolve to any controls.
                            // NOTE: This also happens to bindings that got all their resolved controls removed because other bindings from the same
                            //       action already grabbed them.
                            if (numControls == 0)
                            {
                                bindingIsDisabled = true;
                            }
                        }

                        // If the binding isn't disabled, resolve its controls, processors, and interactions.
                        if (!bindingIsDisabled)
                        {
                            // Instantiate processors.
                            var processorString = unresolvedBinding.effectiveProcessors;
                            if (!string.IsNullOrEmpty(processorString))
                            {
                                // Add processors from binding.
                                firstProcessorIndex = ResolveProcessors(processorString);
                                if (firstProcessorIndex != InputActionState.kInvalidIndex)
                                {
                                    numProcessors = totalProcessorCount - firstProcessorIndex;
                                }
                            }
                            if (!string.IsNullOrEmpty(action.m_Processors))
                            {
                                // Add processors from action.
                                var index = ResolveProcessors(action.m_Processors);
                                if (index != InputActionState.kInvalidIndex)
                                {
                                    if (firstProcessorIndex == InputActionState.kInvalidIndex)
                                    {
                                        firstProcessorIndex = index;
                                    }
                                    numProcessors += totalProcessorCount - index;
                                }
                            }

                            // Instantiate interactions.
                            var interactionString = unresolvedBinding.effectiveInteractions;
                            if (!string.IsNullOrEmpty(interactionString))
                            {
                                // Add interactions from binding.
                                firstInteractionIndex = ResolveInteractions(interactionString);
                                if (firstInteractionIndex != InputActionState.kInvalidIndex)
                                {
                                    numInteractions = totalInteractionCount - firstInteractionIndex;
                                }
                            }
                            if (!string.IsNullOrEmpty(action.m_Interactions))
                            {
                                // Add interactions from action.
                                var index = ResolveInteractions(action.m_Interactions);
                                if (index != InputActionState.kInvalidIndex)
                                {
                                    if (firstInteractionIndex == InputActionState.kInvalidIndex)
                                    {
                                        firstInteractionIndex = index;
                                    }
                                    numInteractions += totalInteractionCount - index;
                                }
                            }

                            // If it's the start of a composite chain, create the composite. Otherwise, go and
                            // resolve controls for the binding.
                            if (isComposite)
                            {
                                // The composite binding entry itself does not resolve to any controls.
                                // It creates a composite binding object which is then populated from
                                // subsequent bindings.

                                // Instantiate. For composites, the path is the name of the composite.
                                var composite = InstantiateBindingComposite(unresolvedBinding.path);
                                currentCompositeIndex =
                                    ArrayHelpers.AppendWithCapacity(ref composites, ref totalCompositeCount, composite);

                                // Record where the controls for parts of the composite start.
                                firstControlIndex = memory.controlCount + resolvedControls.Count;
                            }
                            else
                            {
                                // If we've reached the end of a composite chain, finish
                                // off the current composite.
                                if (!isPartOfComposite && currentCompositeBindingIndex != InputActionState.kInvalidIndex)
                                {
                                    currentCompositePartCount        = 0;
                                    currentCompositeBindingIndex     = InputActionState.kInvalidIndex;
                                    currentCompositeIndex            = InputActionState.kInvalidIndex;
                                    currentCompositeAction           = null;
                                    currentCompositeActionIndexInMap = InputActionState.kInvalidIndex;
                                }
                            }
                        }

                        // If the binding is part of a composite, pass the resolved controls
                        // on to the composite.
                        if (isPartOfComposite && currentCompositeBindingIndex != InputActionState.kInvalidIndex && numControls > 0)
                        {
                            // Make sure the binding is named. The name determines what in the composite
                            // to bind to.
                            if (string.IsNullOrEmpty(unresolvedBinding.name))
                            {
                                throw new InvalidOperationException(
                                          $"Binding '{unresolvedBinding}' that is part of composite '{composites[currentCompositeIndex]}' is missing a name");
                            }

                            // Give a part index for the
                            partIndex = AssignCompositePartIndex(composites[currentCompositeIndex], unresolvedBinding.name,
                                                                 ref currentCompositePartCount);

                            // Keep track of total number of controls bound in the composite.
                            bindingStatesPtr[currentCompositeBindingIndex].controlCount += numControls;

                            // Force action index on part binding to be same as that of composite.
                            actionIndexForBinding = bindingStatesPtr[currentCompositeBindingIndex].actionIndex;
                        }
                        else if (actionIndexInMap != InputActionState.kInvalidIndex)
                        {
                            actionIndexForBinding = actionStartIndex + actionIndexInMap;
                        }

                        // Store resolved binding.
                        *bindingState = new InputActionState.BindingState
                        {
                            controlStartIndex = firstControlIndex,
                            // For composites, this will be adjusted as we add each part.
                            controlCount                     = numControls,
                            interactionStartIndex            = firstInteractionIndex,
                            interactionCount                 = numInteractions,
                            processorStartIndex              = firstProcessorIndex,
                            processorCount                   = numProcessors,
                            isComposite                      = isComposite,
                            isPartOfComposite                = unresolvedBinding.isPartOfComposite,
                            partIndex                        = partIndex,
                            actionIndex                      = actionIndexForBinding,
                            compositeOrCompositeBindingIndex = isComposite ? currentCompositeIndex : currentCompositeBindingIndex,
                            mapIndex = totalMapCount,
                            wantsInitialStateCheck = action?.wantsInitialStateCheck ?? false
                        };
                    }
                    catch (Exception exception)
                    {
                        Debug.LogError(
                            $"{exception.GetType().Name} while resolving binding '{unresolvedBinding}' in action map '{map}'");
                        Debug.LogException(exception);

                        // Don't swallow exceptions that indicate something is wrong in the code rather than
                        // in the data.
                        if (exception.IsExceptionIndicatingBugInCode())
                        {
                            throw;
                        }
                    }
                }
Example #9
0
 public ActionConstraint Performed(InputAction action, InputControl control = null)
 {
     return(new ActionConstraint(InputActionPhase.Performed, action, control));
 }
 public InputActionProperty(InputAction action)
 {
     m_UseReference = false;
     m_Action       = action;
     m_Reference    = null;
 }
 public bool Equals(InputAction other)
 {
     return(ReferenceEquals(action, other));
 }
 public static InputActionProperty ToInputActionProperty(InputAction action)
 {
     return(new InputActionProperty(action));
 }
 /// <summary>
 /// Initiate an operation that interactively rebinds the given action based on received input.
 /// </summary>
 /// <param name="action">Action to perform rebinding on.</param>
 /// <returns></returns>
 /// <exception cref="ArgumentNullException"></exception>
 /// <exception cref="ArgumentException"></exception>
 public static RebindingOperation PerformInteractiveRebinding(this InputAction action)
 {
     return(new RebindingOperation().WithAction(action));
 }
Example #14
0
 public RebindingOperation WithCancelAction(InputAction action)
 {
     throw new NotImplementedException();
 }
Example #15
0
 private void BindBool(UnityEngine.InputSystem.InputAction action, BoolClosure prop)
 {
     action.performed += context => prop(context.ReadValue <float>() >= InputSystem.settings.defaultButtonPressPoint);
     action.canceled  += context => prop(false);
 }
Example #16
0
 public ActionConstraint Canceled(InputAction action, InputControl control = null)
 {
     return(new ActionConstraint(InputActionPhase.Canceled, action, control));
 }
Example #17
0
 private void BindFloat(UnityEngine.InputSystem.InputAction action, FloatClosure prop)
 {
     action.performed += context => prop(context.ReadValue <float>());
     action.canceled  += context => prop(0);
 }
Example #18
0
 public ActionConstraint Performed <TInteraction>(InputAction action, InputControl control = null)
     where TInteraction : IInputInteraction
 {
     return(new ActionConstraint(InputActionPhase.Performed, action, control, interaction: typeof(TInteraction)));
 }
        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}'", nameof(action));
            }

            if (action == null)
            {
                return(AddBinding(actionMap, path: path, interactions: interactions, groups: groups));
            }

            return(AddBinding(actionMap, path: path, interactions: interactions, groups: groups,
                              action: action.id));
        }
 public ActionConstraint Canceled(InputAction action, InputControl control = null, double?time = null, double?duration = null, object value = null)
 {
     return(new ActionConstraint(InputActionPhase.Canceled, action, control, time: time, duration: duration, value: value));
 }
 public static BindingSyntax ChangeBindingWithGroup(this InputAction action, string group)
 {
     return(action.ChangeBinding(new InputBinding {
         groups = group
     }));
 }
Example #22
0
 public ActionConstraint Started(InputAction action, InputControl control = null, double?time = null)
 {
     return(new ActionConstraint(InputActionPhase.Started, action, control, time: time, duration: 0));
 }
 internal BindingSyntax(InputActionMap map, InputAction action, int bindingIndex)
 {
     m_ActionMap    = map;
     m_Action       = action;
     m_BindingIndex = bindingIndex;
 }
Example #24
0
 public ActionConstraint Performed(InputAction action, InputControl control = null, double?time = null, double?duration = null)
 {
     return(new ActionConstraint(InputActionPhase.Performed, action, control, time: time, duration: duration));
 }
Example #25
0
 public ActionConstraint Canceled(InputAction action, InputControl control = null, double?time = null)
 {
     return(new ActionConstraint(InputActionPhase.Canceled, action, control, time: time));
 }
Example #26
0
 public ActionConstraint Performed <TValue>(InputAction action, InputControl <TValue> control, TValue value, double?time = null, double?duration = null)
     where TValue : struct
 {
     return(new ActionConstraint(InputActionPhase.Performed, action, control, value, time: time, duration: duration));
 }
Example #27
0
 public ActionConstraint Canceled <TInteraction>(InputAction action, InputControl control = null, double?time = null)
     where TInteraction : IInputInteraction
 {
     return(new ActionConstraint(InputActionPhase.Canceled, action, control, interaction: typeof(TInteraction), time: time));
 }
Example #28
0
 public ActionConstraint Performed <TInteraction>(InputAction action, InputControl control = null, object value = null, double?time = null, double?duration = null)
     where TInteraction : IInputInteraction
 {
     return(new ActionConstraint(InputActionPhase.Performed, action, control, interaction: typeof(TInteraction), time: time,
                                 duration: duration, value: value));
 }
        public unsafe void AddActionMap(InputActionMap map)
        {
            Debug.Assert(map != null);

            var actionsInThisMap      = map.m_Actions;
            var bindingsInThisMap     = map.m_Bindings;
            var bindingCountInThisMap = bindingsInThisMap?.Length ?? 0;
            var actionCountInThisMap  = actionsInThisMap?.Length ?? 0;
            var mapIndex = totalMapCount;

            // Keep track of indices for this map.
            var actionStartIndex      = totalActionCount;
            var bindingStartIndex     = totalBindingCount;
            var controlStartIndex     = totalControlCount;
            var interactionStartIndex = totalInteractionCount;
            var processorStartIndex   = totalProcessorCount;
            var compositeStartIndex   = totalCompositeCount;

            // Allocate an initial block of memory. We probably will have to re-allocate once
            // at the end to accommodate interactions and controls added from the map.
            var newMemory = new InputActionState.UnmanagedMemory();

            newMemory.Allocate(
                mapCount: totalMapCount + 1,
                actionCount: totalActionCount + actionCountInThisMap,
                bindingCount: totalBindingCount + bindingCountInThisMap,
                // We reallocate for the following once we know the final count.
                interactionCount: totalInteractionCount,
                compositeCount: totalCompositeCount,
                controlCount: totalControlCount);
            if (memory.isAllocated)
            {
                newMemory.CopyDataFrom(memory);
            }

            ////TODO: make sure composite objects get all the bindings they need
            ////TODO: handle case where we have bindings resolving to the same control
            ////      (not so clear cut what to do there; each binding may have a different interaction setup, for example)
            var         currentCompositeBindingIndex     = InputActionState.kInvalidIndex;
            var         currentCompositeIndex            = InputActionState.kInvalidIndex;
            var         currentCompositePartCount        = 0;
            var         currentCompositeActionIndexInMap = InputActionState.kInvalidIndex;
            InputAction currentCompositeAction           = null;
            var         bindingMaskOnThisMap             = map.m_BindingMask;
            var         devicesForThisMap = map.devices;

            // Can't use `using` as we need to use it with `ref`.
            var resolvedControls = new InputControlList <InputControl>(Allocator.Temp);

            // We gather all controls in temporary memory and then move them over into newMemory once
            // we're done resolving.
            try
            {
                for (var n = 0; n < bindingCountInThisMap; ++n)
                {
                    var     bindingStatesPtr  = newMemory.bindingStates;
                    ref var unresolvedBinding = ref bindingsInThisMap[n];
                    var     bindingIndex      = bindingStartIndex + n;
                    var     isComposite       = unresolvedBinding.isComposite;
                    var     isPartOfComposite = !isComposite && unresolvedBinding.isPartOfComposite;
                    var     bindingState      = &bindingStatesPtr[bindingIndex];

                    try
                    {
                        ////TODO: if it's a composite, check if any of the children matches our binding masks (if any) and skip composite if none do

                        // Set binding state to defaults.
                        bindingState->mapIndex = totalMapCount;
                        bindingState->compositeOrCompositeBindingIndex = InputActionState.kInvalidIndex;
                        bindingState->actionIndex = InputActionState.kInvalidIndex;

                        // Make sure that if it's part of a composite, we are actually part of a composite.
                        if (isPartOfComposite && currentCompositeBindingIndex == InputActionState.kInvalidIndex)
                        {
                            throw new InvalidOperationException(
                                      $"Binding '{unresolvedBinding}' is marked as being part of a composite but the preceding binding is not a composite");
                        }

                        // Skip binding if it is disabled (path is empty string).
                        var path = unresolvedBinding.effectivePath;
                        if (string.IsNullOrEmpty(path))
                        {
                            continue;
                        }

                        // Skip binding if it doesn't match with our binding mask (might be empty).
                        if (!isComposite && bindingMask != null && !bindingMask.Value.Matches(ref unresolvedBinding))
                        {
                            continue;
                        }

                        // Skip binding if it doesn't match the binding mask on the map (might be empty).
                        if (!isComposite && bindingMaskOnThisMap != null &&
                            !bindingMaskOnThisMap.Value.Matches(ref unresolvedBinding))
                        {
                            continue;
                        }

                        // Try to find action.
                        //
                        // NOTE: We ignore actions on bindings that are part of composites. We only allow
                        //       actions to be triggered from the composite itself.
                        var         actionIndexInMap = InputActionState.kInvalidIndex;
                        var         actionName       = unresolvedBinding.action;
                        InputAction action           = null;
                        if (!isPartOfComposite)
                        {
                            if (!string.IsNullOrEmpty(actionName))
                            {
                                ////REVIEW: should we fail here if we don't manage to find the action
                                actionIndexInMap = map.FindActionIndex(actionName);
                            }
                            else if (map.m_SingletonAction != null)
                            {
                                // Special-case for singleton actions that don't have names.
                                actionIndexInMap = 0;
                            }

                            if (actionIndexInMap != InputActionState.kInvalidIndex)
                            {
                                action = actionsInThisMap[actionIndexInMap];
                            }
                        }
                        else
                        {
                            actionIndexInMap = currentCompositeActionIndexInMap;
                            action           = currentCompositeAction;
                        }

                        // Skip binding if it doesn't match the binding mask on the action (might be empty).
                        if (!isComposite && action?.m_BindingMask != null &&
                            !action.m_BindingMask.Value.Matches(ref unresolvedBinding))
                        {
                            continue;
                        }

                        // Instantiate processors.
                        var firstProcessorIndex = InputActionState.kInvalidIndex;
                        var numProcessors       = 0;
                        var processorString     = unresolvedBinding.effectiveProcessors;
                        if (!string.IsNullOrEmpty(processorString))
                        {
                            // Add processors from binding.
                            firstProcessorIndex = ResolveProcessors(processorString);
                            if (firstProcessorIndex != InputActionState.kInvalidIndex)
                            {
                                numProcessors = totalProcessorCount - firstProcessorIndex;
                            }
                        }
                        if (action != null && !string.IsNullOrEmpty(action.m_Processors))
                        {
                            // Add processors from action.
                            var index = ResolveProcessors(action.m_Processors);
                            if (index != InputActionState.kInvalidIndex)
                            {
                                if (firstProcessorIndex == InputActionState.kInvalidIndex)
                                {
                                    firstProcessorIndex = index;
                                }
                                numProcessors += totalProcessorCount - index;
                            }
                        }

                        // Instantiate interactions.
                        var firstInteractionIndex = InputActionState.kInvalidIndex;
                        var numInteractions       = 0;
                        var interactionString     = unresolvedBinding.effectiveInteractions;
                        if (!string.IsNullOrEmpty(interactionString))
                        {
                            // Add interactions from binding.
                            firstInteractionIndex = ResolveInteractions(interactionString);
                            if (firstInteractionIndex != InputActionState.kInvalidIndex)
                            {
                                numInteractions = totalInteractionCount - firstInteractionIndex;
                            }
                        }
                        if (action != null && !string.IsNullOrEmpty(action.m_Interactions))
                        {
                            // Add interactions from action.
                            var index = ResolveInteractions(action.m_Interactions);
                            if (index != InputActionState.kInvalidIndex)
                            {
                                if (firstInteractionIndex == InputActionState.kInvalidIndex)
                                {
                                    firstInteractionIndex = index;
                                }
                                numInteractions += totalInteractionCount - index;
                            }
                        }

                        // If it's the start of a composite chain, create the composite.
                        if (isComposite)
                        {
                            var actionIndexForComposite = actionIndexInMap != InputActionState.kInvalidIndex
                                ? actionStartIndex + actionIndexInMap
                                : InputActionState.kInvalidIndex;

                            // Instantiate. For composites, the path is the name of the composite.
                            var composite = InstantiateBindingComposite(unresolvedBinding.path);
                            currentCompositeIndex =
                                ArrayHelpers.AppendWithCapacity(ref composites, ref totalCompositeCount, composite);
                            currentCompositeBindingIndex     = bindingIndex;
                            currentCompositeAction           = action;
                            currentCompositeActionIndexInMap = actionIndexInMap;

                            *bindingState = new InputActionState.BindingState
                            {
                                actionIndex = actionIndexForComposite,
                                compositeOrCompositeBindingIndex = currentCompositeIndex,
                                processorStartIndex   = firstProcessorIndex,
                                processorCount        = numProcessors,
                                interactionCount      = numInteractions,
                                interactionStartIndex = firstInteractionIndex,
                                mapIndex    = totalMapCount,
                                isComposite = true,
                                // Record where the controls for parts of the composite start.
                                controlStartIndex = memory.controlCount + resolvedControls.Count,
                            };

                            // The composite binding entry itself does not resolve to any controls.
                            // It creates a composite binding object which is then populated from
                            // subsequent bindings.
                            continue;
                        }

                        // If we've reached the end of a composite chain, finish
                        // off the current composite.
                        if (!isPartOfComposite && currentCompositeBindingIndex != InputActionState.kInvalidIndex)
                        {
                            currentCompositePartCount        = 0;
                            currentCompositeBindingIndex     = InputActionState.kInvalidIndex;
                            currentCompositeIndex            = InputActionState.kInvalidIndex;
                            currentCompositeAction           = null;
                            currentCompositeActionIndexInMap = InputActionState.kInvalidIndex;
                        }

                        // Look up controls.
                        //
                        // NOTE: We continuously add controls here to `resolvedControls`. Once we've completed our
                        //       pass over the bindings in the map, `resolvedControls` will have all the controls for
                        //       the current map.
                        var firstControlIndex = memory.controlCount + resolvedControls.Count;
                        var numControls       = 0;
                        if (devicesForThisMap != null)
                        {
                            // Search in devices for only this map.
                            var list = devicesForThisMap.Value;
                            for (var i = 0; i < list.Count; ++i)
                            {
                                var device = list[i];
                                if (!device.added)
                                {
                                    continue; // Skip devices that have been removed.
                                }
                                numControls += InputControlPath.TryFindControls(device, path, 0, ref resolvedControls);
                            }
                        }
                        else
                        {
                            // Search globally.
                            numControls = InputSystem.FindControls(path, ref resolvedControls);
                        }

                        // If the binding is part of a composite, pass the resolved controls
                        // on to the composite.
                        var partIndex             = InputActionState.kInvalidIndex;
                        var actionIndexForBinding = InputActionState.kInvalidIndex;
                        if (isPartOfComposite && currentCompositeBindingIndex != InputActionState.kInvalidIndex && numControls > 0)
                        {
                            // Make sure the binding is named. The name determines what in the composite
                            // to bind to.
                            if (string.IsNullOrEmpty(unresolvedBinding.name))
                            {
                                throw new InvalidOperationException(
                                          $"Binding '{unresolvedBinding}' that is part of composite '{composites[currentCompositeIndex]}' is missing a name");
                            }

                            // Give a part index for the
                            partIndex = AssignCompositePartIndex(composites[currentCompositeIndex], unresolvedBinding.name,
                                                                 ref currentCompositePartCount);

                            // Keep track of total number of controls bound in the composite.
                            bindingStatesPtr[currentCompositeBindingIndex].controlCount += numControls;

                            // Force action index on part binding to be same as that of composite.
                            actionIndexForBinding = bindingStatesPtr[currentCompositeBindingIndex].actionIndex;
                        }
                        else if (actionIndexInMap != InputActionState.kInvalidIndex)
                        {
                            actionIndexForBinding = actionStartIndex + actionIndexInMap;
                        }

                        // Add entry for resolved binding.
                        *bindingState = new InputActionState.BindingState
                        {
                            controlStartIndex                = firstControlIndex,
                            controlCount                     = numControls,
                            interactionStartIndex            = firstInteractionIndex,
                            interactionCount                 = numInteractions,
                            processorStartIndex              = firstProcessorIndex,
                            processorCount                   = numProcessors,
                            isPartOfComposite                = unresolvedBinding.isPartOfComposite,
                            partIndex                        = partIndex,
                            actionIndex                      = actionIndexForBinding,
                            compositeOrCompositeBindingIndex = currentCompositeBindingIndex,
                            mapIndex = totalMapCount,
                            wantsInitialStateCheck = action?.wantsInitialStateCheck ?? false
                        };
                    }
                    catch (Exception exception)
                    {
                        Debug.LogError(
                            $"{exception.GetType().Name} while resolving binding '{unresolvedBinding}' in action map '{map}'");
                        Debug.LogException(exception);

                        // Don't swallow exceptions that indicate something is wrong in the code rather than
                        // in the data.
                        if (exception.IsExceptionIndicatingBugInCode())
                        {
                            throw;
                        }
                    }
                }

                // Re-allocate memory to accommodate controls and interaction states. The count for those
                // we only know once we've completed all resolution.
                var controlCountInThisMap = resolvedControls.Count;
                var newTotalControlCount  = memory.controlCount + controlCountInThisMap;
                if (newMemory.interactionCount != totalInteractionCount ||
                    newMemory.compositeCount != totalCompositeCount ||
                    newMemory.controlCount != newTotalControlCount)
                {
                    var finalMemory = new InputActionState.UnmanagedMemory();

                    finalMemory.Allocate(
                        mapCount: newMemory.mapCount,
                        actionCount: newMemory.actionCount,
                        bindingCount: newMemory.bindingCount,
                        controlCount: newTotalControlCount,
                        interactionCount: totalInteractionCount,
                        compositeCount: totalCompositeCount);

                    finalMemory.CopyDataFrom(newMemory);

                    newMemory.Dispose();
                    newMemory = finalMemory;
                }

                // Add controls to array.
                var controlCountInArray = memory.controlCount;
                ArrayHelpers.AppendListWithCapacity(ref controls, ref controlCountInArray, resolvedControls);
                Debug.Assert(controlCountInArray == newTotalControlCount,
                             "Control array should have combined count of old and new controls");

                // Set up control to binding index mapping.
                for (var i = 0; i < bindingCountInThisMap; ++i)
                {
                    var bindingStatesPtr = newMemory.bindingStates;
                    var bindingState     = &bindingStatesPtr[bindingStartIndex + i];
                    var numControls      = bindingState->controlCount;
                    var startIndex       = bindingState->controlStartIndex;
                    for (var n = 0; n < numControls; ++n)
                    {
                        newMemory.controlIndexToBindingIndex[startIndex + n] = bindingStartIndex + i;
                    }
                }

                // Initialize initial interaction states.
                for (var i = memory.interactionCount; i < newMemory.interactionCount; ++i)
                {
                    newMemory.interactionStates[i].phase = InputActionPhase.Waiting;
                }

                // Initialize action data.
                var runningIndexInBindingIndices = memory.bindingCount;
                for (var i = 0; i < actionCountInThisMap; ++i)
                {
                    var action      = actionsInThisMap[i];
                    var actionIndex = actionStartIndex + i;

                    // Correlate action with its trigger state.
                    action.m_ActionIndexInState = actionIndex;

                    // Collect bindings for action.
                    var bindingStartIndexForAction      = runningIndexInBindingIndices;
                    var bindingCountForAction           = 0;
                    var numPossibleConcurrentActuations = 0;

                    for (var n = 0; n < bindingCountInThisMap; ++n)
                    {
                        var bindingIndex = bindingStartIndex + n;
                        var bindingState = &newMemory.bindingStates[bindingIndex];
                        if (bindingState->actionIndex != actionIndex)
                        {
                            continue;
                        }
                        if (bindingState->isPartOfComposite)
                        {
                            continue;
                        }

                        Debug.Assert(bindingIndex <= ushort.MaxValue, "Binding index exceeds limit");
                        newMemory.actionBindingIndices[runningIndexInBindingIndices] = (ushort)bindingIndex;
                        ++runningIndexInBindingIndices;
                        ++bindingCountForAction;

                        // Keep track of how many concurrent actuations we may be seeing on the action so that
                        // we know whether we need to enable conflict resolution or not.
                        if (bindingState->isComposite)
                        {
                            // Composite binding. Actuates as a whole. Check if the composite has successfully
                            // resolved any controls. If so, it adds one possible actuation.
                            if (bindingState->controlCount > 0)
                            {
                                ++numPossibleConcurrentActuations;
                            }
                        }
                        else
                        {
                            // Normal binding. Every successfully resolved control results in one possible actuation.
                            numPossibleConcurrentActuations += bindingState->controlCount;
                        }
                    }
                    Debug.Assert(bindingStartIndexForAction < ushort.MaxValue, "Binding start index on action exceeds limit");
                    Debug.Assert(bindingCountForAction < ushort.MaxValue, "Binding count on action exceeds limit");
                    newMemory.actionBindingIndicesAndCounts[actionIndex * 2]     = (ushort)bindingStartIndexForAction;
                    newMemory.actionBindingIndicesAndCounts[actionIndex * 2 + 1] = (ushort)bindingCountForAction;

                    // See if we may need conflict resolution on this action. Never needed for pass-through actions.
                    // Otherwise, if we have more than one bound control or have several bindings and one of them
                    // is a composite, we enable it.
                    var isPassThroughAction       = action.type == InputActionType.PassThrough;
                    var mayNeedConflictResolution = !isPassThroughAction && numPossibleConcurrentActuations > 1;

                    // Initialize initial trigger state.
                    newMemory.actionStates[actionIndex] =
                        new InputActionState.TriggerState
                    {
                        phase                     = InputActionPhase.Disabled,
                        mapIndex                  = mapIndex,
                        controlIndex              = InputActionState.kInvalidIndex,
                        interactionIndex          = InputActionState.kInvalidIndex,
                        passThrough               = isPassThroughAction,
                        mayNeedConflictResolution = mayNeedConflictResolution,
                    };
                }

                // Store indices for map.
                newMemory.mapIndices[mapIndex] =
                    new InputActionState.ActionMapIndices
                {
                    actionStartIndex      = actionStartIndex,
                    actionCount           = actionCountInThisMap,
                    controlStartIndex     = controlStartIndex,
                    controlCount          = controlCountInThisMap,
                    bindingStartIndex     = bindingStartIndex,
                    bindingCount          = bindingCountInThisMap,
                    interactionStartIndex = interactionStartIndex,
                    interactionCount      = totalInteractionCount - interactionStartIndex,
                    processorStartIndex   = processorStartIndex,
                    processorCount        = totalProcessorCount - processorStartIndex,
                    compositeStartIndex   = compositeStartIndex,
                    compositeCount        = totalCompositeCount - compositeStartIndex,
                };
                map.m_MapIndexInState = mapIndex;
                var finalActionMapCount = memory.mapCount;
                ArrayHelpers.AppendWithCapacity(ref maps, ref finalActionMapCount, map, capacityIncrement: 4);
                Debug.Assert(finalActionMapCount == newMemory.mapCount,
                             "Final action map count should match old action map count plus one");

                // As a final act, swap the new memory in.
                memory.Dispose();
                memory = newMemory;
            }
Example #30
0
 public static IEnumerable <InputBinding> GetBindingOverrides(this InputAction action)
 {
     throw new NotImplementedException();
 }