private void OnNewPoses(params object[] args)
    {
        var i = (int)index;

        isValid = false;
        var poses = (Valve.VR.TrackedDevicePose_t[])args[0];
        if (poses.Length <= i)
            return;

        if (!poses[i].bDeviceIsConnected)
            return;

        if (!poses[i].bPoseIsValid)
            return;

        isValid = true;

        var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

        if (origin != null)
        {
            pose = new SteamVR_Utils.RigidTransform(origin) * pose;
            pose.pos.x *= origin.localScale.x;
            pose.pos.y *= origin.localScale.y;
            pose.pos.z *= origin.localScale.z;
            transform.position = pose.pos;
            transform.rotation = pose.rot;
        }
        else
        {
            transform.localPosition = pose.pos;
            transform.localRotation = pose.rot;
        }
    }
Пример #2
0
    private SteamVR()
    {
        hmd = OpenVR.System;
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = OpenVR.Compositor;
        overlay = OpenVR.Overlay;

        // Setup render values
        uint w = 0, h = 0;
        hmd.GetRecommendedRenderTargetSize(ref w, ref h);
        sceneWidth = (float)w;
        sceneHeight = (float)h;

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;
        hmd.GetProjectionRaw(EVREye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);

        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;
        hmd.GetProjectionRaw(EVREye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        textureBounds = new VRTextureBounds_t[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f - 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f - 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f - 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f - 0.5f * r_top / tanHalfFov.y;

        // Grow the recommended size to account for the overlapping fov
        sceneWidth = sceneWidth / Mathf.Max(textureBounds[0].uMax - textureBounds[0].uMin, textureBounds[1].uMax - textureBounds[1].uMin);
        sceneHeight = sceneHeight / Mathf.Max(textureBounds[0].vMax - textureBounds[0].vMin, textureBounds[1].vMax - textureBounds[1].vMin);

        aspect = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Right)) };

        if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL"))
            graphicsAPI = EGraphicsAPIConvention.API_OpenGL;
        else
            graphicsAPI = EGraphicsAPIConvention.API_DirectX;

        SteamVR_Utils.Event.Listen("initializing", OnInitializing);
        SteamVR_Utils.Event.Listen("calibrating", OnCalibrating);
        SteamVR_Utils.Event.Listen("out_of_range", OnOutOfRange);
        SteamVR_Utils.Event.Listen("device_connected", OnDeviceConnected);
        SteamVR_Utils.Event.Listen("new_poses", OnNewPoses);
    }
Пример #3
0
    public void UpdateOverlay(SteamVR vr)
    {
        if (texture != null)
        {
            var settings = new Compositor_OverlaySettings();
            settings.size = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Compositor_OverlaySettings));
            settings.curved = curved;
            settings.antialias = antialias;
            settings.scale = scale;
            settings.distance = distance;
            settings.alpha = alpha;
            settings.uOffset = uvOffset.x;
            settings.vOffset = uvOffset.y;
            settings.uScale = uvOffset.z;
            settings.vScale = uvOffset.w;
            settings.gridDivs = gridDivs;
            settings.gridWidth = gridWidth;
            settings.gridScale = gridScale;

            var vrcam = SteamVR_Render.Top();
            if (vrcam != null && vrcam.origin != null)
            {
                var offset = new SteamVR_Utils.RigidTransform(vrcam.origin, transform);
                offset.pos.x /= vrcam.origin.localScale.x;
                offset.pos.y /= vrcam.origin.localScale.y;
                offset.pos.z /= vrcam.origin.localScale.z;
                settings.transform = offset.ToHmdMatrix44();

                // The overlay transform is always rendered in standing space, so we transform it here
                // to seated space when using the seated universe origin in Unity.
                if (SteamVR_Render.instance.trackingSpace == TrackingUniverseOrigin.TrackingUniverseSeated)
                {
                    var seated = vr.hmd.GetSeatedZeroPoseToStandingAbsoluteTrackingPose();
                    offset = new SteamVR_Utils.RigidTransform(seated) * offset;
                    settings.transform = offset.ToHmdMatrix44();
                }
            }

            vr.compositor.SetOverlay(texture.GetNativeTexturePtr(), ref settings);
        }
        else
        {
            vr.compositor.ClearOverlay();
        }
    }
        private void OnSteamVrPose(params object[] args)
        {
            var i = (int)OpenVR.k_unTrackedDeviceIndex_Hmd;

            var poses = (TrackedDevicePose_t[])args[0];
            if (poses.Length <= i)
                return;

            if (!poses[i].bDeviceIsConnected)
                return;

            if (!poses[i].bPoseIsValid)
                return;

            var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

            _currentOvrRotation = pose.rot;
        }
Пример #5
0
        public void OrientateOverlay()
        {
            Quaternion rot = Quaternion.Euler(Vector3.Project(HMD.hmd.transform.rotation.eulerAngles, Vector3.up));

            transform.position = HMD.hmd.transform.localPosition + rot * Vector3.forward * 3.5f;
            Vector3 Pos = transform.position;

            Pos.y = HMD.hmd.transform.position.y;
            transform.rotation = Quaternion.LookRotation(HMD.hmd.transform.forward);//Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(-HMD.hmd.transform.forward), 0.2f);

            transform.rotation = Quaternion.Euler(0f, transform.rotation.eulerAngles.y, 0f);
            transform.position = Pos;



            //var offset = new SteamVR_Utils.RigidTransform(HMD.hmd.transform, transform);

            //var t = offset.ToHmdMatrix34();

            var t = new SteamVR_Utils.RigidTransform(transform).ToHmdMatrix34();

            OpenVR.Overlay.SetOverlayTransformAbsolute(overlayHandle, SteamVR.settings.trackingSpace, ref t);
        }
Пример #6
0
        public void UpdateState(SteamVR_Utils.RigidTransform pose, SteamVR_Controller.Device state)
        {
            // position the controller object
            transform.position = Scene.DevicePoseToWorld(pose.pos);
            transform.rotation = Scene.DevicePoseToWorld(pose.rot);

            // set the layer to render to
            gameObject.layer = Scene.RenderLayer;

            // update individual manipulator states (hand controls)
            if (role == ETrackedControllerRole.LeftHand)
            {
                UpdateStateLeft(pose, state);
            }
            else if (role == ETrackedControllerRole.RightHand)
            {
                UpdateStateRight(pose, state);
            }
            else
            {
                throw new Exception("Unsupported controller role: " + role);
            }
        }
Пример #7
0
        private void OnSteamVrPose(TrackedDevicePose_t[] poses)
        {
            var i = (int)OpenVR.k_unTrackedDeviceIndex_Hmd;

            if (poses.Length <= i)
            {
                return;
            }

            if (!poses[i].bDeviceIsConnected)
            {
                return;
            }

            if (!poses[i].bPoseIsValid)
            {
                return;
            }

            var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

            _ovrRot = pose.rot;
        }
Пример #8
0
    private void SendTrackingEvents(int steamDeviceIndex, int deviceIndex, TrackedDevicePose_t[] poses)
    {
        var pose          = new SteamVR_Utils.RigidTransform(poses[steamDeviceIndex].mDeviceToAbsoluteTracking);
        var localPosition = pose.pos;
        var localRotation = pose.rot;

        if (localPosition == m_LastPositionValues[steamDeviceIndex] && localRotation == m_LastRotationValues[steamDeviceIndex])
        {
            return;
        }

        var inputEvent = InputSystem.CreateEvent <VREvent>();

        inputEvent.deviceType    = typeof(VRInputDevice);
        inputEvent.deviceIndex   = deviceIndex;
        inputEvent.localPosition = localPosition;
        inputEvent.localRotation = localRotation;

        m_LastPositionValues[steamDeviceIndex] = inputEvent.localPosition;
        m_LastRotationValues[steamDeviceIndex] = inputEvent.localRotation;

        InputSystem.QueueEvent(inputEvent);
    }
Пример #9
0
        private void OnDevicePosesReady(TrackedDevicePose_t[] devicePoses)
        {
            // detect devices that have (dis)connected
            for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                bool isConnected = devicePoses[i].bDeviceIsConnected;
                if (isDeviceConnected[i] != isConnected)
                {
                    SteamVR_Events.DeviceConnected.Send((int)i, isConnected);
                }
                isDeviceConnected[i] = isConnected;
            }

            // update poses for tracked devices
            SteamVR_Controller.Update();

            // update Manipulator objects' state
            if (DeviceIndexIsValid(ControllerIndexLeft))
            {
                SteamVR_Utils.RigidTransform controllerPose = new SteamVR_Utils.RigidTransform(
                    devicePoses[ControllerIndexLeft].mDeviceToAbsoluteTracking);
                SteamVR_Controller.Device controllerState =
                    SteamVR_Controller.Input((int)ControllerIndexLeft);

                ManipulatorLeft.GetComponent <Manipulator>().UpdateState(controllerPose, controllerState);
            }

            if (DeviceIndexIsValid(ControllerIndexRight))
            {
                SteamVR_Utils.RigidTransform controllerPose = new SteamVR_Utils.RigidTransform(
                    devicePoses[ControllerIndexRight].mDeviceToAbsoluteTracking);
                SteamVR_Controller.Device controllerState =
                    SteamVR_Controller.Input((int)ControllerIndexRight);

                ManipulatorRight.GetComponent <Manipulator>().UpdateState(controllerPose, controllerState);
            }
        }
Пример #10
0
 /// <summary>
 /// Update the Overlay's Position and return the resulting HmdMatrix34_t
 /// </summary>
 /// <returns></returns>
 private HmdMatrix34_t GetOverlayPosition()
 {
     if (OverlayReference == null)
     {
         OverlayReference = new GameObject("Overlay Reference")
         {
             hideFlags = HideFlags.HideInHierarchy
         }
     }
     ;
     if (_anchor == OpenVR.k_unTrackedDeviceIndexInvalid)
     {
         var offset = new SteamVR_Utils.RigidTransform(OverlayReference.transform, transform);
         offset.pos.x /= OverlayReference.transform.localScale.x;
         offset.pos.y /= OverlayReference.transform.localScale.y;
         offset.pos.z /= OverlayReference.transform.localScale.z;
         var t = offset.ToHmdMatrix34();
         return(t);
     }
     else
     {
         if (ZeroReference == null)
         {
             ZeroReference = new GameObject("Zero Reference")
             {
                 hideFlags = HideFlags.HideInHierarchy
             }
         }
         ;
         var offset = new SteamVR_Utils.RigidTransform(ZeroReference.transform, OverlayReference.transform);
         offset.pos.x /= ZeroReference.transform.localScale.x;
         offset.pos.y /= ZeroReference.transform.localScale.y;
         offset.pos.z /= ZeroReference.transform.localScale.z;
         var t = offset.ToHmdMatrix34();
         return(t);
     }
 }
        private void OnNewPoses(TrackedDevicePose_t[] poses)
        {
            int index = HandType == Hand.LEFT ? HI5_BindInfoManager.LeftID : HI5_BindInfoManager.RightID;

            if (index == -1)
            {
                return;
            }

            if (poses.Length <= index)
            {
                return;
            }

            if (!poses[index].bDeviceIsConnected)
            {
                return;
            }

            if (!poses[index].bPoseIsValid)
            {
                return;
            }

            var pose = new SteamVR_Utils.RigidTransform(poses[index].mDeviceToAbsoluteTracking);

            Vector3    pos = pose.pos;
            Quaternion rot = pose.rot;

            if (m_Status.Status != GloveStatus.NoGlove &&
                m_Status.Status != GloveStatus.NoDongle &&
                HI5_Manager.IsDongleAvailable() &&
                HI5_Manager.IsHasDongle)
            {
                ApplyHandMotion_Position(pos, rot);
            }
        }
Пример #12
0
    void UpdateTrackedObj()
    {
        TrackedDevicePose_t[] allPoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];

        _vrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, allPoses);

        for (int i = 0; i < _validDeviceIds.Count; i++)
        {
            if (i < targetObjs.Length)
            {
                var pose        = allPoses[_validDeviceIds[i]];
                var absTracking = pose.mDeviceToAbsoluteTracking;
                var mat         = new SteamVR_Utils.RigidTransform(absTracking);
                if (origin != null)
                {
                    targetObjs[i].transform.SetPositionAndRotation(origin.TransformPoint(mat.pos), origin.rotation * mat.rot);
                }
                else
                {
                    targetObjs[i].transform.SetPositionAndRotation(mat.pos, mat.rot);
                }
            }
        }
    }
Пример #13
0
        // --------------------- OTHER ---------------------


        private void UpdateTrackedDevicePositions()
        {
            if (!isConnected)
            {
                return;
            }

            if (OpenVR.Compositor == null)
            {
                return;
            }


            OpenVR.Compositor.GetLastPoses(poses, gamePoses);

            if (leftHandIndex != OpenVR.k_unTrackedDeviceIndexInvalid && poses.Length > leftHandIndex)
            {
                var lPose = new SteamVR_Utils.RigidTransform(poses[leftHandIndex].mDeviceToAbsoluteTracking);
                lHandTrans.transform.position = lPose.pos;
                lHandTrans.transform.rotation = lPose.rot;
            }

            if (rightHandIndex != OpenVR.k_unTrackedDeviceIndexInvalid && poses.Length > rightHandIndex)
            {
                var rPose = new SteamVR_Utils.RigidTransform(poses[rightHandIndex].mDeviceToAbsoluteTracking);
                rHandTrans.transform.position = rPose.pos;
                rHandTrans.transform.rotation = rPose.rot;
            }

            if (poses.Length > hmdIndex)
            {
                var hmdPose = new SteamVR_Utils.RigidTransform(poses[hmdIndex].mDeviceToAbsoluteTracking);
                hmdTrans.position = hmdPose.pos;
                hmdTrans.rotation = hmdPose.rot;
            }
        }
Пример #14
0
    //指定されたdeviceが有効かチェックした上で、オーバーレイと交点を持つかチェック
    private bool checkRay(uint idx, TrackedDevicePose_t[] allDevicePose, ref VROverlayIntersectionResults_t results)
    {
#pragma warning disable 0219
        string Tag = "[" + this.GetType().Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(); //クラス名とメソッド名を自動取得
#pragma warning restore 0219

        //device indexが有効
        if (idx != OpenVR.k_unTrackedDeviceIndexInvalid)
        {
            //接続されていて姿勢情報が有効
            if (allDevicePose[idx].bDeviceIsConnected && allDevicePose[idx].bPoseIsValid)
            {
                //姿勢情報などを変換してもらう
                TrackedDevicePose_t          Pose  = allDevicePose[idx];
                SteamVR_Utils.RigidTransform Trans = new SteamVR_Utils.RigidTransform(Pose.mDeviceToAbsoluteTracking);

                //コントローラー用に45度前方に傾けた方向ベクトルを計算
                Vector3 vect = (Trans.rot * Quaternion.AngleAxis(45, Vector3.right)) * Vector3.forward;

                return(ComputeOverlayIntersection(Trans.pos, vect, ref results));
            }
        }
        return(false);
    }
Пример #15
0
        /// <summary>
        /// Get the lighthouse positions from SteamVR.
        /// </summary>
        void OnNewPoses(TrackedDevicePose_t[] poses)
        {
            ready = false;

            // Need at least three slots
            if (poses.Length < 3)
            {
                return;
            }

            var system = OpenVR.System;

            if (system == null)
            {
                return;
            }

            int index = 0;

            for (int i = 0; i < poses.Length && index < 2; ++i)
            {
                if (!poses[i].bDeviceIsConnected || !poses[i].bPoseIsValid)
                {
                    continue;
                }

                // Filter lighthouses
                if (system.GetTrackedDeviceClass((uint)i) == ETrackedDeviceClass.TrackingReference)
                {
                    lighthouses[index++] =
                        new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking).pos;
                }
            }

            ready = index == 2;
        }
Пример #16
0
 void _getPose()
 {
     lock (thisLock)
     {
         while (!workFinished)
         {
             TrackedDevicePose_t[]
             allPoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
             vrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, allPoses);
             var pose = allPoses[0];
             if (pose.bPoseIsValid)
             {
                 var absTracking = pose.mDeviceToAbsoluteTracking;
                 var mat         = new SteamVR_Utils.RigidTransform(absTracking);
                 Debug.Log("Position: " + mat.pos + " Rotation: " + mat.rot.eulerAngles);
                 dataManager.AddHeadPos(0.0f, mat.pos, mat.rot.eulerAngles);
             }
         }
         if (workFinished)
         {
             dataManager.WriteHeadPosData();
         }
     }
 }
        private void OnNewPoses(TrackedDevicePose_t[] poses)
        {
            if (!HI5_Calibration.IsCalibratingBPose)
            {
                return;
            }

            if (_deviceType == OPTDeviceType.Unknown)
            {
                return;
            }

            if (IsNullOrEmpty(_deviceSerialNumber))
            {
                return;
            }

            if (_deviceIndex <= (int)SteamVR_TrackedObject.EIndex.Hmd)
            {
                return;
            }

            if (!_steamVrTrackedObject.isValid)
            {
                return;
            }

            if (poses[_deviceIndex].eTrackingResult != ETrackingResult.Running_OK)
            {
                return;
            }

            var pose = new SteamVR_Utils.RigidTransform(poses[_deviceIndex].mDeviceToAbsoluteTracking);

            ExportOpticalData(pose);
        }
Пример #18
0
        /// <summary>
        /// On LateUpdate, dispatch OpenVR events, run the main HMD loop code.
        /// </summary>
        private void LateUpdate()
        {
            // dispatch any OpenVR events
            if (hmdState == HmdState.Initialized)
            {
                DispatchOpenVREvents();
            }

            // check if the current scene allows VR
            HmdIsAllowed = Scene.Instance.SceneAllowsVR();

            // process the state of OpenVR
            ProcessHmdState();

            // check if we are running the HMD
            HmdIsRunning = HmdIsAllowed && (hmdState == HmdState.Initialized) && HmdIsEnabled;

            // perform regular updates if HMD is initialized
            if (HmdIsRunning)
            {
                EVRCompositorError vrCompositorError = EVRCompositorError.None;

                // we've just started VR
                if (!hmdIsRunningPrev)
                {
                    Utils.Log("HMD is now on");
                    Scene.Instance.SetupScene();
                    ResetInitialHmdPosition();
                }

                try {
                    // get latest device poses, emit an event to indicate devices have been updated
                    float secondsToPhotons = Utils.CalculatePredictedSecondsToPhotons();
                    OpenVR.System.GetDeviceToAbsoluteTrackingPose(Scene.Instance.TrackingSpace, secondsToPhotons, devicePoses);
                    SteamVR_Events.NewPoses.Send(devicePoses);

                    HmdMatrix34_t vrLeftEyeTransform  = OpenVR.System.GetEyeToHeadTransform(EVREye.Eye_Left);
                    HmdMatrix34_t vrRightEyeTransform = OpenVR.System.GetEyeToHeadTransform(EVREye.Eye_Right);
                    vrCompositorError = OpenVR.Compositor.WaitGetPoses(renderPoses, gamePoses);

                    if (vrCompositorError != EVRCompositorError.None)
                    {
                        throw new Exception("WaitGetPoses failed: (" + (int)vrCompositorError + ") " + vrCompositorError.ToString());
                    }

                    // convert SteamVR poses to Unity coordinates
                    var hmdTransform = new SteamVR_Utils.RigidTransform(devicePoses[OpenVR.k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking);
                    SteamVR_Utils.RigidTransform[] hmdEyeTransform = new SteamVR_Utils.RigidTransform[2];
                    hmdEyeTransform[0] = new SteamVR_Utils.RigidTransform(vrLeftEyeTransform);
                    hmdEyeTransform[1] = new SteamVR_Utils.RigidTransform(vrRightEyeTransform);

                    // don't highlight parts with the mouse
                    Mouse.HoveredPart = null;

                    // render each eye
                    for (int i = 0; i < 2; i++)
                    {
                        RenderHmdCameras(
                            (EVREye)i,
                            hmdTransform,
                            hmdEyeTransform[i],
                            hmdEyeRenderTexture[i],
                            hmdEyeTexture[i]);
                    }

                    // [insert dark magic here]
                    OpenVR.Compositor.PostPresentHandoff();

                    // render to the game screen
                    if (RenderHmdToScreen)
                    {
                        Graphics.Blit(hmdEyeRenderTexture[0], null as RenderTexture);
                    }
                } catch (Exception e) {
                    // shut off VR when an error occurs
                    Utils.LogError(e);
                    HmdIsEnabled = false;
                    HmdIsRunning = false;
                }
            }

            // reset cameras when HMD is turned off
            if (!HmdIsRunning && hmdIsRunningPrev)
            {
                Utils.Log("HMD is now off, resetting cameras...");
                Scene.Instance.CloseScene();

                // TODO: figure out why we can no longer manipulate the IVA camera in the regular game
            }


#if DEBUG
            // debug hooks
            if (Input.GetKeyDown(KeyCode.Y))
            {
                // Utils.PrintAllCameras();
                // Utils.PrintAllLayers();
                Utils.PrintDebug();
                // Utils.PrintFonts();
                // Utils.PrintCollisionMatrix();
            }
#endif

            // keep track of whether we were running the HMD
            hmdIsRunningPrev = HmdIsRunning;
        }
Пример #19
0
    private SteamVR(System.IntPtr pHmd, System.IntPtr pCompositor, System.IntPtr pOverlay)
    {
        hmd = new CVRSystem(pHmd);
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = new CVRCompositor(pCompositor);
        overlay    = new CVROverlay(pOverlay);

        var capacity = compositor.GetLastError(null, 0);

        if (capacity > 1)
        {
            var result = new System.Text.StringBuilder((int)capacity);
            compositor.GetLastError(result, capacity);
            Debug.Log("Compositor - " + result);
        }

        // Hook up the render thread event.
        var error = HmdError.None;

        SetUnityRenderCallback(OpenVR.GetGenericInterface(IVRHmdDistortPresent_Version, ref error));

        // Setup render values
        uint w = 0, h = 0;

        hmd.GetRecommendedRenderTargetSize(ref w, ref h);
        sceneWidth  = (float)w;
        sceneHeight = (float)h;

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;

        hmd.GetProjectionRaw(Hmd_Eye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);

        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;

        hmd.GetProjectionRaw(Hmd_Eye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        textureBounds = new VRTextureBounds_t[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f - 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f - 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f - 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f - 0.5f * r_top / tanHalfFov.y;

        // Grow the recommended size to account for the overlapping fov
        sceneWidth  = sceneWidth / Mathf.Max(textureBounds[0].uMax - textureBounds[0].uMin, textureBounds[1].uMax - textureBounds[1].uMin);
        sceneHeight = sceneHeight / Mathf.Max(textureBounds[0].vMax - textureBounds[0].vMin, textureBounds[1].vMax - textureBounds[1].vMin);

        aspect      = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Right))
        };

        if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL"))
        {
            graphicsAPI = GraphicsAPIConvention.API_OpenGL;
        }
        else
        {
            graphicsAPI = GraphicsAPIConvention.API_DirectX;
        }

        SteamVR_Utils.Event.Listen("initializing", OnInitializing);
        SteamVR_Utils.Event.Listen("calibrating", OnCalibrating);
        SteamVR_Utils.Event.Listen("out_of_range", OnOutOfRange);
        SteamVR_Utils.Event.Listen("device_connected", OnDeviceConnected);
        SteamVR_Utils.Event.Listen("new_poses", OnNewPoses);
    }
Пример #20
0
 public static SteamVR_Utils.RigidTransform Interpolate(SteamVR_Utils.RigidTransform a, SteamVR_Utils.RigidTransform b, float t)
 {
     return(new SteamVR_Utils.RigidTransform(Vector3.Lerp(a.pos, b.pos, t), Quaternion.Slerp(a.rot, b.rot, t)));
 }
Пример #21
0
 public SteamVR_Utils.RigidTransform GetInverse()
 {
     SteamVR_Utils.RigidTransform result = new SteamVR_Utils.RigidTransform(this.pos, this.rot);
     result.Inverse();
     return(result);
 }
Пример #22
0
 public void UpdateComponents()
 {
     Transform transform = base.transform;
     if (transform.childCount == 0)
     {
         return;
     }
     using (SteamVR_RenderModel.RenderModelInterfaceHolder renderModelInterfaceHolder = new SteamVR_RenderModel.RenderModelInterfaceHolder())
     {
         VRControllerState_t vRControllerState_t = (this.index == SteamVR_TrackedObject.EIndex.None) ? default(VRControllerState_t) : SteamVR_Controller.Input((int)this.index).GetState();
         for (int i = 0; i < transform.childCount; i++)
         {
             Transform child = transform.GetChild(i);
             CVRRenderModels instance = renderModelInterfaceHolder.instance;
             if (instance == null)
             {
                 break;
             }
             RenderModel_ComponentState_t renderModel_ComponentState_t = default(RenderModel_ComponentState_t);
             RenderModel_ControllerMode_State_t renderModel_ControllerMode_State_t = default(RenderModel_ControllerMode_State_t);
             if (instance.GetComponentState(this.renderModelName, child.name, ref vRControllerState_t, ref renderModel_ControllerMode_State_t, ref renderModel_ComponentState_t))
             {
                 SteamVR_Utils.RigidTransform rigidTransform = new SteamVR_Utils.RigidTransform(renderModel_ComponentState_t.mTrackingToComponentRenderModel);
                 child.localPosition = rigidTransform.pos;
                 child.localRotation = rigidTransform.rot;
                 Transform transform2 = child.FindChild("attach");
                 if (transform2 != null)
                 {
                     SteamVR_Utils.RigidTransform rigidTransform2 = new SteamVR_Utils.RigidTransform(renderModel_ComponentState_t.mTrackingToComponentLocal);
                     transform2.position = transform.TransformPoint(rigidTransform2.pos);
                     transform2.rotation = transform.rotation * rigidTransform2.rot;
                 }
                 bool flag = (renderModel_ComponentState_t.uProperties & 2u) != 0u;
                 if (flag != child.gameObject.activeSelf)
                 {
                     child.gameObject.SetActive(flag);
                 }
             }
         }
     }
 }
Пример #23
0
    private void OnNewPoses(params object[] args)
    {
        if (index == EIndex.None)
        {
            return;
        }

        var i = (int)index;

        isValid = false;
        var poses = (Valve.VR.TrackedDevicePose_t[])args[0];

        if (poses.Length <= i)
        {
            return;
        }

        if (!poses[i].bDeviceIsConnected)
        {
            return;
        }

        if (!poses[i].bPoseIsValid)
        {
            return;
        }

        isValid = true;

        var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

        if (origin != null)
        {
            pose               = new SteamVR_Utils.RigidTransform(origin) * pose;
            pose.pos.x        *= origin.localScale.x;
            pose.pos.y        *= origin.localScale.y;
            pose.pos.z        *= origin.localScale.z;
            transform.position = pose.pos;
            transform.rotation = pose.rot;
        }
        else
        {
            transform.localPosition = pose.pos + pose.rot * offset;
            transform.localRotation = pose.rot * angles;
        }

        var vr             = SteamVR.instance;
        var isController   = (vr.hmd.GetTrackedDeviceClass((uint)i) == ETrackedDeviceClass.Controller);
        var state          = new VRControllerState_t();
        var success        = vr.hmd.GetControllerState((uint)i, ref state);
        var triggerPressed = (state.ulButtonPressed & SteamVR_Controller.ButtonMask.Trigger) != 0;

        if (Time.time >= cooldown)
        {
            if (triggerPressed)
            {
                Debug.Log("trigger pressed");
                GameObject bPrefab = Instantiate(bulletPrefab, pose.pos, pose.rot) as GameObject;
                Rigidbody  rb      = bPrefab.AddComponent <Rigidbody>(); // Add the rigidbody.
                rb.mass = 1;                                             // Set the GO's mass to 5 via the Rigidbody.
                rb.AddForce(pose.rot * Vector3.down * 3000f);
                cooldown = Time.time + attackSpeed;
            }
        }
    }
Пример #24
0
	public void UpdateOverlay()
	{
		var overlay = OpenVR.Overlay;
		if (overlay == null)
			return;

		if (texture != null)
		{
			var error = overlay.ShowOverlay(handle);
			if (error == EVROverlayError.InvalidHandle || error == EVROverlayError.UnknownOverlay)
			{
				if (overlay.FindOverlay(key, ref handle) != EVROverlayError.None)
					return;
			}

			var tex = new Texture_t();
			tex.handle = texture.GetNativeTexturePtr();
			tex.eType = SteamVR.instance.graphicsAPI;
			tex.eColorSpace = EColorSpace.Auto;
            overlay.SetOverlayTexture(handle, ref tex);

			overlay.SetOverlayAlpha(handle, alpha);
			overlay.SetOverlayWidthInMeters(handle, scale);
			overlay.SetOverlayAutoCurveDistanceRangeInMeters(handle, curvedRange.x, curvedRange.y);

			var textureBounds = new VRTextureBounds_t();
			textureBounds.uMin = (0 + uvOffset.x) * uvOffset.z;
			textureBounds.vMin = (1 + uvOffset.y) * uvOffset.w;
			textureBounds.uMax = (1 + uvOffset.x) * uvOffset.z;
			textureBounds.vMax = (0 + uvOffset.y) * uvOffset.w;
			overlay.SetOverlayTextureBounds(handle, ref textureBounds);

			var vecMouseScale = new HmdVector2_t();
			vecMouseScale.v0 = mouseScale.x;
			vecMouseScale.v1 = mouseScale.y;
			overlay.SetOverlayMouseScale(handle, ref vecMouseScale);

			var vrcam = SteamVR_Render.Top();
			if (vrcam != null && vrcam.origin != null)
			{
				var offset = new SteamVR_Utils.RigidTransform(vrcam.origin, transform);
				offset.pos.x /= vrcam.origin.localScale.x;
				offset.pos.y /= vrcam.origin.localScale.y;
				offset.pos.z /= vrcam.origin.localScale.z;

				offset.pos.z += distance;

				var t = offset.ToHmdMatrix34();
				overlay.SetOverlayTransformAbsolute(handle, SteamVR_Render.instance.trackingSpace, ref t);
			}

			overlay.SetOverlayInputMethod(handle, inputMethod);

			if (curved || antialias)
				highquality = true;

			if (highquality)
			{
				overlay.SetHighQualityOverlay(handle);
				overlay.SetOverlayFlag(handle, VROverlayFlags.Curved, curved);
				overlay.SetOverlayFlag(handle, VROverlayFlags.RGSS4X, antialias);
			}
			else if (overlay.GetHighQualityOverlay() == handle)
			{
				overlay.SetHighQualityOverlay(OpenVR.k_ulOverlayHandleInvalid);
			}
		}
		else
		{
			overlay.HideOverlay(handle);
		}
	}
Пример #25
0
	public void UpdateComponents()
	{
		var t = transform;
		if (t.childCount == 0)
			return;

		using (var holder = new RenderModelInterfaceHolder())
		{
			var controllerState = (index != SteamVR_TrackedObject.EIndex.None) ?
				SteamVR_Controller.Input((int)index).GetState() : new VRControllerState_t();

			for (int i = 0; i < t.childCount; i++)
			{
				var child = t.GetChild(i);

				var renderModels = holder.instance;
				if (renderModels == null)
					break;

				var componentState = new RenderModel_ComponentState_t();
                if (!renderModels.GetComponentState(renderModelName, child.name, ref controllerState, ref controllerModeState, ref componentState))
					continue;

				var componentTransform = new SteamVR_Utils.RigidTransform(componentState.mTrackingToComponentRenderModel);
				child.localPosition = componentTransform.pos;
				child.localRotation = componentTransform.rot;

				var attach = child.FindChild(k_localTransformName);
				if (attach != null)
				{
					var attachTransform = new SteamVR_Utils.RigidTransform(componentState.mTrackingToComponentLocal);
					attach.position = t.TransformPoint(attachTransform.pos);
					attach.rotation = t.rotation * attachTransform.rot;
				}

				bool visible = (componentState.uProperties & (uint)EVRComponentProperty.IsVisible) != 0;
				if (visible != child.gameObject.activeSelf)
				{
					child.gameObject.SetActive(visible);
				}
			}
		}
	}
        private void OnSteamVrPose(params object[] args)
        {
            var i = (int)OpenVR.k_unTrackedDeviceIndex_Hmd;

            var poses = (TrackedDevicePose_t[])args[0];
            if (poses.Length <= i)
                return;

            if (!poses[i].bDeviceIsConnected)
                return;

            if (!poses[i].bPoseIsValid)
                return;

            var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

            var prevRot = _ovrRot;
            _ovrRot = pose.rot;

            var deltaAngle = Quaternion.Angle(prevRot, _ovrRot);

            HasSteadyOpenVrPose = (Mathf.Abs(deltaAngle) < SteadyAngleThreshold);
        }
        private void OnNewPoses(params object[] args)
        {
            if (index == EIndex.None || relativeToIndex == EIndex.None)
                return;

            var i = (int)index;
            var relIndex = (int)relativeToIndex;

            isValid = false;
            var poses = (Valve.VR.TrackedDevicePose_t[])args[0];
            if (poses.Length <= Math.Max(i, relIndex))
                return;

            if (!poses[i].bDeviceIsConnected || !poses[relIndex].bDeviceIsConnected)
                return;

            if (!poses[i].bPoseIsValid || !poses[relIndex].bPoseIsValid)
                return;

            isValid = true;

            var relPose = new SteamVR_Utils.RigidTransform(poses[relIndex].mDeviceToAbsoluteTracking);
            var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

            if (origin != null)
            {
                pose = new SteamVR_Utils.RigidTransform(origin) * pose;

                pose.pos.x *= origin.localScale.x;
                pose.pos.y *= origin.localScale.y;
                pose.pos.z *= origin.localScale.z;

                ApplyPose(relPose, pose);
            }
            else
            {
                ApplyPose(relPose, pose);
            }
        }
 public DelayedPose(SteamVR_Utils.RigidTransform pose)
     : this()
 {
     Pose = pose;
 }
Пример #29
0
    private SteamVR(System.IntPtr pHmd, System.IntPtr pCompositor)
    {
        hmd = new CVRSystem(pHmd);
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = new CVRCompositor(pCompositor);

        var device = new UnityGraphicsDevice();
        GetUnityGraphicsDevice(ref device);
        switch (device.type)
        {
            case GfxDeviceRenderer.kGfxRendererD3D11:
                compositor.SetGraphicsDevice(Compositor_DeviceType.D3D11, device.ptr);
                break;
            case GfxDeviceRenderer.kGfxRendererOpenGL:
                compositor.SetGraphicsDevice(Compositor_DeviceType.OpenGL, device.ptr);
                break;
            default:
                throw new System.Exception("Unsupported device type.");
        }

        var capacity = compositor.GetLastError(null, 0);
        if (capacity > 1)
        {
            var result = new System.Text.StringBuilder((int)capacity);
            compositor.GetLastError(result, capacity);
            Debug.Log("Compositor - " + result);
        }

        // Register for a callback if our graphics device goes away, so we can properly clean up.
        var resetDelegate = new UnityResetDelegate(SteamVR.SafeDispose);
        callbackHandle = GCHandle.Alloc(resetDelegate);
        SetUnityResetCallback(Marshal.GetFunctionPointerForDelegate(resetDelegate));

        // Hook up the render thread present event just in case we wind up needing to use this.
        var error = HmdError.None;
        SetUnityRenderCallback(OpenVR.GetGenericInterface(IVRHmdDistortPresent_Version, ref error));

        // Setup render values
        uint w = 0, h = 0;
        hmd.GetRecommendedRenderTargetSize(ref w, ref h);
        sceneWidth = (float)w;
        sceneHeight = (float)h;

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;
        hmd.GetProjectionRaw(Hmd_Eye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);

        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;
        hmd.GetProjectionRaw(Hmd_Eye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        textureBounds = new Compositor_TextureBounds[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f + 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f + 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f + 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f + 0.5f * r_top / tanHalfFov.y;

        aspect = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Right)) };

        SteamVR_Utils.Event.Listen("initializing", OnInitializing);
        SteamVR_Utils.Event.Listen("calibrating", OnCalibrating);
        SteamVR_Utils.Event.Listen("out_of_range", OnOutOfRange);
        SteamVR_Utils.Event.Listen("device_connected", OnDeviceConnected);
        SteamVR_Utils.Event.Listen("new_poses", OnNewPoses);
    }
Пример #30
0
    public static int GetDeviceIndex(SteamVR_Controller.DeviceRelation relation, ETrackedDeviceClass deviceClass = ETrackedDeviceClass.Controller, int relativeTo = 0)
    {
        int result = -1;

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

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

        while ((long)num2 < 64L)
        {
            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 vector2    = new Vector3(vector.x, 0f, vector.z);
                        Vector3 normalized = vector2.normalized;
                        float   num4       = Vector3.Dot(normalized, Vector3.forward);
                        Vector3 vector3    = Vector3.Cross(normalized, Vector3.forward);
                        if (relation == SteamVR_Controller.DeviceRelation.Leftmost)
                        {
                            num3 = ((vector3.y <= 0f) ? num4 : (2f - num4));
                        }
                        else
                        {
                            num3 = ((vector3.y >= 0f) ? num4 : (2f - num4));
                        }
                    }
                    if (num3 > num)
                    {
                        result = num2;
                        num    = num3;
                    }
                }
            }
            num2++;
        }
        return(result);
    }
Пример #31
0
    /// <summary>
    /// Push Updates to our Overlay to the OpenVR System
    /// </summary>
    private void UpdateOverlay()
    {
        var overlay = OpenVR.Overlay;

        if (overlay == null)
        {
            return;
        }

        if (OverlayTexture != null)
        {
            var error = overlay.ShowOverlay(_handle);
            if (error == EVROverlayError.InvalidHandle || error == EVROverlayError.UnknownOverlay)
            {
                if (overlay.FindOverlay(Key, ref _handle) != EVROverlayError.None)
                {
                    return;
                }
            }

            var tex = new Texture_t
            {
                handle      = OverlayTexture.GetNativeTexturePtr(),
                eType       = SteamVR.instance.textureType,
                eColorSpace = EColorSpace.Auto
            };
            overlay.SetOverlayColor(_handle, 1f, 1f, 1f);
            //overlay.SetOverlayGamma(_handle, 2.2f); // Doesn't exist yet :(
            overlay.SetOverlayTexture(_handle, ref tex);
            overlay.SetOverlayAlpha(_handle, AnimateOnGaze == AnimationType.Alpha || AnimateOnGaze == AnimationType.AlphaAndScale ? _alpha : Alpha);
            overlay.SetOverlayWidthInMeters(_handle, AnimateOnGaze == AnimationType.Scale || AnimateOnGaze == AnimationType.AlphaAndScale ? _scale : Scale);
            overlay.SetOverlayAutoCurveDistanceRangeInMeters(_handle, CurvedRange.x, CurvedRange.y);

            var textureBounds = new VRTextureBounds_t
            {
                uMin = (0 + UvOffset.x) * UvOffset.z,
                vMin = (1 + UvOffset.y) * UvOffset.w,
                uMax = (1 + UvOffset.x) * UvOffset.z,
                vMax = (0 + UvOffset.y) * UvOffset.w
            };
            overlay.SetOverlayTextureBounds(_handle, ref textureBounds);

            var vecMouseScale = new HmdVector2_t
            {
                v0 = MouseScale.x,
                v1 = MouseScale.y
            };
            overlay.SetOverlayMouseScale(_handle, ref vecMouseScale);

            if (_anchor != OpenVR.k_unTrackedDeviceIndexInvalid) // Attached to some HOTK_TrackedDevice, used for Controllers
            {
                var t = GetOverlayPosition();
                overlay.SetOverlayTransformTrackedDeviceRelative(_handle, _anchor, ref t);
            }
            else if (AnchorDevice == MountDevice.World) // Attached to World
            {
                var t = GetOverlayPosition();
                overlay.SetOverlayTransformAbsolute(_handle, SteamVR_Render.instance.trackingSpace, ref t);
            }
            else
            {
                var vrcam = SteamVR_Render.Top();
                if (vrcam != null && vrcam.origin != null) // Attached to Camera (We are Rendering)
                {
                    var offset = new SteamVR_Utils.RigidTransform(vrcam.origin, transform);
                    offset.pos.x /= vrcam.origin.localScale.x;
                    offset.pos.y /= vrcam.origin.localScale.y;
                    offset.pos.z /= vrcam.origin.localScale.z;

                    var t = offset.ToHmdMatrix34();
                    overlay.SetOverlayTransformAbsolute(_handle, SteamVR_Render.instance.trackingSpace, ref t);
                }
                else // Attached to Camera (We are Not Rendering)
                {
                    var t = GetOverlayPosition();
                    overlay.SetOverlayTransformTrackedDeviceRelative(_handle, 0, ref t);
                }
            }

            overlay.SetOverlayInputMethod(_handle, InputMethod);

            if (Highquality)
            {
                if (HighQualityOverlay != this && HighQualityOverlay != null)
                {
                    if (HighQualityOverlay.Highquality)
                    {
                        Debug.LogWarning("Only one Overlay can be in HighQuality mode as per the OpenVR API.");
                        HighQualityOverlay.Highquality = false;
                    }
                    HighQualityOverlay = this;
                }
                else if (HighQualityOverlay == null)
                {
                    HighQualityOverlay = this;
                }

                overlay.SetHighQualityOverlay(_handle);
                overlay.SetOverlayFlag(_handle, VROverlayFlags.Curved, Curved);
                overlay.SetOverlayFlag(_handle, VROverlayFlags.RGSS4X, Antialias);
            }
            else if (overlay.GetHighQualityOverlay() == _handle)
            {
                overlay.SetHighQualityOverlay(OpenVR.k_ulOverlayHandleInvalid);
            }
        }
        else
        {
            overlay.HideOverlay(_handle);
        }
    }
Пример #32
0
    private void OnNewPoses(params object[] args)
    {
        // If our Tracked Type changes, we are no longer valid
        if (_type != Type)
        {
            _type   = Type;
            IsValid = false;
        }

        // If we aren't valid, try and find our index
        if (!IsValid)
        {
            Index = EIndex.None;
            if (Type != EType.None)
            {
                switch (Type)
                {
                case EType.None:
                    return;

                case EType.HMD:
                    if (HOTK_TrackedDeviceManager.Instance.HMDIndex != OpenVR.k_unTrackedDeviceIndexInvalid)
                    {
                        Index = (EIndex)HOTK_TrackedDeviceManager.Instance.HMDIndex;
                    }
                    break;

                case EType.LeftController:
                    if (HOTK_TrackedDeviceManager.Instance.LeftIndex != OpenVR.k_unTrackedDeviceIndexInvalid)
                    {
                        Index = (EIndex)HOTK_TrackedDeviceManager.Instance.LeftIndex;
                    }
                    break;

                case EType.RightController:
                    if (HOTK_TrackedDeviceManager.Instance.RightIndex != OpenVR.k_unTrackedDeviceIndexInvalid)
                    {
                        Index = (EIndex)HOTK_TrackedDeviceManager.Instance.RightIndex;
                    }
                    break;

                case EType.ThirdController:
                    if (HOTK_TrackedDeviceManager.Instance.ThirdIndex != OpenVR.k_unTrackedDeviceIndexInvalid)
                    {
                        Index = (EIndex)HOTK_TrackedDeviceManager.Instance.ThirdIndex;
                    }
                    break;

                case EType.FourthController:
                    if (HOTK_TrackedDeviceManager.Instance.FourthIndex != OpenVR.k_unTrackedDeviceIndexInvalid)
                    {
                        Index = (EIndex)HOTK_TrackedDeviceManager.Instance.FourthIndex;
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            //UpdateRenderModel();
        }

        // Check if our device is valid

        IsValid = false;

        if (Index == EIndex.None)
        {
            return; // This TrackedDevice is not set to track anything
        }
        var i = (int)Index;

        var poses = (TrackedDevicePose_t[])args[0];

        if (poses.Length <= i)
        {
            return; // SteamVR did not send poses this update
        }
        if (!poses[i].bDeviceIsConnected)
        {
            return; // SteamVR reports device has been disconnected or was never connected
        }
        if (!poses[i].bPoseIsValid)
        {
            return; // SteamVR reports device is not valid (not being tracked currently)
        }
        IsValid = true;

        // Get our poses and change our position/rotation to match the device

        var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

        if (Origin != null) // Our device is 'anchored' to something else in the scene
        {
            pose               = new SteamVR_Utils.RigidTransform(Origin) * pose;
            pose.pos.x        *= Origin.localScale.x;
            pose.pos.y        *= Origin.localScale.y;
            pose.pos.z        *= Origin.localScale.z;
            transform.position = pose.pos;
            transform.rotation = pose.rot;
        }
        else // Our device is not attached to anything, use it's raw tracked position
        {
            transform.localPosition = pose.pos;
            transform.localRotation = pose.rot;
        }
    }
Пример #33
0
    private SteamVR()
    {
        hmd = OpenVR.System;
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = OpenVR.Compositor;
        overlay    = OpenVR.Overlay;

        // Setup render values
        uint w = 0, h = 0;

        hmd.GetRecommendedRenderTargetSize(ref w, ref h);
        sceneWidth  = (float)w;
        sceneHeight = (float)h;

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;

        hmd.GetProjectionRaw(EVREye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);

        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;

        hmd.GetProjectionRaw(EVREye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        textureBounds = new VRTextureBounds_t[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f - 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f - 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f - 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f - 0.5f * r_top / tanHalfFov.y;

#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
        SteamVR.Unity.SetSubmitParams(textureBounds[0], textureBounds[1], EVRSubmitFlags.Submit_Default);
#endif
        // Grow the recommended size to account for the overlapping fov
        sceneWidth  = sceneWidth / Mathf.Max(textureBounds[0].uMax - textureBounds[0].uMin, textureBounds[1].uMax - textureBounds[1].uMin);
        sceneHeight = sceneHeight / Mathf.Max(textureBounds[0].vMax - textureBounds[0].vMin, textureBounds[1].vMax - textureBounds[1].vMin);

        aspect      = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Right))
        };

        if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL"))
        {
            graphicsAPI = EGraphicsAPIConvention.API_OpenGL;
        }
        else
        {
            graphicsAPI = EGraphicsAPIConvention.API_DirectX;
        }

        SteamVR_Utils.Event.Listen("initializing", OnInitializing);
        SteamVR_Utils.Event.Listen("calibrating", OnCalibrating);
        SteamVR_Utils.Event.Listen("out_of_range", OnOutOfRange);
        SteamVR_Utils.Event.Listen("device_connected", OnDeviceConnected);
        SteamVR_Utils.Event.Listen("new_poses", OnNewPoses);
    }
Пример #34
0
    public void Init(SteamVR_Camera tracker, SteamVR.Hmd_Eye eye, float depth)
    {
        this.tracker = tracker;
        this.eye     = eye;

        var hmd = SteamVR.IHmd.instance;
        var i   = (int)eye;

        uint x = 0, y = 0, w = 0, h = 0;

        hmd.GetEyeOutputViewport(eye, ref x, ref y, ref w, ref h);

        overlaySettings.kernel = new Vector3[] {         // AA sub-pixel sampling (2x2 RGSS)
            new Vector3(0.125f / w, -0.375f / h, 0),
            new Vector3(0.375f / w, 0.125f / h, 0),
            new Vector3(-0.125f / w, 0.375f / h, 0),
            new Vector3(-0.375f / w, -0.125f / h, 0)
        };

        float left = 0.0f, right = 0.0f, top = 0.0f, bottom = 0.0f;

        hmd.GetProjectionRaw(eye, ref left, ref right, ref top, ref bottom);

        var   camera = GetComponent <Camera>();
        float zFar   = camera.farClipPlane;
        float zNear  = camera.nearClipPlane;

        var m = Matrix4x4.identity;

        float idx = 1.0f / (right - left);
        float idy = 1.0f / (bottom - top);
        float idz = 1.0f / (zFar - zNear);
        float sx  = right + left;
        float sy  = bottom + top;

        m[0, 0] = 2 * idx; m[0, 1] = 0;     m[0, 2] = sx * idx;    m[0, 3] = 0;
        m[1, 0] = 0;     m[1, 1] = 2 * idy; m[1, 2] = sy * idy;    m[1, 3] = 0;
        m[2, 0] = 0;     m[2, 1] = 0;     m[2, 2] = -zFar * idz; m[2, 3] = -zFar * zNear * idz;
        m[3, 0] = 0;     m[3, 1] = 0;     m[3, 2] = -1.0f;     m[3, 3] = 0;

        camera.projectionMatrix = m;
        camera.depth            = depth;                                // enforce rendering order
        camera.eventMask        = 0;                                    // disable mouse events
        camera.orthographic     = false;                                // force perspective
        camera.aspect           = (float)w / h;

        // Use fov of projection matrix (which is grown to account for non-linear undistort)
        camera.fieldOfView = (Mathf.Atan(bottom) - Mathf.Atan(top)) * Mathf.Rad2Deg;

        // Copy and clear clearFlags to avoid duplicate work.
        if ((int)clearFlags == 0)
        {
            clearFlags        = camera.clearFlags;
            camera.clearFlags = CameraClearFlags.Nothing;
        }

        camera.targetTexture = SteamVR_Camera.sceneTexture;

        overlaySettings.invProj = m.inverse;

        transform.parent     = tracker.offset;
        transform.localScale = Vector3.one;

        var t = new SteamVR_Utils.RigidTransform(hmd.GetHeadFromEyePose(eye));

        transform.localPosition = t.pos;
        transform.localRotation = t.rot;

        if (distortMesh[i] == null)
        {
            var viewportWidth  = SteamVR_Camera.viewportTexture.width;
            var viewportHeight = SteamVR_Camera.viewportTexture.height;

            var eyeViewport = new Rect(
                2.0f * x / viewportWidth - 1.0f,
                2.0f * y / viewportHeight - 1.0f,
                2.0f * w / viewportWidth,
                2.0f * h / viewportHeight);

            distortMesh[i] = SteamVR_Utils.CreateDistortMesh(hmd, eye, 32, 32, eyeViewport);
        }
    }
Пример #35
0
    public void ReadConfig()
    {
        try {
            var mCam          = new HmdMatrix34_t();
            var readCamMatrix = false;

            object c     = config; // box
            var    lines = File.ReadAllLines(configPath);
            foreach (var line in lines)
            {
                var split = line.Split('=');
                if (split.Length == 2)
                {
                    var key = split[0];
                    if (key == "m")
                    {
                        var values = split[1].Split(',');
                        if (values.Length == 12)
                        {
                            mCam.m0       = float.Parse(values[0]);
                            mCam.m1       = float.Parse(values[1]);
                            mCam.m2       = float.Parse(values[2]);
                            mCam.m3       = float.Parse(values[3]);
                            mCam.m4       = float.Parse(values[4]);
                            mCam.m5       = float.Parse(values[5]);
                            mCam.m6       = float.Parse(values[6]);
                            mCam.m7       = float.Parse(values[7]);
                            mCam.m8       = float.Parse(values[8]);
                            mCam.m9       = float.Parse(values[9]);
                            mCam.m10      = float.Parse(values[10]);
                            mCam.m11      = float.Parse(values[11]);
                            readCamMatrix = true;
                        }
                    }
                    else if (key == "disableStandardAssets")
                    {
                        var field = c.GetType().GetField(key);
                        if (field != null)
                        {
                            field.SetValue(c, bool.Parse(split[1]));
                        }
                    }
                    else
                    {
                        var field = c.GetType().GetField(key);
                        if (field != null)
                        {
                            field.SetValue(c, float.Parse(split[1]));
                        }
                    }
                }
            }
            config = (Config)c; //unbox

            // Convert calibrated camera matrix settings.
            if (readCamMatrix)
            {
                var t = new SteamVR_Utils.RigidTransform(mCam);
                config.x = t.pos.x;
                config.y = t.pos.y;
                config.z = t.pos.z;
                var angles = t.rot.eulerAngles;
                config.rx = angles.x;
                config.ry = angles.y;
                config.rz = angles.z;
            }
        } catch {
        }
    }
Пример #36
0
    private void OnNewPoses(params object[] args)
    {
        if (index == EIndex.None)
            return;

        var i = (int)index;

        isValid = false;
        var poses = (Valve.VR.TrackedDevicePose_t[])args[0];
        if (poses.Length <= i)
            return;

        if (!poses[i].bDeviceIsConnected)
            return;

        if (!poses[i].bPoseIsValid)
            return;

        isValid = true;

        var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

        if (origin != null)
        {
            pose = new SteamVR_Utils.RigidTransform(origin) * pose;
            pose.pos.x *= origin.localScale.x;
            pose.pos.y *= origin.localScale.y;
            pose.pos.z *= origin.localScale.z;
            transform.position = pose.pos;
            transform.rotation = pose.rot;
        }
        else
        {
            transform.localPosition = pose.pos + pose.rot*offset;
            transform.localRotation = pose.rot*angles;

        }

        var vr = SteamVR.instance;
        var isController = (vr.hmd.GetTrackedDeviceClass((uint)i) == ETrackedDeviceClass.Controller);
        var state = new VRControllerState_t();
        var success = vr.hmd.GetControllerState((uint)i, ref state);
        var triggerPressed = (state.ulButtonPressed & SteamVR_Controller.ButtonMask.Trigger) != 0;

        if (Time.time >= cooldown) {
            if (triggerPressed) {
                Debug.Log ("trigger pressed");
                GameObject bPrefab = Instantiate(bulletPrefab, pose.pos, pose.rot) as GameObject;
                Rigidbody rb = bPrefab.AddComponent<Rigidbody>(); // Add the rigidbody.
                rb.mass = 1; // Set the GO's mass to 5 via the Rigidbody.
                rb.AddForce (pose.rot*Vector3.down * 3000f);
                cooldown = Time.time + attackSpeed;
            }
        }
    }
Пример #37
0
    public void ReadConfig()
    {
        try
        {
            var mCam = new HmdMatrix34_t();
            var readCamMatrix = false;

            object c = config; // box
            var lines = System.IO.File.ReadAllLines(configPath);
            foreach (var line in lines)
            {
                var split = line.Split('=');
                if (split.Length == 2)
                {
                    var key = split[0];
                    if (key == "m")
                    {
                        var values = split[1].Split(',');
                        if (values.Length == 12)
                        {
                            mCam.m0 = float.Parse(values[0]);
                            mCam.m1 = float.Parse(values[1]);
                            mCam.m2 = float.Parse(values[2]);
                            mCam.m3 = float.Parse(values[3]);
                            mCam.m4 = float.Parse(values[4]);
                            mCam.m5 = float.Parse(values[5]);
                            mCam.m6 = float.Parse(values[6]);
                            mCam.m7 = float.Parse(values[7]);
                            mCam.m8 = float.Parse(values[8]);
                            mCam.m9 = float.Parse(values[9]);
                            mCam.m10 = float.Parse(values[10]);
                            mCam.m11 = float.Parse(values[11]);
                            readCamMatrix = true;
                        }
                    }
                    else if (key == "disableStandardAssets")
                    {
                        var field = c.GetType().GetField(key);
                        if (field != null)
                            field.SetValue(c, bool.Parse(split[1]));
                    }
                    else
                    {
                        var field = c.GetType().GetField(key);
                        if (field != null)
                            field.SetValue(c, float.Parse(split[1]));
                    }
                }
            }
            config = (Config)c; //unbox

            // Convert calibrated camera matrix settings.
            if (readCamMatrix)
            {
                var t = new SteamVR_Utils.RigidTransform(mCam);
                config.x = t.pos.x;
                config.y = t.pos.y;
                config.z = t.pos.z;
                var angles = t.rot.eulerAngles;
                config.rx = angles.x;
                config.ry = angles.y;
                config.rz = angles.z;
            }
        }
        catch { }
    }
Пример #38
0
	public void UpdateTracking()
	{
		var head = SteamVR_Utils.RigidTransform.identity;
		if (!disableTracking)
		{
			var hmd = SteamVR.IHmd.instance;
			var pose = new SteamVR.HmdMatrix34_t();
			if (Time.renderedFrameCount != renderedFrameCount)
			{
				renderedFrameCount = Time.renderedFrameCount;

				var result = SteamVR.HmdTrackingResult.TrackingResult_Uninitialized;
				if (hmd.GetTrackerFromHeadPose(0.0f, ref pose, ref result))
					head = new SteamVR_Utils.RigidTransform(pose);

				var calibrating =
					result == SteamVR.HmdTrackingResult.TrackingResult_Calibrating_InProgress ||
					result == SteamVR.HmdTrackingResult.TrackingResult_Calibrating_OutOfRange;
				if (calibrating != SteamVR_Camera.calibrating)
				{
					SteamVR_Utils.Event.Send("calibrating", calibrating);
				}

				var trackingOutOfRange =
					result == SteamVR.HmdTrackingResult.TrackingResult_Running_OutOfRange ||
					result == SteamVR.HmdTrackingResult.TrackingResult_Calibrating_OutOfRange;
				if (trackingOutOfRange != SteamVR_Camera.trackingOutOfRange)
				{
					SteamVR_Utils.Event.Send("absolute_tracking", !trackingOutOfRange);
				}
			}
			else
			{
				if (hmd.GetLastTrackerFromHeadPose(ref pose))
					head = new SteamVR_Utils.RigidTransform(pose);
			}
		}

		offset.localPosition = head.pos;
		offset.localRotation = head.rot;

		// Update shared optional overlay shader variables
		if (overlaySettings.texture != null && applyDistortion)
		{
			distortMaterial.SetFloat("alpha", Mathf.Clamp01(overlaySettings.alpha));
			distortMaterial.SetVector("uvOffset", overlaySettings.uvOffset);

			var rot = Matrix4x4.identity;
			rot.SetColumn(0, head.rot * Vector3.right);
			rot.SetColumn(1, head.rot * Vector3.up);
			rot.SetColumn(2, head.rot * Vector3.forward);
			distortMaterial.SetMatrix("rot", rot);

			float aspect = (float)overlaySettings.texture.width / overlaySettings.texture.height;
			if (overlaySettings.curved)
			{
				var range = new Vector2(0.1f, 1.0f); // probably should make this tweakable
				var theta = Mathf.Lerp(60.0f, 5.0f, Mathf.SmoothStep(range.x, range.y, -offset.localPosition.z));
				var coef = new Vector4(2.0f * theta * Mathf.Deg2Rad, aspect / overlaySettings.scale, aspect, 2.0f * overlaySettings.distance);
				distortMaterial.SetVector("coef", coef);
				overlaySettings.radius = overlaySettings.scale / coef.x;
			}
			else
			{
				var coef = new Vector4(1.0f / overlaySettings.scale, aspect / overlaySettings.scale, 0, 0);
				distortMaterial.SetVector("coef", coef);
				overlaySettings.radius = 0.0f;
			}
		}
	}
    // Helper to create (or reuse if possible) each of our different overlay types.
    ulong GetOverlayHandle(string overlayName, Transform transform, float widthInMeters = 1.0f)
    {
        ulong handle = OpenVR.k_ulOverlayHandleInvalid;

        var overlay = OpenVR.Overlay;
        if (overlay == null)
            return handle;

        var key = SteamVR_Overlay.key + "." + overlayName;

        var error = overlay.FindOverlay(key, ref handle);
        if (error != EVROverlayError.None)
            error = overlay.CreateOverlay(key, overlayName, ref handle);
        if (error == EVROverlayError.None)
        {
            overlay.ShowOverlay(handle);
            overlay.SetOverlayAlpha(handle, alpha);
            overlay.SetOverlayWidthInMeters(handle, widthInMeters);

            // D3D textures are upside-down in Unity to match OpenGL.
            if (SteamVR.instance.graphicsAPI == EGraphicsAPIConvention.API_DirectX)
            {
                var textureBounds = new VRTextureBounds_t();
                textureBounds.uMin = 0;
                textureBounds.vMin = 1;
                textureBounds.uMax = 1;
                textureBounds.vMax = 0;
                overlay.SetOverlayTextureBounds(handle, ref textureBounds);
            }

            // Convert from world space to tracking space using the top-most camera.
            var vrcam = (loadingScreenDistance == 0.0f) ? SteamVR_Render.Top() : null;
            if (vrcam != null && vrcam.origin != null)
            {
                var offset = new SteamVR_Utils.RigidTransform(vrcam.origin, transform);
                offset.pos.x /= vrcam.origin.localScale.x;
                offset.pos.y /= vrcam.origin.localScale.y;
                offset.pos.z /= vrcam.origin.localScale.z;

                var t = offset.ToHmdMatrix34();
                overlay.SetOverlayTransformAbsolute(handle, SteamVR_Render.instance.trackingSpace, ref t);
            }
            else
            {
                var t = new SteamVR_Utils.RigidTransform(transform).ToHmdMatrix34();
                overlay.SetOverlayTransformAbsolute(handle, SteamVR_Render.instance.trackingSpace, ref t);
            }
        }

        return handle;
    }
Пример #40
0
    private void OnNewPoses(params object[] args)
    {
        var poses = (TrackedDevicePose_t[])args[0];
        if (poses.Length <= OpenVR.k_unTrackedDeviceIndex_Hmd)
            return;

        if (!poses[OpenVR.k_unTrackedDeviceIndex_Hmd].bPoseIsValid)
            return;

        var hmd = new SteamVR_Utils.RigidTransform(poses[OpenVR.k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking);
        zoffset = hmd.pos.z;
    }
Пример #41
0
 public void Multiply(SteamVR_Utils.RigidTransform a, SteamVR_Utils.RigidTransform b)
 {
     this.rot = a.rot * b.rot;
     this.pos = a.pos + a.rot * b.pos;
 }
Пример #42
0
 public void UpdateOverlay()
 {
     CVROverlay overlay = OpenVR.Overlay;
     if (overlay == null)
     {
         return;
     }
     if (this.texture != null)
     {
         EVROverlayError eVROverlayError = overlay.ShowOverlay(this.handle);
         if ((eVROverlayError == EVROverlayError.InvalidHandle || eVROverlayError == EVROverlayError.UnknownOverlay) && overlay.FindOverlay(SteamVR_Overlay.key, ref this.handle) != EVROverlayError.None)
         {
             return;
         }
         Texture_t texture_t = default(Texture_t);
         texture_t.handle = this.texture.GetNativeTexturePtr();
         texture_t.eType = SteamVR.instance.graphicsAPI;
         texture_t.eColorSpace = EColorSpace.Auto;
         overlay.SetOverlayTexture(this.handle, ref texture_t);
         overlay.SetOverlayAlpha(this.handle, this.alpha);
         overlay.SetOverlayWidthInMeters(this.handle, this.scale);
         overlay.SetOverlayAutoCurveDistanceRangeInMeters(this.handle, this.curvedRange.x, this.curvedRange.y);
         VRTextureBounds_t vRTextureBounds_t = default(VRTextureBounds_t);
         vRTextureBounds_t.uMin = (0f + this.uvOffset.x) * this.uvOffset.z;
         vRTextureBounds_t.vMin = (1f + this.uvOffset.y) * this.uvOffset.w;
         vRTextureBounds_t.uMax = (1f + this.uvOffset.x) * this.uvOffset.z;
         vRTextureBounds_t.vMax = (0f + this.uvOffset.y) * this.uvOffset.w;
         overlay.SetOverlayTextureBounds(this.handle, ref vRTextureBounds_t);
         HmdVector2_t hmdVector2_t = default(HmdVector2_t);
         hmdVector2_t.v0 = this.mouseScale.x;
         hmdVector2_t.v1 = this.mouseScale.y;
         overlay.SetOverlayMouseScale(this.handle, ref hmdVector2_t);
         SteamVR_Camera steamVR_Camera = SteamVR_Render.Top();
         if (steamVR_Camera != null && steamVR_Camera.origin != null)
         {
             SteamVR_Utils.RigidTransform rigidTransform = new SteamVR_Utils.RigidTransform(steamVR_Camera.origin, base.transform);
             rigidTransform.pos.x = rigidTransform.pos.x / steamVR_Camera.origin.localScale.x;
             rigidTransform.pos.y = rigidTransform.pos.y / steamVR_Camera.origin.localScale.y;
             rigidTransform.pos.z = rigidTransform.pos.z / steamVR_Camera.origin.localScale.z;
             rigidTransform.pos.z = rigidTransform.pos.z + this.distance;
             HmdMatrix34_t hmdMatrix34_t = rigidTransform.ToHmdMatrix34();
             overlay.SetOverlayTransformAbsolute(this.handle, SteamVR_Render.instance.trackingSpace, ref hmdMatrix34_t);
         }
         overlay.SetOverlayInputMethod(this.handle, this.inputMethod);
         if (this.curved || this.antialias)
         {
             this.highquality = true;
         }
         if (this.highquality)
         {
             overlay.SetHighQualityOverlay(this.handle);
             overlay.SetOverlayFlag(this.handle, VROverlayFlags.Curved, this.curved);
             overlay.SetOverlayFlag(this.handle, VROverlayFlags.RGSS4X, this.antialias);
         }
         else if (overlay.GetHighQualityOverlay() == this.handle)
         {
             overlay.SetHighQualityOverlay(0uL);
         }
     }
     else
     {
         overlay.HideOverlay(this.handle);
     }
 }
Пример #43
0
 public void Interpolate(SteamVR_Utils.RigidTransform to, float t)
 {
     this.pos = SteamVR_Utils.Lerp(this.pos, to.pos, t);
     this.rot = SteamVR_Utils.Slerp(this.rot, to.rot, t);
 }
Пример #44
0
    private SteamVR(System.IntPtr pHmd, System.IntPtr pCompositor, System.IntPtr pOverlay)
    {
        hmd = new CVRSystem(pHmd);
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = new CVRCompositor(pCompositor);
        overlay = new CVROverlay(pOverlay);

        var capacity = compositor.GetLastError(null, 0);
        if (capacity > 1)
        {
            var result = new System.Text.StringBuilder((int)capacity);
            compositor.GetLastError(result, capacity);
            Debug.Log("Compositor - " + result);
        }

        // Setup render values
        uint w = 0, h = 0;
        hmd.GetRecommendedRenderTargetSize(ref w, ref h);
        sceneWidth = (float)w;
        sceneHeight = (float)h;

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;
        hmd.GetProjectionRaw(Hmd_Eye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);

        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;
        hmd.GetProjectionRaw(Hmd_Eye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        textureBounds = new VRTextureBounds_t[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f - 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f - 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f - 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f - 0.5f * r_top / tanHalfFov.y;

        Unity.SetSubmitParams(textureBounds[0], textureBounds[1], VRSubmitFlags_t.Submit_Default);

        // Grow the recommended size to account for the overlapping fov
        sceneWidth = sceneWidth / Mathf.Max(textureBounds[0].uMax - textureBounds[0].uMin, textureBounds[1].uMax - textureBounds[1].uMin);
        sceneHeight = sceneHeight / Mathf.Max(textureBounds[0].vMax - textureBounds[0].vMin, textureBounds[1].vMax - textureBounds[1].vMin);

        aspect = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Right)) };

        if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL"))
            graphicsAPI = GraphicsAPIConvention.API_OpenGL;
        else
            graphicsAPI = GraphicsAPIConvention.API_DirectX;

        SteamVR_Utils.Event.Listen("initializing", OnInitializing);
        SteamVR_Utils.Event.Listen("calibrating", OnCalibrating);
        SteamVR_Utils.Event.Listen("out_of_range", OnOutOfRange);
        SteamVR_Utils.Event.Listen("device_connected", OnDeviceConnected);
        SteamVR_Utils.Event.Listen("new_poses", OnNewPoses);
    }
Пример #45
0
    void Update()
    {
        #if UNITY_EDITOR
        if (!Application.isPlaying)
        {
            // See if anything has changed since this gets called whenever anything gets touched.
            var fields = GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            bool modified = false;

            if (values == null)
            {
                modified = true;
            }
            else
            {
                foreach (var f in fields)
                {
                    if (!values.Contains(f) || !f.GetValue(this).Equals(values[f]))
                    {
                        modified = true;
                        break;
                    }
                }
            }

            if (modified)
            {
                SetModel(modelOverride);

                values = new Hashtable();
                foreach (var f in fields)
                    values[f] = f.GetValue(this);
            }

            return; // Do not update transforms (below) when not playing in Editor (to avoid keeping OpenVR running all the time).
        }
        #endif
        // Update component transforms dynamically.
        if (updateDynamically)
        {
            using (var holder = new RenderModelInterfaceHolder())
            {
                var controllerState = SteamVR_Controller.Input((int)index).GetState();

                var t = transform;
                var baseTransform = new SteamVR_Utils.RigidTransform(t);

                for (int i = 0; i < t.childCount; i++)
                {
                    var child = t.GetChild(i);

                    var renderModels = holder.instance;
                    if (renderModels == null)
                        break;

                    var componentState = new RenderModel_ComponentState_t();
                    if (!renderModels.GetComponentState(renderModelName, child.name, ref controllerState, ref componentState))
                        continue;

                    var componentTransform = new SteamVR_Utils.RigidTransform(componentState.mTrackingToComponentRenderModel);
                    child.localPosition = componentTransform.pos;
                    child.localRotation = componentTransform.rot;

                    var attach = child.FindChild(k_localTransformName);
                    if (attach != null)
                    {
                        var attachTransform = baseTransform * new SteamVR_Utils.RigidTransform(componentState.mTrackingToComponentLocal);
                        attach.position = attachTransform.pos;
                        attach.rotation = attachTransform.rot;
                    }

                    bool visible = (componentState.uProperties & (uint)EVRComponentProperty.VRComponentProperty_IsVisible) != 0;
                    if (visible != child.gameObject.activeSelf)
                    {
                        child.gameObject.SetActive(visible);
                    }
                }
            }
        }
    }
Пример #46
0
	private void OnNewPoses(params object[] args)
	{
		var poses = (TrackedDevicePose_t[])args[0];

		// Update eye offsets to account for IPD changes.
		eyes[0] = new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Left));
		eyes[1] = new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Right));

		for (int i = 0; i < poses.Length; i++)
		{
			var connected = poses[i].bDeviceIsConnected;
			if (connected != SteamVR.connected[i])
			{
				SteamVR_Utils.Event.Send("device_connected", i, connected);
			}
		}

		if (poses.Length > OpenVR.k_unTrackedDeviceIndex_Hmd)
		{
			var result = poses[OpenVR.k_unTrackedDeviceIndex_Hmd].eTrackingResult;

			var initializing = result == ETrackingResult.Uninitialized;
			if (initializing != SteamVR.initializing)
			{
				SteamVR_Utils.Event.Send("initializing", initializing);
			}

			var calibrating =
				result == ETrackingResult.Calibrating_InProgress ||
				result == ETrackingResult.Calibrating_OutOfRange;
			if (calibrating != SteamVR.calibrating)
			{
				SteamVR_Utils.Event.Send("calibrating", calibrating);
			}

			var outOfRange =
				result == ETrackingResult.Running_OutOfRange ||
				result == ETrackingResult.Calibrating_OutOfRange;
			if (outOfRange != SteamVR.outOfRange)
			{
				SteamVR_Utils.Event.Send("out_of_range", outOfRange);
			}
		}
	}
Пример #47
0
    private SteamVR()
    {
        hmd = OpenVR.System;
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = OpenVR.Compositor;
        overlay    = OpenVR.Overlay;

        // Setup render values
        uint w = 0, h = 0;

        hmd.GetRecommendedRenderTargetSize(ref w, ref h);
        sceneWidth  = (float)w;
        sceneHeight = (float)h;

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;

        hmd.GetProjectionRaw(EVREye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);

        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;

        hmd.GetProjectionRaw(EVREye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        textureBounds = new VRTextureBounds_t[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f - 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f - 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f - 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f - 0.5f * r_top / tanHalfFov.y;

        // Grow the recommended size to account for the overlapping fov
        sceneWidth  = sceneWidth / Mathf.Max(textureBounds[0].uMax - textureBounds[0].uMin, textureBounds[1].uMax - textureBounds[1].uMin);
        sceneHeight = sceneHeight / Mathf.Max(textureBounds[0].vMax - textureBounds[0].vMin, textureBounds[1].vMax - textureBounds[1].vMin);

        aspect      = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(EVREye.Eye_Right))
        };

        switch (SystemInfo.graphicsDeviceType)
        {
#if (UNITY_5_4)
        case UnityEngine.Rendering.GraphicsDeviceType.OpenGL2:
#endif
        case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
        case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
        case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
            textureType = ETextureType.OpenGL;
            break;

#if !(UNITY_5_4)
        case UnityEngine.Rendering.GraphicsDeviceType.Vulkan:
            textureType = ETextureType.Vulkan;
            break;
#endif
        default:
            textureType = ETextureType.DirectX;
            break;
        }

        SteamVR_Events.Initializing.Listen(OnInitializing);
        SteamVR_Events.Calibrating.Listen(OnCalibrating);
        SteamVR_Events.OutOfRange.Listen(OnOutOfRange);
        SteamVR_Events.DeviceConnected.Listen(OnDeviceConnected);
        SteamVR_Events.NewPoses.Listen(OnNewPoses);
    }
    private void OnNewPoses(TrackedDevicePose_t[] poses)
    {
        if (index == EIndex.None)
        {
            return;
        }

        var i = (int)index;

        isValid = false;
        if (poses.Length <= i)
        {
            return;
        }

        if (!poses[i].bDeviceIsConnected)
        {
            return;
        }

        var trackerIndex = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.First, ETrackedDeviceClass.GenericTracker);

        if (i == trackerIndex)
        {
            tracker = this.gameObject;
        }
        if (index == EIndex.Hmd)
        {
            isValid = true;
            return;

            if (poses[0].bPoseIsValid)
            {
                headCamera.transform.SetParent(headTracking.transform);
            }
            else
            {
                if (tracker != null)
                {
                    headCamera.transform.SetParent(tracker.transform);
                }
            }
        }

        if (!poses[i].bPoseIsValid)
        {
            return;
        }

        isValid = true;

        var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);

        if (origin != null)
        {
            transform.position = origin.transform.TransformPoint(pose.pos);
            transform.rotation = origin.rotation * pose.rot;
        }
        else
        {
            transform.localPosition = pose.pos;
            transform.localRotation = pose.rot;
        }
    }
    public void UpdateOverlay(SteamVR vr)
    {
        if (texture != null)
        {
            var error = vr.overlay.ShowOverlay(handle);
            if (error == VROverlayError.InvalidHandle || error == VROverlayError.UnknownOverlay)
            {
                if (vr.overlay.FindOverlay(key, ref handle) != VROverlayError.None)
                    return;
            }

            vr.overlay.SetOverlayTexture(handle, texture.GetNativeTexturePtr());
            vr.overlay.SetOverlayAlpha(handle, alpha);
            vr.overlay.SetOverlayGamma(handle, gamma);
            vr.overlay.SetOverlayWidthInMeters(handle, scale);

            var textureBounds = new VRTextureBounds_t();
            textureBounds.uMin = (0 + uvOffset.x) * uvOffset.z;
            textureBounds.vMin = (1 + uvOffset.y) * uvOffset.w;
            textureBounds.uMax = (1 + uvOffset.x) * uvOffset.z;
            textureBounds.vMax = (0 + uvOffset.y) * uvOffset.w;
            vr.overlay.SetOverlayTextureBounds(handle, ref textureBounds);

            var vecMouseScale = new HmdVector2_t();
            vecMouseScale.v = new float[] { mouseScale.x, mouseScale.y };
            vr.overlay.SetOverlayMouseScale(handle, ref vecMouseScale);

            var vrcam = SteamVR_Render.Top();
            if (vrcam != null && vrcam.origin != null)
            {
                var offset = new SteamVR_Utils.RigidTransform(vrcam.origin, transform);
                offset.pos.x /= vrcam.origin.localScale.x;
                offset.pos.y /= vrcam.origin.localScale.y;
                offset.pos.z /= vrcam.origin.localScale.z;

                offset.pos.z += distance;

                var t = offset.ToHmdMatrix34();
                vr.overlay.SetOverlayTransformAbsolute(handle, SteamVR_Render.instance.trackingSpace, ref t);
            }

            vr.overlay.SetOverlayVisibility(handle, visibility);
            vr.overlay.SetOverlayInputMethod(handle, inputMethod);

            if (curved || antialias)
                highquality = true;

            if (highquality)
            {
                vr.overlay.SetHighQualityOverlay(handle);
                vr.overlay.SetOverlayFlag(handle, VROverlayFlags.Curved, curved);
                vr.overlay.SetOverlayFlag(handle, VROverlayFlags.RGSS4X, antialias);
            }
            else if (vr.overlay.GetHighQualityOverlay() == handle)
            {
                vr.overlay.SetHighQualityOverlay(OpenVR.k_ulOverlayHandleInvalid);
            }
        }
        else
        {
            vr.overlay.HideOverlay(handle);
        }
    }
Пример #50
0
    public void UpdateOverlay()
    {
        var overlay = OpenVR.Overlay;

        if (overlay == null)
        {
            return;
        }

        if (texture != null)
        {
            var error = overlay.ShowOverlay(handle);
            if (error == EVROverlayError.InvalidHandle || error == EVROverlayError.UnknownOverlay)
            {
                if (overlay.FindOverlay(key, ref handle) != EVROverlayError.None)
                {
                    return;
                }
            }

            var tex = new Texture_t();
            tex.handle      = texture.GetNativeTexturePtr();
            tex.eType       = SteamVR.instance.graphicsAPI;
            tex.eColorSpace = EColorSpace.Auto;
            overlay.SetOverlayTexture(handle, ref tex);

            overlay.SetOverlayAlpha(handle, alpha);
            overlay.SetOverlayWidthInMeters(handle, scale);
            overlay.SetOverlayAutoCurveDistanceRangeInMeters(handle, curvedRange.x, curvedRange.y);

            var textureBounds = new VRTextureBounds_t();
            textureBounds.uMin = (0 + uvOffset.x) * uvOffset.z;
            textureBounds.vMin = (1 + uvOffset.y) * uvOffset.w;
            textureBounds.uMax = (1 + uvOffset.x) * uvOffset.z;
            textureBounds.vMax = (0 + uvOffset.y) * uvOffset.w;
            overlay.SetOverlayTextureBounds(handle, ref textureBounds);

            var vecMouseScale = new HmdVector2_t();
            vecMouseScale.v0 = mouseScale.x;
            vecMouseScale.v1 = mouseScale.y;
            overlay.SetOverlayMouseScale(handle, ref vecMouseScale);

            var vrcam = SteamVR_Render.Top();
            if (vrcam != null && vrcam.origin != null)
            {
                var offset = new SteamVR_Utils.RigidTransform(vrcam.origin, transform);
                offset.pos.x /= vrcam.origin.localScale.x;
                offset.pos.y /= vrcam.origin.localScale.y;
                offset.pos.z /= vrcam.origin.localScale.z;

                offset.pos.z += distance;

                var t = offset.ToHmdMatrix34();
                overlay.SetOverlayTransformAbsolute(handle, SteamVR_Render.instance.trackingSpace, ref t);
            }

            overlay.SetOverlayInputMethod(handle, inputMethod);

            if (curved || antialias)
            {
                highquality = true;
            }

            if (highquality)
            {
                overlay.SetHighQualityOverlay(handle);
                overlay.SetOverlayFlag(handle, VROverlayFlags.Curved, curved);
                overlay.SetOverlayFlag(handle, VROverlayFlags.RGSS4X, antialias);
            }
            else if (overlay.GetHighQualityOverlay() == handle)
            {
                overlay.SetHighQualityOverlay(OpenVR.k_ulOverlayHandleInvalid);
            }
        }
        else
        {
            overlay.HideOverlay(handle);
        }
    }
Пример #51
0
        private void UpdateDevicePose(bool obj)
        {
            IVRModuleDeviceState   prevState;
            IVRModuleDeviceStateRW currState;

            FlushDeviceState();

            var vrSystem     = OpenVR.System;
            var vrCompositor = OpenVR.Compositor;

            if (vrSystem == null || vrCompositor == null)
            {
                for (uint i = 0, imax = GetDeviceStateLength(); i < imax; ++i)
                {
                    if (TryGetValidDeviceState(i, out prevState, out currState) && currState.isConnected)
                    {
                        currState.Reset();
                    }
                }

                return;
            }

            vrCompositor.GetLastPoses(m_poses, m_gamePoses);

            for (uint i = 0u, imax = (uint)m_poses.Length; i < imax; ++i)
            {
                if (!m_poses[i].bDeviceIsConnected)
                {
                    if (TryGetValidDeviceState(i, out prevState, out currState) && prevState.isConnected)
                    {
                        s_devicePathHandles[i] = OpenVR.k_ulInvalidInputValueHandle;
                        currState.Reset();
                    }
                }
                else
                {
                    EnsureValidDeviceState(i, out prevState, out currState);

                    if (!prevState.isConnected)
                    {
                        currState.isConnected     = true;
                        currState.deviceClass     = (VRModuleDeviceClass)vrSystem.GetTrackedDeviceClass(i);
                        currState.serialNumber    = QueryDeviceStringProperty(vrSystem, i, ETrackedDeviceProperty.Prop_SerialNumber_String);
                        currState.modelNumber     = QueryDeviceStringProperty(vrSystem, i, ETrackedDeviceProperty.Prop_ModelNumber_String);
                        currState.renderModelName = QueryDeviceStringProperty(vrSystem, i, ETrackedDeviceProperty.Prop_RenderModelName_String);

                        SetupKnownDeviceModel(currState);

                        m_originDataCache.Clear();
                    }

                    // update device status
                    currState.isPoseValid     = m_poses[i].bPoseIsValid;
                    currState.isOutOfRange    = m_poses[i].eTrackingResult == ETrackingResult.Running_OutOfRange || m_poses[i].eTrackingResult == ETrackingResult.Calibrating_OutOfRange;
                    currState.isCalibrating   = m_poses[i].eTrackingResult == ETrackingResult.Calibrating_InProgress || m_poses[i].eTrackingResult == ETrackingResult.Calibrating_OutOfRange;
                    currState.isUninitialized = m_poses[i].eTrackingResult == ETrackingResult.Uninitialized;
                    currState.velocity        = new Vector3(m_poses[i].vVelocity.v0, m_poses[i].vVelocity.v1, -m_poses[i].vVelocity.v2);
                    currState.angularVelocity = new Vector3(-m_poses[i].vAngularVelocity.v0, -m_poses[i].vAngularVelocity.v1, m_poses[i].vAngularVelocity.v2);

                    var rigidTransform = new SteamVR_Utils.RigidTransform(m_poses[i].mDeviceToAbsoluteTracking);
                    currState.position = rigidTransform.pos;
                    currState.rotation = rigidTransform.rot;
                }
            }

            ProcessConnectedDeviceChanged();
            ProcessDevicePoseChanged();
        }
Пример #52
0
 public void UpdatePos()
 {
     SteamVR_Utils.RigidTransform rigid = new SteamVR_Utils.RigidTransform(this.transform);
     Valve.VR.HmdMatrix34_t trans = rigid.ToHmdMatrix34();
     SteamVR.instance.overlay.SetKeyboardTransformAbsolute(Valve.VR.ETrackingUniverseOrigin.TrackingUniverseStanding, ref trans);
 }