Inheritance: MonoBehaviour
    public void ReadAxes(InputSystem inputSystem)
    {
        var inputManager = AssetDatabase.LoadAllAssetsAtPath ("ProjectSettings/InputManager.asset")[0];
        var obj = new SerializedObject (inputManager);
        var axisArray = obj.FindProperty ("m_Axes");

        if (axisArray.arraySize == 0) {
            Debug.LogError ("No input axes defined!");
        }

        var axes = new List<string> ();
        for (int i = 0; i < axisArray.arraySize; ++i) {
            var axis = axisArray.GetArrayElementAtIndex (i);

            var name = axis.FindPropertyRelative ("m_Name").stringValue;
            //var axisVal = axis.FindPropertyRelative ("axis").intValue;
            //var inputType = (InputType)axis.FindPropertyRelative ("type").intValue;

            axes.Add (name);
        }

        // TODO: Find a way to store the axes
        //PlayerPrefs.SetString (REGISTERED_AXIS_KEY, Stringify (axes));

        foreach (var axis in axes) {
            inputSystem.InputManager.RegisterAxis (axis);
        }

        var timestamp = System.DateTime.Now;
        Debug.Log (timestamp + ": Updated " + axisArray.arraySize + " input axes.");
    }
        public override void OnEnable()
        {
            base.OnEnable();

            _inputSystem = (InputSystem)target;
            _keyboardKeys = InputSystem.GetNonJoystickKeys();
            _keyboardKeyNames = _keyboardKeyNames ?? _keyboardKeys.ToStringArray();
            _keyboardAxes = InputSystemUtility.GetKeyboardAxes();
        }
 public void RecieveInputs(InputSystem inputSystem)
 {
     // Calculate x axis walk velocity
     _velocityInput.x =
         (inputSystem.R_STICK.x == 0)
         ? Mathf.MoveTowards(_velocityInput.x,0,_rotationInertia * Time.deltaTime * _rotationSpeed)
         :  Mathf.Clamp(_velocityInput.x + (inputSystem.R_STICK.x * Time.deltaTime * _rotationAcceleration * _rotationSpeed), -_rotationSpeed, _rotationSpeed);
     // Calculate y axis walk velocity
     _velocityInput.y =
         (inputSystem.R_STICK.y == 0)
         ? Mathf.MoveTowards(_velocityInput.y,0,_rotationInertia * Time.deltaTime * _rotationSpeed)
         :  Mathf.Clamp(_velocityInput.y + (inputSystem.R_STICK.y * Time.deltaTime * _rotationAcceleration * -_rotationSpeed), -_rotationSpeed, _rotationSpeed);
 }
    public void RecieveInputs(InputSystem inputSystem)
    {
        // Calculate walk velocity from inputs
        _walk.RecieveInputs(inputSystem);

        // If player use jump button and is on ground
        if(inputSystem.A && _physic._onGround){
            // Reset gravity
            _physic.ResetGravity();
            // Apply jump impultion to conserved velocity
            _physic.ApplyJump(_jump);
        }

        // [Debug] Character rotation
        Quaternion newRotation = _transform.localRotation;
        newRotation *= Quaternion.AngleAxis(Time.deltaTime * inputSystem.R_STICK.x * _debug_rotationSpeed, Vector3.up);
        _transform.localRotation = newRotation;
    }
        /// <summary>
        /// Update the spatial grip input from the device.
        /// </summary>
        /// <param name="interactionSourceState">The InteractionSourceState retrieved from the platform.</param>
        private void UpdateGripData(InteractionSourceState interactionSourceState, MixedRealityInteractionMapping interactionMapping)
        {
            switch (interactionMapping.AxisType)
            {
            case AxisType.SixDof:
            {
                // The data queried in UpdateSourceData is the grip pose.
                // Reuse that data to save two method calls and transforms.
                currentGripPose.Position = currentSourcePosition;
                currentGripPose.Rotation = currentSourceRotation;

                // Update the interaction data source
                interactionMapping.PoseData = currentGripPose;

                // If our value changed raise it.
                if (interactionMapping.Changed)
                {
                    // Raise input system Event if it enabled
                    InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, interactionMapping.MixedRealityInputAction, currentGripPose);
                }
            }
            break;
            }
        }
Example #6
0
        public static void Main(string[] args)
        {
            OpenTKWindow window = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? (OpenTKWindow) new DedicatedThreadWindow() : new SameThreadWindow();

            window.Title   = "ge.Main";
            window.Visible = true;
            Game           game = new Game();
            GraphicsSystem gs   = new GraphicsSystem(window);

            game.SystemRegistry.Register(gs);
            gs.AddFreeRenderItem(new ShadowMapPreview(gs.Context));

            InputSystem inputSystem = new InputSystem(window);

            inputSystem.RegisterCallback((input) =>
            {
                if (input.GetKeyDown(Key.F4) && (input.GetKey(Key.AltLeft) || input.GetKey(Key.AltRight)))
                {
                    game.Exit();
                }
                if (input.GetKeyDown(Key.F11))
                {
                    window.WindowState = window.WindowState == WindowState.Normal ? WindowState.FullScreen : WindowState.Normal;
                }
                if (input.GetKeyDown(Key.F12))
                {
                    gs.ToggleOctreeVisualizer();
                }
            });

            game.SystemRegistry.Register(inputSystem);

            ImGuiRenderer imGuiRenderer = new ImGuiRenderer(gs.Context, window.NativeWindow, inputSystem);

            gs.AddFreeRenderItem(imGuiRenderer);
            ImGuiNET.ImGui.GetIO().FontAllowUserScaling = true;

            AssetSystem assetSystem = new AssetSystem(Path.Combine(AppContext.BaseDirectory, "Assets"));

            game.SystemRegistry.Register(assetSystem);

            BehaviorUpdateSystem bus = new BehaviorUpdateSystem(game.SystemRegistry);

            game.SystemRegistry.Register(bus);
            bus.Register(imGuiRenderer);

            PhysicsSystem ps = new PhysicsSystem();

            game.SystemRegistry.Register(ps);

            ScoreSystem ss = new ScoreSystem();

            game.SystemRegistry.Register(ss);

            ConsoleCommandSystem ccs = new ConsoleCommandSystem(game.SystemRegistry);

            game.SystemRegistry.Register(ccs);

            window.Closed += game.Exit;

            LooseFileDatabase db = new LooseFileDatabase(AppContext.BaseDirectory);

            AddBinGameScene();
            SceneAsset scene = new SceneAsset();
            var        goqs  = game.SystemRegistry.GetSystem <GameObjectQuerySystem>();

            scene.GameObjects = goqs.GetAllGameObjects().Select(go => new SerializedGameObject(go)).ToArray();
            db.SaveDefinition(scene, "BINSCENE.scene");

            //var scene = db.LoadAsset<SceneAsset>("BINSCENE.scene_New");
            //scene.GenerateGameObjects();

            game.RunMainLoop();
        }
Example #7
0
        [ConditionalShow, SerializeField] private bool useless; //在没有数据的时候让标题正常显示
#endif

        //Input
        public void Move(Vector2 val)
        {
            InputSystem.Move(val);
        }
        /// <inheritdoc />
        protected override void UpdateInteractions(SimulatedHandData handData)
        {
            lastPointerPose = currentPointerPose;
            lastGripPose    = currentGripPose;

            // For convenience of simulating in Unity Editor, make the ray use the index
            // finger position instead of knuckle, since the index finger doesn't move when we press.
            Vector3 pointerPosition = jointPoses[TrackedHandJoint.IndexTip].Position;

            IsPositionAvailable = IsRotationAvailable = pointerPosition != Vector3.zero;

            if (IsPositionAvailable)
            {
                HandRay.Update(pointerPosition, GetPalmNormal(), CameraCache.Main.transform, ControllerHandedness);

                Ray ray = HandRay.Ray;

                currentPointerPose.Position = ray.origin;
                currentPointerPose.Rotation = Quaternion.LookRotation(ray.direction);

                currentGripPose = jointPoses[TrackedHandJoint.Palm];

                currentIndexPose = jointPoses[TrackedHandJoint.IndexTip];
            }

            if (lastGripPose != currentGripPose)
            {
                if (IsPositionAvailable && IsRotationAvailable)
                {
                    InputSystem?.RaiseSourcePoseChanged(InputSource, this, currentGripPose);
                }
                else if (IsPositionAvailable && !IsRotationAvailable)
                {
                    InputSystem?.RaiseSourcePositionChanged(InputSource, this, currentPointerPosition);
                }
                else if (!IsPositionAvailable && IsRotationAvailable)
                {
                    InputSystem?.RaiseSourceRotationChanged(InputSource, this, currentPointerRotation);
                }
            }

            for (int i = 0; i < Interactions?.Length; i++)
            {
                switch (Interactions[i].InputType)
                {
                case DeviceInputType.SpatialPointer:
                    Interactions[i].PoseData = currentPointerPose;
                    if (Interactions[i].Changed)
                    {
                        InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentPointerPose);
                    }
                    break;

                case DeviceInputType.SpatialGrip:
                    Interactions[i].PoseData = currentGripPose;
                    if (Interactions[i].Changed)
                    {
                        InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentGripPose);
                    }
                    break;

                case DeviceInputType.Select:
                    Interactions[i].BoolData = handData.IsPinching;

                    if (Interactions[i].Changed)
                    {
                        if (Interactions[i].BoolData)
                        {
                            InputSystem?.RaiseOnInputDown(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                        else
                        {
                            InputSystem?.RaiseOnInputUp(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                    }
                    break;

                case DeviceInputType.TriggerPress:
                    Interactions[i].BoolData = handData.IsPinching;

                    if (Interactions[i].Changed)
                    {
                        if (Interactions[i].BoolData)
                        {
                            InputSystem?.RaiseOnInputDown(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                        else
                        {
                            InputSystem?.RaiseOnInputUp(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction);
                        }
                    }
                    break;

                case DeviceInputType.IndexFinger:
                    Interactions[i].PoseData = currentIndexPose;
                    if (Interactions[i].Changed)
                    {
                        InputSystem?.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[i].MixedRealityInputAction, currentIndexPose);
                    }
                    break;
                }
            }
        }
 private static void RuntimeInitializeOnLoad()
 {
     InputSystem.RegisterLayout <SteamDemoController>(matches: deviceMatcher);
 }
Example #10
0
 public void Update(float dt)
 {
     _deltaTime = dt;
     InputSystem.Update();
 }
 void Start()
 {
     inputSystem = InputSystem.Instance;
     gameWorld = GameWorld.Instance;
 }
Example #12
0
 void Start()
 {
     input = InputSystem.Instance;
 }
Example #13
0
    void Start()
    {
        // reference to children
        foreach (Transform child in transform) {
            children.Add(child);
        }

        //Transform UICanvas = GameObject.Find ("UICanvas").transform;
        // Each character has children at start
        // 1st child - input system
        // 2nd child - gun or weapon
        // 3rd child - gun or weapon shoot guide
        // 4th child - GUI Canvas
        // 5th child - Camera

        iSystem = children [0].GetComponent<InputSystem> ();

        // reparent all other children
        children [1].SetParent(null);
        children [2].SetParent(null);
        children [3].SetParent(null);

        children [4].GetComponent<FollowCam> ().target = GetComponent<_NetCharacter> ();
        children [4].SetParent(null);

        gun = children [1].gameObject;

        // rigidbody component
        body = GetComponent<Rigidbody2D> ();
        // animator component
        anim = GetComponent<Animator> ();

        // rotation variable
        orientation = transform.eulerAngles;

        // enable or disable components
        iSystem.enabled = true;
        iSystem.shootGuide.gameObject.SetActive(true);
        children [3].gameObject.SetActive(true);
        children [4].gameObject.SetActive(true);
        children [4].GetComponent<FollowCam> ().enabled = true;

        // clear list
        children.Clear ();
    }
        public override void Initialize()
        {
            starsCollected = 1;
            levelManager = new LevelManager();
            levelManager.Init(ScreenSystem.Game, ScreenSystem.SpriteBatch);
            if (level == 0)
            {
                curLevel = levelManager.NextLevel();
            }
            else
            {
                curLevel = levelManager.GetLevel(level);
            }

            //Inits the audio
            switch (level)
            {
                case 1:
                    audioManager = new AudioManager("spacetheme");
                    break;
                case 2:
                    audioManager = new AudioManager("spacetheme");
                    break;
                case 3:
                    audioManager = new AudioManager("lavatheme");
                    break;
            }

            audioManager.LoadContent();

            objectManager = (ObjectManager)ScreenSystem.Game.Services.GetService((typeof(ObjectManager)));
            collisionManager = (IManageCollisionsService)ScreenSystem.Game.Services.GetService((typeof(IManageCollisionsService)));
            _input = (InputManager)ScreenSystem.Game.Services.GetService(typeof(IInputService));
            input = ScreenSystem.InputSystem;
            input.NewAction("Pause", Keys.Escape);
            screenOverlayManager = new ScreenOverlayManager(ScreenSystem.Game, this);
            ScreenSystem.Game.Components.Add(screenOverlayManager);
            Entering += new TransitionEventHandler(PlayScreen_Entering);
        }
Example #15
0
    public void Users_CanDetectUseOfUnpairedDevice()
    {
        // Instead of adding a standard Gamepad, add a custom one that has a noisy gyro
        // control added to it so that we can test whether the system can differentiate the
        // noise of the gyro from real user input.
        const string gamepadWithNoisyGyro = @"
            {
                ""name"" : ""GamepadWithNoisyGyro"",
                ""extend"" : ""Gamepad"",
                ""controls"" : [
                    { ""name"" : ""gyro"", ""layout"" : ""Quaternion"", ""noisy"" : true }
                ]
            }
        ";

        InputUser.listenForUnpairedDeviceActivity = true;

        InputControl receivedControl = null;

        InputUser.onUnpairedDeviceUsed +=
            control =>
        {
            Assert.That(control, Is.Not.Null);
            Assert.That(receivedControl, Is.Null);
            receivedControl = control;
        };

        InputSystem.RegisterLayout(gamepadWithNoisyGyro);
        var gamepad = (Gamepad)InputSystem.AddDevice("GamepadWithNoisyGyro");

        // First send some noise on the gyro.
        InputSystem.QueueDeltaStateEvent((QuaternionControl)gamepad["gyro"], new Quaternion(1, 2, 3, 4));
        InputSystem.Update();

        Assert.That(receivedControl, Is.Null);

        // Now send some real interaction.
        InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.A));
        InputSystem.Update();

        Assert.That(receivedControl, Is.SameAs(gamepad.aButton));

        receivedControl = null;

        // Now pair the device to a user and try the same thing again.
        var user = InputUser.PerformPairingWithDevice(gamepad);

        InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.B));
        InputSystem.Update();

        Assert.That(receivedControl, Is.Null);

        receivedControl = null;

        // Unpair the device and turn off the feature to make sure we're not getting a notification.
        user.UnpairDevice(gamepad);
        InputUser.listenForUnpairedDeviceActivity = false;

        InputSystem.QueueStateEvent(gamepad, new GamepadState().WithButton(GamepadButton.A));
        InputSystem.Update();

        Assert.That(receivedControl, Is.Null);
    }
Example #16
0
    public void State_CanSetUpMonitorsForStateChanges()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var          monitorFired    = false;
        InputControl receivedControl = null;
        double?      receivedTime    = null;

        var monitor = InputSystem.AddStateChangeMonitor(gamepad.leftStick,
                                                        (control, time, monitorIndex) =>
        {
            Assert.That(!monitorFired);
            monitorFired    = true;
            receivedControl = control;
            receivedTime    = time;
        });

        // Left stick only.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.5f, 0.5f)
        }, 0.5);
        InputSystem.Update();

        Assert.That(monitorFired, Is.True);
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
        Assert.That(receivedTime.Value, Is.EqualTo(0.5).Within(0.000001));

        monitorFired    = false;
        receivedControl = null;
        receivedTime    = 0;

        // Left stick again but with no value change.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.5f, 0.5f)
        }, 0.6);
        InputSystem.Update();

        Assert.That(monitorFired, Is.False);

        // Left and right stick.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState {
            rightStick = new Vector2(0.75f, 0.75f), leftStick = new Vector2(0.75f, 0.75f)
        }, 0.7);
        InputSystem.Update();

        Assert.That(monitorFired, Is.True);
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
        Assert.That(receivedTime.Value, Is.EqualTo(0.7).Within(0.000001));

        monitorFired    = false;
        receivedControl = null;
        receivedTime    = 0;

        // Right stick only.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState {
            rightStick = new Vector2(0.5f, 0.5f), leftStick = new Vector2(0.75f, 0.75f)
        }, 0.8);
        InputSystem.Update();

        Assert.That(monitorFired, Is.False);

        // Component control of left stick.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.75f, 0.5f)
        }, 0.9);
        InputSystem.Update();

        Assert.That(monitorFired, Is.True);
        ////REVIEW: do we want to be able to detect the child control that actually changed? could be multiple, though
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
        Assert.That(receivedTime.Value, Is.EqualTo(0.9).Within(0.000001));

        // Remove state monitor and change leftStick again.
        InputSystem.RemoveStateChangeMonitor(gamepad.leftStick, monitor);

        monitorFired    = false;
        receivedControl = null;
        receivedTime    = 0;

        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = new Vector2(0.0f, 0.0f)
        }, 1.0);
        InputSystem.Update();

        Assert.That(monitorFired, Is.False);
    }
Example #17
0
 // Use this for initialization
 void Start()
 {
     instance = this;
 }
Example #18
0
File: Program.cs Project: zhuowp/ge
        public static void Main(string[] args)
        {
            CommandLineOptions commandLineOptions = new CommandLineOptions(args);
            // Force-load prefs.
            var prefs = EditorPreferences.Instance;

            OpenTKWindow window = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? (OpenTKWindow)new DedicatedThreadWindow(960, 540, WindowState.Maximized)
                : new SameThreadWindow(960, 540, WindowState.Maximized);
            window.Title = "ge.Editor";
            Game game = new Game();
            GraphicsBackEndPreference backEndPref = commandLineOptions.PreferOpenGL ? GraphicsBackEndPreference.OpenGL : GraphicsBackEndPreference.None;
            GraphicsSystem gs = new GraphicsSystem(window, prefs.RenderQuality, backEndPref);
            gs.Context.ResourceFactory.AddShaderLoader(new EmbeddedResourceShaderLoader(typeof(Program).GetTypeInfo().Assembly));
            game.SystemRegistry.Register(gs);
            game.LimitFrameRate = false;

            InputSystem inputSystem = new InputSystem(window);
            inputSystem.RegisterCallback((input) =>
            {
                if (input.GetKeyDown(Key.F4) && (input.GetKey(Key.AltLeft) || input.GetKey(Key.AltRight)))
                {
                    game.Exit();
                }
            });

            game.SystemRegistry.Register(inputSystem);

            ImGuiRenderer imGuiRenderer = new ImGuiRenderer(gs.Context, window.NativeWindow, inputSystem);
            gs.SetImGuiRenderer(imGuiRenderer);

            var als = new AssemblyLoadSystem();
            game.SystemRegistry.Register(als);

            AssetSystem assetSystem = new EditorAssetSystem(Path.Combine(AppContext.BaseDirectory, "Assets"), als.Binder);
            game.SystemRegistry.Register(assetSystem);

            EditorSceneLoaderSystem esls = new EditorSceneLoaderSystem(game, game.SystemRegistry.GetSystem<GameObjectQuerySystem>());
            game.SystemRegistry.Register<SceneLoaderSystem>(esls);
            esls.AfterSceneLoaded += () => game.ResetDeltaTime();

            CommandLineOptions.AudioEnginePreference? audioPreference = commandLineOptions.AudioPreference;
            AudioEngineOptions audioEngineOptions =
                !audioPreference.HasValue ? AudioEngineOptions.Default
                : audioPreference == CommandLineOptions.AudioEnginePreference.None ? AudioEngineOptions.UseNullAudio
                : AudioEngineOptions.UseOpenAL;
            AudioSystem audioSystem = new AudioSystem(audioEngineOptions);
            game.SystemRegistry.Register(audioSystem);

            BehaviorUpdateSystem bus = new BehaviorUpdateSystem(game.SystemRegistry);
            game.SystemRegistry.Register(bus);
            bus.Register(imGuiRenderer);

            PhysicsSystem ps = new PhysicsSystem(PhysicsLayersDescription.Default);
            game.SystemRegistry.Register(ps);

            ConsoleCommandSystem ccs = new ConsoleCommandSystem(game.SystemRegistry);
            game.SystemRegistry.Register(ccs);

            game.SystemRegistry.Register(new SynchronizationHelperSystem());

            window.Closed += game.Exit;

            var editorSystem = new EditorSystem(game.SystemRegistry, commandLineOptions, imGuiRenderer);
            editorSystem.DiscoverComponentsFromAssembly(typeof(Program).GetTypeInfo().Assembly);
            // Editor system registers itself.

            game.RunMainLoop();

            window.NativeWindow.Dispose();

            EditorPreferences.Instance.Save();
        }
Example #19
0
    public void Devices_SupportsAndroidGamepad()
    {
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            interfaceName = "Android",
            deviceClass   = "AndroidGameController",
            capabilities  = new AndroidDeviceCapabilities
            {
                inputSources = AndroidInputSource.Gamepad | AndroidInputSource.Joystick,
            }.ToJson()
        });

        // Gamepad class is always adding dpad in FinishSetup so AndroidGamepadWithDpadButtons instead of AndroidGamepad is used
        Assert.That(device, Is.TypeOf <AndroidGamepadWithDpadButtons>());
        var controller = (AndroidGamepad)device;

        var leftStick  = new Vector2(0.789f, 0.987f);
        var rightStick = new Vector2(0.654f, 0.321f);

        // Note: Regarding triggers, android sends different events depending to which device the controller is connected.
        //       For ex., when NVIDIA shield controller when connected to Shield Console, triggers generate events:
        //            Left Trigger -> AndroidAxis.Brake, AndroidAxis.LtTrigger
        //            Right Trigger -> AndroidAxis.Gas, AndroidAxis.RtTrigger
        //       BUT
        //           when NVIDIA shield controller when connected to Samsung phone, triggers generate events:
        //            Left Trigger -> AndroidAxis.Brake
        //            Right Trigger -> AndroidAxis.Gas
        //
        //       This is why we're only reading and validating that events are correctly processed from AndroidAxis.Brake & AndroidAxis.Gas
        InputSystem.QueueStateEvent(controller,
                                    new AndroidGameControllerState()
                                    .WithAxis(AndroidAxis.Brake, 0.123f)
                                    .WithAxis(AndroidAxis.Gas, 0.456f)
                                    .WithAxis(AndroidAxis.X, leftStick.x)
                                    .WithAxis(AndroidAxis.Y, leftStick.y)
                                    .WithAxis(AndroidAxis.Z, rightStick.x)
                                    .WithAxis(AndroidAxis.Rz, rightStick.y));

        InputSystem.Update();

        var leftStickDeadzone  = controller.leftStick.TryGetProcessor <StickDeadzoneProcessor>();
        var rightStickDeadzone = controller.leftStick.TryGetProcessor <StickDeadzoneProcessor>();

        // Y is upside down on Android.
        Assert.That(controller.leftStick.ReadValue(), Is.EqualTo(leftStickDeadzone.Process(new Vector2(leftStick.x, -leftStick.y))));
        Assert.That(controller.rightStick.ReadValue(), Is.EqualTo(rightStickDeadzone.Process(new Vector2(rightStick.x, -rightStick.y))));

        Assert.That(controller.leftStick.left.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.leftStick.right.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.x)));
        Assert.That(controller.leftStick.up.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.leftStick.down.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.y)));

        Assert.That(controller.rightStick.left.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.rightStick.right.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.x)));
        Assert.That(controller.rightStick.up.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.rightStick.down.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.y)));

        Assert.That(controller.leftTrigger.ReadValue(), Is.EqualTo(0.123).Within(0.000001));
        Assert.That(controller.rightTrigger.ReadValue(), Is.EqualTo(0.456).Within(0.000001));

        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonA), controller.buttonSouth);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonX), controller.buttonWest);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonY), controller.buttonNorth);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonB), controller.buttonEast);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonThumbl), controller.leftStickButton);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonThumbr), controller.rightStickButton);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonL1), controller.leftShoulder);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonR1), controller.rightShoulder);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonStart), controller.startButton);
        AssertButtonPress(controller, new AndroidGameControllerState().WithButton(AndroidKeyCode.ButtonSelect), controller.selectButton);

        // Move sticks to opposite directions
        InputSystem.QueueStateEvent(controller,
                                    new AndroidGameControllerState()
                                    .WithAxis(AndroidAxis.X, -leftStick.x)
                                    .WithAxis(AndroidAxis.Y, -leftStick.y)
                                    .WithAxis(AndroidAxis.Z, -rightStick.x)
                                    .WithAxis(AndroidAxis.Rz, -rightStick.y));

        InputSystem.Update();

        Assert.That(controller.leftStick.left.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.x)));
        Assert.That(controller.leftStick.right.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.leftStick.up.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(leftStick.y)));
        Assert.That(controller.leftStick.down.ReadValue(), Is.EqualTo(0.0f));

        Assert.That(controller.rightStick.left.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.x)));
        Assert.That(controller.rightStick.right.ReadValue(), Is.EqualTo(0.0f));
        Assert.That(controller.rightStick.up.ReadValue(), Is.EqualTo(new AxisDeadzoneProcessor().Process(rightStick.y)));
        Assert.That(controller.rightStick.down.ReadValue(), Is.EqualTo(0.0f));
    }
 static SteamDemoController()
 {
     InputSystem.RegisterLayout <SteamDemoController>(matches: deviceMatcher);
 }
Example #21
0
    public void Actions_CanReactToGamePadAxisChanges()
    {
        var device = InputSystem.AddDevice(new InputDeviceDescription
        {
            interfaceName = "Android",
            deviceClass   = "AndroidGameController",
            capabilities  = new AndroidDeviceCapabilities
            {
                inputSources = AndroidInputSource.Gamepad | AndroidInputSource.Joystick,
            }.ToJson()
        });

        var controller = (AndroidGamepad)device;

        var leftStick  = new Vector2(0.3f, 0.3f);
        var rightStick = new Vector2(0.35f, 0.35f);

        var updateSticks = new Action(() =>
        {
            InputSystem.QueueStateEvent(controller,
                                        new AndroidGameControllerState()
                                        .WithAxis(AndroidAxis.X, leftStick.x)
                                        .WithAxis(AndroidAxis.Y, leftStick.y)
                                        .WithAxis(AndroidAxis.Z, rightStick.x)
                                        .WithAxis(AndroidAxis.Rz, rightStick.y));
        });

        var processStickValue = new Func <Vector2, Vector2>(v =>
        {
            v.y = -v.y;
            return(new StickDeadzoneProcessor().Process(v));
        });


        updateSticks();
        InputSystem.Update();
        InputSystem.Update();

        var leftStickAction  = new InputAction(binding: "/<Gamepad>/leftStick");
        var rightStickAction = new InputAction(binding: "/<Gamepad>/rightStick");

        var leftStickActionPerformed  = 0;
        var rightStickActionPerformed = 0;
        var receivedLeftStick         = Vector2.zero;
        var receivedRightStick        = Vector2.zero;

        leftStickAction.performed += ctx =>
        {
            receivedLeftStick = ctx.ReadValue <Vector2>();
            ++leftStickActionPerformed;
        };

        rightStickAction.performed += ctx =>
        {
            receivedRightStick = ctx.ReadValue <Vector2>();
            ++rightStickActionPerformed;
        };

        leftStickAction.Enable();
        rightStickAction.Enable();

        // Actions are called the first time they're enabled?
        InputSystem.Update();
        Assert.That(leftStickActionPerformed, Is.EqualTo(1));
        Assert.That(rightStickActionPerformed, Is.EqualTo(1));

        // Update only left stick's X value
        leftStick.x += 0.1f;
        updateSticks();
        InputSystem.Update();
        Assert.That(leftStickActionPerformed, Is.EqualTo(2));
        Assert.That(rightStickActionPerformed, Is.EqualTo(1));
        Assert.That(controller.leftStick.ReadValue(), Is.EqualTo(processStickValue(leftStick)).Using(Vector2EqualityComparer.Instance));
        Assert.That(controller.rightStick.ReadValue(), Is.EqualTo(processStickValue(rightStick)).Using(Vector2EqualityComparer.Instance));

        // Update only left stick's Y value
        leftStick.y += 0.1f;
        updateSticks();
        InputSystem.Update();
        Assert.That(leftStickActionPerformed, Is.EqualTo(3));
        Assert.That(rightStickActionPerformed, Is.EqualTo(1));
        Assert.That(controller.leftStick.ReadValue(), Is.EqualTo(processStickValue(leftStick)).Using(Vector2EqualityComparer.Instance));
        Assert.That(controller.rightStick.ReadValue(), Is.EqualTo(processStickValue(rightStick)).Using(Vector2EqualityComparer.Instance));

        // Update only right stick's X value
        rightStick.x += 0.1f;
        updateSticks();
        InputSystem.Update();
        Assert.That(leftStickActionPerformed, Is.EqualTo(3));
        Assert.That(rightStickActionPerformed, Is.EqualTo(2));
        Assert.That(controller.leftStick.ReadValue(), Is.EqualTo(processStickValue(leftStick)).Using(Vector2EqualityComparer.Instance));
        Assert.That(controller.rightStick.ReadValue(), Is.EqualTo(processStickValue(rightStick)).Using(Vector2EqualityComparer.Instance));

        // Update only right stick's Y value
        rightStick.y += 0.1f;
        updateSticks();
        InputSystem.Update();
        Assert.That(leftStickActionPerformed, Is.EqualTo(3));
        Assert.That(rightStickActionPerformed, Is.EqualTo(3));
        Assert.That(controller.leftStick.ReadValue(), Is.EqualTo(processStickValue(leftStick)).Using(Vector2EqualityComparer.Instance));
        Assert.That(controller.rightStick.ReadValue(), Is.EqualTo(processStickValue(rightStick)).Using(Vector2EqualityComparer.Instance));
    }
    public unsafe void Events_AreTimeslicedByDefault()
    {
        runtime.fixedUpdateIntervalInSeconds = 1.0 / 60; // 60 FPS.

        var gamepad = InputSystem.AddDevice <Gamepad>();

        var receivedEvents = new List <InputEvent>();

        InputSystem.onEvent +=
            eventPtr => receivedEvents.Add(*eventPtr.ToPointer());

        // First fixed update should just take everything.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.1234f
        }, 1);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.2345f
        }, 2);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.3456f
        }, 2.9);

        runtime.currentTime = 3;

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(3));
        Assert.That(receivedEvents[0].time, Is.EqualTo(1).Within(0.00001));
        Assert.That(receivedEvents[1].time, Is.EqualTo(2).Within(0.00001));
        Assert.That(receivedEvents[2].time, Is.EqualTo(2.9).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.3456).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3).Within(0.0001));

        receivedEvents.Clear();

        // From now on, fixed updates should only take what falls in their slice.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.1234f
        }, 3 + 0.001);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.2345f
        }, 3 + 0.002);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.3456f
        }, 3 + 1.0 / 60 + 0.001);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftTrigger = 0.4567f
        }, 3 + 2 * (1.0 / 60) + 0.001);

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(2));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 0.001).Within(0.00001));
        Assert.That(receivedEvents[1].time, Is.EqualTo(3 + 0.002).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.2345).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.EqualTo(2));
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 1.0 / 60).Within(0.0001));

        receivedEvents.Clear();

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(1));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 1.0 / 60 + 0.001).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.3456).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.EqualTo(1));
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 2 * (1.0 / 60)).Within(0.0001));

        receivedEvents.Clear();

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.EqualTo(1));
        Assert.That(receivedEvents[0].time, Is.EqualTo(3 + 2 * (1.0 / 60) + 0.001).Within(0.00001));
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.4567).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 3 * (1.0 / 60)).Within(0.0001));

        receivedEvents.Clear();

        InputSystem.Update(InputUpdateType.Fixed);

        Assert.That(receivedEvents, Has.Count.Zero);
        Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.4567).Within(0.00001));

        Assert.That(InputUpdate.s_LastUpdateRetainedEventCount, Is.Zero);
        Assert.That(InputUpdate.s_LastFixedUpdateTime, Is.EqualTo(3 + 4 * (1.0 / 60)).Within(0.0001));
    }
            protected override void ContextClickedItem(int id)
            {
                var item = FindItem(id, rootItem);

                if (item == null)
                {
                    return;
                }

                if (item is DeviceItem deviceItem)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(Contents.openDebugView, false, () => InputDeviceDebuggerWindow.CreateOrShowExisting(deviceItem.device));
                    menu.AddItem(Contents.copyDeviceDescription, false,
                                 () => EditorGUIUtility.systemCopyBuffer = deviceItem.device.description.ToJson());
                    menu.AddItem(Contents.removeDevice, false, () => InputSystem.RemoveDevice(deviceItem.device));
                    if (deviceItem.device.enabled)
                    {
                        menu.AddItem(Contents.disableDevice, false, () => InputSystem.DisableDevice(deviceItem.device));
                    }
                    else
                    {
                        menu.AddItem(Contents.enableDevice, false, () => InputSystem.EnableDevice(deviceItem.device));
                    }
                    menu.ShowAsContext();
                }

                if (item is UnsupportedDeviceItem unsupportedDeviceItem)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(Contents.copyDeviceDescription, false,
                                 () => EditorGUIUtility.systemCopyBuffer = unsupportedDeviceItem.description.ToJson());
                    menu.ShowAsContext();
                }

                if (item is LayoutItem layoutItem)
                {
                    var layout = EditorInputControlLayoutCache.TryGetLayout(layoutItem.layoutName);
                    if (layout != null)
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(Contents.copyLayoutAsJSON, false,
                                     () => EditorGUIUtility.systemCopyBuffer = layout.ToJson());
                        if (layout.isDeviceLayout)
                        {
                            menu.AddItem(Contents.createDeviceFromLayout, false,
                                         () => InputSystem.AddDevice(layout.name));
                            menu.AddItem(Contents.generateCodeFromLayout, false, () =>
                            {
                                var fileName   = EditorUtility.SaveFilePanel("Generate InputDevice Code", "", "Fast" + layoutItem.layoutName, "cs");
                                var isInAssets = fileName.StartsWith(Application.dataPath, StringComparison.OrdinalIgnoreCase);
                                if (isInAssets)
                                {
                                    fileName = "Assets/" + fileName.Substring(Application.dataPath.Length + 1);
                                }
                                if (!string.IsNullOrEmpty(fileName))
                                {
                                    var code = InputLayoutCodeGenerator.GenerateCodeFileForDeviceLayout(layoutItem.layoutName, fileName, prefix: "Fast");
                                    File.WriteAllText(fileName, code);
                                    if (isInAssets)
                                    {
                                        AssetDatabase.Refresh();
                                    }
                                }
                            });
                        }
                        menu.ShowAsContext();
                    }
                }
            }
        private void SetupInputControl()
        {
            Debug.Assert(m_Control == null);
            Debug.Assert(m_NextControlOnDevice == null);
            Debug.Assert(!m_InputEventPtr.valid);

            // Nothing to do if we don't have a control path.
            if (string.IsNullOrEmpty(m_ControlPath))
            {
                return;
            }

            // Determine what type of device to work with.
            var layoutName = InputControlPath.TryGetDeviceLayout(m_ControlPath);

            if (layoutName == null)
            {
                Debug.LogError(
                    string.Format(
                        "Cannot determine device layout to use based on control path '{0}' used in {1} component",
                        m_ControlPath, GetType().Name), this);
                return;
            }

            // Try to find existing on-screen device that matches.
            var internedLayoutName = new InternedString(layoutName);
            var deviceInfoIndex    = -1;

            for (var i = 0; i < s_OnScreenDevices.length; ++i)
            {
                if (s_OnScreenDevices[i].device.m_Layout == internedLayoutName)
                {
                    deviceInfoIndex = i;
                    break;
                }
            }

            // If we don't have a matching one, create a new one.
            InputDevice device;

            if (deviceInfoIndex == -1)
            {
                // Try to create device.
                try
                {
                    device = InputSystem.AddDevice(layoutName);
                }
                catch (Exception exception)
                {
                    Debug.LogError(string.Format("Could not create device with layout '{0}' used in '{1}' component", layoutName,
                                                 GetType().Name));
                    Debug.LogException(exception);
                    return;
                }

                // Create event buffer.
                var buffer = StateEvent.From(device, out var eventPtr, Allocator.Persistent);

                // Add to list.
                deviceInfoIndex = s_OnScreenDevices.Append(new OnScreenDeviceInfo
                {
                    eventPtr = eventPtr,
                    buffer   = buffer,
                    device   = device,
                });
            }
            else
            {
                device = s_OnScreenDevices[deviceInfoIndex].device;
            }

            // Try to find control on device.
            m_Control = InputControlPath.TryFindControl(device, m_ControlPath);
            if (m_Control == null)
            {
                Debug.LogError(
                    string.Format(
                        "Cannot find control with path '{0}' on device of type '{1}' referenced by component '{2}'",
                        m_ControlPath, layoutName, GetType().Name), this);

                // Remove the device, if we just created one.
                if (s_OnScreenDevices[deviceInfoIndex].firstControl == null)
                {
                    s_OnScreenDevices[deviceInfoIndex].Destroy();
                    s_OnScreenDevices.RemoveAt(deviceInfoIndex);
                }

                return;
            }
            m_InputEventPtr = s_OnScreenDevices[deviceInfoIndex].eventPtr;

            // We have all we need. Permanently add us.
            s_OnScreenDevices[deviceInfoIndex] =
                s_OnScreenDevices[deviceInfoIndex].AddControl(this);
        }
            protected override TreeViewItem BuildRoot()
            {
                var id = 0;

                var root = new TreeViewItem
                {
                    id    = id++,
                    depth = -1
                };

                ////TODO: this will need to be improved for multi-user scenarios
                // Actions.
                m_EnabledActions.Clear();
                InputSystem.ListEnabledActions(m_EnabledActions);
                if (m_EnabledActions.Count > 0)
                {
                    actionsItem = AddChild(root, "", ref id);
                    AddEnabledActions(actionsItem, ref id);

                    if (!actionsItem.hasChildren)
                    {
                        // We are culling actions that are assigned to users so we may end up with an empty
                        // list even if we have enabled actions. If we do, remove the "Actions" item from the tree.
                        root.children.Remove(actionsItem);
                    }
                    else
                    {
                        // Update title to include action count.
                        actionsItem.displayName = $"Actions ({actionsItem.children.Count})";
                    }
                }

                // Users.
                var userCount = InputUser.all.Count;

                if (userCount > 0)
                {
                    usersItem = AddChild(root, $"Users ({userCount})", ref id);
                    foreach (var user in InputUser.all)
                    {
                        AddUser(usersItem, user, ref id);
                    }
                }

                // Devices.
                var devices = InputSystem.devices;

                devicesItem = AddChild(root, $"Devices ({devices.Count})", ref id);
                var          haveRemotes      = devices.Any(x => x.remote);
                TreeViewItem localDevicesNode = null;

                if (haveRemotes)
                {
                    // Split local and remote devices into groups.

                    localDevicesNode = AddChild(devicesItem, "Local", ref id);
                    AddDevices(localDevicesNode, devices, ref id);

                    var remoteDevicesNode = AddChild(devicesItem, "Remote", ref id);
                    foreach (var player in EditorConnection.instance.ConnectedPlayers)
                    {
                        var playerNode = AddChild(remoteDevicesNode, player.name, ref id);
                        AddDevices(playerNode, devices, ref id, player.playerId);
                    }
                }
                else
                {
                    // We don't have remote devices so don't add an extra group for local devices.
                    // Put them all directly underneath the "Devices" node.
                    AddDevices(devicesItem, devices, ref id);
                }

                ////TDO: unsupported and disconnected devices should also be shown for remotes

                if (m_UnsupportedDevices == null)
                {
                    m_UnsupportedDevices = new List <InputDeviceDescription>();
                }
                m_UnsupportedDevices.Clear();
                InputSystem.GetUnsupportedDevices(m_UnsupportedDevices);
                if (m_UnsupportedDevices.Count > 0)
                {
                    var parent = haveRemotes ? localDevicesNode : devicesItem;
                    var unsupportedDevicesNode = AddChild(parent, $"Unsupported ({m_UnsupportedDevices.Count})", ref id);
                    foreach (var device in m_UnsupportedDevices)
                    {
                        var item = new UnsupportedDeviceItem
                        {
                            id          = id++,
                            depth       = unsupportedDevicesNode.depth + 1,
                            displayName = device.ToString(),
                            description = device
                        };
                        unsupportedDevicesNode.AddChild(item);
                    }
                    unsupportedDevicesNode.children.Sort((a, b) =>
                                                         string.Compare(a.displayName, b.displayName, StringComparison.InvariantCulture));
                }

                var disconnectedDevices = InputSystem.disconnectedDevices;

                if (disconnectedDevices.Count > 0)
                {
                    var parent = haveRemotes ? localDevicesNode : devicesItem;
                    var disconnectedDevicesNode = AddChild(parent, $"Disconnected ({disconnectedDevices.Count})", ref id);
                    foreach (var device in disconnectedDevices)
                    {
                        AddChild(disconnectedDevicesNode, device.ToString(), ref id);
                    }
                    disconnectedDevicesNode.children.Sort((a, b) =>
                                                          string.Compare(a.displayName, b.displayName, StringComparison.InvariantCulture));
                }

                // Layouts.
                layoutsItem = AddChild(root, "Layouts", ref id);
                AddControlLayouts(layoutsItem, ref id);

                ////FIXME: this shows local configuration only
                // Settings.
                var settings          = InputSystem.settings;
                var settingsAssetPath = AssetDatabase.GetAssetPath(settings);
                var settingsLabel     = "Settings";

                if (!string.IsNullOrEmpty(settingsAssetPath))
                {
                    settingsLabel = $"Settings ({Path.GetFileName(settingsAssetPath)})";
                }
                settingsItem = AddChild(root, settingsLabel, ref id);
                AddValueItem(settingsItem, "Update Mode", settings.updateMode, ref id);
                AddValueItem(settingsItem, "Compensate For Screen Orientation", settings.compensateForScreenOrientation, ref id);
                AddValueItem(settingsItem, "Filter Noise On .current", settings.filterNoiseOnCurrent, ref id);
                AddValueItem(settingsItem, "Default Button Press Point", settings.defaultButtonPressPoint, ref id);
                AddValueItem(settingsItem, "Default Deadzone Min", settings.defaultDeadzoneMin, ref id);
                AddValueItem(settingsItem, "Default Deadzone Max", settings.defaultDeadzoneMax, ref id);
                AddValueItem(settingsItem, "Default Tap Time", settings.defaultTapTime, ref id);
                AddValueItem(settingsItem, "Default Slow Tap Time", settings.defaultSlowTapTime, ref id);
                AddValueItem(settingsItem, "Default Hold Time", settings.defaultHoldTime, ref id);
                AddValueItem(settingsItem, "Lock Input To Game View", InputEditorUserSettings.lockInputToGameView, ref id);
                if (settings.supportedDevices.Count > 0)
                {
                    var supportedDevices = AddChild(settingsItem, "Supported Devices", ref id);
                    foreach (var item in settings.supportedDevices)
                    {
                        var icon = EditorInputControlLayoutCache.GetIconForLayout(item);
                        AddChild(supportedDevices, item, ref id, icon);
                    }
                }
                settingsItem.children.Sort((a, b) => string.Compare(a.displayName, b.displayName));

                // Metrics.
                var metrics = InputSystem.metrics;

                metricsItem = AddChild(root, "Metrics", ref id);
                AddChild(metricsItem,
                         "Current State Size in Bytes: " + StringHelpers.NicifyMemorySize(metrics.currentStateSizeInBytes),
                         ref id);
                AddValueItem(metricsItem, "Current Control Count", metrics.currentControlCount, ref id);
                AddValueItem(metricsItem, "Current Layout Count", metrics.currentLayoutCount, ref id);

                return(root);
            }
Example #26
0
    public IEnumerator Actions_CanDriveUI()
    {
        // Create devices.
        var gamepad = InputSystem.AddDevice <Gamepad>();
        var mouse   = InputSystem.AddDevice <Mouse>();

        // Set up GameObject with EventSystem.
        var systemObject = new GameObject("System");
        var eventSystem  = systemObject.AddComponent <TestEventSystem>();
        var uiModule     = systemObject.AddComponent <UIActionInputModule>();

        eventSystem.UpdateModules();
        eventSystem.InvokeUpdate(); // Initial update only sets current module.

        // Set up canvas on which we can perform raycasts.
        var canvasObject = new GameObject("Canvas");
        var canvas       = canvasObject.AddComponent <Canvas>();

        canvas.renderMode = RenderMode.ScreenSpaceCamera;
        canvasObject.AddComponent <GraphicRaycaster>();
        var cameraObject = new GameObject("Camera");
        var camera       = cameraObject.AddComponent <Camera>();

        canvas.worldCamera = camera;
        camera.pixelRect   = new Rect(0, 0, 640, 480);

        // Set up a GameObject hierarchy that we send events to. In a real setup,
        // this would be a hierarchy involving UI components.
        var parentGameObject = new GameObject("Parent");
        var parentTransform  = parentGameObject.AddComponent <RectTransform>();

        parentGameObject.AddComponent <UICallbackReceiver>();
        var leftChildGameObject = new GameObject("Left Child");
        var leftChildTransform  = leftChildGameObject.AddComponent <RectTransform>();

        leftChildGameObject.AddComponent <Image>();
        var leftChildReceiver    = leftChildGameObject.AddComponent <UICallbackReceiver>();
        var rightChildGameObject = new GameObject("Right Child");
        var rightChildTransform  = rightChildGameObject.AddComponent <RectTransform>();

        rightChildGameObject.AddComponent <Image>();
        var rightChildReceiver = rightChildGameObject.AddComponent <UICallbackReceiver>();

        parentTransform.SetParent(canvas.transform, worldPositionStays: false);
        leftChildTransform.SetParent(parentTransform, worldPositionStays: false);
        rightChildTransform.SetParent(parentTransform, worldPositionStays: false);

        // Parent occupies full space of canvas.
        parentTransform.sizeDelta = new Vector2(640, 480);

        // Left child occupies left half of parent.
        leftChildTransform.anchoredPosition = new Vector2(-(640 / 4), 0);
        leftChildTransform.sizeDelta        = new Vector2(320, 480);

        // Right child occupies right half of parent.
        rightChildTransform.anchoredPosition = new Vector2(640 / 4, 0);
        rightChildTransform.sizeDelta        = new Vector2(320, 480);

        // Create actions.
        var map               = new InputActionMap();
        var pointAction       = map.AddAction("point");
        var moveAction        = map.AddAction("move");
        var submitAction      = map.AddAction("submit");
        var cancelAction      = map.AddAction("cancel");
        var leftClickAction   = map.AddAction("leftClick");
        var rightClickAction  = map.AddAction("rightClick");
        var middleClickAction = map.AddAction("middleClick");
        var scrollAction      = map.AddAction("scroll");

        // Create bindings.
        pointAction.AddBinding(mouse.position);
        leftClickAction.AddBinding(mouse.leftButton);
        rightClickAction.AddBinding(mouse.rightButton);
        middleClickAction.AddBinding(mouse.middleButton);
        scrollAction.AddBinding(mouse.scroll);
        moveAction.AddBinding(gamepad.leftStick);
        submitAction.AddBinding(gamepad.buttonSouth);
        cancelAction.AddBinding(gamepad.buttonEast);

        // Wire up actions.
        // NOTE: In a normal usage scenario, the user would wire these up in the inspector.
        uiModule.point       = new InputActionProperty(pointAction);
        uiModule.move        = new InputActionProperty(moveAction);
        uiModule.submit      = new InputActionProperty(submitAction);
        uiModule.cancel      = new InputActionProperty(cancelAction);
        uiModule.leftClick   = new InputActionProperty(leftClickAction);
        uiModule.middleClick = new InputActionProperty(middleClickAction);
        uiModule.rightClick  = new InputActionProperty(rightClickAction);
        uiModule.scrollWheel = new InputActionProperty(scrollAction);

        // Enable the whole thing.
        map.Enable();

        // We need to wait a frame to let the underlying canvas update and properly order the graphics images for raycasting.
        yield return(null);

        // Move mouse over left child.
        InputSystem.QueueStateEvent(mouse, new MouseState {
            position = new Vector2(100, 100)
        });
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Enter));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Check basic down/up
        InputSystem.QueueStateEvent(mouse, new MouseState {
            position = new Vector2(100, 100), buttons = (ushort)(1 << (int)MouseState.Button.Left)
        });
        InputSystem.QueueStateEvent(mouse, new MouseState {
            position = new Vector2(100, 100), buttons = (ushort)0
        });
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(4));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Down));
        Assert.That(leftChildReceiver.events[1].type, Is.EqualTo(EventType.PotentialDrag));
        Assert.That(leftChildReceiver.events[2].type, Is.EqualTo(EventType.Up));
        Assert.That(leftChildReceiver.events[3].type, Is.EqualTo(EventType.Click));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Check down and drag
        InputSystem.QueueStateEvent(mouse, new MouseState {
            position = new Vector2(100, 100), buttons = (ushort)(1 << (int)MouseState.Button.Right)
        });
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(2));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Down));
        Assert.That(leftChildReceiver.events[1].type, Is.EqualTo(EventType.PotentialDrag));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Move to new location on left child
        InputSystem.QueueDeltaStateEvent(mouse.position, new Vector2(100, 200));
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(2));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.BeginDrag));
        Assert.That(leftChildReceiver.events[1].type, Is.EqualTo(EventType.Dragging));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Move children
        InputSystem.QueueDeltaStateEvent(mouse.position, new Vector2(400, 200));
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(2));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Exit));
        Assert.That(leftChildReceiver.events[1].type, Is.EqualTo(EventType.Dragging));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(rightChildReceiver.events[0].type, Is.EqualTo(EventType.Enter));
        rightChildReceiver.Reset();

        // Release button
        InputSystem.QueueStateEvent(mouse, new MouseState {
            position = new Vector2(400, 200), buttons = (ushort)0
        });
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(2));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Up));
        Assert.That(leftChildReceiver.events[1].type, Is.EqualTo(EventType.EndDrag));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(rightChildReceiver.events[0].type, Is.EqualTo(EventType.Drop));
        rightChildReceiver.Reset();

        // Check Scroll
        InputSystem.QueueDeltaStateEvent(mouse.scroll, Vector2.one);
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(0));
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(rightChildReceiver.events[0].type, Is.EqualTo(EventType.Scroll));
        rightChildReceiver.Reset();

        // Reset Scroll
        InputSystem.QueueDeltaStateEvent(mouse.scroll, Vector2.zero);
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(0));
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(rightChildReceiver.events[0].type, Is.EqualTo(EventType.Scroll));
        rightChildReceiver.Reset();

        // Test Selection
        eventSystem.SetSelectedGameObject(leftChildGameObject);
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Select));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Check Move Axes
        InputSystem.QueueDeltaStateEvent(gamepad.leftStick, new Vector2(1.0f, 0.0f));
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Move));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Check Submit
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = (uint)(1 << (int)GamepadState.Button.South)
        });
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Submit));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Check Cancel
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = (uint)(1 << (int)GamepadState.Button.East)
        });
        InputSystem.Update();
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Cancel));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(0));

        // Check Selection Swap
        eventSystem.SetSelectedGameObject(rightChildGameObject);
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(leftChildReceiver.events[0].type, Is.EqualTo(EventType.Deselect));
        leftChildReceiver.Reset();
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(rightChildReceiver.events[0].type, Is.EqualTo(EventType.Select));
        rightChildReceiver.Reset();

        // Check Deselect
        eventSystem.SetSelectedGameObject(null);
        eventSystem.InvokeUpdate();

        Assert.That(leftChildReceiver.events, Has.Count.EqualTo(0));
        Assert.That(rightChildReceiver.events, Has.Count.EqualTo(1));
        Assert.That(rightChildReceiver.events[0].type, Is.EqualTo(EventType.Deselect));
        rightChildReceiver.Reset();
    }
Example #27
0
        /// <summary>
        /// Checks for input to draw, erase or select tiles using the mouse.
        /// </summary>
        private static void CheckForMouseInput()
        {
            _mouseRectInGameWorld = InputSystem.GetMouseRectGameWorld();
            IndexOfMouse          = CalcHelper.GetIndexInGameWorld(_mouseRectInGameWorld.X, _mouseRectInGameWorld.Y);

            if (!IsIntersectingUi())
            {
                if (InputSystem.IsLeftMousePressed() && InputSystem.IsRightMousePressed())
                {
                    return;
                }

                if (InputSystem.IsLeftMousePressed())
                {
                    if (Brush.CurrentBrushMode == Brush.BrushMode.Build && lastAddedTile != IndexOfMouse)
                    {
                        lastAddedTile   = IndexOfMouse;
                        lastRemovedTile = -1;
                        UpdateSelectedTiles(SelectedId);
                    }
                    else if (Brush.CurrentBrushMode == Brush.BrushMode.Erase && lastRemovedTile != IndexOfMouse)
                    {
                        lastRemovedTile = IndexOfMouse;
                        lastAddedTile   = -1;
                        UpdateSelectedTiles(0);
                    }
                    else if (Brush.CurrentBrushMode == Brush.BrushMode.Select)
                    {
                        Tile tile = GameWorld.GetTile(IndexOfMouse);
                        tile.InteractInEditMode();
                    }
                }
                if (InputSystem.IsRightMousePressed())
                {
                    if (!OnWallMode)
                    {
                        ChangeWallModeTo(true);
                    }
                    if (Brush.CurrentBrushMode == Brush.BrushMode.Build && lastAddedTile != IndexOfMouse)
                    {
                        // Entities cannot be placed in wall mode.
                        if ((int)SelectedId < 200)
                        {
                            lastAddedTile   = IndexOfMouse;
                            lastRemovedTile = -1;
                            UpdateSelectedTiles(SelectedId);
                        }
                    }
                    else if (Brush.CurrentBrushMode == Brush.BrushMode.Erase && lastRemovedTile != IndexOfMouse)
                    {
                        lastRemovedTile = IndexOfMouse;
                        lastAddedTile   = -1;
                        UpdateSelectedTiles(0);
                    }
                }
                else if (InputSystem.IsMiddleMousePressed())
                {
                    TileType lastSelectedId = SelectedId;
                    SelectedId = GameWorld.WorldData.TileIDs[IndexOfMouse];
                    if (SelectedId == 0)
                    {
                        SelectedId = GameWorld.WorldData.WallIDs[IndexOfMouse];
                    }
                    if (SelectedId != 0)
                    {
                        HotBar.AddToHotBarFromWorld(SelectedId);
                        Brush.ChangeBrushMode(Brush.BrushMode.Build);
                    }
                    else
                    {
                        SelectedId = lastSelectedId;
                    }
                }
                else
                {
                    if (OnWallMode)
                    {
                        ChangeWallModeTo(false);
                    }
                }
            }
        }
Example #28
0
    public void Controls_DpadVectorsAreCircular()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        // Up.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadUp
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.up));

        // Up left.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadUp | 1 << (int)GamepadState.Button.DpadLeft
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x, Is.EqualTo((Vector2.up + Vector2.left).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y, Is.EqualTo((Vector2.up + Vector2.left).normalized.y).Within(0.00001));

        // Left.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadLeft
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.left));

        // Down left.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadDown | 1 << (int)GamepadState.Button.DpadLeft
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x, Is.EqualTo((Vector2.down + Vector2.left).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y, Is.EqualTo((Vector2.down + Vector2.left).normalized.y).Within(0.00001));

        // Down.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadDown
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.down));

        // Down right.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadDown | 1 << (int)GamepadState.Button.DpadRight
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x,
                    Is.EqualTo((Vector2.down + Vector2.right).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y,
                    Is.EqualTo((Vector2.down + Vector2.right).normalized.y).Within(0.00001));

        // Right.
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            buttons = 1 << (int)GamepadState.Button.DpadRight
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.right));

        // Up right.
        InputSystem.QueueStateEvent(gamepad,
                                    new GamepadState
        {
            buttons = 1 << (int)GamepadState.Button.DpadUp | 1 << (int)GamepadState.Button.DpadRight
        });
        InputSystem.Update();

        Assert.That(gamepad.dpad.ReadValue().x, Is.EqualTo((Vector2.up + Vector2.right).normalized.x).Within(0.00001));
        Assert.That(gamepad.dpad.ReadValue().y, Is.EqualTo((Vector2.up + Vector2.right).normalized.y).Within(0.00001));
    }
Example #29
0
        public void Update()
        {
            ScreenWidth  = device.Viewport.Width;
            ScreenHeight = device.Viewport.Height;


            BG.X      = 0;
            BG.Y      = 0;
            BG.Width  = (int)ScreenWidth;
            BG.Height = (int)ScreenHeight;

            recTitle.X      = (int)(ScreenWidth * 0.33);
            recTitle.Y      = (int)(ScreenHeight * 0.083);
            recTitle.Height = (int)(ScreenHeight * 0.2);
            recTitle.Width  = (int)(ScreenWidth * 0.33);

            recButtonsBkg.X      = (int)(ScreenWidth * 0.083);
            recButtonsBkg.Y      = (int)(ScreenHeight * 0.33);
            recButtonsBkg.Width  = (int)(ScreenWidth * 0.83);
            recButtonsBkg.Height = (int)(ScreenHeight * 0.6);

            recNewGameButton.X      = recButtonsBkg.X + recButtonsBkg.Width / 12;
            recNewGameButton.Y      = recButtonsBkg.Y + recButtonsBkg.Height / 6;
            recNewGameButton.Width  = recButtonsBkg.Width / 8;
            recNewGameButton.Height = recButtonsBkg.Height / 9;

            recLoadButton.X      = recButtonsBkg.X + recButtonsBkg.Width / 12;
            recLoadButton.Y      = recNewGameButton.Y + recButtonsBkg.Height / 8;
            recLoadButton.Width  = recButtonsBkg.Width / 10;
            recLoadButton.Height = recButtonsBkg.Height / 9;

            recOptionButton.X      = recButtonsBkg.X + recButtonsBkg.Width / 12;
            recOptionButton.Y      = recLoadButton.Y + recButtonsBkg.Height / 8;
            recOptionButton.Width  = recButtonsBkg.Width / 9;
            recOptionButton.Height = recButtonsBkg.Height / 9;

            recAboutButton.X      = recButtonsBkg.X + recButtonsBkg.Width / 12;
            recAboutButton.Y      = recOptionButton.Y + recButtonsBkg.Height / 8;
            recAboutButton.Width  = recButtonsBkg.Width / 8;
            recAboutButton.Height = recButtonsBkg.Height / 9;

            recAuthorsButton.X      = recButtonsBkg.X + recButtonsBkg.Width / 12;
            recAuthorsButton.Y      = recAboutButton.Y + recButtonsBkg.Height / 8;
            recAuthorsButton.Width  = recButtonsBkg.Width / 9;
            recAuthorsButton.Height = recButtonsBkg.Height / 9;

            recExitButton.X      = recButtonsBkg.X + recButtonsBkg.Width / 12;
            recExitButton.Y      = recAuthorsButton.Y + recButtonsBkg.Height / 8;
            recExitButton.Width  = recButtonsBkg.Width / 12;
            recExitButton.Height = recButtonsBkg.Height / 9;

            recStory.X      = recButtonsBkg.X + (recButtonsBkg.Width / 100) * 43;
            recStory.Y      = recNewGameButton.Y - recButtonsBkg.Height / 16;
            recStory.Width  = recButtonsBkg.Width / 2;
            recStory.Height = (recButtonsBkg.Height / 100) * 80;

            recAudioSliderBG.X      = recStory.X + recStory.Width / 10;
            recAudioSliderBG.Y      = recStory.Y + recStory.Height / 18;
            recAudioSliderBG.Height = recButtonsBkg.Height / 14;
            recAudioSliderBG.Width  = recButtonsBkg.Width / 2;

            recAudioSlider.X      = recAudioSliderBG.X;
            recAudioSlider.Y      = recAudioSliderBG.Y;
            recAudioSlider.Height = recButtonsBkg.Height / 14;
            recAudioSlider.Width  = (int)(recAudioSliderBG.Width * AudioVolume);



            recEffectsSliderBG.X      = recAudioSliderBG.X;
            recEffectsSliderBG.Y      = recAudioSliderBG.Y + recStory.Height / 5;
            recEffectsSliderBG.Height = recAudioSliderBG.Height;
            recEffectsSliderBG.Width  = recAudioSliderBG.Width;

            recEffectsSlider.X      = recEffectsSliderBG.X;
            recEffectsSlider.Y      = recEffectsSliderBG.Y;
            recEffectsSlider.Height = recEffectsSliderBG.Height;
            recEffectsSlider.Width  = (int)(recEffectsSliderBG.Width * EffectVolume);


            recAudioMute.X      = recAudioSliderBG.X - recAudioSliderBG.Width / 16;
            recAudioMute.Y      = recAudioSliderBG.Y;
            recAudioMute.Height = recAudioSlider.Height;
            recAudioMute.Width  = recAudioMute.Height;

            recEffectMute.X      = recEffectsSliderBG.X - recEffectsSliderBG.Width / 16;
            recEffectMute.Y      = recEffectsSliderBG.Y;
            recEffectMute.Height = recEffectsSliderBG.Height;
            recEffectMute.Width  = recEffectMute.Height;

            recLevelEasy.X      = recEffectsSliderBG.X - recEffectsSliderBG.Width / 16;
            recLevelEasy.Y      = recEffectsSliderBG.Y + recEffectsSliderBG.Height * 3;
            recLevelEasy.Width  = recEffectMute.Width;
            recLevelEasy.Height = recEffectMute.Height;

            recLevelMedium.X      = recLevelEasy.X + recEffectsVolume.Width * 2;
            recLevelMedium.Y      = recEffectsSliderBG.Y + recEffectsSliderBG.Height * 3;
            recLevelMedium.Width  = recEffectMute.Width;
            recLevelMedium.Height = recEffectMute.Height;

            recLevelHard.X      = recLevelEasy.X + recEffectsVolume.Width * 4;
            recLevelHard.Y      = recEffectsSliderBG.Y + recEffectsSliderBG.Height * 3;
            recLevelHard.Width  = recEffectMute.Width;
            recLevelHard.Height = recEffectMute.Height;

            recAudioVolume.X      = recAudioMute.X - (int)(recAudioMute.Width * 3.8);
            recAudioVolume.Y      = recAudioMute.Y + recAudioMute.Height / 4;
            recAudioVolume.Width  = recAudioSliderBG.Width / 5;
            recAudioVolume.Height = recAudioSliderBG.Height / 2;

            recEffectsVolume.X      = recEffectMute.X - (int)(recAudioMute.Width * 3.8);
            recEffectsVolume.Y      = recEffectMute.Y + recEffectMute.Height / 4;
            recEffectsVolume.Width  = recEffectsSliderBG.Width / 5;
            recEffectsVolume.Height = recEffectsSliderBG.Height / 2;


            recEasy.X      = recEffectsVolume.X + recLevelEasy.Width * 2;
            recEasy.Y      = recLevelEasy.Y + recLevelEasy.Height / 6;
            recEasy.Width  = recEffectsVolume.Width / 3;
            recEasy.Height = recEffectsVolume.Height * 2;

            recMedium.X      = recEasy.X + recLevelEasy.Width * 6;
            recMedium.Y      = recEasy.Y;
            recMedium.Height = recEasy.Height;
            recMedium.Width  = recEasy.Width + recEasy.Width / 2;

            recHard.X      = recMedium.X + recLevelEasy.Width * 7;
            recHard.Y      = recMedium.Y;
            recHard.Width  = recEasy.Width;
            recHard.Height = recEasy.Height;



            recAuthors.X      = recButtonsBkg.X + (recButtonsBkg.Width / 10) * 4;
            recAuthors.Y      = recButtonsBkg.Y + recButtonsBkg.Height / 7;
            recAuthors.Width  = recButtonsBkg.Width / 2;
            recAuthors.Height = recButtonsBkg.Height / 2;

            if (AuthorsButtonEvent() && !ifAuthors)
            {
                inOptions = false;
                ifStory   = false;
                ifAuthors = true;
            }


            if (AboutButtonEvent() && !ifStory)
            {
                ifAuthors = false;
                inOptions = false;
                ifStory   = true;
            }
            if (OptionButtonEvent() && !inOptions)
            {
                ifAuthors = false;
                ifStory   = false;
                inOptions = true;
            }

            if (inOptions)
            {
                if (AudioSliderEvents())
                {
                    recAudioSlider.Width = InputSystem.mouseState.Position.X - recAudioSliderBG.X;
                    AudioVolume          = 1.0f * recAudioSlider.Width / recAudioSliderBG.Width;
                    MediaPlayer.Volume   = AudioVolume;
                }
                if (EffectSliderEvents())
                {
                    recEffectsSlider.Width = InputSystem.mouseState.Position.X - recEffectsSliderBG.X;
                    EffectVolume           = 1.0f * recEffectsSlider.Width / recEffectsSliderBG.Width;
                    if (AudioSystem.effectEnable)
                    {
                        SoundEffect.MasterVolume = EffectVolume;
                        AudioSystem.growl[0].Play();
                    }
                }
                if (AudioCheckboxEvents())
                {
                    AudioSystem.audioEnable = !AudioSystem.audioEnable;
                    MediaPlayer.IsMuted     = !AudioSystem.audioEnable;
                }

                if (EffectCheckboxEvents())
                {
                    AudioSystem.effectEnable = !AudioSystem.effectEnable;
                    if (AudioSystem.effectEnable)
                    {
                        SoundEffect.MasterVolume = EffectVolume;
                    }
                    else
                    {
                        SoundEffect.MasterVolume = 0;
                    }
                }

                if (LevelMediumCheckboxEvents())
                {
                    if (level != 1)
                    {
                        level          = 1;
                        Resources.Meat = 50;
                    }
                }
                if (LevelEasyCheckboxEvents())
                {
                    if (level != 0)
                    {
                        level          = 0;
                        Resources.Meat = 100;
                    }
                }
                if (LevelHardCheckboxEvents())
                {
                    if (level != 2)
                    {
                        level          = 2;
                        Resources.Meat = 10;
                    }
                }
            }

            InputSystem.UpdateCursorPosition();

            ScreenWidth  = device.Viewport.Width;
            ScreenHeight = device.Viewport.Height;
        }
Example #30
0
    public void Users_CanPairDevice_WhenDeviceNeedsPlatformLevelUserAccountSelection()
    {
        var receivedChanges = new List <UserChange>();

        InputUser.onChange +=
            (usr, change, device) => { receivedChanges.Add(new UserChange(usr, change, device)); };

        // Start out with device not being paired.
        var returnUserAccountHandle             = 0;
        var returnUserAccountName               = "";
        var returnUserAccountId                 = "";
        var returnUserAccountSelectionCancelled = false;

        var gamepadId = runtime.AllocateDeviceId();
        var receivedPairingRequest = false;
        var receivedUserIdRequest  = false;

        runtime.SetDeviceCommandCallback(gamepadId,
                                         (id, command) =>
        {
            unsafe
            {
                if (command->type == QueryPairedUserAccountCommand.Type)
                {
                    receivedUserIdRequest = true;
                    var result            = InputDeviceCommand.kGenericSuccess;
                    if (returnUserAccountHandle != 0)
                    {
                        var queryPairedUser     = (QueryPairedUserAccountCommand *)command;
                        queryPairedUser->handle = (uint)returnUserAccountHandle;
                        queryPairedUser->name   = returnUserAccountName;
                        queryPairedUser->id     = returnUserAccountId;
                        result |= (long)QueryPairedUserAccountCommand.Result.DevicePairedToUserAccount;
                    }

                    if (returnUserAccountSelectionCancelled)
                    {
                        result |= (long)QueryPairedUserAccountCommand.Result.UserAccountSelectionCancelled;
                    }
                    return(result);
                }
                if (command->type == InitiateUserAccountPairingCommand.Type)
                {
                    Assert.That(receivedPairingRequest, Is.False);
                    receivedPairingRequest = true;
                    return((long)InitiateUserAccountPairingCommand.Result.SuccessfullyInitiated);
                }
            }

            return(InputDeviceCommand.kGenericFailure);
        });

        runtime.ReportNewInputDevice <Gamepad>(gamepadId);

        InputSystem.Update();
        var gamepad = InputSystem.GetDevice <Gamepad>();

        Assert.That(InputUser.all, Has.Count.Zero);
        Assert.That(receivedUserIdRequest, Is.False);
        Assert.That(receivedPairingRequest, Is.False);
        Assert.That(receivedChanges, Is.Empty);

        // Initiate pairing.
        var user = InputUser.PerformPairingWithDevice(gamepad);

        Assert.That(user.valid, Is.True);
        Assert.That(user.platformUserAccountHandle, Is.Null);
        Assert.That(user.platformUserAccountId, Is.Null);
        Assert.That(user.platformUserAccountName, Is.Null);
        ////REVIEW: is this really the most useful behavior? should we always pair?
        Assert.That(user.pairedDevices, Is.Empty); // We pair only on completion of account selection.
        Assert.That(receivedUserIdRequest, Is.True);
        Assert.That(receivedPairingRequest, Is.True);
        Assert.That(receivedChanges, Is.EquivalentTo(new[]
        {
            new UserChange(user, InputUserChange.Added),
            new UserChange(user, InputUserChange.AccountSelectionInProgress, gamepad),
        }));

        receivedUserIdRequest  = false;
        receivedPairingRequest = false;
        receivedChanges.Clear();

        // Pretend it's complete.
        returnUserAccountHandle = 1;
        returnUserAccountName   = "TestUser";
        returnUserAccountId     = "TestId";

        InputSystem.QueueConfigChangeEvent(gamepad);
        InputSystem.Update();

        Assert.That(user.platformUserAccountHandle, Is.EqualTo(new InputUserAccountHandle("Test", 1)));
        Assert.That(user.platformUserAccountId, Is.EqualTo("TestId"));
        Assert.That(user.platformUserAccountName, Is.EqualTo("TestUser"));
        Assert.That(user.pairedDevices, Is.EquivalentTo(new[] { gamepad }));
        Assert.That(receivedUserIdRequest, Is.True);
        Assert.That(receivedPairingRequest, Is.False);
        Assert.That(receivedChanges, Is.EquivalentTo(new[]
        {
            new UserChange(user, InputUserChange.AccountSelectionComplete, gamepad),
            new UserChange(user, InputUserChange.DevicePaired, gamepad),
        }));

        receivedUserIdRequest  = false;
        receivedPairingRequest = false;
        receivedChanges.Clear();

        // Force another pairing.
        var secondPairingUser = InputUser.PerformPairingWithDevice(gamepad,
                                                                   user: user,
                                                                   options: InputUserPairingOptions.ForcePlatformUserAccountSelection);

        Assert.That(secondPairingUser, Is.EqualTo(user));
        Assert.That(receivedUserIdRequest, Is.False); // When we force, shouldn't ask OS for currently paired user.
        Assert.That(receivedPairingRequest, Is.True);
        Assert.That(receivedChanges, Is.EquivalentTo(new[]
        {
            new UserChange(user, InputUserChange.AccountSelectionInProgress, gamepad),
        }));

        receivedUserIdRequest  = false;
        receivedPairingRequest = false;
        receivedChanges.Clear();

        // Cancel account selection.
        returnUserAccountSelectionCancelled = true;

        InputSystem.QueueConfigChangeEvent(gamepad);
        InputSystem.Update();

        Assert.That(user.platformUserAccountHandle, Is.EqualTo(new InputUserAccountHandle("Test", 1)));
        Assert.That(user.platformUserAccountId, Is.EqualTo("TestId"));
        Assert.That(user.platformUserAccountName, Is.EqualTo("TestUser"));
        Assert.That(user.pairedDevices, Is.EquivalentTo(new[] { gamepad }));
        Assert.That(receivedUserIdRequest, Is.True);
        Assert.That(receivedPairingRequest, Is.False);
        Assert.That(receivedChanges, Is.EquivalentTo(new[]
        {
            new UserChange(user, InputUserChange.AccountSelectionCancelled, gamepad)
        }));

        receivedUserIdRequest  = false;
        receivedPairingRequest = false;
        receivedChanges.Clear();

        // Force another pairing.
        InputUser.PerformPairingWithDevice(gamepad,
                                           user: user,
                                           options: InputUserPairingOptions.ForcePlatformUserAccountSelection);

        Assert.That(receivedUserIdRequest, Is.False); // When we force, shouldn't ask OS for currently paired user.
        Assert.That(receivedPairingRequest, Is.True);
        Assert.That(receivedChanges, Is.EquivalentTo(new[]
        {
            new UserChange(user, InputUserChange.AccountSelectionInProgress, gamepad)
        }));

        receivedUserIdRequest  = false;
        receivedPairingRequest = false;
        receivedChanges.Clear();

        // Complete it.
        returnUserAccountHandle             = 2;
        returnUserAccountName               = "OtherUser";
        returnUserAccountId                 = "OtherId";
        returnUserAccountSelectionCancelled = false;

        InputSystem.QueueConfigChangeEvent(gamepad);
        InputSystem.Update();

        Assert.That(user.platformUserAccountHandle, Is.EqualTo(new InputUserAccountHandle("Test", 2)));
        Assert.That(user.platformUserAccountId, Is.EqualTo("OtherId"));
        Assert.That(user.platformUserAccountName, Is.EqualTo("OtherUser"));
        Assert.That(user.pairedDevices, Is.EquivalentTo(new[] { gamepad }));
        Assert.That(receivedUserIdRequest, Is.True);
        Assert.That(receivedPairingRequest, Is.False);
        Assert.That(receivedChanges, Is.EquivalentTo(new[]
        {
            new UserChange(user, InputUserChange.AccountSelectionComplete, gamepad)
        }));
    }
 public void Setup()
 {
     InputSystem.SaveAndReset();
 }
    public IEnumerator SetUp()
    {
        // Set up input.
        input = new InputTestFixture();
        input.Setup();

        // See if we have a platform set for the current test.
        var testProperties = TestContext.CurrentContext.Test.Properties;

        if (testProperties.ContainsKey("Platform"))
        {
            var value = (string)testProperties["Platform"][0];
            switch (value.ToLower())
            {
            case "windows":
                platform = RuntimePlatform.WindowsPlayer;
                break;

            case "osx":
                platform = RuntimePlatform.OSXPlayer;
                break;

            case "android":
                platform = RuntimePlatform.Android;
                break;

            case "ios":
                platform = RuntimePlatform.IPhonePlayer;
                break;

            default:
                throw new NotImplementedException();
            }
        }
        else
        {
            platform = Application.platform;
        }
        DemoGame.platform = platform;

        // Give us a fresh scene.
        yield return(SceneManager.LoadSceneAsync("Assets/Demo/Demo.unity", LoadSceneMode.Single));

        game = GameObject.Find("DemoGame").GetComponent <DemoGame>();

        // If there's a "Platform" property on the test or no specific "Device" property, add the default
        // set of devices for the current platform.
        if (testProperties.ContainsKey("Platform") || !testProperties.ContainsKey("Device"))
        {
            // Set up default device matrix for current platform.
            // NOTE: We use strings here instead of types as not all devices are available in all players.
            switch (platform)
            {
            case RuntimePlatform.WindowsEditor:
            case RuntimePlatform.WindowsPlayer:
                keyboard    = (Keyboard)InputSystem.AddDevice("Keyboard");
                mouse       = (Mouse)InputSystem.AddDevice("Mouse");
                pen         = (Pen)InputSystem.AddDevice("Pen");
                touchscreen = (Touchscreen)InputSystem.AddDevice("Touchscreen");
                ps4Gamepad  = (DualShockGamepad)InputSystem.AddDevice("DualShockGamepadHID");
                xboxGamepad = (XInputController)InputSystem.AddDevice("XInputController");
                ////TODO: joystick
                break;

            case RuntimePlatform.OSXPlayer:
            case RuntimePlatform.OSXEditor:
                keyboard    = (Keyboard)InputSystem.AddDevice("Keyboard");
                mouse       = (Mouse)InputSystem.AddDevice("Mouse");
                ps4Gamepad  = (DualShockGamepad)InputSystem.AddDevice("DualShockGamepadHID");
                xboxGamepad = (XInputController)InputSystem.AddDevice("XInputController");
                ////TODO: joystick
                break;

            ////TODO: other platforms
            default:
                throw new NotImplementedException();
            }
        }

        // Add whatever devices are specified in explicit "Device" properties.
        if (testProperties.ContainsKey("Device"))
        {
            foreach (var value in testProperties["Device"])
            {
                switch (((string)value).ToLower())
                {
                case "gamepad":
                    InputSystem.AddDevice <Gamepad>();
                    break;

                case "keyboard":
                    InputSystem.AddDevice <Keyboard>();
                    break;

                case "mouse":
                    InputSystem.AddDevice <Mouse>();
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
        }

        // Check if we should add VR support.
        if (testProperties.ContainsKey("VR"))
        {
            var value = (string)testProperties["VR"][0];
            switch (value.ToLower())
            {
            case "":
            case "any":
                // Add a combination of generic XRHMD and XRController instances that don't
                // represent any specific set of hardware out there.
                hmd       = InputSystem.AddDevice <XRHMD>();
                leftHand  = InputSystem.AddDevice <XRController>();
                rightHand = InputSystem.AddDevice <XRController>();
                InputSystem.SetDeviceUsage(leftHand, CommonUsages.LeftHand);
                InputSystem.SetDeviceUsage(rightHand, CommonUsages.RightHand);
                break;

            default:
                throw new NotImplementedException();
            }

            DemoGame.vrSupported = true;
        }

        // Check if we should add Steam support.
        if (testProperties.ContainsKey("Steam"))
        {
            ////TODO: create steam test fixture
            steamController = InputSystem.AddDevice("SteamDemoController");
        }
    }
 public void TearDown()
 {
     InputSystem.Restore();
 }
Example #34
0
    public void State_CanWaitForStateChangeWithinGivenAmountOfTime()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var          monitorFired       = false;
        var          timeoutFired       = false;
        double?      receivedTime       = null;
        int?         receivedTimerIndex = null;
        InputControl receivedControl    = null;

        var monitor = InputSystem.AddStateChangeMonitor(gamepad.leftStick,
                                                        (control, time, monitorIndex) =>
        {
            Assert.That(!monitorFired);
            monitorFired = true;
        }, timerExpiredCallback:
                                                        (control, time, monitorIndex, timerIndex) =>
        {
            Assert.That(!timeoutFired);
            timeoutFired       = true;
            receivedTime       = time;
            receivedTimerIndex = timerIndex;
            receivedControl    = control;
        });

        // Add and immediately expire timeout.
        InputSystem.AddStateChangeMonitorTimeout(gamepad.leftStick, monitor, testRuntime.currentTime + 1,
                                                 timerIndex: 1234);
        testRuntime.currentTime += 2;
        InputSystem.Update();

        Assert.That(timeoutFired);
        Assert.That(!monitorFired);
        Assert.That(receivedTimerIndex.Value, Is.EqualTo(1234));
        Assert.That(receivedTime.Value, Is.EqualTo(testRuntime.currentTime).Within(0.00001));
        Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));

        timeoutFired       = false;
        receivedTimerIndex = null;
        receivedTime       = null;

        // Add timeout and obsolete it by state change. Then advance past timeout time
        // and make sure we *don't* get a notification.
        InputSystem.AddStateChangeMonitorTimeout(gamepad.leftStick, monitor, testRuntime.currentTime + 1,
                                                 timerIndex: 4321);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = Vector2.one
        });
        InputSystem.Update();

        Assert.That(monitorFired);
        Assert.That(!timeoutFired);

        testRuntime.currentTime += 2;
        InputSystem.Update();

        Assert.That(!timeoutFired);

        // Add and remove timeout. Then advance past timeout time and make sure we *don't*
        // get a notification.
        InputSystem.AddStateChangeMonitorTimeout(gamepad.leftStick, monitor, testRuntime.currentTime + 1,
                                                 timerIndex: 1423);
        InputSystem.RemoveStateChangeMonitorTimeout(monitor, timerIndex: 1423);
        InputSystem.QueueStateEvent(gamepad, new GamepadState {
            leftStick = Vector2.one
        });
        InputSystem.Update();

        Assert.That(!timeoutFired);
    }
Example #35
0
 static SwipeInteraction()
 {
     InputSystem.RegisterInteraction <SwipeInteraction>();
 }
Example #36
0
 static RemapInputProcessor()
 {
     InputSystem.RegisterProcessor <RemapInputProcessor>();
 }
Example #37
0
    public void Layouts_AllFeatureTypes_AreRepresentedInTheGeneratedLayout()
    {
        runtime.ReportNewInputDevice(TestXRDeviceState.CreateDeviceDescription().ToJson());

        InputSystem.Update();

        var generatedLayout = InputSystem.LoadLayout("XRInputV1::XRManufacturer::XRDevice");

        Assert.That(generatedLayout, Is.Not.Null);
        Assert.That(generatedLayout.controls.Count, Is.EqualTo(kNumBaseHMDControls + 9));

        var binaryControl = generatedLayout["Button"];

        Assert.That(binaryControl.name, Is.EqualTo(new InternedString("Button")));
        Assert.That(binaryControl.offset, Is.EqualTo(0));
        Assert.That(binaryControl.layout, Is.EqualTo(new InternedString("Button")));
        Assert.That(binaryControl.usages.Count, Is.EqualTo(1));
        Assert.That(binaryControl.usages[0], Is.EqualTo(new InternedString("ButtonUsage")));

        var discreteControl = generatedLayout["DiscreteState"];

        Assert.That(discreteControl.name, Is.EqualTo(new InternedString("DiscreteState")));
        Assert.That(discreteControl.offset, Is.EqualTo(4));
        Assert.That(discreteControl.layout, Is.EqualTo(new InternedString("Integer")));
        Assert.That(discreteControl.usages.Count, Is.EqualTo(1));
        Assert.That(discreteControl.usages[0], Is.EqualTo(new InternedString("DiscreteStateUsage")));

        var axisControl = generatedLayout["Axis"];

        Assert.That(axisControl.name, Is.EqualTo(new InternedString("Axis")));
        Assert.That(axisControl.offset, Is.EqualTo(8));
        Assert.That(axisControl.layout, Is.EqualTo(new InternedString("Analog")));
        Assert.That(axisControl.usages.Count, Is.EqualTo(1));
        Assert.That(axisControl.usages[0], Is.EqualTo(new InternedString("Axis1DUsage")));

        var vec2Control = generatedLayout["Vector2"];

        Assert.That(vec2Control.name, Is.EqualTo(new InternedString("Vector2")));
        Assert.That(vec2Control.offset, Is.EqualTo(12));
        Assert.That(vec2Control.layout, Is.EqualTo(new InternedString("Vector2")));
        Assert.That(vec2Control.usages.Count, Is.EqualTo(1));
        Assert.That(vec2Control.usages[0], Is.EqualTo(new InternedString("Axis2DUsage")));

        var vec3Control = generatedLayout["Vector3"];

        Assert.That(vec3Control.name, Is.EqualTo(new InternedString("Vector3")));
        Assert.That(vec3Control.offset, Is.EqualTo(20));
        Assert.That(vec3Control.layout, Is.EqualTo(new InternedString("Vector3")));
        Assert.That(vec3Control.usages.Count, Is.EqualTo(1));
        Assert.That(vec3Control.usages[0], Is.EqualTo(new InternedString("Axis3DUsage")));

        var rotationControl = generatedLayout["Rotation"];

        Assert.That(rotationControl.name, Is.EqualTo(new InternedString("Rotation")));
        Assert.That(rotationControl.offset, Is.EqualTo(32));
        Assert.That(rotationControl.layout, Is.EqualTo(new InternedString("Quaternion")));
        Assert.That(rotationControl.usages.Count, Is.EqualTo(1));
        Assert.That(rotationControl.usages[0], Is.EqualTo(new InternedString("RotationUsage")));

        // Custom element is skipped, but occupies 256 bytes

        var lastControl = generatedLayout["Last"];

        Assert.That(lastControl.name, Is.EqualTo(new InternedString("Last")));
        Assert.That(lastControl.offset, Is.EqualTo(304));
        Assert.That(lastControl.layout, Is.EqualTo(new InternedString("Button")));
        Assert.That(lastControl.usages.Count, Is.EqualTo(2));
        Assert.That(lastControl.usages[0], Is.EqualTo(new InternedString("LastElementUsage")));
        Assert.That(lastControl.usages[1], Is.EqualTo(new InternedString("SecondUsage")));
    }
Example #38
0
    // TODO: This should be applied before all updates, or whenever
    // input normally is applied (based on the InputSystem configuration).
    // TODO: There's a bug where although a press and release are recorded,
    // sometimes the InputSystem does not correctly reset state.
    private void Update()
    {
        var keyboardMessages = new Dictionary <uint, List <Parsec.ParsecMessage> >();
        var gamepadMessages  = new Dictionary <uint, List <Parsec.ParsecMessage> >();

        while (parsec.HostPollInput(0u, out Parsec.ParsecGuest guest, out Parsec.ParsecMessage msg))
        {
            switch (msg.type)
            {
            case Parsec.ParsecMessageType.MESSAGE_KEYBOARD:
                if (!keyboardMessages.ContainsKey(guest.id))
                {
                    keyboardMessages[guest.id] = new List <Parsec.ParsecMessage>();
                }

                keyboardMessages[guest.id].Add(msg);
                break;

            case Parsec.ParsecMessageType.MESSAGE_MOUSE_BUTTON:
                ParsecUnityController.Log($"Guest {guest.id} {(msg.mouseButton.pressed ? "pressed" : "released")} mouse button {msg.mouseButton} at {Time.time}");
                break;

            case Parsec.ParsecMessageType.MESSAGE_GAMEPAD_BUTTON:
                if (!gamepadMessages.ContainsKey(guest.id))
                {
                    gamepadMessages[guest.id] = new List <Parsec.ParsecMessage>();
                }

                gamepadMessages[guest.id].Add(msg);
                break;

            case Parsec.ParsecMessageType.MESSAGE_GAMEPAD_AXIS:
                if (!gamepadMessages.ContainsKey(guest.id))
                {
                    gamepadMessages[guest.id] = new List <Parsec.ParsecMessage>();
                }

                gamepadMessages[guest.id].Add(msg);
                break;

            default:
                break;
            }
        }

        // Unity's low level input event queuing system apparently does not like
        // multiple events to be queued for a single device each input round,
        // making it necessary to store all events per device ahead of time.
        foreach (var kvp in keyboardMessages)
        {
            if (!guests[kvp.Key].Get(out Keyboard keyboard))
            {
                keyboard = guests[kvp.Key].Add <Keyboard>();
            }

            using (StateEvent.From(keyboard, out InputEventPtr eventPtr))
            {
                foreach (var msg in kvp.Value)
                {
                    if (ParsecInputSystemMapping.Keys.TryGetValue(msg.keyboard.code, out Key key))
                    {
                        if (guests[kvp.Key].Use(keyboard))
                        {
                            ParsecUnityController.Log($"Guest {kvp.Key} switched current device to keyboard at {Time.time}");
                        }

                        ParsecUnityController.Log($"Guest {kvp.Key} {(msg.keyboard.pressed ? "pressed" : "released")} key {key} at {Time.time}");

                        keyboard[key].WriteValueIntoEvent <float>(msg.keyboard.pressed ? 1 : 0, eventPtr);
                    }
                }

                InputSystem.QueueEvent(eventPtr);
            }
        }

        foreach (var kvp in gamepadMessages)
        {
            if (!guests[kvp.Key].Get(out Gamepad gamepad))
            {
                gamepad = guests[kvp.Key].Add <Gamepad>();
            }

            using (StateEvent.From(gamepad, out InputEventPtr eventPtr))
            {
                foreach (var msg in kvp.Value)
                {
                    if (msg.type == Parsec.ParsecMessageType.MESSAGE_GAMEPAD_BUTTON)
                    {
                        var button = ParsecInputSystemMapping.ParsecToGamepadButton(gamepad, msg.gamepadButton.button);

                        if (button != null)
                        {
                            if (guests[kvp.Key].Use(gamepad))
                            {
                                ParsecUnityController.Log($"Guest {kvp.Key} switched current device to gamepad {msg.gamepadButton.id} at {Time.time}");
                            }

                            ParsecUnityController.Log($"Guest {kvp.Key} {(msg.gamepadButton.pressed ? "pressed" : "released")} {button} on gamepad {msg.gamepadButton.id} at {Time.time}");

                            button.WriteValueIntoEvent <float>(msg.gamepadButton.pressed ? 1 : 0, eventPtr);
                        }
                    }
                    else if (msg.type == Parsec.ParsecMessageType.MESSAGE_GAMEPAD_AXIS)
                    {
                        var axis = ParsecInputSystemMapping.ParsecToGamepadAxis(gamepad, msg.gamepadAxis.axis);

                        if (axis != null)
                        {
                            float value = (float)msg.gamepadAxis.value / short.MaxValue;

                            // TODO: Set a constant for this value that makes sense to avoid deadzoned values switching devices.
                            if (Mathf.Abs(value) > 0.4f && guests[kvp.Key].Use(gamepad))
                            {
                                ParsecUnityController.Log($"Guest {kvp.Key} switched current device to gamepad {msg.gamepadButton.id} at {Time.time}");
                            }

                            axis.WriteValueIntoEvent(value, eventPtr);
                        }
                    }
                }

                InputSystem.QueueEvent(eventPtr);
            }
        }
    }
Example #39
0
    public void Components_CanUpdateGameObjectTransformThroughTrackedPoseDriver()
    {
        var position = new Vector3(1.0f, 2.0f, 3.0f);
        var rotation = new Quaternion(0.09853293f, 0.09853293f, 0.09853293f, 0.9853293f);

        var go     = new GameObject();
        var tpd    = go.AddComponent <TrackedPoseDriver>();
        var device = InputSystem.AddDevice <TestHMD>();

        using (StateEvent.From(device, out var stateEvent))
        {
            var positionAction = new InputAction();
            positionAction.AddBinding("<TestHMD>/vector3");

            var rotationAction = new InputAction();
            rotationAction.AddBinding("<TestHMD>/quaternion");

            tpd.positionAction = positionAction;
            tpd.rotationAction = rotationAction;

            // before render only
            var go1 = tpd.gameObject;
            go1.transform.position = Vector3.zero;
            go1.transform.rotation = new Quaternion(0, 0, 0, 0);
            tpd.updateType         = TrackedPoseDriver.UpdateType.BeforeRender;
            tpd.trackingType       = TrackedPoseDriver.TrackingType.RotationAndPosition;

            device.quaternion.WriteValueIntoEvent(rotation, stateEvent);
            device.vector3.WriteValueIntoEvent(position, stateEvent);

            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.Dynamic);
            Assert.That(tpd.gameObject.transform.position, Is.Not.EqualTo(position));
            Assert.That(!tpd.gameObject.transform.rotation.Equals(rotation));

            var go2 = tpd.gameObject;
            go2.transform.position = Vector3.zero;
            go2.transform.rotation = new Quaternion(0, 0, 0, 0);
            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.BeforeRender);
            Assert.That(tpd.gameObject.transform.position, Is.EqualTo(position));
            Assert.That(tpd.gameObject.transform.rotation.Equals(rotation));

            // update only
            var go3 = tpd.gameObject;
            go3.transform.position = Vector3.zero;
            go3.transform.rotation = new Quaternion(0, 0, 0, 0);
            tpd.updateType         = TrackedPoseDriver.UpdateType.Update;
            tpd.trackingType       = TrackedPoseDriver.TrackingType.RotationAndPosition;

            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.Dynamic);
            Assert.That(tpd.gameObject.transform.position, Is.EqualTo(position));
            Assert.That(tpd.gameObject.transform.rotation.Equals(rotation));

            var go4 = tpd.gameObject;
            go4.transform.position = Vector3.zero;
            go4.transform.rotation = new Quaternion(0, 0, 0, 0);
            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.BeforeRender);
            Assert.That(tpd.gameObject.transform.position, Is.Not.EqualTo(position));
            Assert.That(!tpd.gameObject.transform.rotation.Equals(rotation));

            // check the rot/pos case also Update AND Render.
            tpd.updateType   = TrackedPoseDriver.UpdateType.UpdateAndBeforeRender;
            tpd.trackingType = TrackedPoseDriver.TrackingType.PositionOnly;
            var go5 = tpd.gameObject;
            go5.transform.position = Vector3.zero;
            go5.transform.rotation = new Quaternion(0, 0, 0, 0);

            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.Dynamic);
            Assert.That(tpd.gameObject.transform.position, Is.EqualTo(position));
            Assert.That(!tpd.gameObject.transform.rotation.Equals(rotation));

            tpd.trackingType = TrackedPoseDriver.TrackingType.RotationOnly;
            var go6 = tpd.gameObject;
            go6.transform.position = Vector3.zero;
            go6.transform.rotation = new Quaternion(0, 0, 0, 0);
            InputSystem.QueueEvent(stateEvent);
            InputSystem.Update(InputUpdateType.BeforeRender);
            Assert.That(tpd.gameObject.transform.position, Is.Not.EqualTo(position));
            Assert.That(tpd.gameObject.transform.rotation.Equals(rotation));
        }
    }