void Update()
        {
            iReport.bDevice = (byte)deviceId;

            var stick = stickAxis.WithDeadzone(joystickDeadzoneDegrees);

            iReport.AxisY    = ConvertStickAxisDegreesToAxisInt(stick.Pitch, HID_USAGES.HID_USAGE_Y);
            iReport.AxisX    = ConvertStickAxisDegreesToAxisInt(stick.Roll, HID_USAGES.HID_USAGE_X);
            iReport.AxisZRot = ConvertStickAxisDegreesToAxisInt(stick.Yaw, HID_USAGES.HID_USAGE_RZ);

            var dThrusters = thrusterAxis.WithDeadzone(directionalThrustersDeadzone);

            iReport.AxisXRot = ConvertAxisRatioToAxisInt(dThrusters.Value.x, HID_USAGES.HID_USAGE_RX);
            iReport.AxisYRot = ConvertAxisRatioToAxisInt(dThrusters.Value.y, HID_USAGES.HID_USAGE_RY);
            iReport.Slider   = ConvertAxisRatioToAxisInt(dThrusters.Value.z, HID_USAGES.HID_USAGE_SL0);

            var throttleWithDeadZone = Mathf.Abs(throttle) < (throttleDeadzonePercentage / 100f) ? 0f : throttle;

            iReport.AxisZ = ConvertAxisRatioToAxisInt(throttleWithDeadZone, HID_USAGES.HID_USAGE_Z);

            iReport.Buttons = buttons;

            iReport.bHats = (uint)((byte)hat[3] << 12)
                            | (uint)((byte)hat[2] << 8)
                            | (uint)((byte)hat[1] << 4)
                            | (uint)hat[0];

            if (!vjoy.UpdateVJD(deviceId, ref iReport))
            {
                SetStatus(VJoyStatus.DeviceError);
                enabled = false;
            }
        }
Example #2
0
        static void UpdateGamepad(DJHControllerMap Map)
        {
            iReport.bDevice = (byte)1;
            if (Map.TT_normal != 0)
            {
                iReport.AxisY = (Map.TT_normal - 0x80) * 0x1FF + 0x3FFF;
            }
            iReport.Dial   = ((Map.Filter_step * 0x1FFF) + (Map.Filter_normal * 0x20) - 0x100) * 3;
            iReport.Slider = (Map.Slider_step * 0x1FFF) + (Map.Slider_normal * 0x20);

            int a = 0x0;

            if (Map.PS >= 0x10)
            {
                a       = 0x40;
                Map.PS -= 0x10;
            }
            else
            {
                a = 0x0;
            }
            iReport.Buttons = (uint)Map.Buttons + (uint)(Map.PS << 0x04) + (uint)a;

            if (Map.DPAD == 0x0F)
            {
                iReport.bHats = 0xFFFFFF;
            }
            else
            {
                iReport.bHats = (uint)4487 * Map.DPAD;
            }

            // Feed the driver
            Gamepad.UpdateVJD(1, ref iReport);
        }
Example #3
0
        /// <summary>
        /// Update vJoy device at driver side.
        /// This call is almost intantaneous, but we add a sleep of 100ms in
        /// case of an error
        /// </summary>
        public void PublishReport()
        {
            // Feed the driver with the position packet
            // If it fails, wait then try to re-acquire device
            bool stt = false;

            try {
                stt = Joystick.UpdateVJD(vJoyDevID, ref Report);
            } catch (Exception ex) {
                LogFormat(LogLevels.DEBUG, "vJoy device number {0}, exception {1}", vJoyDevID, ex.Message);
                Thread.Sleep(100);
            }
            if (!stt)
            {
                LogFormat(LogLevels.DEBUG, "Feeding vJoy device number {0} failed - trying to re-enable vJoy device", vJoyDevID);

                // Add some delay before re-enabling vJoy
                int ok = Acquire(vJoyDevID);
                if (ok != 1)
                {
                    LogFormat(LogLevels.ERROR, "Cannot acquire device number {0} - try to restart this program or check your vJoy installation", vJoyDevID);
                    Thread.Sleep(100);
                }
            }
        }
Example #4
0
 public void SetJoystickInput(vJoy.JoystickState _iReport)
 {
     if (!_joystick.UpdateVJD(_id, ref _iReport))
     {
         _logger.WriteLog($"Feeding vJoy device number {_id} failed - try to enable device then press enter");
         Console.ReadKey(true);
         _joystick.AcquireVJD(_id);
     }
 }
 public void update()
 {
     if (!device.UpdateVJD(id, ref state))
     {
         device.AcquireVJD(id);
         Thread.Sleep(1);
         update();
     }
 }
Example #6
0
        /// <summary>
        /// Updates a state of joystick (values of buttons, axes, etc.) using a JoystickState struct
        /// </summary>
        /// <param name="joyState">Struct storing updated values of joystick state</param>
        public void PostCurrentState(vJoy.JoystickState joyState)
        {
            if (!IsBusy)
            {
                throw new Exception("You cannot change a state of a joystick which isn't connected.");
            }

            if (!_joystick.UpdateVJD(_joyId, ref joyState))
            {
                Disconnect();
            }
        }
        void Update()
        {
            iReport.bDevice = (byte)deviceId;

            if (MapAxisEnabled)
            {
                // Translation
                iReport.AxisXRot = ConvertAxisRatioToAxisInt(mapTranslationAxis.x, HID_USAGES.HID_USAGE_RX);
                iReport.AxisYRot = ConvertAxisRatioToAxisInt(mapTranslationAxis.y, HID_USAGES.HID_USAGE_RY);
                iReport.Slider   = ConvertAxisRatioToAxisInt(mapTranslationAxis.z, HID_USAGES.HID_USAGE_SL0);

                // Pitch / Yaw
                iReport.AxisY    = ConvertAxisRatioToAxisInt(-mapPitchAxis, HID_USAGES.HID_USAGE_Y);
                iReport.AxisZRot = ConvertAxisRatioToAxisInt(mapYawAxis, HID_USAGES.HID_USAGE_RZ);

                // Zoom
                iReport.Dial = ConvertAxisRatioToAxisInt(mapZoomAxis, HID_USAGES.HID_USAGE_SL1);

                // Make sure all the joystick axis are reset
                iReport.AxisX = ConvertStickAxisDegreesToAxisInt(0, HID_USAGES.HID_USAGE_X);
                iReport.AxisZ = ConvertAxisRatioToAxisInt(0, HID_USAGES.HID_USAGE_Z);
            }
            else
            {
                var stick = stickAxis.WithDeadzone(joystickDeadzoneDegrees);

                iReport.AxisY    = ConvertStickAxisDegreesToAxisInt(-stick.Pitch, HID_USAGES.HID_USAGE_Y);
                iReport.AxisX    = ConvertStickAxisDegreesToAxisInt(stick.Roll, HID_USAGES.HID_USAGE_X);
                iReport.AxisZRot = ConvertStickAxisDegreesToAxisInt(stick.Yaw, HID_USAGES.HID_USAGE_RZ);

                var dThrusters = thrusterAxis.WithDeadzone(directionalThrustersDeadzonePercentage / 100f);

                iReport.AxisXRot = ConvertAxisRatioToAxisInt(dThrusters.Value.x, HID_USAGES.HID_USAGE_RX);
                iReport.AxisYRot = ConvertAxisRatioToAxisInt(dThrusters.Value.y, HID_USAGES.HID_USAGE_RY);
                iReport.Slider   = ConvertAxisRatioToAxisInt(dThrusters.Value.z, HID_USAGES.HID_USAGE_SL0);

                var throttleWithDeadZone = Mathf.Abs(throttle) < (throttleDeadzonePercentage / 100f) ? 0f : throttle;
                iReport.AxisZ = ConvertAxisRatioToAxisInt(throttleWithDeadZone, HID_USAGES.HID_USAGE_Z);
            }

            iReport.Buttons = buttons;

            iReport.bHats = (uint)((byte)hat[3] << 12)
                            | (uint)((byte)hat[2] << 8)
                            | (uint)((byte)hat[1] << 4)
                            | (uint)hat[0];

            if (!vjoy.UpdateVJD(deviceId, ref iReport))
            {
                SetStatus(VJoyStatus.DeviceError);
                enabled = false;
            }
        }
Example #8
0
        private void Update()
        {
            iReport.bDevice = (byte)deviceId;

            iReport.Buttons = buttons;

            // ReSharper disable once InvertIf
            if (!vjoy.UpdateVJD(deviceId, ref iReport))
            {
                SetStatus(VJoyStatus.DeviceError);
                enabled = false;
            }
        }
Example #9
0
        public bool Poll()
        {
            JoystickState state;

            if ((wheelDevice == null) || (handbrakeDevice == null))
            {
                return(false);
            }
            try
            {
                // poll the joystick
                handbrakeDevice.Poll();
                // update the joystick state field
                state           = handbrakeDevice.GetCurrentState();
                iReport.bDevice = (byte)id;
                iReport.AxisZ   = (int)((double)state.X * axisScale);

                wheelDevice.Poll();
                // update the joystick state field
                state            = wheelDevice.GetCurrentState();
                iReport.AxisX    = (int)((double)state.X * axisScale);
                iReport.AxisY    = (int)((double)state.Y * axisScale);
                iReport.AxisZRot = (int)((double)state.RotationZ * axisScale);

                // Set joystick buttons one by one
                bool[] buttons = state.Buttons;
                for (int i = 0; i < buttons.Length; i++)
                {
                    if (buttons[i])
                    {
                        iReport.Buttons |= (uint)1 << i;
                    }
                }

                // joystick povs
                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    MessageBox.Show("Feeding vJoy device failed - try to enable device then press OK", "Error");
                    joystick.AcquireVJD(id);
                }
            }
            catch (Exception)
            {
                ClearDevices();
                //MessageBox.Show("Connection to Joystick/Throttle was lost. Was it unplugged or locked by another application?", "Error");
                return(false);
            }
            return(true);
        }
Example #10
0
 public void OnUSBPolled(object sender, EventArgs e)
 {
     //_joystick.SetAxis(Convert.ToInt32(_usb.Axes[0].Value / 100.0 * _maxVal), 1, HID_USAGES.HID_USAGE_X);
     _jState.bDevice  = 1;
     _jState.AxisX    = _usb.Axes[0].JoystickValue;
     _jState.AxisY    = _usb.Axes[1].JoystickValue;
     _jState.AxisZ    = _usb.Axes[2].JoystickValue;
     _jState.AxisXRot = _usb.Axes[3].JoystickValue;
     //_jState.AxisX = _usb.Axes[0].Value;
     //_jState.AxisY = _usb.Axes[1].Value;
     //_jState.AxisZ = _usb.Axes[2].Value;
     //_jState.AxisXRot = _usb.Axes[3].Value;
     bool tmp = _joystick.UpdateVJD(1, ref _jState);
 }
Example #11
0
        private bool FeedVJoy()
        {
            const int id = 1;

            var state = _state;

            if (!_joystick.UpdateVJD(id, ref state))
            {
                Console.WriteLine("Feeding vJoy device number {0} failed.", id);
                _isAcquired = false;
                return(false);
            }

            return(true);
        }
        private void GamePad()
        {
            try {
                client = new UdpClient(DATA_PORT);
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, DATA_PORT);

                vJoy.JoystickState joystickState = new vJoy.JoystickState();
                joystickState.bDevice = id;

                while (true)
                {
                    byte[] data = client.Receive(ref endPoint);
                    // TODO: Remove?

                    /*if(data.Length < 32) {
                     *  continue;
                     * }*/

                    joystickState.AxisZRot = BitConverter.ToUInt16(data, 0);
                    joystickState.AxisXRot = BitConverter.ToUInt16(data, 2);
                    joystickState.AxisYRot = BitConverter.ToUInt16(data, 4);

                    joystickState.AxisZ = BitConverter.ToUInt16(data, 6);
                    joystickState.AxisX = BitConverter.ToUInt16(data, 8);
                    joystickState.AxisY = BitConverter.ToUInt16(data, 10);

                    joystickState.Slider = BitConverter.ToUInt16(data, 12);
                    joystickState.Dial   = BitConverter.ToUInt16(data, 14);

                    joystickState.Buttons = BitConverter.ToUInt32(data, 16);

                    joystickState.ButtonsEx1 = BitConverter.ToUInt32(data, 20);

                    joystickState.ButtonsEx2 = BitConverter.ToUInt32(data, 24);

                    joystickState.ButtonsEx3 = BitConverter.ToUInt32(data, 28);

                    joystick.UpdateVJD(id, ref joystickState);
                }
            }
            catch {
                Debug.WriteLine("Receive loop exit");
            }

            joystick.RelinquishVJD(id);
        }
        public void PublishiReport()
        {
            // Feed the driver with the position packet
            // If it fails, wait then try to re-acquire device
            if (!Joystick.UpdateVJD(joyID, ref Report))
            {
                LogFormat(LogLevels.DEBUG, "Feeding vJoy device number {0} failed - trying to re-enable device", joyID);

                // Add some delay before re-enabling vJoy
                var stt = Acquire(joyID);
                if (stt != 1)
                {
                    LogFormat(LogLevels.ERROR, "Cannot acquire device number {0} - try to restart this program", joyID);
                    //Console.ReadKey(true);
                }
            }
        }
Example #14
0
        public void JoySubmit(uint parDSid)
        {
            uint id = GetvjFromDS(parDSid);

            joystick.UpdateVJD(id, ref joyReport[parDSid - 1]);
            joyReport[id - 1].Buttons    = 0;
            joyReport[id - 1].ButtonsEx1 = 0;
            joyReport[id - 1].ButtonsEx2 = 0;
            joyReport[id - 1].ButtonsEx3 = 0;
            //Set Axis to mid value
            //Needed as ButtonsAsAxis don't reset to axis
            joyReport[id - 1].AxisX    = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].AxisY    = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].AxisZ    = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].AxisXRot = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].AxisYRot = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].AxisZRot = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].Slider   = vJoyConstants.HALF_AXIS_VALUE;
            joyReport[id - 1].Dial     = vJoyConstants.HALF_AXIS_VALUE;
        }
Example #15
0
        internal static void UpdateState()
        {
            if (Verbose)
            {
                Loger.InfoContinue($"Axe1X {SerialStates.Axes[0]} Axe1Y {SerialStates.Axes[1]} Axe2X {SerialStates.Axes[2]} Axe2y {SerialStates.Axes[3]}");
            }


            iReport.bDevice = (byte)id;

            iReport.AxisX = SerialStates.ConverAxeValue(0);
            iReport.AxisY = SerialStates.ConverAxeValue(1);

            iReport.AxisXRot = SerialStates.ConverAxeValue(2);
            iReport.AxisYRot = SerialStates.ConverAxeValue(3);


            iReport.bHats = SerialStates.HatStates;

            iReport.Buttons = 0;
            if (!(SerialStates.Buttons[0] && SerialStates.Buttons[1]))
            {
                for (int i = 0; i < SerialStates.Buttons.Length; i++)
                {
                    if (SerialStates.Buttons[i])
                    {
                        iReport.Buttons = iReport.Buttons | ((uint)0b1 << i);
                    }
                }
            }



            if (!joystick.UpdateVJD(id, ref iReport))
            {
                Loger.Error($"Feeding vJoy device number {id} failed - wait 1s");
                Thread.Sleep(1000);
                joystick.AcquireVJD(id);
            }
        }
Example #16
0
        public bool Poll()
        {
            if (!AllDevicesReady())
            {
                return(false);
            }
            if (!vjoyEnabled)
            {
                vjoyEnabled = joystick.AcquireVJD(id);
                if (!vjoyEnabled)
                {
                    return(false);
                }
            }

            try
            {
                iReport.bDevice = (byte)id;
                iReport.Buttons = 0;
                iReport.bHats   = iReport.bHatsEx1 = iReport.bHatsEx2 = iReport.bHatsEx3 = uint.MaxValue;

                Feed();

                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    vjoyEnabled = false;
                    mainForm.ReportVJoyDisconnect();
                }
            }
            catch (System.Exception)
            {
                ClearDevices();
                return(false);
            }
            return(true);
        }
Example #17
0
        public static void vJoyLoop()
        {
            joystick.ResetVJD(vjd);
            Console.WriteLine("Starting update loop...");
            JoystickState iReport;

            while (true)
            {
                iReport = new JoystickState();

                // make all of them -1 (no angle)
                // also aren't these all uints? wouldn't it just underflow?
                // it works tho
                iReport.bHatsEx1--;
                iReport.bHatsEx2--;
                iReport.bHatsEx3--;

                controllers.ForEach((c) => c.Poll());

                //buttons
                iReport.Buttons = controller.GetButtonData();

                //pov
                iReport.bHats = (uint)(GetPOVMultiplier(controller.GetPov(0)) * 4487.5);

                //sticks
                Position leftPos  = controller.GetStick(0);
                Position rightPos = controller.GetStick(1);
                iReport.AxisX    = leftPos.x;
                iReport.AxisY    = leftPos.y;
                iReport.AxisXRot = rightPos.x;
                iReport.AxisYRot = rightPos.y;

                joystick.UpdateVJD(vjd, ref iReport);
                //Thread.Sleep((1 / 60) * 1000); // joycons update @ 60hz
            }
        }
Example #18
0
        public bool activateVJoy()
        {
            VjdStat status = joystick.GetVJDStatus(id);

            switch (status)
            {
            case VjdStat.VJD_STAT_OWN:
                context.logmMssage("vJoy Device " + id + " Connected Successfully");
                break;

            case VjdStat.VJD_STAT_FREE:
                context.logmMssage("vJoy Device " + id + " Connected Successfully");
                break;

            case VjdStat.VJD_STAT_BUSY:
                context.logmMssage("vJoy Device " + id + " is already owned by another feeder\nCannot continue\n");
                return(false);

            case VjdStat.VJD_STAT_MISS:
                context.logmMssage("vJoy Device is not installed or disabled\nCannot continue\n");
                return(false);

            default:
                context.logmMssage("vJoy Device general error\nCannot continue\n");
                return(false);
            }
            ;

            bool AxisX  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_X);
            bool AxisY  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Y);
            bool AxisZ  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Z);
            bool AxisRX = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RX);
            bool AxisRZ = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RZ);

            // Get the number of buttons and POV Hat switchessupported by this vJoy device
            nButtons      = joystick.GetVJDButtonNumber(id);
            ContPovNumber = joystick.GetVJDContPovNumber(id);
            DiscPovNumber = joystick.GetVJDDiscPovNumber(id);

            // Print results
            Console.WriteLine("\nvJoy Device {0} capabilities:\n", id);
            Console.WriteLine("Numner of buttons\t\t{0}\n", nButtons);
            Console.WriteLine("Numner of Continuous POVs\t{0}\n", ContPovNumber);
            Console.WriteLine("Numner of Descrete POVs\t\t{0}\n", DiscPovNumber);
            Console.WriteLine("Axis X\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Y\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Z\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Rx\t\t{0}\n", AxisRX ? "Yes" : "No");
            Console.WriteLine("Axis Rz\t\t{0}\n", AxisRZ ? "Yes" : "No");


            UInt32 DllVer = 0, DrvVer = 0;
            bool   match = joystick.DriverMatch(ref DllVer, ref DrvVer);

            if (match)
            {
                Console.WriteLine("Version of Driver Matches DLL Version ({0:X})\n", DllVer);
            }
            else
            {
                Console.WriteLine("Version of Driver ({0:X}) does NOT match DLL Version ({1:X})\n", DrvVer, DllVer);
            }


            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(id))))
            {
                context.logmMssage("Failed to acquire vJoy device number " + id);
                return(false);
            }
            else
            {
                context.logmMssage("Acquired: vJoy device number " + id);
            }

            joystick.GetVJDAxisMax(id, HID_USAGES.HID_USAGE_X, ref joyStickMaxval);

            Console.WriteLine("max val is: " + joyStickMaxval);

            iReport.bDevice = (byte)id;

            joystick.ResetVJD(id);


            OperateJoyStick(0, 0);
            operatePOV(0xFFFFFFFF);

            joystick.UpdateVJD(id, ref iReport);


            return(true);
        }
Example #19
0
 public bool _UpdateVJD()
 {
     report.bDevice = (byte)Index;
     return(_joystick.UpdateVJD(Index, ref report));
 }
Example #20
0
        public static void Initialize(uint id)  //(string[] args)
        {
            // Create one joystick object and a position structure.
            joystick = new vJoy();
            iReport  = new vJoy.JoystickState();

            string buffer;

            // Device ID can only be in the range 1-16
            if (id < 1 || id > 16)
            {
                buffer = string.Format("Illegal device ID {0}\nExit!", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                return;
            }

            // Get the driver attributes (Vendor ID, Product ID, Version Number)
            if (!joystick.vJoyEnabled())
            {
                BalanceWalker.FormMain.consoleBoxWriteLine("vJoy driver not enabled: Failed Getting vJoy attributes.\n");
                return;
            }
            else
            {
                buffer = string.Format("Vendor: {0}\nProduct :{1}\nVersion Number:{2}\n", joystick.GetvJoyManufacturerString(), joystick.GetvJoyProductString(), joystick.GetvJoySerialNumberString());     //BalanceWalker.FormMain.consoleBoxWriteLine($"Vendor: {joystick.GetvJoyManufacturerString()}\nProduct :{joystick.GetvJoyProductString()}\nVersion Number:{joystick.GetvJoySerialNumberString()}\n");
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            }


            // Get the state of the requested device
            VjdStat status = joystick.GetVJDStatus(id);

            switch (status)
            {
            case VjdStat.VJD_STAT_OWN:
                buffer = string.Format("vJoy Device {0} is already owned by this feeder\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                break;

            case VjdStat.VJD_STAT_FREE:
                buffer = string.Format("vJoy Device {0} is free\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                break;

            case VjdStat.VJD_STAT_BUSY:
                buffer = string.Format("vJoy Device {0} is already owned by another feeder\nCannot continue\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                return;

            case VjdStat.VJD_STAT_MISS:
                buffer = string.Format("vJoy Device {0} is not installed or disabled. \nCannot continue\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                return;

            default:
                buffer = string.Format("vJoy Device {0} general error\nCannot continue\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                return;
            }
            ;

            // Check which axes are supported
            bool AxisX  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_X);
            bool AxisY  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Y);
            bool AxisZ  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Z);
            bool AxisRX = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RX);
            bool AxisRZ = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RZ);
            bool AxisRY = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RY);
            // Get the number of buttons and POV Hat switches supported by this vJoy device
            int nButtons      = joystick.GetVJDButtonNumber(id);
            int ContPovNumber = joystick.GetVJDContPovNumber(id);
            int DiscPovNumber = joystick.GetVJDDiscPovNumber(id);

            // Print results
            buffer = string.Format("\nvJoy Device {0} capabilities:\n", id);
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Number of buttons\t\t{0}\n", nButtons);
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Number of Continuous POVs\t{0}\n", ContPovNumber);
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Number of Descrete POVs\t\t{0}\n", DiscPovNumber);
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Axis X\t\t{0}\n", AxisX ? "Yes" : "No");
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Axis Y\t\t{0}\n", AxisY ? "Yes" : "No");
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Axis Z\t\t{0}\n", AxisZ ? "Yes" : "No");
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Axis Rx\t\t{0}\n", AxisRX ? "Yes" : "No");
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Axis Ry\t\t{0}\n", AxisRY ? "Yes" : "No");
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            buffer = string.Format("Axis Rz\t\t{0}\n", AxisRZ ? "Yes" : "No");
            BalanceWalker.FormMain.consoleBoxWriteLine(buffer);

            if (!(AxisX && AxisY && AxisZ && AxisRX && AxisRZ && AxisRY))
            {
                buffer = string.Format("Please enable Axes X,Y,Z,RX,RY,RZ in vJoyConf for device number", id, " in order to use all functions", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            }
            if (nButtons < 1)
            {
                buffer = string.Format("Please enable at least 1 button in vJoyConf for device ", id, " in order to use the only button on the wii balance board");
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            }
            // Test if DLL matches the driver
            UInt32 DllVer = 0, DrvVer = 0;
            bool   match = joystick.DriverMatch(ref DllVer, ref DrvVer);

            if (match)
            {
                buffer = string.Format("Version of Driver Matches DLL Version ({0:X})\n", DllVer);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            }
            else
            {
                buffer = string.Format("Version of Driver ({0:X}) does NOT match DLL Version ({1:X})\n", DrvVer, DllVer);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            }

            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(id))))
            {
                buffer = string.Format("Failed to acquire vJoy device number {0}.\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
                return;
            }
            else
            {
                buffer = string.Format("Acquired: vJoy device number {0}.\n", id);
                BalanceWalker.FormMain.consoleBoxWriteLine(buffer);
            }
            int  X, Y, Z, XR, ZR;
            uint count  = 0;
            long maxval = 0;    // maxval is -32767 +32767

            X  = 20;
            Y  = 30;
            Z  = 40;
            XR = 60;
            ZR = 80;

            joystick.GetVJDAxisMax(id, HID_USAGES.HID_USAGE_X, ref maxval);

#if ROBUST
            bool res;
            // Reset this device to default values
            joystick.ResetVJD(id);

            // set this to true to test if the vJoy driver is working. This will feed vjoy with an endless loop of joystick commands.

            while (false)
            {
                // Set position of 4 axes
                res = joystick.SetAxis(X, id, HID_USAGES.HID_USAGE_X);
                res = joystick.SetAxis(Y, id, HID_USAGES.HID_USAGE_Y);
                res = joystick.SetAxis(Z, id, HID_USAGES.HID_USAGE_Z);
                res = joystick.SetAxis(XR, id, HID_USAGES.HID_USAGE_RX);
                res = joystick.SetAxis(ZR, id, HID_USAGES.HID_USAGE_RZ);

                // Press/Release Buttons
                res = joystick.SetBtn(true, id, count / 50);
                res = joystick.SetBtn(false, id, 1 + count / 50);

                // If Continuous POV hat switches installed - make them go round
                // For high values - put the switches in neutral state
                if (ContPovNumber > 0)
                {
                    if ((count * 70) < 30000)
                    {
                        res = joystick.SetContPov(((int)count * 70), id, 1);
                        res = joystick.SetContPov(((int)count * 70) + 2000, id, 2);
                        res = joystick.SetContPov(((int)count * 70) + 4000, id, 3);
                        res = joystick.SetContPov(((int)count * 70) + 6000, id, 4);
                    }
                    else
                    {
                        res = joystick.SetContPov(-1, id, 1);
                        res = joystick.SetContPov(-1, id, 2);
                        res = joystick.SetContPov(-1, id, 3);
                        res = joystick.SetContPov(-1, id, 4);
                    };
                }
                ;

                // If Discrete POV hat switches installed - make them go round
                // From time to time - put the switches in neutral state
                if (DiscPovNumber > 0)
                {
                    if (count < 550)
                    {
                        joystick.SetDiscPov((((int)count / 20) + 0) % 4, id, 1);
                        joystick.SetDiscPov((((int)count / 20) + 1) % 4, id, 2);
                        joystick.SetDiscPov((((int)count / 20) + 2) % 4, id, 3);
                        joystick.SetDiscPov((((int)count / 20) + 3) % 4, id, 4);
                    }
                    else
                    {
                        joystick.SetDiscPov(-1, id, 1);
                        joystick.SetDiscPov(-1, id, 2);
                        joystick.SetDiscPov(-1, id, 3);
                        joystick.SetDiscPov(-1, id, 4);
                    };
                }
                ;

                System.Threading.Thread.Sleep(20);
                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
                count++;

                if (count > 640)
                {
                    count = 0;
                }
            } // While (Robust)
#endif // ROBUST
#if EFFICIENT   // todo: unused, from the original vjoy feeder demo code.
            byte[] pov = new byte[4];

            while (true)
            {
                iReport.bDevice  = (byte)id;
                iReport.AxisX    = X;
                iReport.AxisY    = Y;
                iReport.AxisZ    = Z;
                iReport.AxisZRot = ZR;
                iReport.AxisXRot = XR;

                // Set buttons one by one
                iReport.Buttons = (uint)(0x1 << (int)(count / 20));

                if (ContPovNumber > 0)
                {
                    // Make Continuous POV Hat spin
                    iReport.bHats    = (count * 70);
                    iReport.bHatsEx1 = (count * 70) + 3000;
                    iReport.bHatsEx2 = (count * 70) + 5000;
                    iReport.bHatsEx3 = 15000 - (count * 70);
                    if ((count * 70) > 36000)
                    {
                        iReport.bHats    = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx1 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx2 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx3 = 0xFFFFFFFF; // Neutral state
                    }
                    ;
                }
                else
                {
                    // Make 5-position POV Hat spin

                    pov[0] = (byte)(((count / 20) + 0) % 4);
                    pov[1] = (byte)(((count / 20) + 1) % 4);
                    pov[2] = (byte)(((count / 20) + 2) % 4);
                    pov[3] = (byte)(((count / 20) + 3) % 4);

                    iReport.bHats = (uint)(pov[3] << 12) | (uint)(pov[2] << 8) | (uint)(pov[1] << 4) | (uint)pov[0];
                    if ((count) > 550)
                    {
                        iReport.bHats = 0xFFFFFFFF;         // Neutral state
                    }
                };

                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    Console.WriteLine("Feeding vJoy device number {0} failed - try to enable device then press enter\n", id);
                    Console.ReadKey(true);
                    joystick.AcquireVJD(id);
                }

                System.Threading.Thread.Sleep(20);
                count++;
                if (count > 640)
                {
                    count = 0;
                }

                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
            }
            ; // While
#endif // EFFICIENT
        }
Example #21
0
        // Update is called once per frame
        void Update()
        {
            if (webCamTextureToMatHelper.IsPlaying() && webCamTextureToMatHelper.DidUpdateThisFrame())
            {
                Mat rgbaMat = webCamTextureToMatHelper.GetMat();


                OpenCVForUnityUtils.SetImage(faceLandmarkDetector, rgbaMat);

                //detect face rects
                List <UnityEngine.Rect> detectResult = faceLandmarkDetector.Detect();

                if (detectResult.Count > 0)
                {
                    //detect landmark points
                    List <Vector2> points = faceLandmarkDetector.DetectLandmark(detectResult [0]);

                    if (displayFacePoints)
                    {
                        OpenCVForUnityUtils.DrawFaceLandmark(rgbaMat, points, new Scalar(0, 255, 0, 255), 2);
                    }

                    MatOfPoint3f objectPoints = null;
                    if (points.Count == 68)
                    {
                        objectPoints = objectPoints68;

                        imagePoints.fromArray(
                            new Point((points [38].x + points [41].x) / 2, (points [38].y + points [41].y) / 2), //l eye (Interpupillary breadth)
                            new Point((points [43].x + points [46].x) / 2, (points [43].y + points [46].y) / 2), //r eye (Interpupillary breadth)
                            new Point(points [30].x, points [30].y),                                             //nose (Tip)
                            new Point(points [33].x, points [33].y),                                             //nose (Subnasale)
                            new Point(points [0].x, points [0].y),                                               //l ear (Bitragion breadth)
                            new Point(points [16].x, points [16].y)                                              //r ear (Bitragion breadth)
                            );


                        float noseDistance  = Mathf.Abs((float)(points [27].y - points [33].y));
                        float mouseDistance = Mathf.Abs((float)(points [62].y - points [66].y));
                    }
                    else if (points.Count == 17)
                    {
                        objectPoints = objectPoints17;

                        imagePoints.fromArray(
                            new Point((points [2].x + points [3].x) / 2, (points [2].y + points [3].y) / 2), //l eye (Interpupillary breadth)
                            new Point((points [4].x + points [5].x) / 2, (points [4].y + points [5].y) / 2), //r eye (Interpupillary breadth)
                            new Point(points [0].x, points [0].y),                                           //nose (Tip)
                            new Point(points [1].x, points [1].y),                                           //nose (Subnasale)
                            new Point(points [6].x, points [6].y),                                           //l ear (Bitragion breadth)
                            new Point(points [8].x, points [8].y)                                            //r ear (Bitragion breadth)
                            );

                        float noseDistance  = Mathf.Abs((float)(points [3].y - points [1].y));
                        float mouseDistance = Mathf.Abs((float)(points [14].y - points [16].y));
                    }
                    else if (points.Count == 6)
                    {
                        objectPoints = objectPoints6;

                        imagePoints.fromArray(
                            new Point((points [2].x + points [3].x) / 2, (points [2].y + points [3].y) / 2), //l eye (Interpupillary breadth)
                            new Point((points [4].x + points [5].x) / 2, (points [4].y + points [5].y) / 2), //r eye (Interpupillary breadth)
                            new Point(points [0].x, points [0].y),                                           //nose (Tip)
                            new Point(points [1].x, points [1].y)                                            //nose (Subnasale)
                            );
                    }
                    else if (points.Count == 5)
                    {
                        objectPoints = objectPoints5;

                        imagePoints.fromArray(
                            new Point(points [3].x, points [3].y), //l eye (Inner corner of the eye)
                            new Point(points [1].x, points [1].y), //r eye (Inner corner of the eye)
                            new Point(points [2].x, points [2].y), //l eye (Tail of the eye)
                            new Point(points [0].x, points [0].y), //r eye (Tail of the eye)
                            new Point(points [4].x, points [4].y)  //nose (Subnasale)
                            );

                        if (fpsMonitor != null)
                        {
                            fpsMonitor.consoleText = "This example supports mainly the face landmark points of 68/17/6 points.";
                        }
                    }

                    // estimate head pose
                    if (rvec == null || tvec == null)
                    {
                        rvec = new Mat(3, 1, CvType.CV_64FC1);
                        tvec = new Mat(3, 1, CvType.CV_64FC1);
                        Calib3d.solvePnP(objectPoints, imagePoints, camMatrix, distCoeffs, rvec, tvec);
                    }


                    double tvec_x = tvec.get(0, 0) [0], tvec_y = tvec.get(1, 0) [0], tvec_z = tvec.get(2, 0) [0];

                    bool    isNotInViewport = false;
                    Vector4 pos             = VP * new Vector4((float)tvec_x, (float)tvec_y, (float)tvec_z, 1.0f);
                    if (pos.w != 0)
                    {
                        float x = pos.x / pos.w, y = pos.y / pos.w, z = pos.z / pos.w;
                        if (x < -1.0f || x > 1.0f || y < -1.0f || y > 1.0f || z < -1.0f || z > 1.0f)
                        {
                            isNotInViewport = true;
                        }
                    }

                    if (double.IsNaN(tvec_z) || isNotInViewport)    // if tvec is wrong data, do not use extrinsic guesses. (the estimated object is not in the camera field of view)
                    {
                        Calib3d.solvePnP(objectPoints, imagePoints, camMatrix, distCoeffs, rvec, tvec);
                    }
                    else
                    {
                        Calib3d.solvePnP(objectPoints, imagePoints, camMatrix, distCoeffs, rvec, tvec, true, Calib3d.SOLVEPNP_ITERATIVE);
                    }

                    if (!isNotInViewport)
                    {
                        if (displayHead)
                        {
                            head.SetActive(true);
                        }
                        if (displayAxes)
                        {
                            axes.SetActive(true);
                        }

                        // Convert to unity pose data.
                        double[] rvecArr = new double[3];
                        rvec.get(0, 0, rvecArr);
                        double[] tvecArr = new double[3];
                        tvec.get(0, 0, tvecArr);
                        PoseData poseData = ARUtils.ConvertRvecTvecToPoseData(rvecArr, tvecArr);

                        // Changes in pos/rot below these thresholds are ignored.
                        if (enableLowPassFilter)
                        {
                            ARUtils.LowpassPoseData(ref oldPoseData, ref poseData, positionLowPass, rotationLowPass);
                        }
                        oldPoseData = poseData;

                        // Create transform matrix.
                        transformationM = Matrix4x4.TRS(poseData.pos, poseData.rot, Vector3.one);

                        //move joystick
                        float t = 0.50f;
                        int   xpos;
                        if ((poseData.rot.eulerAngles.x - oldPoseData.rot.eulerAngles.x) < 10 && (poseData.rot.eulerAngles.x - oldPoseData.rot.eulerAngles.x) > 0)
                        {
                            xpos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.x, oldPoseData.rot.eulerAngles.x, t));
                        }
                        else
                        {
                            xpos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.x, oldPoseData.rot.eulerAngles.x, 1));
                        }


                        int ypos;
                        if ((poseData.rot.eulerAngles.y - oldPoseData.rot.eulerAngles.y) < 10 && (poseData.rot.eulerAngles.y - oldPoseData.rot.eulerAngles.y) > 0)
                        {
                            ypos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.y, oldPoseData.rot.eulerAngles.y, t));
                        }
                        else
                        {
                            ypos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.y, oldPoseData.rot.eulerAngles.y, 1));
                        }


                        int rpos;
                        if ((poseData.rot.eulerAngles.z - oldPoseData.rot.eulerAngles.z) < 10 && (poseData.rot.eulerAngles.z - oldPoseData.rot.eulerAngles.z) > 0)
                        {
                            rpos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.z, oldPoseData.rot.eulerAngles.z, t));
                        }
                        else
                        {
                            rpos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.z, oldPoseData.rot.eulerAngles.z, 1));
                        }


                        //int ypos = Convert.ToInt16(Mathf.Lerp(poseData.rot.eulerAngles.y, oldPoseData.rot.eulerAngles.y,t));
                        int zpos = Convert.ToInt16(poseData.pos.z);

                        //zoom
                        int scZ = Convert.ToInt32(Scale(zpos, 400, 800, 0, 32000));

                        //up down
                        int scX;
                        if (xpos >= 0 && xpos < 20)
                        {
                            scX = Convert.ToInt32(Scale(xpos, 0, 10, 29000, 32000));
                        }
                        else
                        {
                            scX = Convert.ToInt32(Scale(xpos, 340, 360, 0, 29000));
                        }

                        //left right
                        int scY = Convert.ToInt32(Scale(ypos, 160, 200, 0, 32000));

                        //roll
                        int scR = Convert.ToInt32(Scale(rpos, 160, 200, 0, 32000));


                        iReport.AxisX  = scX;
                        iReport.AxisY  = scY;
                        iReport.AxisZ  = scZ;
                        iReport.Slider = scR;
                        bool upd = joystick.UpdateVJD(id, ref iReport);

                        string message = "x:" + scX + " y:" + scY + " z:" + scZ + " r:" + scR;
                        Debug.Log(message);
                    }


                    // right-handed coordinates system (OpenCV) to left-handed one (Unity)
                    ARM = invertYM * transformationM;

                    // Apply Z-axis inverted matrix.
                    ARM = ARM * invertZM;

                    if (shouldMoveARCamera)
                    {
                        ARM = ARGameObject.transform.localToWorldMatrix * ARM.inverse;
                        ARUtils.SetTransformFromMatrix(ARCamera.transform, ref ARM);
                    }
                    else
                    {
                        ARM = ARCamera.transform.localToWorldMatrix * ARM;
                        ARUtils.SetTransformFromMatrix(ARGameObject.transform, ref ARM);
                    }
                }

                Imgproc.putText(rgbaMat, "W:" + rgbaMat.width() + " H:" + rgbaMat.height() + " SO:" + Screen.orientation, new Point(5, rgbaMat.rows() - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar(255, 255, 255, 255), 1, Imgproc.LINE_AA, false);



                OpenCVForUnity.UnityUtils.Utils.fastMatToTexture2D(rgbaMat, texture);
            }
        }
        static void Main(string[] args)
        {
            // Create one joystick object and a position structure.
            joystick = new vJoy();
            iReport  = new vJoy.JoystickState();


            // Device ID can only be in the range 1-16
            if (args.Length > 0 && !String.IsNullOrEmpty(args[0]))
            {
                id = Convert.ToUInt32(args[0]);
            }
            if (id <= 0 || id > 16)
            {
                Console.WriteLine("Illegal device ID {0}\nExit!", id);
                return;
            }

            // Get the driver attributes (Vendor ID, Product ID, Version Number)
            if (!joystick.vJoyEnabled())
            {
                Console.WriteLine("vJoy driver not enabled: Failed Getting vJoy attributes.\n");
                return;
            }
            else
            {
                Console.WriteLine("Vendor: {0}\nProduct :{1}\nVersion Number:{2}\n", joystick.GetvJoyManufacturerString(), joystick.GetvJoyProductString(), joystick.GetvJoySerialNumberString());
            }

            // Get the state of the requested device
            VjdStat status = joystick.GetVJDStatus(id);

            switch (status)
            {
            case VjdStat.VJD_STAT_OWN:
                Console.WriteLine("vJoy Device {0} is already owned by this feeder\n", id);
                break;

            case VjdStat.VJD_STAT_FREE:
                Console.WriteLine("vJoy Device {0} is free\n", id);
                break;

            case VjdStat.VJD_STAT_BUSY:
                Console.WriteLine("vJoy Device {0} is already owned by another feeder\nCannot continue\n", id);
                return;

            case VjdStat.VJD_STAT_MISS:
                Console.WriteLine("vJoy Device {0} is not installed or disabled\nCannot continue\n", id);
                return;

            default:
                Console.WriteLine("vJoy Device {0} general error\nCannot continue\n", id);
                return;
            }
            ;

            // Check which axes are supported
            bool AxisX  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_X);
            bool AxisY  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Y);
            bool AxisZ  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Z);
            bool AxisRX = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RX);
            bool AxisRZ = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RZ);
            // Get the number of buttons and POV Hat switchessupported by this vJoy device
            int nButtons      = joystick.GetVJDButtonNumber(id);
            int ContPovNumber = joystick.GetVJDContPovNumber(id);
            int DiscPovNumber = joystick.GetVJDDiscPovNumber(id);

            // Print results
            Console.WriteLine("\nvJoy Device {0} capabilities:\n", id);
            Console.WriteLine("Numner of buttons\t\t{0}\n", nButtons);
            Console.WriteLine("Numner of Continuous POVs\t{0}\n", ContPovNumber);
            Console.WriteLine("Numner of Descrete POVs\t\t{0}\n", DiscPovNumber);
            Console.WriteLine("Axis X\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Y\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Z\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Rx\t\t{0}\n", AxisRX ? "Yes" : "No");
            Console.WriteLine("Axis Rz\t\t{0}\n", AxisRZ ? "Yes" : "No");

            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(id))))
            {
                Console.WriteLine("Failed to acquire vJoy device number {0}.\n", id);
                return;
            }
            else
            {
                Console.WriteLine("Acquired: vJoy device number {0}.\n", id);
            }

            Console.WriteLine("\npress enter to stat feeding");
            Console.ReadKey(true);

            int  X, Y, Z, ZR, XR;
            uint count  = 0;
            long maxval = 0;

            X  = 20;
            Y  = 30;
            Z  = 40;
            XR = 60;
            ZR = 80;

            joystick.GetVJDAxisMax(id, HID_USAGES.HID_USAGE_X, ref maxval);

#if ROBUST
            bool res;
            // Reset this device to default values
            joystick.ResetVJD(id);

            // Feed the device in endless loop
            while (true)
            {
                // Set position of 4 axes
                res = joystick.SetAxis(X, id, HID_USAGES.HID_USAGE_X);
                res = joystick.SetAxis(Y, id, HID_USAGES.HID_USAGE_Y);
                res = joystick.SetAxis(Z, id, HID_USAGES.HID_USAGE_Z);
                res = joystick.SetAxis(XR, id, HID_USAGES.HID_USAGE_RX);
                res = joystick.SetAxis(ZR, id, HID_USAGES.HID_USAGE_RZ);

                // Press/Release Buttons
                res = joystick.SetBtn(true, id, count / 50);
                res = joystick.SetBtn(false, id, 1 + count / 50);

                // If Continuous POV hat switches installed - make them go round
                // For high values - put the switches in neutral state
                if (ContPovNumber > 0)
                {
                    if ((count * 70) < 30000)
                    {
                        res = joystick.SetContPov(((int)count * 70), id, 1);
                        res = joystick.SetContPov(((int)count * 70) + 2000, id, 2);
                        res = joystick.SetContPov(((int)count * 70) + 4000, id, 3);
                        res = joystick.SetContPov(((int)count * 70) + 6000, id, 4);
                    }
                    else
                    {
                        res = joystick.SetContPov(-1, id, 1);
                        res = joystick.SetContPov(-1, id, 2);
                        res = joystick.SetContPov(-1, id, 3);
                        res = joystick.SetContPov(-1, id, 4);
                    };
                }
                ;

                // If Discrete POV hat switches installed - make them go round
                // From time to time - put the switches in neutral state
                if (DiscPovNumber > 0)
                {
                    if (count < 550)
                    {
                        joystick.SetDiscPov((((int)count / 20) + 0) % 4, id, 1);
                        joystick.SetDiscPov((((int)count / 20) + 1) % 4, id, 2);
                        joystick.SetDiscPov((((int)count / 20) + 2) % 4, id, 3);
                        joystick.SetDiscPov((((int)count / 20) + 3) % 4, id, 4);
                    }
                    else
                    {
                        joystick.SetDiscPov(-1, id, 1);
                        joystick.SetDiscPov(-1, id, 2);
                        joystick.SetDiscPov(-1, id, 3);
                        joystick.SetDiscPov(-1, id, 4);
                    };
                }
                ;

                System.Threading.Thread.Sleep(20);
                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
                count++;

                if (count > 640)
                {
                    count = 0;
                }
            } // While (Robust)
#endif // ROBUST
#if EFFICIENT
            byte[] pov = new byte[4];

            while (true)
            {
                iReport.bDevice  = (byte)id;
                iReport.AxisX    = X;
                iReport.AxisY    = Y;
                iReport.AxisZ    = Z;
                iReport.AxisZRot = ZR;
                iReport.AxisXRot = XR;

                // Set buttons one by one
                iReport.Buttons = (uint)(0x1 << (int)(count / 20));

                if (ContPovNumber > 0)
                {
                    // Make Continuous POV Hat spin
                    iReport.bHats    = (count * 70);
                    iReport.bHatsEx1 = (count * 70) + 3000;
                    iReport.bHatsEx2 = (count * 70) + 5000;
                    iReport.bHatsEx3 = 15000 - (count * 70);
                    if ((count * 70) > 36000)
                    {
                        iReport.bHats    = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx1 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx2 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx3 = 0xFFFFFFFF; // Neutral state
                    }
                    ;
                }
                else
                {
                    // Make 5-position POV Hat spin

                    pov[0] = (byte)(((count / 20) + 0) % 4);
                    pov[1] = (byte)(((count / 20) + 1) % 4);
                    pov[2] = (byte)(((count / 20) + 2) % 4);
                    pov[3] = (byte)(((count / 20) + 3) % 4);

                    iReport.bHats = (uint)(pov[3] << 12) | (uint)(pov[2] << 8) | (uint)(pov[1] << 4) | (uint)pov[0];
                    if ((count) > 550)
                    {
                        iReport.bHats = 0xFFFFFFFF;         // Neutral state
                    }
                };

                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    Console.WriteLine("Feeding vJoy device number {0} failed - try to enable device then press enter\n", id);
                    Console.ReadKey(true);
                    joystick.AcquireVJD(id);
                }

                System.Threading.Thread.Sleep(20);
                count++;
                if (count > 640)
                {
                    count = 0;
                }

                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
            }
            ; // While
#endif // EFFICIENT
        } // Main
Example #23
0
        static void Main(string[] args)
        {
            // Create one joystick object and a position structure.
            joystick = new vJoy();
            iReport  = new vJoy.JoystickState();


            // Device ID can only be in the range 1-16
            if (args.Length > 0 && !String.IsNullOrEmpty(args[0]))
            {
                id = Convert.ToUInt32(args[0]);
            }
            if (id <= 0 || id > 16)
            {
                Console.WriteLine("Illegal device ID {0}\nExit!", id);
                return;
            }

            // Get the driver attributes (Vendor ID, Product ID, Version Number)
            if (!joystick.vJoyEnabled())
            {
                Console.WriteLine("vJoy driver not enabled: Failed Getting vJoy attributes.\n");
                return;
            }
            else
            {
                Console.WriteLine("Vendor: {0}\nProduct :{1}\nVersion Number:{2}\n", joystick.GetvJoyManufacturerString(), joystick.GetvJoyProductString(), joystick.GetvJoySerialNumberString());
            }

            // Get the state of the requested device
            VjdStat status = joystick.GetVJDStatus(id);

            switch (status)
            {
            case VjdStat.VJD_STAT_OWN:
                Console.WriteLine("vJoy Device {0} is already owned by this feeder\n", id);
                break;

            case VjdStat.VJD_STAT_FREE:
                Console.WriteLine("vJoy Device {0} is free\n", id);
                break;

            case VjdStat.VJD_STAT_BUSY:
                Console.WriteLine("vJoy Device {0} is already owned by another feeder\nCannot continue\n", id);
                return;

            case VjdStat.VJD_STAT_MISS:
                Console.WriteLine("vJoy Device {0} is not installed or disabled\nCannot continue\n", id);
                return;

            default:
                Console.WriteLine("vJoy Device {0} general error\nCannot continue\n", id);
                return;
            }
            ;

            // Check which axes are supported
            bool AxisX  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_X);
            bool AxisY  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Y);
            bool AxisZ  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Z);
            bool AxisRX = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RX);
            bool AxisRZ = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RZ);
            // Get the number of buttons and POV Hat switchessupported by this vJoy device
            int nButtons      = joystick.GetVJDButtonNumber(id);
            int ContPovNumber = joystick.GetVJDContPovNumber(id);
            int DiscPovNumber = joystick.GetVJDDiscPovNumber(id);

            // Print results
            Console.WriteLine("\nvJoy Device {0} capabilities:\n", id);
            Console.WriteLine("Numner of buttons\t\t{0}\n", nButtons);
            Console.WriteLine("Numner of Continuous POVs\t{0}\n", ContPovNumber);
            Console.WriteLine("Numner of Descrete POVs\t\t{0}\n", DiscPovNumber);
            Console.WriteLine("Axis X\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Y\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Z\t\t{0}\n", AxisX ? "Yes" : "No");
            Console.WriteLine("Axis Rx\t\t{0}\n", AxisRX ? "Yes" : "No");
            Console.WriteLine("Axis Rz\t\t{0}\n", AxisRZ ? "Yes" : "No");

            // Test if DLL matches the driver
            UInt32 DllVer = 0, DrvVer = 0;
            bool   match = joystick.DriverMatch(ref DllVer, ref DrvVer);

            if (match)
            {
                Console.WriteLine("Version of Driver Matches DLL Version ({0:X})\n", DllVer);
            }
            else
            {
                Console.WriteLine("Version of Driver ({0:X}) does NOT match DLL Version ({1:X})\n", DrvVer, DllVer);
            }


            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(id))))
            {
                Console.WriteLine("Failed to acquire vJoy device number {0}.\n", id);
                return;
            }
            else
            {
                Console.WriteLine("Acquired: vJoy device number {0}.\n", id);
            }

            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(2))))
            {
                Console.WriteLine("Failed to acquire vJoy device number {0}.\n", 2);
                return;
            }
            else
            {
                Console.WriteLine("Acquired: vJoy device number {0}.\n", 2);
            }

            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(3))))
            {
                Console.WriteLine("Failed to acquire vJoy device number {0}.\n", 3);
                return;
            }
            else
            {
                Console.WriteLine("Acquired: vJoy device number {0}.\n", 3);
            }

            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(4))))
            {
                Console.WriteLine("Failed to acquire vJoy device number {0}.\n", 4);
                return;
            }
            else
            {
                Console.WriteLine("Acquired: vJoy device number {0}.\n", 4);
            }

            int  X, Y, Z, ZR, XR;
            uint count  = 0;
            long maxval = 0;

            X  = 20;
            Y  = 30;
            Z  = 40;
            XR = 60;
            ZR = 80;

            joystick.GetVJDAxisMax(id, HID_USAGES.HID_USAGE_X, ref maxval);

#if LMAONEITHER
            bool res;
            // Reset this device to default values
            joystick.ResetVJD(id);

            // Connecting to socket.io server (make sure the server is up first!)
            var socket = IO.Socket("http://localhost:14178");
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                socket.Emit("clientconnect", "iamclient");
                Console.WriteLine("Thanks for using LocalLink! This is a controller log; feel free to minimize it, but DO NOT CLOSE IT unless you're finished using our program.");
            });
            socket.On("buttondown", (data) => {
                JObject a = (JObject)data;
                joystick.SetBtn(true, Convert.ToUInt32((string)a["controllerid"]), Convert.ToUInt32((string)a["buttonid"]));
                Console.WriteLine("\ngot button " + (string)a["buttonid"] + " down on controller " + (string)a["controllerid"]);
            });
            socket.On("buttonup", (data) => {
                JObject a = (JObject)data;
                joystick.SetBtn(false, Convert.ToUInt32((string)a["controllerid"]), Convert.ToUInt32((string)a["buttonid"]));
                Console.WriteLine("\ngot button " + (string)a["buttonid"] + " up on controller " + (string)a["controllerid"]);
            });
            socket.On("setaxis", (data) =>
            {
                JObject a = (JObject)data;
                switch (a["axis"].ToString().ToLower())
                {
                case "x":
                    joystick.SetAxis((int)a["value"], Convert.ToUInt32((string)a["controllerid"]), HID_USAGES.HID_USAGE_X);
                    Console.WriteLine("got x " + (int)a["value"]);
                    break;

                case "y":
                    joystick.SetAxis((int)a["value"], Convert.ToUInt32((string)a["controllerid"]), HID_USAGES.HID_USAGE_Y);
                    break;

                case "z":
                    joystick.SetAxis((int)a["value"], Convert.ToUInt32((string)a["controllerid"]), HID_USAGES.HID_USAGE_Z);
                    break;

                case "rx":
                    joystick.SetAxis((int)a["value"], Convert.ToUInt32((string)a["controllerid"]), HID_USAGES.HID_USAGE_RX);
                    break;

                case "ry":
                    joystick.SetAxis((int)a["value"], Convert.ToUInt32((string)a["controllerid"]), HID_USAGES.HID_USAGE_RY);
                    break;

                case "rz":
                    joystick.SetAxis((int)a["value"], Convert.ToUInt32((string)a["controllerid"]), HID_USAGES.HID_USAGE_RZ);
                    break;
                }
            });

            Console.ReadLine();
#endif // LMAONEITHER
#if ROBUST
            bool res;
            // Reset this device to default values
            joystick.ResetVJD(id);

            // Feed the device in endless loop
            while (true)
            {
                // Set position of 4 axes
                res = joystick.SetAxis(X, id, HID_USAGES.HID_USAGE_X);
                res = joystick.SetAxis(Y, id, HID_USAGES.HID_USAGE_Y);
                res = joystick.SetAxis(Z, id, HID_USAGES.HID_USAGE_Z);
                res = joystick.SetAxis(XR, id, HID_USAGES.HID_USAGE_RX);
                res = joystick.SetAxis(ZR, id, HID_USAGES.HID_USAGE_RZ);

                // Press/Release Buttons
                res = joystick.SetBtn(true, id, count / 50);
                res = joystick.SetBtn(false, id, 1 + count / 50);

                // If Continuous POV hat switches installed - make them go round
                // For high values - put the switches in neutral state
                if (ContPovNumber > 0)
                {
                    if ((count * 70) < 30000)
                    {
                        res = joystick.SetContPov(((int)count * 70), id, 1);
                        res = joystick.SetContPov(((int)count * 70) + 2000, id, 2);
                        res = joystick.SetContPov(((int)count * 70) + 4000, id, 3);
                        res = joystick.SetContPov(((int)count * 70) + 6000, id, 4);
                    }
                    else
                    {
                        res = joystick.SetContPov(-1, id, 1);
                        res = joystick.SetContPov(-1, id, 2);
                        res = joystick.SetContPov(-1, id, 3);
                        res = joystick.SetContPov(-1, id, 4);
                    };
                }
                ;

                // If Discrete POV hat switches installed - make them go round
                // From time to time - put the switches in neutral state
                if (DiscPovNumber > 0)
                {
                    if (count < 550)
                    {
                        joystick.SetDiscPov((((int)count / 20) + 0) % 4, id, 1);
                        joystick.SetDiscPov((((int)count / 20) + 1) % 4, id, 2);
                        joystick.SetDiscPov((((int)count / 20) + 2) % 4, id, 3);
                        joystick.SetDiscPov((((int)count / 20) + 3) % 4, id, 4);
                    }
                    else
                    {
                        joystick.SetDiscPov(-1, id, 1);
                        joystick.SetDiscPov(-1, id, 2);
                        joystick.SetDiscPov(-1, id, 3);
                        joystick.SetDiscPov(-1, id, 4);
                    };
                }
                ;

                System.Threading.Thread.Sleep(20);
                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
                count++;

                if (count > 640)
                {
                    count = 0;
                }
            } // While (Robust)
#endif // ROBUST
#if EFFICIENT
            byte[] pov = new byte[4];

            while (true)
            {
                iReport.bDevice  = (byte)id;
                iReport.AxisX    = X;
                iReport.AxisY    = Y;
                iReport.AxisZ    = Z;
                iReport.AxisZRot = ZR;
                iReport.AxisXRot = XR;

                // Set buttons one by one
                iReport.Buttons = (uint)(0x1 << (int)(count / 20));

                if (ContPovNumber > 0)
                {
                    // Make Continuous POV Hat spin
                    iReport.bHats    = (count * 70);
                    iReport.bHatsEx1 = (count * 70) + 3000;
                    iReport.bHatsEx2 = (count * 70) + 5000;
                    iReport.bHatsEx3 = 15000 - (count * 70);
                    if ((count * 70) > 36000)
                    {
                        iReport.bHats    = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx1 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx2 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx3 = 0xFFFFFFFF; // Neutral state
                    }
                    ;
                }
                else
                {
                    // Make 5-position POV Hat spin

                    pov[0] = (byte)(((count / 20) + 0) % 4);
                    pov[1] = (byte)(((count / 20) + 1) % 4);
                    pov[2] = (byte)(((count / 20) + 2) % 4);
                    pov[3] = (byte)(((count / 20) + 3) % 4);

                    iReport.bHats = (uint)(pov[3] << 12) | (uint)(pov[2] << 8) | (uint)(pov[1] << 4) | (uint)pov[0];
                    if ((count) > 550)
                    {
                        iReport.bHats = 0xFFFFFFFF;         // Neutral state
                    }
                };

                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    Console.WriteLine("Feeding vJoy device number {0} failed - try to enable device then press enter\n", id);
                    Console.ReadKey(true);
                    joystick.AcquireVJD(id);
                }

                System.Threading.Thread.Sleep(20);
                count++;
                if (count > 640)
                {
                    count = 0;
                }

                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
            }
            ; // While
#endif // EFFICIENT
        } // Main
        public TesterForm()
        {
            InitializeComponent();
            joystick = new vJoy();
            position = new vJoy.JoystickState();


            /////	General driver data
            short  iVer    = joystick.GetvJoyVersion();
            bool   enabled = joystick.vJoyEnabled();
            string Prd     = joystick.GetvJoyProductString();
            string Mnf     = joystick.GetvJoyManufacturerString();
            string Srl     = joystick.GetvJoySerialNumberString();
            string prt     = String.Format("Product: {0}; Version {1:X}; Manuf: {2}; Serial:{3}", Prd, iVer, Mnf, Srl);

            label1.Text   = prt;
            Enbld.Checked = enabled;

            /////	vJoy Device properties
            int  nBtn     = joystick.GetVJDButtonNumber(id);
            int  nDPov    = joystick.GetVJDDiscPovNumber(id);
            int  nCPov    = joystick.GetVJDContPovNumber(id);
            bool X_Exist  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_X);
            bool Y_Exist  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Y);
            bool Z_Exist  = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_Z);
            bool RX_Exist = joystick.GetVJDAxisExist(id, HID_USAGES.HID_USAGE_RX);

            prt         = String.Format("Device[{0}]: Buttons={1}; DiscPOVs:{2}; ContPOVs:{3}", id, nBtn, nDPov, nCPov);
            label2.Text = prt;

            UInt32 DllVer = 0, DrvVer = 0;
            bool   match = joystick.DriverMatch(ref DllVer, ref DrvVer);

            if (match)
            {
                prt = String.Format("Version of Driver Matches DLL Version {0:X}", DllVer);
            }
            else
            {
                prt = String.Format("Version of Driver ({0:X}) does NOT match DLL Version ({1:X})", DrvVer, DllVer);
            }
            label7.Text = prt;

            long max = 10, min = 10;
            bool ok;

            ok = joystick.GetVJDAxisMax(id, HID_USAGES.HID_USAGE_X, ref max);
            ok = joystick.GetVJDAxisMin(id, HID_USAGES.HID_USAGE_X, ref min);

            /////	Write access to vJoy Device - Basic
            VjdStat status;

            status = joystick.GetVJDStatus(id);
            bool acq = joystick.AcquireVJD(id);

            status = joystick.GetVJDStatus(id);

            position.AxisX      = 1000;
            position.AxisY      = 5000;
            position.AxisZ      = 10000;
            position.AxisXRot   = 20000;
            position.Buttons    = 0xA5A5A5A5;
            position.ButtonsEx1 = 0;
            bool upd = joystick.UpdateVJD(id, ref position);

            status = joystick.GetVJDStatus(id);

            //// Reset functions
            joystick.ResetButtons(id);

            // Register callback function
            // Function to register:     Removal()
            // User data to pass:        label2
            joystick.RegisterRemovalCB(Removal, label2);
        }
Example #25
0
 public override void SetState()
 {
     joystick.UpdateVJD((uint)id, ref state);
 }
Example #26
0
        public void joyThread()
        {
            while (true)
            {
                iReport.bDevice  = (byte)id;
                iReport.AxisX    = X;
                iReport.AxisY    = Y;
                iReport.AxisXRot = RX;
                iReport.AxisYRot = RY;

                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    Console.WriteLine("Feeding vJoy device number {0} failed - try to enable device then press enter\n", id);
                    System.Threading.Thread.Sleep(40);
                    joystick.AcquireVJD(id);
                }

                if (IsHandleCreated && chartCheckBox.Checked)
                {
                    long from = myCircularBuff.FindIndex(5000000);
                    long to   = myCircularBuff.buffLenght();

                    rollChart.Invoke((MethodInvoker) delegate
                    {
                        // Running on the UI thread
                        rollChart.Series["rollSeries"].Points.Clear();
                        if (from != -1)
                        {
                            for (long i = from; i < to; i++)
                            {
                                rollChart.Series["rollSeries"].Points.AddXY(myCircularBuff.Get(i).Timestamp, myCircularBuff.Get(i).Roll);
                            }
                        }
                    });
                    pitchChart.Invoke((MethodInvoker) delegate
                    {
                        // Running on the UI thread
                        pitchChart.Series["pitchSeries"].Points.Clear();
                        if (from != -1)
                        {
                            for (long i = from; i < to; i++)
                            {
                                pitchChart.Series["pitchSeries"].Points.AddXY(myCircularBuff.Get(i).Timestamp, myCircularBuff.Get(i).Pitch);
                            }
                        }
                    });
                    yawChart.Invoke((MethodInvoker) delegate
                    {
                        // Running on the UI thread
                        yawChart.Series["yawSeries"].Points.Clear();
                        if (from != -1)
                        {
                            for (long i = from; i < to; i++)
                            {
                                yawChart.Series["yawSeries"].Points.AddXY(myCircularBuff.Get(i).Timestamp, myCircularBuff.Get(i).Yaw);
                            }
                        }
                    });
                    heightChart.Invoke((MethodInvoker) delegate
                    {
                        // Running on the UI thread
                        heightChart.Series["heightSeries"].Points.Clear();
                        if (from != -1)
                        {
                            for (long i = from; i < to; i++)
                            {
                                heightChart.Series["heightSeries"].Points.AddXY(myCircularBuff.Get(i).Timestamp, myCircularBuff.Get(i).Height);
                            }
                        }
                    });
                }


                System.Threading.Thread.Sleep(40);
            }
        }
Example #27
0
        void Update()
        {
            iReport.bDevice  = (byte)deviceId;
            iReport2.bDevice = (byte)secondaryDeviceId;

            // Device 1, joystick/throttle
            if (!MapAxisEnabled)
            {
                var stick = stickAxis.WithDeadzone(joystickDeadzoneDegrees);

                iReport.AxisY    = ConvertStickAxisDegreesToAxisInt(deviceId, -stick.Pitch, HID_USAGES.HID_USAGE_Y);
                iReport.AxisX    = ConvertStickAxisDegreesToAxisInt(deviceId, stick.Roll, HID_USAGES.HID_USAGE_X);
                iReport.AxisZRot = ConvertStickAxisDegreesToAxisInt(deviceId, stick.Yaw, HID_USAGES.HID_USAGE_RZ);

                var dThrusters = thrusterAxis.WithDeadzone(directionalThrustersDeadzonePercentage / 100f);

                iReport.AxisXRot = ConvertAxisRatioToAxisInt(deviceId, dThrusters.Value.x, HID_USAGES.HID_USAGE_RX);
                iReport.AxisYRot = ConvertAxisRatioToAxisInt(deviceId, dThrusters.Value.y, HID_USAGES.HID_USAGE_RY);
                iReport.Slider   = ConvertAxisRatioToAxisInt(deviceId, dThrusters.Value.z, HID_USAGES.HID_USAGE_SL0);

                var throttleWithDeadZone = Mathf.Abs(throttle) < (throttleDeadzonePercentage / 100f) ? 0f : throttle;
                iReport.AxisZ = ConvertAxisRatioToAxisInt(deviceId, throttleWithDeadZone, HID_USAGES.HID_USAGE_Z);

                // @todo Sensor zoom azis
                iReport.Dial = ConvertAxisRatioToAxisInt(deviceId, sensorZoom, HID_USAGES.HID_USAGE_SL1);
            }
            else
            {
                // Make sure all the joystick axis are reset
                iReport.AxisY    = ConvertStickAxisDegreesToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_Y);
                iReport.AxisX    = ConvertStickAxisDegreesToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_X);
                iReport.AxisZRot = ConvertStickAxisDegreesToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_RZ);
                iReport.AxisXRot = ConvertAxisRatioToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_RX);
                iReport.AxisYRot = ConvertAxisRatioToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_RY);
                iReport.Slider   = ConvertAxisRatioToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_SL0);
                iReport.AxisZ    = ConvertAxisRatioToAxisInt(deviceId, 0, HID_USAGES.HID_USAGE_Z);
            }

            iReport.Buttons = buttons;

            iReport.bHats = (uint)((byte)hat[3] << 12)
                            | (uint)((byte)hat[2] << 8)
                            | (uint)((byte)hat[1] << 4)
                            | (uint)hat[0];

            // Device 2, primarily map
            if (MapAxisEnabled)
            {
                // Translation
                iReport2.AxisX = ConvertAxisRatioToAxisInt(secondaryDeviceId, mapTranslationAxis.x, HID_USAGES.HID_USAGE_X);
                iReport2.AxisY = ConvertAxisRatioToAxisInt(secondaryDeviceId, mapTranslationAxis.y, HID_USAGES.HID_USAGE_Y);
                iReport2.AxisZ = ConvertAxisRatioToAxisInt(secondaryDeviceId, mapTranslationAxis.z, HID_USAGES.HID_USAGE_Z);

                // Pitch / Yaw
                iReport2.AxisXRot = ConvertAxisRatioToAxisInt(secondaryDeviceId, -mapPitchAxis, HID_USAGES.HID_USAGE_RX);
                iReport2.AxisZRot = ConvertAxisRatioToAxisInt(secondaryDeviceId, mapYawAxis, HID_USAGES.HID_USAGE_RZ);

                // Zoom
                iReport2.Dial = ConvertAxisRatioToAxisInt(secondaryDeviceId, -mapZoomAxis, HID_USAGES.HID_USAGE_SL1);
            }
            else
            {
                // Make sure the map axis are reset
                iReport2.AxisX    = ConvertAxisRatioToAxisInt(secondaryDeviceId, 0, HID_USAGES.HID_USAGE_X);
                iReport2.AxisY    = ConvertAxisRatioToAxisInt(secondaryDeviceId, 0, HID_USAGES.HID_USAGE_Y);
                iReport2.AxisZ    = ConvertAxisRatioToAxisInt(secondaryDeviceId, 0, HID_USAGES.HID_USAGE_Z);
                iReport2.AxisXRot = ConvertAxisRatioToAxisInt(secondaryDeviceId, 0, HID_USAGES.HID_USAGE_RX);
                iReport2.AxisZRot = ConvertAxisRatioToAxisInt(secondaryDeviceId, 0, HID_USAGES.HID_USAGE_RZ);
                iReport2.Dial     = ConvertAxisRatioToAxisInt(secondaryDeviceId, 0, HID_USAGES.HID_USAGE_SL1);
            }

            if (!vjoy.UpdateVJD(deviceId, ref iReport))
            {
                Debug.LogFormat("vJoy Device {0} update failed", deviceId);
                SetStatus(VJoyStatus.DeviceError);
                enabled = false;
            }
            if (!vjoy.UpdateVJD(secondaryDeviceId, ref iReport2))
            {
                Debug.LogFormat("vJoy Device {0} update failed", secondaryDeviceId);
                SetStatus(VJoyStatus.DeviceError);
                enabled = false;
            }
        }
Example #28
0
        public void Feed(InputReport genericReport)
        {
            // Validation
            if (_joystick == null || _deviceId < 1)
            {
                throw new PTGenericException("vJoy not initialized. Cannot feed inputs.");
            }

            if (genericReport == null || _previousMessageId > genericReport.MessageTimestamp)
            {
                // If we've already processed a message from a future point in time,
                // then discard this message as it's no longer valid.
                return;
            }

            var buttonReport = genericReport.ButtonReport ?? new ButtonReport();
            var axisReport   = genericReport.AxisReport ?? new InputAxisReport {
                Axis1 = new Axis(), Axis2 = new Axis()
            };

            vJoy.JoystickState report = new vJoy.JoystickState();

            if (_axisX)
            {
                report.AxisX = GetAxisValue(axisReport.Axis1.X, _axisMinX, _axisMaxX);
            }

            if (_axisY)
            {
                report.AxisY = GetAxisValue(axisReport.Axis1.Y, _axisMinY, _axisMaxY);
            }

            if (_axisZ)
            {
                report.AxisZ = GetAxisValue(axisReport.Axis1.Z, _axisMinZ, _axisMaxZ);
            }

            if (_axisRX)
            {
                report.AxisXRot = GetAxisValue(axisReport.Axis2.X, _axisMinRX, _axisMaxRX);
            }

            if (_axisRY)
            {
                report.AxisYRot = GetAxisValue(axisReport.Axis2.Y, _axisMinRY, _axisMaxRY);
            }

            if (_axisRZ)
            {
                report.AxisZRot = GetAxisValue(axisReport.Axis2.Z, _axisMinRZ, _axisMaxRZ);
            }

            report.Buttons = (uint)buttonReport.Buttons;

            if (!_joystick.UpdateVJD(_deviceId, ref report))
            {
                if (!TryReconnect() || !_joystick.UpdateVJD(_deviceId, ref report))
                {
                    throw new PTGenericException($"Failed to feed vJoy device number '{_deviceId}'. Try reconnecting the device.");
                }
            }
        }
Example #29
0
        public void Feed(PhoneData data)
        {
            // Get the number of buttons and POV Hat switchessupported by this vJoy device
            int nButtons      = _joystick.GetVJDButtonNumber(_id);
            int contPovNumber = _joystick.GetVJDContPovNumber(_id);
            int discPovNumber = _joystick.GetVJDDiscPovNumber(_id);



            long maxval = 0;

            _joystick.GetVJDAxisMax(_id, HID_USAGES.HID_USAGE_X, ref maxval);

            _axisX = data.AxisX; if (_axisX > maxval)
            {
                _axisX = (int)maxval;
            }
            if (_axisX < 0)
            {
                _axisX = 0;
            }
            _axisY = data.AxisY; if (_axisY > maxval)
            {
                _axisY = (int)maxval;
            }
            if (_axisY < 0)
            {
                _axisY = 0;
            }
            _axisZ = data.AxisZ; if (_axisZ > maxval)
            {
                _axisZ = (int)maxval;
            }
            if (_axisZ < 0)
            {
                _axisZ = 0;
            }

            uint count = 0;

            byte[] pov = new byte[4];

            _joystickState.bDevice = (byte)_id;
            _joystickState.AxisX   = _axisX;
            _joystickState.AxisY   = _axisY;
            _joystickState.AxisZ   = _axisZ;

            var btn1 = data.Button1 == 0 ? 0 : 1;
            var btn2 = data.Button2 == 0 ? 0 : 2;
            var btn3 = data.Button3 == 0 ? 0 : 4;
            var btn4 = data.Button4 == 0 ? 0 : 8;

            _joystickState.Buttons = (uint)(btn1 | btn2 | btn3 | btn4);

            if (contPovNumber > 0)
            {
                _joystickState.bHats    = 0xFFFFFFFF;  // Neutral state
                _joystickState.bHatsEx1 = 0xFFFFFFFF;  // Neutral state
                _joystickState.bHatsEx2 = 0xFFFFFFFF;  // Neutral state
                _joystickState.bHatsEx3 = 0xFFFFFFFF;  // Neutral state
            }
            else
            {
                _joystickState.bHats = 0xFFFFFFFF;     // Neutral state
            };

            /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/

            if (!_joystick.UpdateVJD(_id, ref _joystickState))
            {
                Console.WriteLine("Feeding vJoy device number {0} failed - try to enable device then press enter\n", _id);
                Console.ReadKey(true);
                _joystick.AcquireVJD(_id);
            }

            System.Threading.Thread.Sleep(20);
            count++;

            if (count > 640)
            {
                count = 0;
            }
        }
Example #30
0
        static public void Feed(double frequency)
        {
            //int nButtons = joystick.GetVJDButtonNumber(id);
            //int ContPovNumber = joystick.GetVJDContPovNumber(id);
            //int DiscPovNumber = joystick.GetVJDDiscPovNumber(id);

            //long maxval = 0;

            joystick.GetVJDAxisMax(id, HID_USAGES.HID_USAGE_X, ref maxval);

#if ROBUST
            //joystick.ResetButtons(id);
            joystick.ResetAll();
            //MOFO CONTROL PANEL
            switch (Convert.ToInt32(frequency))
            {
            //32 main notes:

/*E3*/ case 82: joystick.SetAxis(Y + 100, id, HID_USAGES.HID_USAGE_Y); stat = "Y+"; break;

/*F3*/ case 87: joystick.SetAxis(X + 100, id, HID_USAGES.HID_USAGE_X); stat = "X+"; break;

/*F#3*/ case 92: joystick.SetAxis(RZ + 100, id, HID_USAGES.HID_USAGE_RZ); stat = "RZ+"; break;

/*G3*/ case 98: joystick.SetAxis(Z + 100, id, HID_USAGES.HID_USAGE_Z); stat = "Z+"; break;

/*G#3*/ case 104: break;

/*A3*/ case 110: joystick.SetAxis(Y - 100, id, HID_USAGES.HID_USAGE_Y); stat = "Y-"; break;

/*A#3*/ case 117: joystick.SetAxis(X - 100, id, HID_USAGES.HID_USAGE_X); stat = "X-"; break;

/*B3*/ case 123: joystick.SetAxis(RZ - 100, id, HID_USAGES.HID_USAGE_RZ); stat = "RZ-"; break;

/*C4*/ case 131: joystick.SetAxis(Z - 100, id, HID_USAGES.HID_USAGE_Z); stat = "Z-"; break;

/*C#4*/ case 139: break;

/*D4*/ case 147: joystick.SetBtn(true, id, 1); stat = "1"; break;

/*D#4*/ case 156: joystick.SetBtn(true, id, 2); stat = "2"; break;

/*E4*/ case 165: joystick.SetBtn(true, id, 3); stat = "3"; break;

/*F4*/ case 175: joystick.SetBtn(true, id, 4); stat = "4"; break;

/*F#4*/ case 185: joystick.SetBtn(true, id, 5); stat = "5"; break;

/*G4*/ case 196: joystick.SetBtn(true, id, 6); stat = "6"; break;

/*G#4*/ case 208: joystick.SetBtn(true, id, 7); stat = "7"; break;

/*A4*/ case 220: joystick.SetBtn(true, id, 8); stat = "8"; break;

/*A#4*/ case 233: joystick.SetBtn(true, id, 9); stat = "9"; break;

/*B4*/ case 247: joystick.SetBtn(true, id, 10); stat = "10"; break;

/*C5*/ case 262: joystick.SetBtn(true, id, 11); stat = "11"; break;

/*C#5*/ case 277: joystick.SetBtn(true, id, 12); stat = "12"; break;

/*D5*/ case 294: joystick.SetBtn(true, id, 13); stat = "13"; break;

/*D#5*/ case 311: joystick.SetBtn(true, id, 14); stat = "14"; break;

/*E5*/ case 329: break;

/*F5*/ case 349: break;

/*F#5*/ case 370: break;

/*G5*/ case 392: break;

/*G#5*/ case 415: break;

/*A5*/ case 440: break;

/*A#5*/ case 466: break;

/*B5*/ case 494: break;

            //stab: joystick.SetBtn(false, id, 1);

            //13 additional notes:
/*C6*/ case 523: break;

/*C#6*/ case 554: break;

/*D6*/ case 587: break;

/*D#6*/ case 622: break;

/*E6*/ case 659: break;

/*F6*/ case 698: break;

/*F#6*/ case 740: break;

/*G6*/ case 784: break;

/*G#6*/ case 831: break;

/*A6*/ case 880: break;

/*A#6*/ case 932: break;

/*B6*/ case 988: break;

/*C7*/ case 1047: break;

            default: break;
            }

            /*
             *  // Feed the device in endless loop
             * while (true)
             * {
             *  // Set position of 4 axes
             *  res = joystick.SetAxis(X, id, HID_USAGES.HID_USAGE_X);
             *  res = joystick.SetAxis(Y, id, HID_USAGES.HID_USAGE_Y);
             *  res = joystick.SetAxis(Z, id, HID_USAGES.HID_USAGE_Z);
             *  res = joystick.SetAxis(XR, id, HID_USAGES.HID_USAGE_RX);
             *  res = joystick.SetAxis(ZR, id, HID_USAGES.HID_USAGE_RZ);
             *
             *  // Press/Release Buttons
             *  res = joystick.SetBtn(true, id, count / 50);
             *  res = joystick.SetBtn(false, id, 1 + count / 50);
             *
             *  // If Continuous POV hat switches installed - make them go round
             *  // For high values - put the switches in neutral state
             *  if (ContPovNumber>0)
             *  {
             *      if ((count * 70) < 30000)
             *      {
             *          res = joystick.SetContPov(((int)count * 70), id, 1);
             *          res = joystick.SetContPov(((int)count * 70) + 2000, id, 2);
             *          res = joystick.SetContPov(((int)count * 70) + 4000, id, 3);
             *          res = joystick.SetContPov(((int)count * 70) + 6000, id, 4);
             *      }
             *      else
             *      {
             *          res = joystick.SetContPov(-1, id, 1);
             *          res = joystick.SetContPov(-1, id, 2);
             *          res = joystick.SetContPov(-1, id, 3);
             *          res = joystick.SetContPov(-1, id, 4);
             *      };
             *  };
             *
             *  // If Discrete POV hat switches installed - make them go round
             *  // From time to time - put the switches in neutral state
             *  if (DiscPovNumber>0)
             *  {
             *      if (count < 550)
             *      {
             *          joystick.SetDiscPov((((int)count / 20) + 0) % 4, id, 1);
             *          joystick.SetDiscPov((((int)count / 20) + 1) % 4, id, 2);
             *          joystick.SetDiscPov((((int)count / 20) + 2) % 4, id, 3);
             *          joystick.SetDiscPov((((int)count / 20) + 3) % 4, id, 4);
             *      }
             *      else
             *      {
             *          joystick.SetDiscPov(-1, id, 1);
             *          joystick.SetDiscPov(-1, id, 2);
             *          joystick.SetDiscPov(-1, id, 3);
             *          joystick.SetDiscPov(-1, id, 4);
             *      };
             *  };
             *
             *  System.Threading.Thread.Sleep(20);
             *
             * } // While (Robust)
             */
#endif // ROBUST
#if EFFICIENT
            byte[] pov = new byte[4];

            while (true)
            {
                iReport.bDevice  = (byte)id;
                iReport.AxisX    = X;
                iReport.AxisY    = Y;
                iReport.AxisZ    = Z;
                iReport.AxisZRot = ZR;
                iReport.AxisXRot = XR;

                // Set buttons one by one
                iReport.Buttons = (uint)(0x1 << (int)(count / 20));

                if (ContPovNumber > 0)
                {
                    // Make Continuous POV Hat spin
                    iReport.bHats    = (count * 70);
                    iReport.bHatsEx1 = (count * 70) + 3000;
                    iReport.bHatsEx2 = (count * 70) + 5000;
                    iReport.bHatsEx3 = 15000 - (count * 70);
                    if ((count * 70) > 36000)
                    {
                        iReport.bHats    = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx1 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx2 = 0xFFFFFFFF; // Neutral state
                        iReport.bHatsEx3 = 0xFFFFFFFF; // Neutral state
                    }
                    ;
                }
                else
                {
                    // Make 5-position POV Hat spin

                    pov[0] = (byte)(((count / 20) + 0) % 4);
                    pov[1] = (byte)(((count / 20) + 1) % 4);
                    pov[2] = (byte)(((count / 20) + 2) % 4);
                    pov[3] = (byte)(((count / 20) + 3) % 4);

                    iReport.bHats = (uint)(pov[3] << 12) | (uint)(pov[2] << 8) | (uint)(pov[1] << 4) | (uint)pov[0];
                    if ((count) > 550)
                    {
                        iReport.bHats = 0xFFFFFFFF;         // Neutral state
                    }
                };

                /*** Feed the driver with the position packet - is fails then wait for input then try to re-acquire device ***/
                if (!joystick.UpdateVJD(id, ref iReport))
                {
                    Console.WriteLine("Feeding vJoy device number {0} failed - try to enable device then press enter\n", id);
                    Console.ReadKey(true);
                    joystick.AcquireVJD(id);
                }

                System.Threading.Thread.Sleep(20);
                count++;
                if (count > 640)
                {
                    count = 0;
                }

                X += 150; if (X > maxval)
                {
                    X = 0;
                }
                Y += 250; if (Y > maxval)
                {
                    Y = 0;
                }
                Z += 350; if (Z > maxval)
                {
                    Z = 0;
                }
                XR += 220; if (XR > maxval)
                {
                    XR = 0;
                }
                ZR += 200; if (ZR > maxval)
                {
                    ZR = 0;
                }
            }
            ; // While
#endif // EFFICIENT
        } // Main