コード例 #1
0
    // Token: 0x06000D52 RID: 3410 RVA: 0x000538FC File Offset: 0x00051AFC
    public static int GetDeviceIndex(SteamVR_Controller.DeviceRelation relation, ETrackedDeviceClass deviceClass = ETrackedDeviceClass.Controller, int relativeTo = 0)
    {
        int result = -1;

        SteamVR_Utils.RigidTransform t = (relativeTo < 16) ? SteamVR_Controller.Input(relativeTo).transform.GetInverse() : SteamVR_Utils.RigidTransform.identity;
        CVRSystem system = OpenVR.System;

        if (system == null)
        {
            return(result);
        }
        float num  = float.MinValue;
        int   num2 = 0;

        while ((long)num2 < 16L)
        {
            if (num2 != relativeTo && system.GetTrackedDeviceClass((uint)num2) == deviceClass)
            {
                SteamVR_Controller.Device device = SteamVR_Controller.Input(num2);
                if (device.connected)
                {
                    if (relation == SteamVR_Controller.DeviceRelation.First)
                    {
                        return(num2);
                    }
                    Vector3 vector = t * device.transform.pos;
                    float   num3;
                    if (relation == SteamVR_Controller.DeviceRelation.FarthestRight)
                    {
                        num3 = vector.x;
                    }
                    else if (relation == SteamVR_Controller.DeviceRelation.FarthestLeft)
                    {
                        num3 = -vector.x;
                    }
                    else
                    {
                        Vector3 normalized = new Vector3(vector.x, 0f, vector.z).normalized;
                        float   num4       = Vector3.Dot(normalized, Vector3.forward);
                        Vector3 vector2    = Vector3.Cross(normalized, Vector3.forward);
                        if (relation == SteamVR_Controller.DeviceRelation.Leftmost)
                        {
                            num3 = ((vector2.y > 0f) ? (2f - num4) : num4);
                        }
                        else
                        {
                            num3 = ((vector2.y < 0f) ? (2f - num4) : num4);
                        }
                    }
                    if (num3 > num)
                    {
                        result = num2;
                        num    = num3;
                    }
                }
            }
            num2++;
        }
        return(result);
    }
コード例 #2
0
        public override void Evaluate(int SpreadMax, CVRSystem system)
        {
            FSystem = system;

            if (OpenVRManager.RenderPoses == null)
            {
                return;
            }

            //poses
            var poseCount      = (int)OpenVR.k_unMaxTrackedDeviceCount;
            var renderPoses    = OpenVRManager.RenderPoses;
            var gamePoses      = OpenVRManager.GamePoses;
            var refreshSerials = FRefreshSerials[0] || FFirstFrame;

            FRenderPosesOut.SliceCount     = poseCount;
            FGamePosesOut.SliceCount       = poseCount;
            FDeviceClassOut.SliceCount     = poseCount;
            FDeviceSerialOut.SliceCount    = poseCount;
            FLighthousePosesOut.SliceCount = 0;
            FControllerPosesOut.SliceCount = 0;
            FTrackerPosesOut.SliceCount    = 0;
            if (refreshSerials)
            {
                FTrackerSerialOut.SliceCount = 0;
            }

            for (int i = 0; i < poseCount; i++)
            {
                FRenderPosesOut[i] = renderPoses[i].mDeviceToAbsoluteTracking.ToMatrix();
                FGamePosesOut[i]   = gamePoses[i].mDeviceToAbsoluteTracking.ToMatrix();
                var deviceClass = system.GetTrackedDeviceClass((uint)i);
                FDeviceClassOut[i] = deviceClass.ToString();
                if (refreshSerials)
                {
                    FDeviceSerialOut[i] = GetSerial(i);
                }

                if (deviceClass == ETrackedDeviceClass.TrackingReference)
                {
                    FLighthousePosesOut.Add(FGamePosesOut[i]);
                }

                if (deviceClass == ETrackedDeviceClass.Controller)
                {
                    FControllerPosesOut.Add(FGamePosesOut[i]);
                }

                if (deviceClass == ETrackedDeviceClass.GenericTracker)
                {
                    FTrackerPosesOut.Add(FGamePosesOut[i]);
                    if (refreshSerials)
                    {
                        FTrackerSerialOut.Add(FDeviceSerialOut[i]);
                    }
                }
            }

            FHMDPoseOut[0] = FRenderPosesOut[0];
        }
コード例 #3
0
ファイル: OpenVRWrapper.cs プロジェクト: you-ri/VMCStudio
        public Dictionary <ETrackedDeviceClass, List <KeyValuePair <SteamVR_Utils.RigidTransform, string> > > GetTrackerPositions()
        {
            var positions = new Dictionary <ETrackedDeviceClass, List <KeyValuePair <SteamVR_Utils.RigidTransform, string> > > ();

            positions.Add(ETrackedDeviceClass.HMD, new List <KeyValuePair <SteamVR_Utils.RigidTransform, string> > ());
            positions.Add(ETrackedDeviceClass.Controller, new List <KeyValuePair <SteamVR_Utils.RigidTransform, string> > ());
            positions.Add(ETrackedDeviceClass.GenericTracker, new List <KeyValuePair <SteamVR_Utils.RigidTransform, string> > ());
            positions.Add(ETrackedDeviceClass.TrackingReference, new List <KeyValuePair <SteamVR_Utils.RigidTransform, string> > ());
            TrackedDevicePose_t[] allPoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
            if (serialNumbers == null)
            {
                serialNumbers = new string[OpenVR.k_unMaxTrackedDeviceCount];
            }
            //TODO: TrackingUniverseStanding??
            openvr.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, allPoses);
            for (uint i = 0; i < allPoses.Length; i++)
            {
                var pose = allPoses[i];
                //0:HMD 1:LeftHand 2:RightHand ??
                var deviceClass = openvr.GetTrackedDeviceClass(i);
                if (pose.bDeviceIsConnected && (deviceClass == ETrackedDeviceClass.HMD || deviceClass == ETrackedDeviceClass.Controller || deviceClass == ETrackedDeviceClass.GenericTracker || deviceClass == ETrackedDeviceClass.TrackingReference))
                {
                    if (serialNumbers[i] == null)
                    {
                        serialNumbers[i] = GetTrackerSerialNumber(i);
                    }
                    positions[deviceClass].Add(new KeyValuePair <SteamVR_Utils.RigidTransform, string> (new SteamVR_Utils.RigidTransform(pose.mDeviceToAbsoluteTracking), serialNumbers[i]));
                }
            }
            return(positions);
        }
コード例 #4
0
        private string GetClass()
        {
            var type = vr.GetTrackedDeviceClass(this.index);

            if (type == ETrackedDeviceClass.Controller)
            {
                this.TrackedDevices.Controllers += 1;
                this.TrackedDevices.IndexesByClasses["Controller"].Add(Convert.ToInt16(index));
                return("Controller");
            }
            if (type == ETrackedDeviceClass.HMD)
            {
                this.TrackedDevices.HMDs += 1;
                this.TrackedDevices.IndexesByClasses["HMD"].Add(Convert.ToInt16(index));
                return("HMD");
            }
            if (type == ETrackedDeviceClass.Tracker)
            {
                this.TrackedDevices.Trackers += 1;
                this.TrackedDevices.IndexesByClasses["Tracker"].Add(Convert.ToInt16(index));
                return("Tracker");
            }
            if (type == ETrackedDeviceClass.TrackingReference)
            {
                this.TrackedDevices.TrackingReferences += 1;
                this.TrackedDevices.IndexesByClasses["Lighthouse"].Add(Convert.ToInt16(index));
                return("Lighthouse");
            }
            return("unknown");
        }
コード例 #5
0
        /// <summary>
        /// Updates the devices.
        /// </summary>
        public override void UpdateDevices()
        {
            // Get indexes of left and right controllers
            _leftControllerIndex  = -1;
            _rightControllerIndex = -1;
            int lhIndex = (int)_vrSystem.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.LeftHand);
            int rhIndex = (int)_vrSystem.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.RightHand);

            _controllers.Clear();
            _trackingReferences.Clear();

            // Update all tracked devices
            for (uint i = 0; i < OVR.k_unMaxTrackedDeviceCount; i++)
            {
                TrackedDevicePose_t pose = _devicePoses[i];

                // We are interested in valid and connected devices only
                if (pose.bDeviceIsConnected && pose.bPoseIsValid)
                {
                    ToVRPose(pose, out Vector3 posePosition, out Quaternion poseOrientation);
                    ETrackedDeviceClass c = _vrSystem.GetTrackedDeviceClass(i);

                    // Update controller
                    if (c == ETrackedDeviceClass.Controller)
                    {
                        VRControllerState_t state_t = default(VRControllerState_t);
                        if (_vrSystem.GetControllerState(i, ref state_t, (uint)System.Runtime.InteropServices.Marshal.SizeOf(state_t)))
                        {
                            VRControllerRole role;
                            if (i == lhIndex)
                            {
                                role = VRControllerRole.LeftHand;
                                _leftControllerIndex = _controllers.Count;
                            }
                            else if (i == rhIndex)
                            {
                                role = VRControllerRole.RightHand;
                                _rightControllerIndex = _controllers.Count;
                            }
                            else
                            {
                                role = VRControllerRole.Undefined;
                            }

                            VRControllerState state = new VRControllerState();
                            state.Update(role, ref state_t, posePosition, poseOrientation);
                            _controllers.Add(state);
                        }
                    }
                    // Update generic reference (base station etc...)
                    else if (c == ETrackedDeviceClass.TrackingReference)
                    {
                        VRTrackingReference reference = new VRTrackingReference();
                        reference.Update(posePosition, poseOrientation);
                        _trackingReferences.Add(reference);
                    }
                }
            }
        }
コード例 #6
0
 public static IEnumerable <int> DevicesInClass(this CVRSystem hmd, ETrackedDeviceClass devClass)
 {
     if (hmd == null)
     {
         throw new ArgumentNullException(nameof(hmd));
     }
     return(DeviceIndexes.Where(i => hmd.GetTrackedDeviceClass((uint)i) == devClass));
 }
コード例 #7
0
        private void TrackingLoop()
        {
            try
            {
                EVRInitError initError = EVRInitError.None;
                CVRSystem    cvrSystem = OpenVR.Init(ref initError, EVRApplicationType.VRApplication_Utility);
                var          chaperone = OpenVR.Chaperone;
                var          quadArea  = new HmdQuad_t();
                chaperone.GetPlayAreaRect(ref quadArea);
                _playArea = quadArea.ToPlayArea();
                if (initError != EVRInitError.None)
                {
                    throw new InvalidOperationException($"EVR init erro: {initError}");
                }
                while (_keepReading)
                {
                    TrackedDevicePose_t[] trackedDevicePoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
                    cvrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0f, trackedDevicePoses);
                    for (uint trackedDeviceIndex = 0; trackedDeviceIndex < OpenVR.k_unMaxTrackedDeviceCount; trackedDeviceIndex++)
                    {
                        if (cvrSystem.IsTrackedDeviceConnected(trackedDeviceIndex))
                        {
                            ETrackedDeviceClass deviceClass = cvrSystem.GetTrackedDeviceClass(trackedDeviceIndex);
                            if (true)
                            {
                                VRControllerState_t controllerState = new VRControllerState_t();
                                cvrSystem.GetControllerState(1, ref controllerState, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t)));
                                ETrackingResult trackingResult = trackedDevicePoses[trackedDeviceIndex].eTrackingResult;

                                bool trigger    = controllerState.rAxis1.x > 0.9f;
                                bool menuButton = (controllerState.ulButtonPressed & (1ul << (int)EVRButtonId.k_EButton_ApplicationMenu)) != 0;
                                bool gripButton = (controllerState.ulButtonPressed & (1ul << (int)EVRButtonId.k_EButton_Grip)) != 0;

                                if (trackingResult == ETrackingResult.Running_OK)
                                {
                                    HmdMatrix34_t trackingMatrix = trackedDevicePoses[trackedDeviceIndex].mDeviceToAbsoluteTracking;

                                    Vector3            speedVector    = trackedDevicePoses[trackedDeviceIndex].vVelocity.ToVelocityVector();
                                    Vector3            position       = trackingMatrix.ToPositionVector();
                                    DeviceTrackingData trackingUpdate = new DeviceTrackingData((int)trackedDeviceIndex, deviceClass.ToString(), position, trackingMatrix.ToRotationQuaternion());
                                    NewPoseUpdate?.Invoke(this, trackingUpdate);
                                }
                            }
                        }
                    }
                    Thread.Sleep(UpdatedInterval);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e}");
            }
            finally
            {
                OpenVR.Shutdown();
            }
        }
コード例 #8
0
        public static int GetDeviceIndex(DeviceRelation relation, ETrackedDeviceClass deviceClass = ETrackedDeviceClass.Controller, int relativeTo = 0)
        {
            int result = -1;

            SteamVR_Utils.RigidTransform t = ((uint)relativeTo >= 64u) ? SteamVR_Utils.RigidTransform.identity : Input(relativeTo).transform.GetInverse();
            CVRSystem system = OpenVR.System;

            if (system == null)
            {
                return(result);
            }
            float num = float.MinValue;

            for (int i = 0; (long)i < 64L; i++)
            {
                if (i == relativeTo || system.GetTrackedDeviceClass((uint)i) != deviceClass)
                {
                    continue;
                }
                Device device = Input(i);
                if (device.connected)
                {
                    if (relation == DeviceRelation.First)
                    {
                        return(i);
                    }
                    SteamVR_Utils.RigidTransform transform = device.transform;
                    Vector3 vector = t * transform.pos;
                    float   num3;
                    switch (relation)
                    {
                    case DeviceRelation.FarthestRight:
                        num3 = vector.x;
                        break;

                    case DeviceRelation.FarthestLeft:
                        num3 = 0f - vector.x;
                        break;

                    default:
                    {
                        Vector3 normalized = new Vector3(vector.x, 0f, vector.z).normalized;
                        float   num2       = Vector3.Dot(normalized, Vector3.forward);
                        Vector3 vector2    = Vector3.Cross(normalized, Vector3.forward);
                        num3 = ((relation != DeviceRelation.Leftmost) ? ((!(vector2.y < 0f)) ? num2 : (2f - num2)) : ((!(vector2.y > 0f)) ? num2 : (2f - num2)));
                        break;
                    }
                    }
                    if (num3 > num)
                    {
                        result = i;
                        num    = num3;
                    }
                }
            }
            return(result);
        }
コード例 #9
0
 private void PrintOpenVRDevices()
 {
     for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
     {
         var deviceClass = vrSystem.GetTrackedDeviceClass(i);
         if (deviceClass != ETrackedDeviceClass.Invalid)
         {
             Debug.Log("OpenVR device at " + i + ": " + deviceClass);
         }
     }
 }
コード例 #10
0
        private static void SteamVr()
        {
            Console.WriteLine("Starting");
            EVRInitError initError = EVRInitError.None;
            CVRSystem    cvrSystem = OpenVR.Init(ref initError, EVRApplicationType.VRApplication_Utility);

            Console.WriteLine("Error: " + initError.ToString());
            if (cvrSystem == null)
            {
                Console.WriteLine("Error!");
            }
            while (true)
            {
                Thread.Sleep(1);
                TrackedDevicePose_t[] trackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
                cvrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseRawAndUncalibrated, 0f, trackedDevicePose);
                VRControllerState_t controllerState = new VRControllerState_t();
                cvrSystem.GetControllerState(1, ref controllerState,
                                             (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t)));
                int  trigger   = controllerState.rAxis1.x > 0.9f ? 1 : 0;
                bool topButtom = (controllerState.ulButtonPressed & (1ul << (int)EVRButtonId.k_EButton_ApplicationMenu)) != 0;

                TrackedDevicePose_t pose           = trackedDevicePose[1];
                ETrackingResult     trackingResult = pose.eTrackingResult;
                HmdMatrix34_t       hmdMatrix      = pose.mDeviceToAbsoluteTracking;
                Position            pos            = new Position(hmdMatrix);
                Rotation            rot            = new Rotation(hmdMatrix);
                Console.WriteLine($"Position: {pos} Rotation: {rot} trigger {trigger} app {topButtom}");
                foreach (Socket client in _clients.ToArray())
                {
                    try
                    {
                        client.Send(Encoding.ASCII.GetBytes($"S{pos.ToData()} {rot.ToData()} {trigger} {(topButtom ? 1 : 0)}E"));
                    }
                    catch (Exception)
                    {
                        _clients.Remove(client);
                    }
                }
            }
            for (int i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                if (cvrSystem?.IsTrackedDeviceConnected((uint)i) ?? false)
                {
                    ETrackedDeviceClass deviceClass = cvrSystem.GetTrackedDeviceClass((uint)i);
                    Console.WriteLine($"index: {i} is {deviceClass}");
                }
            }
            Console.ReadLine();
            OpenVR.Shutdown();
            Console.WriteLine("Shut down");
            Console.ReadLine();
        }
コード例 #11
0
 private void ShowOpenVRDevices()
 {
     for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
     {
         var deviceClass = vrSystem.GetTrackedDeviceClass(i);
         if (deviceClass != ETrackedDeviceClass.Invalid)
         {
             var deviceReading = deviceClass.ToString();
             Devices[i] = deviceReading;
         }
     }
 }
コード例 #12
0
ファイル: SteamVR_Frustum.cs プロジェクト: ahvonenj/TheForest
    private void OnDeviceConnected(params object[] args)
    {
        int num = (int)args[0];

        if (num != (int)this.index)
        {
            return;
        }
        base.GetComponent <MeshFilter>().mesh = null;
        bool flag = (bool)args[1];

        if (flag)
        {
            CVRSystem system = OpenVR.System;
            if (system != null && system.GetTrackedDeviceClass((uint)num) == ETrackedDeviceClass.TrackingReference)
            {
                ETrackedPropertyError eTrackedPropertyError = ETrackedPropertyError.TrackedProp_Success;
                float floatTrackedDeviceProperty            = system.GetFloatTrackedDeviceProperty((uint)num, ETrackedDeviceProperty.Prop_FieldOfViewLeftDegrees_Float, ref eTrackedPropertyError);
                if (eTrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    this.fovLeft = floatTrackedDeviceProperty;
                }
                floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)num, ETrackedDeviceProperty.Prop_FieldOfViewRightDegrees_Float, ref eTrackedPropertyError);
                if (eTrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    this.fovRight = floatTrackedDeviceProperty;
                }
                floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)num, ETrackedDeviceProperty.Prop_FieldOfViewTopDegrees_Float, ref eTrackedPropertyError);
                if (eTrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    this.fovTop = floatTrackedDeviceProperty;
                }
                floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)num, ETrackedDeviceProperty.Prop_FieldOfViewBottomDegrees_Float, ref eTrackedPropertyError);
                if (eTrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    this.fovBottom = floatTrackedDeviceProperty;
                }
                floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)num, ETrackedDeviceProperty.Prop_TrackingRangeMinimumMeters_Float, ref eTrackedPropertyError);
                if (eTrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    this.nearZ = floatTrackedDeviceProperty;
                }
                floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)num, ETrackedDeviceProperty.Prop_TrackingRangeMaximumMeters_Float, ref eTrackedPropertyError);
                if (eTrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    this.farZ = floatTrackedDeviceProperty;
                }
                this.UpdateModel();
            }
        }
    }
コード例 #13
0
 void SetDeviceIds()
 {
     _validDeviceIds.Clear();
     for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
     {
         var deviceClass = _vrSystem.GetTrackedDeviceClass(i);
         if (deviceClass != ETrackedDeviceClass.Invalid && deviceClass == targetClass)
         {
             Debug.Log("OpenVR device at " + i + ": " + deviceClass);
             _validDeviceIds.Add((int)i);
             targetObjs[_validDeviceIds.Count - 1].SetActive(true);
         }
     }
 }
コード例 #14
0
ファイル: OpenVRService.cs プロジェクト: sjb8100/C3DE
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            VREvent_t evt = new VREvent_t();

            while (_hmd.PollNextEvent(ref evt, (uint)Marshal.SizeOf(evt)))
            {
                ProcessEvent(ref evt);
            }

            _validPoseCount          = 0;
            _trackedControllerCount  = 0;
            _leftControllerDeviceID  = -1;
            _rightControllerDeviceID = -1;

            OpenVR.Compositor.WaitGetPoses(_trackedDevices, _gamePose);

            for (var i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; ++i)
            {
                if (_trackedDevices[i].bPoseIsValid)
                {
                    _validPoseCount++;
                    _devicePoses[i] = _trackedDevices[i].mDeviceToAbsoluteTracking.ToXNA();

                    if (_hmd.GetTrackedDeviceClass((uint)i) == ETrackedDeviceClass.Controller)
                    {
                        _trackedControllerCount++;

                        if (_hmd.GetControllerRoleForTrackedDeviceIndex((uint)i) == ETrackedControllerRole.LeftHand)
                        {
                            _leftControllerDeviceID = i;
                            _leftControllerPose     = _devicePoses[i];
                        }
                        else if (_hmd.GetControllerRoleForTrackedDeviceIndex((uint)i) == ETrackedControllerRole.RightHand)
                        {
                            _rightControllerDeviceID = i;
                            _rightControllerPose     = _devicePoses[i];
                        }
                    }
                }
            }

            if (_trackedDevices[OpenVR.k_unTrackedDeviceIndex_Hmd].bPoseIsValid)
            {
                _hmdPose = _devicePoses[OpenVR.k_unTrackedDeviceIndex_Hmd];
            }
        }
コード例 #15
0
    // show vr devices (hmd,tracker..etc) and populate in string array
    private void ShowOpenVRDevices()
    {
        int index = 0;

        for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
        {
            var deviceClass = vrSystem.GetTrackedDeviceClass(i);
            if (deviceClass == ETrackedDeviceClass.GenericTracker)
            {
                var deviceReading = deviceClass.ToString();
                Devices[index]         = deviceReading;
                genericTrackers[index] = (int)i;
                index++;
            }
        }
    }
コード例 #16
0
 // Token: 0x06000D8A RID: 3466 RVA: 0x00055420 File Offset: 0x00053620
 private void OnDeviceConnected(int i, bool connected)
 {
     if (i != (int)this.index)
     {
         return;
     }
     base.GetComponent <MeshFilter>().mesh = null;
     if (connected)
     {
         CVRSystem system = OpenVR.System;
         if (system != null && system.GetTrackedDeviceClass((uint)i) == ETrackedDeviceClass.TrackingReference)
         {
             ETrackedPropertyError etrackedPropertyError = ETrackedPropertyError.TrackedProp_Success;
             float floatTrackedDeviceProperty            = system.GetFloatTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_FieldOfViewLeftDegrees_Float, ref etrackedPropertyError);
             if (etrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
             {
                 this.fovLeft = floatTrackedDeviceProperty;
             }
             floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_FieldOfViewRightDegrees_Float, ref etrackedPropertyError);
             if (etrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
             {
                 this.fovRight = floatTrackedDeviceProperty;
             }
             floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_FieldOfViewTopDegrees_Float, ref etrackedPropertyError);
             if (etrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
             {
                 this.fovTop = floatTrackedDeviceProperty;
             }
             floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_FieldOfViewBottomDegrees_Float, ref etrackedPropertyError);
             if (etrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
             {
                 this.fovBottom = floatTrackedDeviceProperty;
             }
             floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_TrackingRangeMinimumMeters_Float, ref etrackedPropertyError);
             if (etrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
             {
                 this.nearZ = floatTrackedDeviceProperty;
             }
             floatTrackedDeviceProperty = system.GetFloatTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_TrackingRangeMaximumMeters_Float, ref etrackedPropertyError);
             if (etrackedPropertyError == ETrackedPropertyError.TrackedProp_Success)
             {
                 this.farZ = floatTrackedDeviceProperty;
             }
             this.UpdateModel();
         }
     }
 }
コード例 #17
0
        void ProcessEvent(VREvent_t vrEvent)
        {
            //Console.WriteLine((EVREventType) vrEvent.eventType);

            switch ((EVREventType)vrEvent.eventType)
            {
            case EVREventType.VREvent_StandingZeroPoseReset:
                break;
            }

            ETrackedDeviceClass trackedDeviceClass = vrContext.GetTrackedDeviceClass(vrEvent.trackedDeviceIndex);

            if (trackedDeviceClass != ETrackedDeviceClass.Controller)
            {
                return;
            }


            controllerSystem.ProcessInputEvent(vrEvent);

            /*
             * if (vrEvent.eventType == (uint)EVREventType.VREvent_ButtonPress)
             * {
             *
             * }
             * else if (vrEvent.eventType == (uint)EVREventType.VREvent_ButtonTouch)
             * {
             *
             * }
             * else if (vrEvent.eventType == (uint)EVREventType.VREvent_ButtonUnpress)
             * {
             *
             * }
             * else if (vrEvent.eventType == (uint)EVREventType.VREvent_ButtonUntouch)
             * {
             *
             * }
             * else if (vrEvent.eventType == (uint)EVREventType.VREvent_TouchPadMove)
             * {
             *  //Console.WriteLine((EVRButtonId)vrEvent.data.touchPadMove.fValueXFirst);
             *  //Console.WriteLine((EVRButtonId)vrEvent.data.touchPadMove.fValueYFirst);
             * }
             */
            //Console.WriteLine(compositor.GetLastFrameRenderer());
        }
コード例 #18
0
    // Token: 0x06000DFB RID: 3579 RVA: 0x00058FAC File Offset: 0x000571AC
    private void OnDeviceConnected(int index, bool connected)
    {
        CVRSystem system = OpenVR.System;

        if (system == null || system.GetTrackedDeviceClass((uint)index) != ETrackedDeviceClass.Controller)
        {
            return;
        }
        if (connected)
        {
            Debug.Log(string.Format("Controller {0} connected.", index));
            this.PrintControllerStatus(index);
            this.controllerIndices.Add(index);
            return;
        }
        Debug.Log(string.Format("Controller {0} disconnected.", index));
        this.PrintControllerStatus(index);
        this.controllerIndices.Remove(index);
    }
コード例 #19
0
    private void OnDeviceConnected(params object[] args)
    {
        uint num  = (uint)((int)args[0]);
        bool flag = this.connected[(int)((UIntPtr)num)];

        this.connected[(int)((UIntPtr)num)] = false;
        bool flag2 = (bool)args[1];

        if (flag2)
        {
            CVRSystem system = OpenVR.System;
            if (system != null && system.GetTrackedDeviceClass(num) == ETrackedDeviceClass.Controller)
            {
                this.connected[(int)((UIntPtr)num)] = true;
                flag = !flag;
            }
        }
        if (flag)
        {
            this.Refresh();
        }
    }
コード例 #20
0
    // Token: 0x06005ED4 RID: 24276 RVA: 0x00213068 File Offset: 0x00211468
    private void OnDeviceConnected(int index, bool connected)
    {
        bool flag = this.connected[index];

        this.connected[index] = false;
        if (connected)
        {
            CVRSystem system = OpenVR.System;
            if (system != null)
            {
                ETrackedDeviceClass trackedDeviceClass = system.GetTrackedDeviceClass((uint)index);
                if (trackedDeviceClass == ETrackedDeviceClass.Controller || trackedDeviceClass == ETrackedDeviceClass.GenericTracker)
                {
                    this.connected[index] = true;
                    flag = !flag;
                }
            }
        }
        if (flag)
        {
            this.Refresh();
        }
    }
コード例 #21
0
        public override void Evaluate(int SpreadMax, CVRSystem system)
        {
            if (FSystemIn.IsConnected)
            {
                //poses
                var renderPoses = OpenVRManager.RenderPoses;
                var gamePoses   = OpenVRManager.GamePoses;
                var poseCount   = renderPoses.Length;

                FRenderPosesOut.SliceCount     = poseCount;
                FGamePosesOut.SliceCount       = poseCount;
                FDeviceClassOut.SliceCount     = poseCount;
                FLighthousePosesOut.SliceCount = 0;
                FControllerPosesOut.SliceCount = 0;

                for (int i = 0; i < poseCount; i++)
                {
                    FRenderPosesOut[i] = renderPoses[i].mDeviceToAbsoluteTracking.ToMatrix();
                    FGamePosesOut[i]   = gamePoses[i].mDeviceToAbsoluteTracking.ToMatrix();
                    var deviceClass = system.GetTrackedDeviceClass((uint)i);
                    FDeviceClassOut[i] = deviceClass.ToString();

                    if (deviceClass == ETrackedDeviceClass.TrackingReference)
                    {
                        FLighthousePosesOut.Add(FGamePosesOut[i]);
                    }

                    if (deviceClass == ETrackedDeviceClass.Controller)
                    {
                        FControllerPosesOut.Add(FGamePosesOut[i]);
                    }
                }

                FHMDPoseOut[0] = FRenderPosesOut[0];
            }
        }
コード例 #22
0
        private void UpdateControllers()
        {
            _trackedControllerIndices.Clear();
            _trackedControllerIdentifiers.Clear();

            for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                if (_vr_system.GetTrackedDeviceClass(i) == ETrackedDeviceClass.Controller)
                {
                    string type       = GetTrackedDevicePropertyString(i, ETrackedDeviceProperty.Prop_ControllerType_String);
                    string identifier = GetTrackedDevicePropertyString(i, ETrackedDeviceProperty.Prop_SerialNumber_String);

                    if (type.Equals("hmd_controller"))
                    {
                        _hmdIndex = i;
                    }
                    else if (_requiredControllers.Contains(type))
                    {
                        _trackedControllerIndices.Add(i, type);
                        _trackedControllerIdentifiers.Add(i, identifier);
                    }
                }
            }
        }
コード例 #23
0
        public (Vector3 Position, Quaternion Rotation, Vector3 Velocity, Vector3 Omega) GetHmdPositioning()
        {
            //return (
            //    new Vector3((float)Math.Sin(sw.Elapsed.TotalSeconds * 3), 0, (float)Math.Sin(sw.Elapsed.TotalSeconds * 3)),
            //    new Quaternion(new Vector3(0, (float)Math.Sin(sw.Elapsed.TotalSeconds * 3), 0), 1),
            //    default,
            //    default);

            for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                var deviceClass = _vrSystem.GetTrackedDeviceClass(i);
                if (deviceClass != ETrackedDeviceClass.Invalid)
                {
                    var deviceReading = GetDeviceReading(i);

                    if (deviceClass == ETrackedDeviceClass.HMD)
                    {
                        //Console.WriteLine("OpenVR device at " + i + ": " + deviceClass + " and rotation " + deviceReading.GetRotation());
                        return(deviceReading);
                    }
                }
            }

            return(default);
コード例 #24
0
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            while (m_System.PollNextEvent(ref m_VREvent, (uint)Marshal.SizeOf(m_VREvent)))
            {
                ProcessEvent(ref m_VREvent);
            }

            OpenVR.Compositor.WaitGetPoses(m_TrackedDevices, m_GamePose);

            for (var i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; ++i)
            {
                if (m_TrackedDevices[i].bPoseIsValid)
                {
                    m_DevicePoses[i] = m_TrackedDevices[i].mDeviceToAbsoluteTracking.ToXNA();

                    if (m_System.GetTrackedDeviceClass((uint)i) == ETrackedDeviceClass.Controller)
                    {
                        if (m_System.GetControllerRoleForTrackedDeviceIndex((uint)i) == ETrackedControllerRole.LeftHand)
                        {
                            m_Controllers[0].Update(m_System, i, m_DevicePoses[i]);
                        }
                        else if (m_System.GetControllerRoleForTrackedDeviceIndex((uint)i) == ETrackedControllerRole.RightHand)
                        {
                            m_Controllers[1].Update(m_System, i, m_DevicePoses[i]);
                        }
                    }
                }
            }

            if (m_TrackedDevices[OpenVR.k_unTrackedDeviceIndex_Hmd].bPoseIsValid)
            {
                m_HMDPose = m_DevicePoses[OpenVR.k_unTrackedDeviceIndex_Hmd];
            }
        }
コード例 #25
0
    private void OnDeviceConnected(params object[] args)
    {
        int       num    = (int)args[0];
        CVRSystem system = OpenVR.System;

        if (system == null || system.GetTrackedDeviceClass((uint)num) != ETrackedDeviceClass.Controller)
        {
            return;
        }
        bool flag = (bool)args[1];

        if (flag)
        {
            Debug.Log(string.Format("Controller {0} connected.", num));
            this.PrintControllerStatus(num);
            this.controllerIndices.Add(num);
        }
        else
        {
            Debug.Log(string.Format("Controller {0} disconnected.", num));
            this.PrintControllerStatus(num);
            this.controllerIndices.Remove(num);
        }
    }
コード例 #26
0
ファイル: VRCXVR.cs プロジェクト: timduru/VRCX
        private static void UpdateDevices(CVRSystem system, ref uint overlayIndex)
        {
            m_Lock.EnterWriteLock();
            try
            {
                m_Devices.Clear();
            }
            finally
            {
                m_Lock.ExitWriteLock();
            }
            var sb    = new StringBuilder(256);
            var state = new VRControllerState_t();

            for (var i = 0u; i < OpenVR.k_unMaxTrackedDeviceCount; ++i)
            {
                var devClass = system.GetTrackedDeviceClass(i);
                if (devClass == ETrackedDeviceClass.Controller ||
                    devClass == ETrackedDeviceClass.GenericTracker ||
                    devClass == ETrackedDeviceClass.TrackingReference)
                {
                    var err = ETrackedPropertyError.TrackedProp_Success;
                    var batteryPercentage = system.GetFloatTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_DeviceBatteryPercentage_Float, ref err);
                    if (err != ETrackedPropertyError.TrackedProp_Success)
                    {
                        batteryPercentage = 1f;
                    }
                    sb.Clear();
                    system.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_TrackingSystemName_String, sb, (uint)sb.Capacity, ref err);
                    var isOculus = sb.ToString().IndexOf("oculus", StringComparison.OrdinalIgnoreCase) >= 0;
                    // Oculus : B/Y, Bit 1, Mask 2
                    // Oculus : A/X, Bit 7, Mask 128
                    // Vive : Menu, Bit 1, Mask 2,
                    // Vive : Grip, Bit 2, Mask 4
                    var role = system.GetControllerRoleForTrackedDeviceIndex(i);
                    if (role == ETrackedControllerRole.LeftHand ||
                        role == ETrackedControllerRole.RightHand)
                    {
                        if (system.GetControllerState(i, ref state, (uint)Marshal.SizeOf(state)) &&
                            (state.ulButtonPressed & (isOculus ? 2u : 4u)) != 0)
                        {
                            if (role == ETrackedControllerRole.LeftHand)
                            {
                                Array.Copy(m_L_Translation, m_Translation, 3);
                                Array.Copy(m_L_Rotation, m_Rotation, 3);
                            }
                            else
                            {
                                Array.Copy(m_R_Translation, m_Translation, 3);
                                Array.Copy(m_R_Rotation, m_Rotation, 3);
                            }
                            overlayIndex = i;
                        }
                    }
                    var type = string.Empty;
                    if (devClass == ETrackedDeviceClass.Controller)
                    {
                        if (role == ETrackedControllerRole.LeftHand)
                        {
                            type = "leftController";
                        }
                        else if (role == ETrackedControllerRole.RightHand)
                        {
                            type = "rightController";
                        }
                        else
                        {
                            type = "controller";
                        }
                    }
                    else if (devClass == ETrackedDeviceClass.GenericTracker)
                    {
                        type = "tracker";
                    }
                    else if (devClass == ETrackedDeviceClass.TrackingReference)
                    {
                        type = "base";
                    }
                    var item = new[]
                    {
                        type,
                        system.IsTrackedDeviceConnected(i)
                            ? "connected"
                            : "disconnected",
                        (batteryPercentage * 100).ToString()
                    };
                    m_Lock.EnterWriteLock();
                    try
                    {
                        m_Devices.Add(item);
                    }
                    finally
                    {
                        m_Lock.ExitWriteLock();
                    }
                }
            }
        }
コード例 #27
0
ファイル: VrGame.cs プロジェクト: lanicon/SparrowHawk
        /**
         * Updates the poses of all tracked devices in the Matrix4 format.
         * Also handles new tracked devices, setting them up in the scene
         * and loading their render models.
         */
        void updateMatrixPose()
        {
            if (mHMD == null)
            {
                return;
            }

            OpenVR.Compositor.WaitGetPoses(mScene.mTrackedDevices, gamePoseArray);

            for (uint i = 0; i < mScene.mTrackedDevices.Length; i++)
            {
                var device = gamePoseArray[i];
                if (device.bPoseIsValid)
                {
                    mScene.mDevicePose[i] = UtilOld.steamVRMatrixToMatrix4(mScene.mTrackedDevices[i].mDeviceToAbsoluteTracking);
                    mHMD.GetTrackedDeviceClass(i);
                    if (mScene.mDeviceClassChar[i] == 0)
                    {
                        switch (mHMD.GetTrackedDeviceClass(i))
                        {
                        case ETrackedDeviceClass.Controller:
                            mScene.mDeviceClassChar[i] = 'C';
                            string name = UtilOld.GetTrackedDeviceString(ref mHMD, i, ETrackedDeviceProperty.Prop_RenderModelName_String);
                            if (name.ToLower().Contains("left"))
                            {
                                mScene.leftControllerIdx = (int)i;
                                // Uncomment to show controller model.
                                //Geometry.Geometry g = new Geometry.Geometry(@"C:/workspace/SparrowHawk/src/resources/external_controller01_left.obj");
                                //Material.Material m = new Material.RGBNormalMaterial(.5f);
                                //SceneNode s = new SceneNode("LeftControllerModel", ref g, ref m);
                                //s.transform = Util.createTranslationMatrix(-mScene.mLeftControllerOffset.M14, -mScene.mLeftControllerOffset.M24, -mScene.mLeftControllerOffset.M34);
                                //mScene.leftControllerNode.add(ref s);
                            }
                            else if (name.ToLower().Contains("right"))
                            {
                                mScene.rightControllerIdx = (int)i;
                            }
                            else if (mScene.leftControllerIdx < 0)
                            {
                                mScene.leftControllerIdx = (int)i;
                            }
                            else if (mScene.rightControllerIdx < 0)
                            {
                                mScene.rightControllerIdx = (int)i;
                            }
                            break;

                        case ETrackedDeviceClass.HMD: mScene.mDeviceClassChar[i] = 'H'; break;

                        case ETrackedDeviceClass.Invalid: mScene.mDeviceClassChar[i] = 'I'; break;

                        case ETrackedDeviceClass.GenericTracker: mScene.mDeviceClassChar[i] = 'G'; break;

                        case ETrackedDeviceClass.TrackingReference: mScene.mDeviceClassChar[i] = 'T'; break;

                        default: mScene.mDeviceClassChar[i] = '?'; break;
                        }
                    }
                }
            }

            if (gamePoseArray[OpenVR.k_unTrackedDeviceIndex_Hmd].bPoseIsValid)
            {
                mScene.mHMDPose = UtilOld.steamVRMatrixToMatrix4(gamePoseArray[OpenVR.k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking).Inverted();
            }

            if (mScene.leftControllerIdx > 0)
            {
                mScene.leftControllerNode.transform = mScene.mDevicePose[mScene.leftControllerIdx] * mScene.mLeftControllerOffset;
            }
            if (mScene.rightControllerIdx > 0)
            {
                mScene.rightControllerNode.transform = mScene.mDevicePose[mScene.rightControllerIdx] * mScene.mRightControllerOffset;
            }
        }
コード例 #28
0
        /// <summary>
        /// Updates the devices.
        /// </summary>
        private void UpdateDevices()
        {
            // Cache HMD
            CVRSystem hmd = Hmd;

            // Get indexes of left and right controllers
            LeftControllerIndex  = -1;
            RightControllerIndex = -1;
            int lhIndex = (int)hmd.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.LeftHand);
            int rhIndex = (int)hmd.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.RightHand);

            controllers.Clear();

            // Update all tracked devices
            for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                TrackedDevicePose_t pose = renderPoses[i];

                // We are interested in valid and connected devices only
                if (pose.bDeviceIsConnected && pose.bPoseIsValid)
                {
                    pose.ToVRPose(out poses[i]);
                    ETrackedDeviceClass c = hmd.GetTrackedDeviceClass(i);

                    // Update controller
                    if (c == ETrackedDeviceClass.Controller)
                    {
                        VRControllerState_t state_t = default(VRControllerState_t);
                        if (hmd.GetControllerState(i, ref state_t, (uint)Marshal.SizeOf(state_t)))
                        {
                            VRControllerRole role;
                            if (i == lhIndex)
                            {
                                role = VRControllerRole.LeftHand;
                                LeftControllerIndex = controllers.Count;
                            }
                            else if (i == rhIndex)
                            {
                                role = VRControllerRole.RightHand;
                                RightControllerIndex = controllers.Count;
                            }
                            else
                            {
                                role = VRControllerRole.Undefined;
                            }

                            VRControllerState state = new VRControllerState();
                            state.Update(role, ref state_t, ref poses[i]);
                            controllers.Add(state);
                        }
                    }
                    // Update generic reference (base station etc...)
                    else if (c == ETrackedDeviceClass.TrackingReference)
                    {
                        VRTrackingReference reference = new VRTrackingReference();
                        reference.Update(poses[i]);
                        trackingReferences.Add(reference);
                    }
                }
            }
            // Convert to array
            trackingReferencesArray = trackingReferences.ToArray();
            controllersArray        = controllers.ToArray();
        }
コード例 #29
0
        void KeepAlive()
        {
            KeepAliveCounter++;

            if (StopRequested)
            {
                Stop();
                return;
            }

            if (VRSys == null)
            {
                if (KeepAliveCounter % InitializationDivider != 0) // do not attempt initialization on every loop.
                {
                    return;
                }

                // ***** INITIALIZATION ******

                //if (!OpenVR.IsHmdPresent()) // Note that this also leaks memory

                // To avoid a memory leak, check that SteamVR is running before trying to Initialize
                if (System.Diagnostics.Process.GetProcessesByName(Config.SteamVRProcessName).Any())
                {
                    if (InitAttemptCount >= InitAttemptLimit)
                    {
                        Stop(true); // no point to keep looping and eating memory forever
                    }

                    InitAttemptCount++;
                    OpenVRConnStatus = OpenVRConnectionStatus.Initializing;
                    // do not carelessly call OpenVR.Init(), it will leak memory
                    VRSys = OpenVR.Init(ref LastOpenVRError, EVRApplicationType.VRApplication_Background);
                    if (LastOpenVRError != EVRInitError.None || VRSys == null)
                    {
                        if (LastOpenVRError == EVRInitError.Init_HmdNotFound || LastOpenVRError == EVRInitError.Init_HmdNotFoundPresenceFailed)
                        {
                            OpenVRConnStatus = OpenVRConnectionStatus.NoHMD;
                            Thread.Sleep(SleepTimeAfterQuit);
                        }
                        return;
                    }

                    bool hmdFound = false;
                    // check devices and find HMD index (but I suppose it's always 0) - Documentation is vague.
                    // For example, what's the purpose of OpenVR.k_unTrackedDeviceIndex_Hmd? What about multiple HMDs...
                    for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
                    {
                        if (VRSys.IsTrackedDeviceConnected(i))
                        {
                            ETrackedDeviceClass c = VRSys.GetTrackedDeviceClass(i);
                            if (c == ETrackedDeviceClass.HMD)
                            {
                                HmdIndex = i;
                                hmdFound = true;
                                break;
                            }
                        }
                    }

                    if (!hmdFound‬)
                    {
                        EndCurrentSession();
                        OpenVRConnStatus = OpenVRConnectionStatus.NoHMD;
                        Thread.Sleep(SleepTimeAfterQuit);

                        return;
                    }

                    PoseArray = new TrackedDevicePose_t[HmdIndex + 1];
                    for (int i = 0; i < PoseArray.Length; i++)
                    {
                        PoseArray[i] = new TrackedDevicePose_t();
                    }

                    if (SteamVRWasOffBefore)
                    {
                        // Wait a bit more before reporting OK and allowing hmd queries when SteamVR is started AFTER CG.
                        // The initial yaw values from the API sometimes threw the counter off by one half-turn.
                        // Maybe there's a small window at the beginning when the headset readings are not stable...
                        // This is very hard to reproduce/test as it happens so rarely. Shooting in the dark here.
                        Thread.Sleep(3000);
                        SteamVRWasOffBefore = false;
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }

                    OpenVRConnStatus = OpenVRConnectionStatus.AllOK;
                }
                else
                {
                    SteamVRWasOffBefore = true;
                    OpenVRConnStatus    = OpenVRConnectionStatus.NoSteamVR;
                }
            }
            else // VRSys != null (connection has been initialized)
            {
                // Check quit request
                VRSys.PollNextEvent(ref NextVREvent, (uint)System.Runtime.InteropServices.Marshal.SizeOf(NextVREvent));
                // this doesn't always work... I suppose the quit event can fly by when the poll rate is relatively low
                // It seems that SteamVR kills the VR processes that don't get Quit event with PollNextEvent().
                if (NextVREvent.eventType == (uint)EVREventType.VREvent_Quit)
                {
                    OpenVRConnStatus = OpenVRConnectionStatus.SteamVRQuit; // to immediately prevent native methods from being called
                    EndCurrentSession();
                    OpenVRConnStatus = OpenVRConnectionStatus.SteamVRQuit; // again to get correct status (changed in EndCurrentSession())
                    // a good sleep before starting to poll steamvr -process again
                    Thread.Sleep(SleepTimeAfterQuit);
                }
                else
                {
                    bool interaction = (VRSys.GetTrackedDeviceActivityLevel(HmdIndex) == EDeviceActivityLevel.k_EDeviceActivityLevel_UserInteraction);
                    if (interaction == HMDUserInteraction_previousReading)
                    {
                        HMDUserInteractionCounter++;
                    }
                    else
                    {
                        HMDUserInteractionCounter = 0;
                    }

                    HMDUserInteraction_previousReading = interaction;

                    // some buffer to filter out false flags (and conveniently some delay for notifications)
                    // ... although false flags are not really possible the way OpenVR currently works
                    if (HMDUserInteractionCounter > HMDUserInteractionDivider)
                    {
                        if (HMDUserInteraction_buffered != interaction)
                        {
                            HMDUserInteraction_buffered = interaction;

                            if (interaction)
                            {
                                Worker.ReportProgress(1, null);
                            }
                            else
                            {
                                Worker.ReportProgress(2, null);
                            }
                        }
                        HMDUserInteractionCounter = 0;
                    }
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        bool InitHMD()
        {
            bool retVal = false;

            // return if HMD has already been initialized
            if (hmdIsInitialized)
            {
                return(true);
            }

            bool   is64bit = (IntPtr.Size == 8);
            string mypath  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            log("OpenVR path set to " + Path.Combine(mypath, is64bit ? "win64" : "win32"));
            SetDllDirectory(Path.Combine(mypath, is64bit ? "win64" : "win32"));

            // check if HMD is connected on the system
            retVal = OpenVR.IsHmdPresent();
            if (!retVal)
            {
                err("HMD not found on this system.");
                return(retVal);
            }

            // check if SteamVR runtime is installed.
            // For this plugin, MAKE SURE IT IS ALREADY RUNNING.
            retVal = OpenVR.IsRuntimeInstalled();
            if (!retVal)
            {
                err("SteamVR runtime not found on this system.");
                return(retVal);
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            vrSystem = OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);

            // return if failure
            retVal = (hmdInitErrorCode == EVRInitError.None);
            if (!retVal)
            {
                err("Failed to initialize HMD. Init returned: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
                return(retVal);
            }
            else
            {
                log("OpenVR.Init passed.");
            }

            // reset "seated position" and capture initial position. this means you should hold the HMD in
            // the position you would like to consider "seated", before running this code.

            ResetInitialHmdPosition();

            // initialize Compositor
            vrCompositor = OpenVR.Compositor;

            // initialize render textures (for displaying on HMD)
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            vrSystem.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);
            //renderTextureWidth /= 2;
            //renderTextureHeight /= 2;

            log("Render Texture size: " + renderTextureWidth + " x " + renderTextureHeight);

            hmdLeftEyeRenderTexture = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
            hmdLeftEyeRenderTexture.Create();

            hmdRightEyeRenderTexture = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
            hmdRightEyeRenderTexture.Create();

            hmdLeftEyeTexture.handle      = hmdLeftEyeRenderTexture.GetNativeTexturePtr();
            hmdLeftEyeTexture.eColorSpace = EColorSpace.Auto;

            hmdRightEyeTexture.handle      = hmdRightEyeRenderTexture.GetNativeTexturePtr();
            hmdRightEyeTexture.eColorSpace = EColorSpace.Auto;


            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGL2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                hmdLeftEyeTexture.eType  = EGraphicsAPIConvention.API_OpenGL;
                hmdRightEyeTexture.eType = EGraphicsAPIConvention.API_OpenGL;
                break;     //doesnt work in unity 5.4 with current SteamVR (12/2016)

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
                throw (new Exception("DirectX9 not supported"));

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                hmdLeftEyeTexture.eType  = EGraphicsAPIConvention.API_DirectX;
                hmdRightEyeTexture.eType = EGraphicsAPIConvention.API_DirectX;
                break;

            default:
                throw (new Exception(SystemInfo.graphicsDeviceType.ToString() + " not supported"));
            }

            // Set rendering bounds on texture to render?
            // I assume min=0.0 and max=1.0 renders to the full extent of the texture
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 0.0f;
            hmdTextureBounds.vMax = 1.0f;

            // TODO: Need to understand better how to create render targets and incorporate hidden area mask mesh

            foreach (Camera camera in Camera.allCameras)
            {
                log("KSP Camera: " + camera.name);
            }

            // search for camera objects to render
            foreach (string cameraName in cameraNamesToRender)
            {
                foreach (Camera camera in Camera.allCameras)
                {
                    if (cameraName.Equals(camera.name))
                    {
                        float nearClipPlane = (camera.name.Equals(cameraNames[3])) ? 0.05f : camera.nearClipPlane;

                        HmdMatrix44_t projLeft  = vrSystem.GetProjectionMatrix(EVREye.Eye_Left, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_OpenGL);
                        HmdMatrix44_t projRight = vrSystem.GetProjectionMatrix(EVREye.Eye_Right, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_OpenGL);
                        //HmdMatrix44_t projLeft = vrSystem.GetProjectionMatrix(EVREye.Eye_Left, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_DirectX); // this doesn't seem to work
                        //HmdMatrix44_t projRight = vrSystem.GetProjectionMatrix(EVREye.Eye_Right, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_DirectX); // this doesn't seem to work
                        camerasToRender.Add(new CameraProperties(camera, camera.projectionMatrix, MathUtils.Matrix4x4_OpenVr2UnityFormat(ref projLeft), MathUtils.Matrix4x4_OpenVr2UnityFormat(ref projRight)));
                        break;
                    }
                }
            }

            // detect controllers
            for (uint idx = 0; idx < OpenVR.k_unMaxTrackedDeviceCount; idx++)
            {
                if ((ctrlIndexLeft == 0) && (vrSystem.GetTrackedDeviceClass(idx) == ETrackedDeviceClass.Controller))
                {
                    ctrlIndexLeft = idx;
                }
                else if ((ctrlIndexRight == 0) && (vrSystem.GetTrackedDeviceClass(idx) == ETrackedDeviceClass.Controller))
                {
                    ctrlIndexRight = idx;
                }
            }
            bool ctrlFocusCaptured = vrSystem.CaptureInputFocus();

            if (!ctrlFocusCaptured)
            {
                warn("Controller input focus was not captured");
            }

            initTmr.Start();

            return(retVal);
        }