Ejemplo n.º 1
2
        private static void StartJoystickCapture(CancellationToken token)
        {
            var joystickGuid = Guid.Empty;
            var di = new DirectInput();
            foreach (var device in di.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AttachedOnly))
            {
                joystickGuid = device.InstanceGuid;
                break;
            }
            _joystick = new SharpDX.DirectInput.Joystick(di, joystickGuid);
            _joystick.Acquire();
            _currentThrottle = 0;
            _currentYawTrim = 0;
            while (!token.IsCancellationRequested)
            {
                var state = _joystick.GetCurrentState();

                _currentThrottle = (1000 - GetAnalogStickValue(state.Sliders[0])) / 2;
                Helicopter.Command.MainThrottle = _currentThrottle;

                Helicopter.Command.Pitch = GetAnalogStickValue(state.Y);

                //Helicopter.Command.Yaw = -1 * (GetAnalogStickValue(state.X) + _currentYawTrim); //For n64 controller
                Helicopter.Command.Yaw = -1 * (GetAnalogStickValue(state.RotationZ) + _currentYawTrim);

                var yawtrimChange = GetYawTrimChange(state.Buttons);
                _currentYawTrim += yawtrimChange;
                Helicopter.Command.YawTrim = _currentYawTrim;

                SetConsoleDisplay(state);
                Thread.Sleep(Speed);
            }
        }
Ejemplo n.º 2
0
        public Gamepad()
        {
            dInput = new DI.DirectInput();
            var list = dInput.GetDevices(DI.DeviceType.Gamepad, DI.DeviceEnumerationFlags.AttachedOnly);

            if (list.Count == 0)
            {
                list = dInput.GetDevices(DI.DeviceType.Joystick, DI.DeviceEnumerationFlags.AttachedOnly);
                if (list.Count == 0)
                {
                    padConnected = false;
                }
                else
                {
                    padConnected = true;
                }
            }
            else
            {
                padConnected = true;
            }

            if (padConnected)
            {
                padTrans = new bool[8];
                Pad      = new DI.Joystick(dInput, list[0].InstanceGuid);
                //Pad.Acquire();
            }
        }
Ejemplo n.º 3
0
        protected override void Initialize()
        {
            if (_joyInfo.IsXInput)
            {
                Enumerate();
            }
            else
            {
                JoystickState.Axis.Clear();

                this._joystick = new SharpDX.DirectInput.Joystick(this._directInput, this._deviceGuid);

                this._window = ((DirectXInputManager)Creator).WindowHandle;

                this._joystick.SetCooperativeLevel(this._window, this._coopSettings);

                if (IsBuffered)
                {
                    this._joystick.Properties.BufferSize = BufferSize;
                }

                //Enumerate all axes/buttons/sliders/etc before aquiring
                Enumerate();

                JoystickState.Clear();

                Capture();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// ctor and init
        /// </summary>
        /// <param name="device">A DXInput device</param>
        /// <param name="hwnd">The WinHandle of the main window</param>
        /// <param name="joystickNum">The 0.. n-1 Joystick from DX enum</param>
        public DevJoystick(SharpDX.DirectInput.Joystick device, Control hwnd)
        {
            //      log.DebugFormat( "JoystickCls ctor - Entry with {0}", device.Information.ProductName );

            m_device = device;
            m_hwnd   = hwnd;
            // Set BufferSize in order to use buffered data.
            m_device.Properties.BufferSize = 128;

            //      log.Debug( "Get JS Objects" );
            try {
                // Set the data format to the c_dfDIJoystick pre-defined format.
                //m_device.SetDataFormat( DeviceDataFormat.Joystick );
                // Set the cooperative level for the device.
                m_device.SetCooperativeLevel(m_hwnd, CooperativeLevel.NonExclusive | CooperativeLevel.Background);
                // Enumerate all the objects on the device.
                foreach (DeviceObjectInstance d in m_device.GetObjects( ))
                {
                    // For axes that are returned, set the DIPROP_RANGE property for the
                    // enumerated axis in order to scale min/max values.
                    if ((0 != (d.ObjectId.Flags & DeviceObjectTypeFlags.Axis)))
                    {
                        // Set the range for the axis.
                        m_device.Properties.Range = new InputRange(-1000, +1000);
                    }
                }
                StartEventHandling( );
            }
            catch (Exception ex) {
                Console.WriteLine("Get JS Objects failed:\n{0}", ex);
            }
            DevJoystick.RegisteredDevices++;
        }
Ejemplo n.º 5
0
        protected override void Dispose(bool disposeManagedResources)
        {
            if (!IsDisposed)
            {
                if (disposeManagedResources)
                {
                    // Dispose managed resources.
                }

                // There are no unmanaged resources to release, but
                // if we add them, they need to be released here.
                if (this._joystick != null)
                {
                    try
                    {
                        this._joystick.Unacquire();
                    }
                    finally
                    {
                        this._joystick.Dispose();
                        this._joystick      = null;
                        this._directInput   = null;
                        this._forceFeedback = null;
                    }

                    ((DirectXInputManager)Creator).ReleaseDevice <Joystick>(this._joyInfo);
                }
            }
            IsDisposed = true;

            // If it is available, make the call to the
            // base class's Dispose(Boolean) method
            base.Dispose(disposeManagedResources);
        }
Ejemplo n.º 6
0
        public Controller()
        {
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                MessageBox.Show("No joystick/Gamepad found.");
            }
            else
            {
                value    = 0;
                joystick = new Joystick(directInput, joystickGuid);
                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;
                // Acquire the joystick
                joystick.Acquire();
            }
        }
Ejemplo n.º 7
0
        public void ObtainJoystick()
        {
            if (DJoystick != null) {
                DJoystick.Dispose();
            }

            directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            if (joystickGuid == Guid.Empty) {
                Log.LogMessage("No joystick connected");
                return;
            }

            // Instantiate the joystick
            DJoystick = new DirectJoystick(directInput, joystickGuid);

            Log.LogMessage("Found Joystick with GUID: {0}		Name: {1}", joystickGuid, DJoystick.Information.ProductName);

            // Set BufferSize in order to use buffered data.
            DJoystick.Properties.BufferSize = 128;

            // Acquire the joystick
            DJoystick.Acquire();
        }
Ejemplo n.º 8
0
        public void ObtainJoystick()
        {
            if (DJoystick != null)
            {
                DJoystick.Dispose();
            }

            directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            if (joystickGuid == Guid.Empty)
            {
                Log.LogMessage("No joystick connected");
                return;
            }

            // Instantiate the joystick
            DJoystick = new DirectJoystick(directInput, joystickGuid);

            Log.LogMessage("Found Joystick with GUID: {0}		Name: {1}", joystickGuid, DJoystick.Information.ProductName);

            // Set BufferSize in order to use buffered data.
            DJoystick.Properties.BufferSize = 128;

            // Acquire the joystick
            DJoystick.Acquire();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// ctor and init
        /// </summary>
        /// <param name="device">A DXInput device</param>
        /// <param name="hwnd">The WinHandle of the main window</param>
        /// <param name="joystickNum">The 0.. n-1 Joystick from DX enum</param>
        /// <param name="panel">The respective JS panel to show the properties</param>
        /// <param name="tabIndex">The Tab index in the GUI</param>
        public JoystickCls(SharpDX.DirectInput.Joystick device, Control hwnd, int joystickNum, UC_JoyPanel panel, int tabIndex)
        {
            log.DebugFormat("JoystickCls ctor - Entry with {0}", device.Information.ProductName);

            m_device         = device;
            m_hwnd           = hwnd;
            m_joystickNumber = joystickNum;     // this remains fixed
            m_xmlInstance    = joystickNum + 1; // initial assignment (is 1 based..)
            m_jPanel         = panel;
            MyTabPageIndex   = tabIndex;
            Activated_low    = false;

            m_senseLimit = AppConfiguration.AppConfig.jsSenseLimit; // can be changed in the app.config file if it is still too little

            // Set BufferSize in order to use buffered data.
            m_device.Properties.BufferSize = 128;

            m_jPanel.Caption      = m_device.Properties.ProductName;
            m_jPanel.nAxis        = AxisCount.ToString( );
            m_jPanel.nButtons     = ButtonCount.ToString( );
            m_jPanel.nPOVs        = POVCount.ToString( );
            m_jPanel.JsAssignment = 0; // default is no assignment

            m_ignoreButtons = new bool[m_state.Buttons.Length];
            ResetButtons(m_ignoreButtons);

            m_modifierButtons = new bool[m_state.Buttons.Length];
            ResetButtons(m_modifierButtons);

            log.Debug("Get JS Objects");
            try {
                // Set the data format to the c_dfDIJoystick pre-defined format.
                //m_device.SetDataFormat( DeviceDataFormat.Joystick );
                // Set the cooperative level for the device.
                m_device.SetCooperativeLevel(m_hwnd, CooperativeLevel.NonExclusive | CooperativeLevel.Background);
                // Enumerate all the objects on the device.
                foreach (DeviceObjectInstance d in m_device.GetObjects( ))
                {
                    // For axes that are returned, set the DIPROP_RANGE property for the
                    // enumerated axis in order to scale min/max values.
                    if ((0 != (d.ObjectId.Flags & DeviceObjectTypeFlags.Axis)))
                    {
                        // Set the range for the axis.
                        m_device.Properties.Range = new InputRange(-1000, +1000);
                    }
                    // Update the controls to reflect what objects the device supports.
                    UpdateControls(d);
                }
            }
            catch (Exception ex) {
                log.Error("Get JS Objects failed", ex);
            }

            ApplySettings_low( ); // get whatever is needed here from Settings
            JoystickCls.RegisteredDevices++;

            Activated_low = true;
        }
Ejemplo n.º 10
0
    public static bool GetButton(SharpDX.DirectInput.Joystick joystick, int buttonNumber)
    {
        JoystickState state = new JoystickState();

        state = joystick.GetCurrentState();

        bool[] buttons = state.Buttons;
        return(buttons[buttonNumber] == true);
    }
 public void Dispose()
 {
     if (stick != null)
     {
         stick.Unacquire();
         stick.Dispose();
         stick = null;
     }
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Shutdown device access
 /// </summary>
 public override void FinishDX()
 {
     if (null != m_device)
     {
         log.DebugFormat("Release DirectInput device: {0}", m_device.Information.ProductName);
         m_device.Unacquire( );
         m_device = null;
     }
 }
Ejemplo n.º 13
0
        public IReader Create(Identifier id)
        {
            var joystick = new SharpDX.DirectInput.Joystick(_directInput, _resolver.Resolve(id));

            joystick.Properties.BufferSize = 128;
            joystick.Acquire();

            return(new Reader(joystick));
        }
    public void Update(GameTime gameTime)
    {
        previousMouseState    = currentMouseState;
        previousKeyboardState = currentKeyboardState;
        previousGamePadState  = (GamePadState[])currentGamePadState.Clone();
        //previousJoyState = currentJoyState;

        currentMouseState    = Mouse.GetState();
        currentKeyboardState = Keyboard.GetState();

        foreach (PlayerIndex index in Enum.GetValues(typeof(PlayerIndex)))
        {
            currentGamePadState[(int)index] = GamePad.GetState(index);
        }

        if (RumbleDuration > 0)
        {
            GamePadVibration(PlayerIndex.One, leftMotor, rightMotor);
            rumbleDuration -= (float)gameTime.ElapsedGameTime.TotalSeconds;
        }

        if (!currentGamePadState[0].IsConnected && enableControllers && joystick == null)
        {
            JoystickPing -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (JoystickPing < 0)
            {
                JoystickPing = JoystickPingDuration;
                var th = new Thread(GenericControllerConnection);
                th.Start();
#if DEBUG
                Console.WriteLine("A new thread has been created!");
#endif
            }
        }
        else if (joystick != null && enableControllers)
        {
            joystick.Poll();
#if DEBUG
            Console.WriteLine("Polling Joystick...");
#endif
            try
            {
                JoystickState state = joystick.GetCurrentState();
                currentJoyState = joystick.GetCurrentState();
                bool[] button = state.Buttons;
                int[]  hats   = state.PointOfViewControllers;
                Console.WriteLine("[{0}]", string.Join(", ", hats));
            }
            catch (Exception)
            {
#if DEBUG
                Console.WriteLine("Oops, the controller disconnected!");
#endif
                joystick = null;
            }
        }
    }
Ejemplo n.º 15
0
        public SharpDX.DirectInput.Joystick AcquireJoystick(string name)
        {
            joystick = getJoyStickByName(name);

            if (joystick == null)
            {
                return(null);
            }

            joystick.Acquire();

            joystick.Poll();

            return(joystick);
        }
Ejemplo n.º 16
0
        public override bool AcquireJoystick(string name)
        {
            joystick = getJoyStickByNameInternal(name);

            if (joystick == null)
            {
                return(false);
            }

            joystick.Acquire();

            joystick.Poll();

            return(true);
        }
        /// <summary>
        /// Function to enumerate the gaming devices supported by this driver.
        /// </summary>
        /// <param name="connectedOnly">[Optional] <b>true</b> to only enumerate devices that are connected, or <b>false</b> to enumerate all devices.</param>
        /// <returns>A read only list of gaming device info values.</returns>
        /// <remarks>
        /// This will return only the devices supported by the driver. In some cases, the driver may not return a complete listing of all gaming devices attached to the system because the underlying provider
        /// may not support those device types.
        /// </remarks>
        public override IReadOnlyList <IGorgonGamingDeviceInfo> EnumerateGamingDevices(bool connectedOnly = false)
        {
            IList <DI.DeviceInstance> devices = _directInput.Value.GetDevices(DI.DeviceClass.GameControl, DI.DeviceEnumerationFlags.AttachedOnly);

            Log.Print("Enumerating DirectInput gaming devices...", LoggingLevel.Verbose);

            // Enumerate all controllers.
            IReadOnlyList <DirectInputDeviceInfo> result = devices
                                                           .Where(item =>
            {
                bool notXInputController = !IsXInputController(item);

                if (!notXInputController)
                {
                    Log.Print("WARNING: Found XInput controller.  The Direct Input driver does not support this type of controller.  Skipping...", LoggingLevel.Verbose);
                    return(false);
                }

                bool isAttached = _directInput.Value.IsDeviceAttached(item.InstanceGuid);

                if ((connectedOnly) || (isAttached))
                {
                    return(true);
                }

                Log.Print("WARNING: Found gaming device '{0}', but it is not attached and enumeration is filtered for attached devices only.  Skipping...",
                          LoggingLevel.Verbose, item.ProductName);

                return(false);
            })
                                                           .Select(item =>
            {
                var info = new DirectInputDeviceInfo(item);

                using (var joystick = new DI.Joystick(_directInput.Value, info.InstanceGuid))
                {
                    info.GetDeviceCaps(joystick);

                    Log.Print("Found DirectInput gaming device \"{0}\"",
                              LoggingLevel.Verbose, info.Description);
                }

                return(info);
            })
                                                           .ToArray();

            return(result);
        }
Ejemplo n.º 18
0
        public bool Init()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                //log.MsgWriteLine(LogWindow.MsgTypes.Error, "No joystick/Gamepad found.");
                return(false);
            }

            // Instantiate the joystick
            dxJoystick = new SharpDX.DirectInput.Joystick(directInput, joystickGuid);

            //log.MsgWriteLine(LogWindow.MsgTypes.Normal, "Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = dxJoystick.GetEffects();

            //foreach (var effectInfo in allEffects)
            //log.MsgWriteLine(LogWindow.MsgTypes.Normal, "Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            dxJoystick.Properties.BufferSize = 128;

            // Acquire the joystick
            dxJoystick.Acquire();

            return(true);
        }
Ejemplo n.º 19
0
        public List<Controlador> ObtenerJoysticks()
        {
            List<DeviceInstance> deviceInstances = new List<DeviceInstance>();

            deviceInstances.AddRange( directInput.GetDevices( DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices ) );
            deviceInstances.AddRange( directInput.GetDevices( DeviceType.Joystick, DeviceEnumerationFlags.AllDevices ) );

            List<Controlador> joysticks = new List<Controlador>();
            foreach ( DeviceInstance item in deviceInstances )
            {
                var joystick = new SharpDX.DirectInput.Joystick( this.directInput, item.InstanceGuid );
                joysticks.Add( new Controlador( joystick ) );
            }

            return joysticks;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Function to perform the creation of the DirectInput joystick object.
        /// </summary>
        /// <param name="directInput">The direct input interface.</param>
        /// <param name="deviceInfo">The device information for the gaming device to use.</param>
        /// <returns>The DirectInput joystick object.</returns>
        private DI.Joystick CreateJoystick(DI.DirectInput directInput, DirectInputDeviceInfo deviceInfo)
        {
            var result = new DI.Joystick(directInput, deviceInfo.InstanceGuid);

            IntPtr mainWindow = FindMainApplicationWindow();

            if (mainWindow == IntPtr.Zero)
            {
                // We have no main window, and DI requires one, so we need to kill this.
                throw new InvalidOperationException(Resources.GORINP_ERR_DI_COULD_NOT_FIND_APP_WINDOW);
            }

            result.SetCooperativeLevel(mainWindow, DI.CooperativeLevel.Foreground | DI.CooperativeLevel.NonExclusive);

            result.Properties.AxisMode = DI.DeviceAxisMode.Absolute;

            // Set up dead zones.
            foreach (GorgonGamingDeviceAxis axis in Axis)
            {
                // Skip the throttle.  Dead zones on the throttle don't work too well for regular joysticks.
                // Game pads may be another story, but the user can manage those settings if required.
                if (axis.Axis == GamingDeviceAxis.Throttle)
                {
                    continue;
                }

                GorgonGamingDeviceAxisInfo info       = Info.AxisInfo[axis.Axis];
                DI.ObjectProperties        properties = result.GetObjectPropertiesById(_info.AxisMappings[axis.Axis]);

                if (properties == null)
                {
                    continue;
                }

                // Set a 0 dead zone.
                properties.DeadZone = 0;

                // Make the dead zone 10% of the range for all axes.
                float deadZone       = axis.Axis == GamingDeviceAxis.Throttle ? 0.02f : 0.10f;
                int   deadZoneActual = (int)(info.Range.Range * deadZone);

                axis.DeadZone = new GorgonRange(info.DefaultValue - deadZoneActual, info.DefaultValue + deadZoneActual);
            }

            return(result);
        }
Ejemplo n.º 21
0
        public void readInput()
        {
            if (gamepadDevice == null)
            {
                return;
            }

            SharpDX.DirectInput.Joystick joystick = new SharpDX.DirectInput.Joystick(directInput, gamepadDevice.InstanceGuid);
            joystick.Properties.BufferSize = 128;

            joystick.Acquire();
            while (true)
            {
                if (joystick.IsDisposed)
                {
                    return;
                }
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.Offset.ToString().Equals("X"))
                    {
                        valueX = state.Value;
                        Console.WriteLine(valueX);
                    }
                    else if (state.Offset.ToString().Equals("Y"))
                    {
                        valueY = state.Value;
                    }
                    else if (state.Offset.ToString().Equals("Buttons0"))
                    {
                        switch (state.Value)
                        {
                        case 0: isButtonClicked = false; break;

                        case 128: isButtonClicked = true; break;
                        }
                    }
                    else if (state.Offset.ToString().Equals("Z"))
                    {
                        valueTriggers = state.Value;
                    }
                }
            }
        }
        void Find_Joystick()
        {
            if (joystickGuid != Guid.Empty)
            {
                return;
            }

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                joystickEnable.Dispatcher.Invoke(() => {
                    joystickEnable.IsChecked = false;
                    joystickEnable.IsEnabled = false;
                });
            }
            else
            {
                // Instantiate the joystick
                joystick = new SharpDX.DirectInput.Joystick(directInput, joystickGuid);

                Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

                joystick.Properties.BufferSize = 128;
                // Acquire the joystick
                joystick.Acquire();
                joystickEnable.Dispatcher.Invoke(() => {
                    joystickEnable.IsEnabled = true;
                });
            }
        }
Ejemplo n.º 23
0
    public static Axe GetAxis(SharpDX.DirectInput.Joystick joystick)
    {
        if (joystick != null)
        {
            JoystickState state = new JoystickState();

            state = joystick.GetCurrentState();

            Axe axis = new Axe();
            axis.Xaxis = state.X;
            axis.Yaxis = state.Y;
            axis.Zaxis = state.Z;

            return(axis);
        }
        else
        {
            return(null);
        }
    }
    protected void GenericControllerConnection()
    {
#if DEBUG
        Console.WriteLine("Launched new thread!");
        Console.WriteLine("Looking for Joystick!");
#endif
        var joystickGuid = Guid.Empty;

        foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
        {
            joystickGuid = deviceInstance.InstanceGuid;
        }

        //If Gamepad not found, look for a Joystick
        if (joystickGuid == Guid.Empty)
        {
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }
        }

        if (joystickGuid == Guid.Empty)
        {
            return;
        }
#if DEBUG
        Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);
#endif

        joystick = new Joystick(directInput, joystickGuid);
        var allEffects = joystick.GetEffects();
#if DEBUG
        foreach (var effectInfo in allEffects)
        {
            Console.WriteLine("Effect available {0}", effectInfo.Name);
        }
#endif
        joystick.Properties.BufferSize = 128;
        joystick.Acquire();
    }
        public void Start()
        {
            foreach (var port in MainV2.Comports)
            {
                foreach (var MAV in port.MAVlist)
                {
                    DG.Drones.Add(new Drone()
                    {
                        MavState = MAV
                    });
                }
            }

            foreach (var device in directInput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
            {
                var joystick = new SharpDX.DirectInput.Joystick(directInput, device.InstanceGuid);

                joystick.Acquire();

                joystick.Poll();

                Console.WriteLine(joystick.Information.ProductName);

                Joysticks.Add(joystick);
            }

            if (threadrun == true)
            {
                threadrun = false;
                return;
            }


            new System.Threading.Thread(mainloop)
            {
                IsBackground = true
            }.Start();

            DG.CurrentMode = DroneGroup.Mode.idle;
        }
Ejemplo n.º 26
0
        public bool start(string name)
        {
            this.name = name;

            joystick = AcquireJoystick(name);

            if (joystick == null)
            {
                return(false);
            }

            enabled = true;

            System.Threading.Thread t11 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
            {
                Name         = "Joystick loop",
                Priority     = System.Threading.ThreadPriority.AboveNormal,
                IsBackground = true
            };
            t11.Start();

            return(true);
        }
        /// <summary>Initialises the joystick.</summary>
        private void InitialiseJoystick()
        {
            List<DI.Joystick> joysticks = GetAttachedJoysticks();

            if(ControllerIndex < joysticks.Count)
            {
                _joystick = joysticks[ControllerIndex];
                _joystickState = _joystick.GetCurrentState();

                System.Diagnostics.Debug.WriteLine("Using joystick: " + _joystick.Information.InstanceName);
            }

            _joystickConnected = (_joystickState != null);
        }
Ejemplo n.º 28
0
 public Reader(SharpDX.DirectInput.Joystick joystick)
 {
     _joystick = joystick;
 }
Ejemplo n.º 29
0
        public bool AcquireJoystick(Guid guid)
        {
            try
            {
                if (_joystick != null)
                {
                    _joystick.Unacquire();
                    _joystick = null;
                }

                var dinput = new DirectInput();
                foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
                {
                    if (device.InstanceGuid == guid)
                    {
                        _joystick = new SharpDX.DirectInput.Joystick(dinput, device.InstanceGuid);
                    }
                }

                if (_joystick != null)
                {
                    foreach (DeviceObjectInstance deviceObject in _joystick.GetObjects())
                    {
                        //if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                        switch (deviceObject.ObjectId.Flags)
                        {
                        case DeviceObjectTypeFlags.Axis:
                        case DeviceObjectTypeFlags.AbsoluteAxis:
                        case DeviceObjectTypeFlags.RelativeAxis:
                            var ir = _joystick.GetObjectPropertiesById(deviceObject.ObjectId);
                            if (ir != null)
                            {
                                try
                                {
                                    ir.Range = new InputRange(-100, 100);
                                }
                                catch (Exception ex)
                                {
                                    MainForm.LogExceptionToFile(ex);
                                }
                            }
                            break;
                        }
                    }

                    _joystick.Acquire();

                    var cps = _joystick.Capabilities;
                    AxisCount = cps.AxeCount;

                    UpdateStatus();
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 30
0
        public bool start(string name)
        {
            self.name = name;

            joystick = AcquireJoystick(name);

            if (joystick == null)
                return false;

            enabled = true;

            System.Threading.Thread t11 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
            {
                Name = "Joystick loop",
                Priority = System.Threading.ThreadPriority.AboveNormal,
                IsBackground = true
            };
            t11.Start();

            return true;
        }
Ejemplo n.º 31
0
        public SharpDX.DirectInput.Joystick AcquireJoystick(string name)
        {
            joystick = getJoyStickByName(name);

            if (joystick == null)
                return null;

            //joystick.SetDataFormat(DeviceDataFormat.Joystick);

            joystick.Acquire();

            System.Threading.Thread.Sleep(500);

            joystick.Poll();

            return joystick;
        }
        void Joystick_Poll(object Sender, EventArgs e)
        {
            if (joystickGuid != Guid.Empty)
            {
                if (!directInput.IsDeviceAttached(joystickGuid))
                {
                    joystick.Dispose();
                    joystick     = null;
                    joystickGuid = Guid.Empty;
                    joystickEnable.Dispatcher.Invoke(() =>
                    {
                        joystickEnable.IsChecked = false;
                        joystickEnable.IsEnabled = false;
                    });
                }
            }

            JoystickState state = null;

            if (joystick != null)
            {
                joystick.Poll();
                state = joystick.GetCurrentState();
            }
            if (state != null)
            {
                if (joystic_enabled)
                {
                    if (state.Buttons[6])
                    {
                        btnZoomIn_Click(null, null);
                    }
                    else if (state.Buttons[4])
                    {
                        btnZoomOut_Click(null, null);
                    }

                    if (state.Buttons[2] && !prevCamSwitchState)
                    {
                        prevCamSwitchState = true;
                        if (currentCamera == CameraSource.RGB_CAMERA_SOURCE)
                        {
                            setCameraVideoSource(CameraSource.IR_CAMERA_SOURCE);
                        }
                        else if (currentCamera == CameraSource.IR_CAMERA_SOURCE)
                        {
                            setCameraVideoSource(CameraSource.RGB_CAMERA_SOURCE);
                        }
                    }
                    else if (!state.Buttons[2])
                    {
                        prevCamSwitchState = false;
                    }

                    if (currentMode == GimbalMode.MODE_RATE)
                    {
                        double pitch_cmd = 0.0;
                        double yaw_cmd   = 0.0;
                        if (Math.Abs(state.Y - 32768) > 30)
                        {
                            pitch_cmd = ((state.Y - 32768.0) / 65536.0 * -2.0) * 3.14 / 2;
                        }
                        else
                        {
                            pitch_cmd = 0.0;
                        }
                        if (Math.Abs(state.X - 32768) > 30)
                        {
                            yaw_cmd = ((state.X - 32768.0) / 65536.0 * -2.0) * 3.14 / 2;
                        }
                        else
                        {
                            yaw_cmd = 0.0;
                        }
                        sendGimbalCommand(pitch_cmd, 0.0, yaw_cmd);
                    }
                }
            }
        }
Ejemplo n.º 33
0
 public bool Close()
 {
     dxJoystick.Dispose();
     dxJoystick = null;
     return(true);
 }
Ejemplo n.º 34
0
    void Update()
    {
        if (FindObjectOfType <PlayerData>() != null)
        {
            if (joystick != null)
            {
                bool ret = false;
                if (bot == false)
                {
                    try
                    {
                        joystick.Poll();
                    }
                    catch
                    {
                        joystick = FindObjectOfType <PlayerData>().controllers[playerNumber];
                        try
                        {
                            joystick.Poll();
                        }
                        catch
                        {
                            FindObjectOfType <PlayerData>().pendingControllers[playerNumber] = true;
                        }
                        button1      = FindObjectOfType <PlayerData>().button1[playerNumber];
                        button2      = FindObjectOfType <PlayerData>().button2[playerNumber];
                        ret          = true;
                        color1Index  = 0;
                        color2Index  = 0;
                        color1.color = colors[0];
                        color2.color = colors[0];
                        FindObjectOfType <PlayerData>().color1[playerNumber] = color1.color;
                        FindObjectOfType <PlayerData>().color2[playerNumber] = color2.color;
                        UI.SetActive(false);
                        joined = false;
                        botObj.SetActive(true);
                        FindObjectOfType <PlayerData>().players.Remove(playerNumber);
                        return;
                    }
                }
                if (ret)
                {
                    return;
                }
            }
            else
            {
                if (FindObjectOfType <PlayerData>().controllers[playerNumber] != null)
                {
                    joystick = FindObjectOfType <PlayerData>().controllers[playerNumber];
                    try
                    {
                        joystick.Poll();
                    }
                    catch
                    {
                        FindObjectOfType <PlayerData>().pendingControllers[playerNumber] = true;
                    }
                    button1 = FindObjectOfType <PlayerData>().button1[playerNumber];
                    button2 = FindObjectOfType <PlayerData>().button2[playerNumber];
                }
            }
        }

        timeTillScene += Time.deltaTime;
        if (joystick != null)
        {
            if (CustomControls.GetButton(joystick, button1))
            {
                Action1();
            }
            else
            {
                CancelAction1();
            }
            if (CustomControls.GetButton(joystick, button2))
            {
                Action2();
            }
            else
            {
                CancelAction2();
            }
            if (keyboard)
            {
                if (CustomControls.GetButton(joystick, dreapta))
                {
                    if (axis == false)
                    {
                        axis = true;
                        if (opposite == false)
                        {
                            SelectDreapta();
                        }
                        else
                        {
                            SelectStanga();
                        }
                    }
                }
                else if (CustomControls.GetButton(joystick, stanga))
                {
                    if (axis == false)
                    {
                        axis = true;
                        if (opposite == false)
                        {
                            SelectStanga();
                        }
                        else
                        {
                            SelectDreapta();
                        }
                    }
                }
                else
                {
                    axis = false;
                }
            }
            else
            {
                if (CustomControls.GetAxis(joystick).Xaxis > 40000)
                {
                    if (axis == false)
                    {
                        axis = true;
                        if (opposite == false)
                        {
                            SelectDreapta();
                        }
                        else
                        {
                            SelectStanga();
                        }
                    }
                }
                else if (CustomControls.GetAxis(joystick).Xaxis < 20000)
                {
                    if (axis == false)
                    {
                        axis = true;
                        if (opposite == false)
                        {
                            SelectStanga();
                        }
                        else
                        {
                            SelectDreapta();
                        }
                    }
                }
                else
                {
                    axis = false;
                }
            }
        }
    }
Ejemplo n.º 35
0
    private void Awake()
    {
        controllers = new List <SharpDX.DirectInput.Joystick>();
        var joystickGuid = Guid.Empty;
        var di           = new DirectInput();
        IList <DeviceInstance> keyboards = di.GetDevices(SharpDX.DirectInput.DeviceType.Keyboard, DeviceEnumerationFlags.AttachedOnly);

        for (int device = 0; device < keyboards.Count; device++)
        {
            joystickGuid = keyboards[device].InstanceGuid;
            controllers.Add(new Joystick(di, joystickGuid));
        }
        IList <DeviceInstance> gamepads = di.GetDevices(SharpDX.DirectInput.DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly);

        for (int device = 0; device < gamepads.Count; device++)
        {
            joystickGuid = gamepads[device].InstanceGuid;
            controllers.Add(new Joystick(di, joystickGuid));
        }
        IList <DeviceInstance> joysticks = di.GetDevices(SharpDX.DirectInput.DeviceType.Joystick, DeviceEnumerationFlags.AttachedOnly);

        for (int device = 0; device < joysticks.Count; device++)
        {
            joystickGuid = joysticks[device].InstanceGuid;
            controllers.Add(new Joystick(di, joystickGuid));
        }
        if (playerNumber <= 2)
        {
            joystick = controllers[0];

            joystick.Acquire();
            if (playerNumber == 1)
            {
                button1 = PlayerPrefs.GetInt("Keyboard #1" + "1", 33);
                button2 = PlayerPrefs.GetInt("Keyboard #1" + "2", 34);
                dreapta = 31;
                stanga  = 29;
                jos     = 30;
                sus     = 16;
            }
            else
            {
                button1 = PlayerPrefs.GetInt("Keyboard #2" + "1", 50);
                button2 = PlayerPrefs.GetInt("Keyboard #2" + "2", 51);
                dreapta = 107;
                stanga  = 106;
                jos     = 109;
                sus     = 104;
            }
        }
        else if (playerNumber <= controllers.Count + 1)
        {
            joystick = controllers[playerNumber - 2];
            joystick.Acquire();
            button1 = PlayerPrefs.GetInt(joystick.Information.ProductName + "1", 0);
            button2 = PlayerPrefs.GetInt(joystick.Information.ProductName + "2", 2);
            Debug.Log(joystick.Properties.InterfacePath);
        }
        FindObjectOfType <PlayerData>().button1[playerNumber] = button1;
        FindObjectOfType <PlayerData>().button2[playerNumber] = button2;
        if (joystick != null)
        {
            defaultAxis = joystick.GetCurrentState().X;
        }
        teamNumber.text = "Team " + (team + 1);
        if (playerNumber >= 10)
        {
            opposite = true;
        }
        teamNumber.gameObject.SetActive(false);
        selected2.gameObject.SetActive(false);
        selected3.gameObject.SetActive(false);
        char1Bg.gameObject.SetActive(false);
        char2Bg.gameObject.SetActive(false);
        char3Bg.gameObject.SetActive(false);
        char1          = characters[0];
        char2          = characters[0];
        char3          = characters[0];
        char1Text.text = char1.ToString();
        char2Text.text = char2.ToString();
        char3Text.text = char3.ToString();
        FindObjectOfType <PlayerData>().playerNames[playerNumber] = char1.ToString() + char2.ToString() + char3.ToString();
    }
        /// <summary>Gets a list of the attached joysticks.</summary>
        /// <returns>A list of joysticks.</returns>
        private List<DI.Joystick> GetAttachedJoysticks()
        {
            List<DI.Joystick> joysticks = new List<DI.Joystick>();

            foreach(DI.DeviceInstance device in _directInput.GetDevices(DI.DeviceClass.GameControl, DI.DeviceEnumerationFlags.AttachedOnly))
            {
                try
                {
                    DI.Joystick joystick = new DI.Joystick(_directInput, device.InstanceGuid);

                    joystick.Acquire();

                    IList<DI.DeviceObjectInstance> deviceObjects = joystick.GetObjects();
                    for(int i = 0; i < deviceObjects.Count; i++)
                    {
                        DI.DeviceObjectInstance deviceObjectInstance = deviceObjects[i];

                        if((deviceObjectInstance.ObjectId.Flags & DI.DeviceObjectTypeFlags.Axis) != 0)
                            joystick.GetObjectPropertiesById(deviceObjectInstance.ObjectId).Range = new DI.InputRange(-1000, 1000);
                    }

                    joysticks.Add(joystick);
                }
                catch(SharpDXException)
                {
                }
            }

            return joysticks;
        }
        public InputDeviceJoystickWindows(DirectInput di, DeviceInstance d, bool paxison)
        {
            jsi = new InputDeviceIdentity()
            {
                Instanceguid = d.InstanceGuid, Productguid = d.ProductGuid, Name = d.InstanceName.RemoveTrailingCZeros()
            };

            axisevents = paxison;

            stick = new SharpDX.DirectInput.Joystick(di, d.InstanceGuid);
            stick.SetNotification(eventhandle);
            stick.Acquire();

            axispresent = new bool[AxisCount];
            axisvalue   = Enumerable.Repeat(AxisNullValue, AxisCount).ToArray();

            Capabilities c = stick.Capabilities;

            butstate = new bool[c.ButtonCount];

            povvalue    = Enumerable.Repeat(POVNotPressed, c.PovCount).ToArray();
            slidercount = 0;

            DeviceProperties p = stick.Properties;

            jsi.VendorId  = p.VendorId;
            jsi.ProductId = p.ProductId;

            //   string s = p.PortDisplayName;

            System.Diagnostics.Debug.WriteLine("JOY {0} {1} but {2} pov {3}", jsi.Name, jsi.Productguid, butstate.Length, povvalue.Length);

            foreach (DeviceObjectInstance deviceObject in stick.GetObjects())
            {
                if ((deviceObject.ObjectId.Flags & DeviceObjectTypeFlags.Axis) != 0)
                {
                    System.Guid guid = deviceObject.ObjectType;
                    //System.Diagnostics.Debug.WriteLine("  {0} {1} {2} {3} {4}", jsi.Name, deviceObject.UsagePage, deviceObject.Usage, deviceObject.Offset, guid.ToString());

                    if (guid == ObjectGuid.XAxis)
                    {
                        axispresent[(int)Axis.X] = true;
                    }
                    else if (guid == ObjectGuid.YAxis)
                    {
                        axispresent[(int)Axis.Y] = true;
                    }
                    else if (guid == ObjectGuid.ZAxis)
                    {
                        axispresent[(int)Axis.Z] = true;
                    }
                    else if (guid == ObjectGuid.RxAxis)
                    {
                        axispresent[(int)Axis.RX] = true;
                    }
                    else if (guid == ObjectGuid.RyAxis)
                    {
                        axispresent[(int)Axis.RY] = true;
                    }
                    else if (guid == ObjectGuid.RzAxis)
                    {
                        axispresent[(int)Axis.RZ] = true;
                    }
                    else if (guid == ObjectGuid.Slider)
                    {
                        int axisentry = (int)Axis.U + slidercount;
                        if (axisentry < AxisCount)
                        {
                            axispresent[axisentry] = true;
                            slidercount++;      // must be sliders, only ones left with axis
                            //System.Diagnostics.Debug.WriteLine("Slider " + slidercount);
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Unknown Axis " + guid.ToString());
                    }

                    ObjectProperties o = stick.GetObjectPropertiesById(deviceObject.ObjectId);
                    o.Range = new InputRange(AxisMinRange, AxisMaxRange);
                }
            }
        }
Ejemplo n.º 38
0
        private void createJoystick(int index)
        {
            DirectInput directInput = new DirectInput();
            Guid guid = Guid.Empty;
            guid = JoysticksAttached()[index].InstanceGuid;

            if (guid != Guid.Empty)
                joystick = new SharpDX.DirectInput.Joystick(directInput, guid);

            if (joystick == null)
            {
                throw new Exception("No joystick found.");
            }
        }
Ejemplo n.º 39
0
        public bool AcquireJoystick(Guid guid)
        {
            try
            {
                if (_joystick != null)
                {
                    _joystick.Unacquire();
                    _joystick = null;
                }

                var dinput = new DirectInput();
                foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
                {
                    if (device.InstanceGuid==guid)
                    {
                        _joystick = new SharpDX.DirectInput.Joystick(dinput, device.InstanceGuid);
                    }
                }

                if (_joystick != null)
                {
                    foreach (DeviceObjectInstance deviceObject in _joystick.GetObjects())
                    {

                        //if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                        switch (deviceObject.ObjectId.Flags)
                        {
                            case DeviceObjectTypeFlags.Axis:
                            case DeviceObjectTypeFlags.AbsoluteAxis:
                            case DeviceObjectTypeFlags.RelativeAxis:
                                var ir = _joystick.GetObjectPropertiesById(deviceObject.ObjectId);
                                if (ir != null)
                                {
                                    try
                                    {
                                        ir.Range = new InputRange(-100, 100);
                                    }
                                    catch (Exception ex)
                                    {
                                        MainForm.LogExceptionToFile(ex);
                                    }
                                }
                                break;
                        }
                    }

                    _joystick.Acquire();

                    var cps = _joystick.Capabilities;
                    AxisCount = cps.AxeCount;

                    UpdateStatus();
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
                return false;
            }

            return true;
        }
Ejemplo n.º 40
-1
        private void createJoystick()
        {
            DirectInput directInput = new DirectInput();
            Guid guid = Guid.Empty;

            //Create joystick device.
            //This process is called Direct Input Device Enumeration
            //IList<DeviceInstance>
                gameControls = directInput.GetDevices(
                DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);

            switch(this.type)
            {
                case JoystickType.MainController:
                    if (gameControls.Count >= 1)
                        guid = gameControls[0].InstanceGuid;
                    break;
                case JoystickType.ManipulatorLeft:
                    if (gameControls.Count >= 2)
                        guid = gameControls[1].InstanceGuid;
                    break;
                case JoystickType.ManipulatorRight:
                    if (gameControls.Count >= 3)
                        guid = gameControls[2].InstanceGuid;
                    break;
            }

            if(guid != Guid.Empty)
                joystick = new SharpDX.DirectInput.Joystick(directInput, guid);

            if (joystick == null)
            {
                //Throw exception if joystick not found.
                throw new Exception("No joystick found.");
            }
        }