Example #1
0
    static SteamVR CreateInstance()
    {
        try
        {
            var error = EVRInitError.None;
            if (!SteamVR.usingNativeSupport)
            {
                Debug.Log("OpenVR initialization failed.  Ensure 'Virtual Reality Supported' is checked in Player Settings, and OpenVR is added to the list of Virtual Reality SDKs.");
                return(null);
            }

            // Verify common interfaces are valid.

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                return(null);
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                return(null);
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError(e);
            return(null);
        }

        return(new SteamVR());
    }
Example #2
0
 public OpenVRInterface()
 {
     if (CoreSettings.CoreSettings.Default.UseTracking)
     {
         OpenVR.Init(ref EVRerror, EVRApplicationType.VRApplication_Overlay);
         if (EVRerror != EVRInitError.None)
         {
             //   throw new Exception("An error occured while initializing OpenVR!");
         }
         OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref EVRerror);
         if (EVRerror != EVRInitError.None)
         {
             // throw new Exception("An error occured while initializing Compositor!");
         }
         OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref EVRerror);
         if (EVRerror != EVRInitError.None)
         {
             // throw new Exception("An error occured while initializing Overlay!");
         }
         SetupDevices();
     }
     else
     {
         EVRerror = EVRInitError.Unknown;
     }
 }
        static void InitOpenVR()
        {
            EVRInitError ovrError = EVRInitError.None;

            OpenVR.Init(ref ovrError, EVRApplicationType.VRApplication_Overlay);

            if (ovrError != EVRInitError.None)
            {
                throw new Exception("Failed to init OpenVR! " + ovrError.ToString());
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref ovrError);

            if (ovrError != EVRInitError.None)
            {
                throw new Exception("Failed to init Compositor! " + ovrError.ToString());
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref ovrError);

            if (ovrError != EVRInitError.None)
            {
                throw new Exception("Failed to init Overlay!");
            }

            SteamVR_Event.Listen("new_poses", OnNewPoses);
            SteamVR_Event.Listen("KeyboardDone", OnKeyboardDone);
            SteamVR_Event.Listen("KeyboardCharInput", OnKeyboardCharInput);
            SteamVR_Event.Listen("KeyboardClosed", OnKeyboardClosed);
        }
Example #4
0
    public static object CallSystemFn(SystemFn fn, params object[] args)
    {
        object result = null;

        if (SteamVR.active)
        {
            result = fn(SteamVR.instance.hmd, args);
        }
        else
        {
            var error   = HmdError.None;
            var pSystem = OpenVR.Init(ref error);
            if (pSystem != System.IntPtr.Zero && error == HmdError.None)
            {
                // Make sure we're using the proper version
                pSystem = OpenVR.GetGenericInterface(OpenVR.IVRSystem_Version, ref error);
                if (pSystem != System.IntPtr.Zero && error == HmdError.None)
                {
                    var system = new CVRSystem(pSystem);
                    result = fn(system, args);
                }
                OpenVR.Shutdown();
            }
        }
        return(result);
    }
Example #5
0
 private static SteamVR CreateInstance()
 {
     try
     {
         EVRInitError evrinitError = EVRInitError.None;
         if (!SteamVR.usingNativeSupport)
         {
             Debug.Log("OpenVR initialization failed.  Ensure 'Virtual Reality Supported' is checked in Player Settings, and OpenVR is added to the list of Virtual Reality SDKs.");
             return(null);
         }
         OpenVR.GetGenericInterface("IVRCompositor_022", ref evrinitError);
         if (evrinitError != EVRInitError.None)
         {
             SteamVR.ReportError(evrinitError);
             return(null);
         }
         OpenVR.GetGenericInterface("IVROverlay_018", ref evrinitError);
         if (evrinitError != EVRInitError.None)
         {
             SteamVR.ReportError(evrinitError);
             return(null);
         }
     }
     catch (Exception message)
     {
         Debug.LogError(message);
         return(null);
     }
     return(new SteamVR());
 }
Example #6
0
        public static bool InitializeTemporarySession(bool initInput = false)
        {
            if (Application.isEditor)
            {
                //bool needsInit = (!active && !usingNativeSupport && !runningTemporarySession);

                EVRInitError initError = EVRInitError.None;
                OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref initError);
                bool needsInit = initError != EVRInitError.None;

                if (needsInit)
                {
                    EVRInitError error = EVRInitError.None;
                    OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);

                    if (error != EVRInitError.None)
                    {
                        Debug.LogError("<b>[SteamVR]</b> Error during OpenVR Init: " + error.ToString());
                        return(false);
                    }

                    IdentifyEditorApplication(false);

                    //SteamVR_Input.IdentifyActionsFile(false);

                    runningTemporarySession = true;
                }



                return(needsInit);
            }

            return(false);
        }
Example #7
0
    IEnumerator UpdateBounds()
    {
        GetComponent <MeshFilter>().mesh = null;        // clear existing

        var vr = SteamVR.instance;

        if (vr == null)
        {
            yield break;
        }

        var error      = HmdError.None;
        var pChaperone = OpenVR.GetGenericInterface(OpenVR.IVRChaperone_Version, ref error);

        if (pChaperone == System.IntPtr.Zero || error != HmdError.None)
        {
            yield break;
        }

        var chaperone = new CVRChaperone(pChaperone);

        while (chaperone.GetCalibrationState() != ChaperoneCalibrationState.OK)
        {
            yield return(null);
        }

        BuildMesh();
    }
Example #8
0
        public void Init(EVRApplicationType ApplicationType = EVRApplicationType.VRApplication_Overlay)
        {
            //Dummy OpenTK Window
            GameWindow window = new GameWindow(300, 300);

            EVRInitError error = EVRInitError.None;

            OpenVR.Init(ref error, ApplicationType);

            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing OpenVR!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Compositor!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Overlay!");
            }

            System.Threading.Thread OverlayThread = new System.Threading.Thread(new System.Threading.ThreadStart(OverlayCycle));
            OverlayThread.IsBackground = true;
            OverlayThread.Start();
        }
Example #9
0
        private void MonitorForm_Load(object sender, EventArgs e)
        {
            var err = EVRInitError.Driver_Failed;

            _vrSystem = OpenVR.Init(ref err, EVRApplicationType.VRApplication_Background);
            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref err);
            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref err);
        }
Example #10
0
    static string[] LoadRenderModelNames()
    {
        var results = new List <string>();

        results.Add("None");

        var error = HmdError.None;

        if (!SteamVR.active)
        {
            OpenVR.Init(ref error);
            if (error != HmdError.None)
            {
                return(results.ToArray());
            }
        }

        var pRenderModels = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);

        if (pRenderModels == System.IntPtr.Zero || error != HmdError.None)
        {
            if (!SteamVR.active)
            {
                OpenVR.Shutdown();
            }
            return(results.ToArray());
        }

        var renderModels = new CVRRenderModels(pRenderModels);

        uint count = renderModels.GetRenderModelCount();

        for (uint i = 0; i < count; i++)
        {
            var buffer       = new StringBuilder();
            var requiredSize = renderModels.GetRenderModelName(i, buffer, 0);
            if (requiredSize == 0)
            {
                continue;
            }

            buffer.EnsureCapacity((int)requiredSize);
            renderModels.GetRenderModelName(i, buffer, requiredSize);
            results.Add(buffer.ToString());
        }

        if (!SteamVR.active)
        {
            OpenVR.Shutdown();
        }

        return(results.ToArray());
    }
Example #11
0
        internal VRSystem()
        {
            if (!OpenVR.IsRuntimeInstalled())
            {
                throw new Exception("VR Runtime not installed");
            }
            if (!OpenVR.IsHmdPresent())
            {
                throw new Exception("HMD not found");
            }
            EVRInitError error = EVRInitError.None;

            vrContext = OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                Console.WriteLine(error);
            }

            compositor  = OpenVR.Compositor;
            RenderModel = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);
            if (RenderModel == IntPtr.Zero)
            {
                ;
            }
            {
                Console.WriteLine(error);
            }

            controllerSystem = new VRControllerSystem(vrContext);

            leftTexture             = new Texture_t();
            leftTexture.eType       = ETextureType.OpenGL;
            leftTexture.eColorSpace = EColorSpace.Gamma;

            rightTexture             = new Texture_t();
            rightTexture.eType       = ETextureType.OpenGL;
            rightTexture.eColorSpace = EColorSpace.Gamma;
            vrContext.GetRecommendedRenderTargetSize(ref height, ref width);

            bound      = new VRTextureBounds_t();
            bound.uMin = 0;
            bound.vMin = 0;
            bound.vMax = 1;
            bound.uMax = 1;

            /*
             * var errProp = new ETrackedPropertyError();
             * var str = new StringBuilder();
             * vrContext.GetStringTrackedDeviceProperty(OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_TrackingSystemName_String, str, 100, ref errProp);
             */
        }
Example #12
0
        private static bool InitOverlays()
        {
            EVRInitError iError  = EVRInitError.None;
            IntPtr       pointer = OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref iError);

            if (iError != EVRInitError.None)
            {
                Debug.Fail("Overlays init failed " + iError.ToString());
                Log.WriteLine("Error " + iError);
                return(false);
            }
            m_cvrOverlay = new CVROverlay(pointer);
            return(true);
        }
Example #13
0
    static SteamVR CreateInstance()
    {
        try
        {
            var error = EVRInitError.None;
            if (!SteamVR.usingNativeSupport)
            {
#if !(UNITY_5_3_OR_NEWER || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
                Debug.Log("OpenVR initialization failed.  Ensure 'Virtual Reality Supported' is checked in Player Settings, and OpenVR is added to the list of Virtual Reality SDKs.");
                return(null);
#else
                OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
                if (error != EVRInitError.None)
                {
                    ReportError(error);
                    ShutdownSystems();
                    return(null);
                }
#endif
            }

            // Verify common interfaces are valid.

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError(e);
            return(null);
        }

        return(new SteamVR());
    }
Example #14
0
        static void Main(string[] args)
        {
            string ResourcePath = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName + "/Resources/";

            // init
            var error = EVRInitError.None;

            OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }


            // create overlay, ...
            var overlay = OpenVR.Overlay;

            ulong overlayHandle = 0, thumbnailHandle = 0;

            overlay.CreateDashboardOverlay("overlayTest", "HL3", ref overlayHandle, ref thumbnailHandle);
            overlay.SetOverlayFromFile(thumbnailHandle, $"{ResourcePath}/white-lambda.png");

            overlay.SetOverlayWidthInMeters(overlayHandle, 2.5f);
            overlay.SetOverlayInputMethod(overlayHandle, VROverlayInputMethod.Mouse);
            Console.CancelKeyPress += (s, e) => overlay.DestroyOverlay(overlayHandle);

            while (true)
            {
                Thread.Sleep(10); // This sucks but will do for now
                if (overlay.IsOverlayVisible(overlayHandle))
                {
                    overlay.SetOverlayFromFile(overlayHandle, $"{ResourcePath}/hl3.jpg");
                }
            }
        }
Example #15
0
    static SteamVR CreateInstance()
    {
        var error = HmdError.None;
        var pHmd  = OpenVR.Init(ref error);

        ReportError(error);

        if (pHmd == System.IntPtr.Zero || error != HmdError.None)
        {
            ShutdownSystems();
            return(null);
        }

        // Make sure we're using the proper version
        pHmd = OpenVR.GetGenericInterface(OpenVR.IVRSystem_Version, ref error);
        ReportError(error);

        if (pHmd == System.IntPtr.Zero || error != HmdError.None)
        {
            ShutdownSystems();
            return(null);
        }

        var pCompositor = OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);

        ReportError(error);

        if (pCompositor == System.IntPtr.Zero || error != HmdError.None)
        {
            ShutdownSystems();
            return(null);
        }

        var pOverlay = OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);

        ReportError(error);

        if (pOverlay == System.IntPtr.Zero || error != HmdError.None)
        {
            ShutdownSystems();
            return(null);
        }

        return(new SteamVR(pHmd, pCompositor, pOverlay));
    }
Example #16
0
        /// <summary>
        /// Initializes the OpenVR subsystem.
        /// </summary>
        private void InitOpenVR()
        {
            Debug.Log("[VR] OpenVR init begin");

            // Initialize OpenVR
            EVRInitError error = EVRInitError.None;

            Hmd = OpenVR.Init(ref error);

            bool success = true;

            if (error != EVRInitError.None)
            {
                VRUtils.ReportInitError(error);
                success = false;
            }

            // Check if compositor is present

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);

            if (error != EVRInitError.None)
            {
                VRUtils.ReportInitError(error);
                success = false;
            }

            // Check if overlay is present

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);

            if (error != EVRInitError.None)
            {
                VRUtils.ReportInitError(error);
                success = false;
            }

            // Shutdown on error
            if (!success)
            {
                OpenVR.Shutdown();
            }

            Debug.Log("[VR] OpenVR init end");
        }
Example #17
0
    // Use this for initialization
    void Start()
    {
        var error = EVRInitError.None;


        var pChaperone = OpenVR.GetGenericInterface(OpenVR.IVRChaperone_Version, ref error);

        if (pChaperone == System.IntPtr.Zero || error != EVRInitError.None)
        {
            // if (!SteamVR.active)
            //   OpenVR.Shutdown();

            return;
        }


        var chaperone      = new CVRChaperone(pChaperone);
        var chaperoneSetup = new CVRChaperoneSetup(pChaperone);

        //var  pQuadsBuffer = new HmdQuad_t[];

        HmdQuad_t[] pQuadsBuffer = null;


        // //pQuadsBuffer= new HmdQuad_t[punQuadsCount];
//
        // int punQuadsCount = 10;
        // HmdQuad_t[] pqd = new HmdQuad_t[[punQuadsCount];
        bool hasBounds = chaperoneSetup.GetLiveCollisionBoundsInfo(out pQuadsBuffer);

        if (hasBounds == true)
        {
            print("YAYA");
            print(pQuadsBuffer);
        }
        else
        {
            print("NOOO");
        }
        //print( chaperone );
        //print( chaperoneSetup );
//    print( rect );
    }
Example #18
0
        private bool IsSteamVR()
        {
#if !HVR_STEAMVR
            return(false);
#else
            //OPENVR_DESKTOP and OPENVR_XR from HurricaneVR.Framework asmdef version defines

#if !OPENVR_DESKTOP && !OPENVR_XR
            return(false);
#else
#if OPENVR_DESKTOP
            if (!Valve.VR.SteamVR.usingNativeSupport)
            {
                return(false);
            }
#endif

            try
            {
                EVRInitError error  = EVRInitError.None;
                EVRInitError error1 = EVRInitError.None;
                EVRInitError error2 = EVRInitError.None;


                OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
                OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error1);
                OpenVR.GetGenericInterface(OpenVR.IVRInput_Version, ref error2);

                if (error != EVRInitError.None || error1 != EVRInitError.None || error2 != EVRInitError.None)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                return(false);
            }

            return(true);
#endif
#endif
        }
Example #19
0
 private static SteamVR CreateInstance()
 {
     try
     {
         EVRInitError eVRInitError = EVRInitError.None;
         if (!SteamVR.usingNativeSupport)
         {
             OpenVR.Init(ref eVRInitError, EVRApplicationType.VRApplication_Scene);
             if (eVRInitError != EVRInitError.None)
             {
                 SteamVR.ReportError(eVRInitError);
                 SteamVR.ShutdownSystems();
                 SteamVR result = null;
                 return(result);
             }
         }
         OpenVR.GetGenericInterface("IVRCompositor_013", ref eVRInitError);
         if (eVRInitError != EVRInitError.None)
         {
             SteamVR.ReportError(eVRInitError);
             SteamVR.ShutdownSystems();
             SteamVR result = null;
             return(result);
         }
         OpenVR.GetGenericInterface("IVROverlay_010", ref eVRInitError);
         if (eVRInitError != EVRInitError.None)
         {
             SteamVR.ReportError(eVRInitError);
             SteamVR.ShutdownSystems();
             SteamVR result = null;
             return(result);
         }
     }
     catch (Exception message)
     {
         Debug.LogError(message);
         SteamVR result = null;
         return(result);
     }
     return(new SteamVR());
 }
Example #20
0
    static SteamVR CreateInstance()
    {
        try
        {
            var error = EVRInitError.None;

            OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }

            // Verify common interfaces are valid.

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }
        }
        catch (System.Exception e)
        {
            throw new System.Exception(e.Message);
        }

        return(new SteamVR());
    }
Example #21
0
        public void Init()
        {
            this.connectionCode = Properties.Settings.Default.ConnectionCode;
            if (this.connectionCode == null || this.connectionCode.Length == 0)
            {
                this.connectionCode = RandomString(16);
                Properties.Settings.Default.ConnectionCode = this.connectionCode;
                Properties.Settings.Default.Save();
            }
            Console.WriteLine("Connection Code: " + this.connectionCode);


            //var controller = HUDCenterController.GetInstance();
            //controller.Init(EVRApplicationType.VRApplication_Overlay);

            EVRInitError error = EVRInitError.None;

            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);

            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing OpenVR!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Compositor!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Overlay!");
            }

            InitOverlay();
        }
Example #22
0
        protected override void Initialize()
        {
            base.Initialize();

            var error = EVRInitError.None;

            bool initialized = true;

            hmd = OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                initialized = false;
            }

            // Verify common interfaces are valid.
            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                initialized = false;
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                initialized = false;
            }

            if (!initialized)
            {
                OpenVR.Shutdown();
                return;
            }

            controllerManager.Initialize();
        }
Example #23
0
        public MyOpenVR()
        {
            if (true)
            {
                m_viewHMD     = Matrix.Identity;
                m_headsetPosD = MatrixD.Identity;
                m_c1pos       = Matrix.Identity;
                m_c2pos       = Matrix.Identity;

                //IntPtr Handle = MyRender11.LoadLibrary(@"D:\KeenSWH.VR\Sandbox\Sources\SpaceEngineers\bin\x64\Debug\Bin64\openvr_api.dll");
                //IntPtr Handle = LoadLibrary(@"C:\Program Files (x86)\Steam\SteamApps\common\SteamVR\bin\win64\openvr_api.dll");
                IntPtr Handle = LoadLibrary(@"openvr_api.dll");
                //IntPtr Handle = MyRender11.LoadLibrary(@"c:\Program Files (x86)\Steam\bin\openvr_api.dll");//err code 193 -  not a valid Win32 application
                //Assembly.LoadFile(@"D:\KeenSWH\Sandbox\Sources\SpaceEngineers\bin\x64\Debug\Bin64\openvr_api.dll");
                if (Handle == IntPtr.Zero)
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Exception(string.Format("Failed to load library (ErrorCode: {0})", errorCode));
                }

                EVRInitError error = EVRInitError.None;
                IntPtr       ptr   = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Scene);
                if (error == EVRInitError.None)
                {
                    m_vrSystem = new CVRSystem(ptr);

                    uint sizeX = 0, sizeY = 0;
                    m_vrSystem.GetRecommendedRenderTargetSize(ref sizeX, ref sizeY);

                    m_vrSystem.SetDisplayVisibility(true);

                    ETrackedPropertyError pError = 0;
                    m_ipd_2 = 0.5f * m_vrSystem.GetFloatTrackedDeviceProperty(0, ETrackedDeviceProperty.Prop_UserIpdMeters_Float, ref pError);
                    SetIPD(m_ipd_2 * 2);

                    IntPtr pointer = OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
                    if (error == EVRInitError.None)
                    {
                        m_vrCompositor = new CVRCompositor(pointer);
                        m_vrCompositor.CompositorBringToFront();
                        m_vrCompositor.ShowMirrorWindow();
                        m_openVR = this;
                    }
                    else
                    {
                        var errString = OpenVR.GetStringForHmdError(error);
                        Log.WriteLineAndConsole(errString);
                        Debug.Fail("No compositor interface");
                        throw new Exception(errString);
                    }
                }
                else
                {
                    var errString = OpenVR.GetStringForHmdError(error);
                    Log.WriteLineAndConsole(errString);
                    //Debug.Fail("OpenVR init failed");
                    throw new Exception(errString);
                }
                InitOverlays();
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            /* Get an invisible GL context real quick :> */
            var window = new GameWindow(300, 300);

            var vr = SteamVR.instance;

            var error = EVRInitError.None;

            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);

            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing OpenVR!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Compositor!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Overlay!");
            }

            var hmd = OpenVR.System;

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

            ulong overlayHandle = 0;


            // Non-dashboard overlay
            EVROverlayError overlayError = overlay.CreateOverlay("overlayTest", "HL3", ref overlayHandle);

            // Dashboard overlay
            // ulong thumbnailHandle = 0;
            // overlay.SetOverlayFromFile(thumbnailHandle, @"image.png");
            // EVROverlayError overlayError = overlay.CreateDashboardOverlay("overlayTest", "HL3", ref overlayHandle, ref thumbnailHandle);

            if (overlayError != EVROverlayError.None)
            {
                throw new Exception(overlayError.ToString());
            }

            // Set overlay parameters
            overlay.SetOverlayWidthInMeters(overlayHandle, 1f);

            // Non-dashboard overlay stuff
            var nmatrix = OpenTKMatrixToOpenVRMatrix(new Matrix3x4(
                                                         new Vector4(1, 0, 0, 0),
                                                         new Vector4(0, 1, 0, 0),
                                                         new Vector4(0, 0, 1, 0)
                                                         ));

            // TODO: Figure out how to always get the left controller index and not hardcode it to 1 which could end up being the basestations or whatever.
            overlay.SetOverlayTransformTrackedDeviceRelative(overlayHandle, 1, ref nmatrix);
            overlay.SetOverlayInputMethod(overlayHandle, VROverlayInputMethod.Mouse);

            var bmp       = new Bitmap(@"image.png");
            var textureID = GL.GenTexture();

            System.Drawing.Imaging.BitmapData TextureData =
                bmp.LockBits(
                    new Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppArgb
                    );

            GL.BindTexture(TextureTarget.Texture2D, textureID);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp.Width, bmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, TextureData.Scan0);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);

            bmp.UnlockBits(TextureData);

            var texture = new Texture_t();

            texture.eType       = EGraphicsAPIConvention.API_OpenGL;
            texture.eColorSpace = EColorSpace.Auto;
            texture.handle      = (IntPtr)textureID;
            overlay.SetOverlayTexture(overlayHandle, ref texture);

            overlay.ShowOverlay(overlayHandle);

            Console.ReadLine();
        }
Example #25
0
    static RenderModel LoadRenderModel(string renderModelName)
    {
        var error = HmdError.None;

        if (!SteamVR.active)
        {
            OpenVR.Init(ref error);
            if (error != HmdError.None)
            {
                return(null);
            }
        }

        var pRenderModels = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);

        if (pRenderModels == System.IntPtr.Zero || error != HmdError.None)
        {
            if (!SteamVR.active)
            {
                OpenVR.Shutdown();
            }
            return(null);
        }

        var renderModels = new CVRRenderModels(pRenderModels);

        var renderModel = new RenderModel_t();

        if (!renderModels.LoadRenderModel(renderModelName, ref renderModel))
        {
            Debug.LogError("Failed to load render model " + renderModelName);

            if (!SteamVR.active)
            {
                OpenVR.Shutdown();
            }
            return(null);
        }

        var vertices = new Vector3[renderModel.unVertexCount];
        var normals  = new Vector3[renderModel.unVertexCount];
        var uv       = new Vector2[renderModel.unVertexCount];

        var type = typeof(RenderModel_Vertex_t);

        for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
        {
            var ptr  = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
            var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

            vertices[iVert] = new Vector3(vert.vPosition.v[0], vert.vPosition.v[1], -vert.vPosition.v[2]);
            normals[iVert]  = new Vector3(vert.vNormal.v[0], vert.vNormal.v[1], -vert.vNormal.v[2]);
            uv[iVert]       = new Vector2(vert.rfTextureCoord[0], vert.rfTextureCoord[1]);
        }

        int indexCount = (int)renderModel.unTriangleCount * 3;
        var indices    = new short[indexCount];

        Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

        var triangles = new int[indexCount];

        for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
        {
            triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
            triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
            triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
        }

        var mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.normals   = normals;
        mesh.uv        = uv;
        mesh.triangles = triangles;

        mesh.Optimize();
        //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

        var textureMapData = new byte[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight * 4];         // RGBA

        Marshal.Copy(renderModel.diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

        var colors = new Color32[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight];
        int iColor = 0;

        for (int iHeight = 0; iHeight < renderModel.diffuseTexture.unHeight; iHeight++)
        {
            for (int iWidth = 0; iWidth < renderModel.diffuseTexture.unWidth; iWidth++)
            {
                var r = textureMapData[iColor++];
                var g = textureMapData[iColor++];
                var b = textureMapData[iColor++];
                var a = textureMapData[iColor++];
                colors[iHeight * renderModel.diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
            }
        }

        var texture = new Texture2D(renderModel.diffuseTexture.unWidth, renderModel.diffuseTexture.unHeight, TextureFormat.ARGB32, true);

        texture.SetPixels32(colors);
        texture.Apply();

        //texture.hideFlags = HideFlags.DontUnloadUnusedAsset;

        renderModels.FreeRenderModel(ref renderModel);

        if (!SteamVR.active)
        {
            OpenVR.Shutdown();
        }

        return(new RenderModel(mesh, texture));
    }
Example #26
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);
    }
Example #27
0
        static void Main(string[] args)
        {
            // Hello fellow Vive-users!
            // Display some mumbojumbo in the console.
            Console.WriteLine("OpenVR Rotational Counter");
            Console.WriteLine("-------------------------");
            Console.WriteLine("Hacked together by Nexz :-). Crashes? [email protected]");
            Console.WriteLine("Licensed under the MIT license.");
            Console.WriteLine("I'm not responsible for any damage to your computer/HMD, no");
            Console.WriteLine("guarantees, not liable for anything, use at own risk, etc etc.");
            Console.WriteLine("");
            Console.WriteLine("Overlay code based on ViveIsAwesome/OpenVROverlayTest.");
            Console.WriteLine("For proper functioning, start SteamVR first!");
            // Define our resource path
            string ResourcePath = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName + "/Resources/";

            // Init OpenVR (or well, some voodoo in the wrapper I guess)
            Console.Write("Init EVR... ");
            var error = EVRInitError.None;

            OpenVR.Init(ref error);


            Console.WriteLine("Done!");

            Console.Write("Error check... ");
            // Show error regardless. You never know.
            Console.Write(error);

            // OpenVROverlayTest Error Exception code. Speaks for itself.
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }


            Console.WriteLine(" - Done!");
            Console.Write("Creating overlay... ");

            // There be lions here! Overlay time.
            var overlay = OpenVR.Overlay;

            Console.WriteLine("Done!");

            // We need to define this array because... of reasons. (Define it so we can use it later).
            Console.Write("Define pose array... ");
            var   pose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
            ulong overlayHandle = 0, thumbnailHandle = 0;

            Console.WriteLine("Done!");

            // Create the clickable overlay button
            Console.Write("Create dash overlay... ");

            overlay.CreateDashboardOverlay("overlayTest", "Rotation", ref overlayHandle, ref thumbnailHandle);

            Console.WriteLine("Done!");

            // Set the backdrop :)
            Console.Write("Set from file (rotation)... ");
            overlay.SetOverlayFromFile(thumbnailHandle, $"{ResourcePath}/rotation.png");
            Console.WriteLine("Done!");

            // I have no idea what I'm doing (OpenVROverlayTest code), but seems pretty reasonable.
            Console.Write("Set overlay parameters... ");
            overlay.SetOverlayWidthInMeters(overlayHandle, 2.5f);
            overlay.SetOverlayInputMethod(overlayHandle, VROverlayInputMethod.Mouse);
            Console.WriteLine("Done!");

            // This was also included. Not sure if it's necessary though.
            Console.Write("Make destroyable... ");
            Console.CancelKeyPress += (s, e) => overlay.DestroyOverlay(overlayHandle);
            Console.WriteLine("Done!");

            // Well, you could loop through all tracking devices presented by the OpenVR dll
            // but I didn't implement it yet. You can check what kind of type it is using OpenVR.
            // Lets just assume it's on 0 for now.
            Console.WriteLine("Assuming HMD is on DeviceIndex 0.");

            if (OpenVR.System.IsTrackedDeviceConnected(0) == true)
            {
                Console.WriteLine("Found HMD... probably ;-).");
            }
            else
            {
                Console.WriteLine("HMD is not connected! Please check if SteamVR is running.");
                Thread.Sleep(5000);
                Environment.Exit(0);
            }

            // Doesnt really need to be done, but was done for testing purposes
            Console.WriteLine("Trying to fetch in 1 second...");
            Thread.Sleep(1000);

            Console.Write("Get pose from Standing (first try)... ");

            OpenVR.System.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, pose);

            Console.WriteLine("Done!");

            // Well, I was using this for another way of calculating the turns, but it didn't work.
            Console.WriteLine("Setting starting position at " + pose[0].mDeviceToAbsoluteTracking.m2);
            float newCheckM2;
            float newCheckM8;
            float newCheckM10;

            int numSpin = 0;

            string drawString = "";

            // Working with quadrants to determine spin:

            /*  ________________________
             * |           |           |
             * |    3      |    0      |
             * |___________|___________|
             * |           |           |
             * |    2      |    1      |
             * |___________|___________|
             */

            int prevQuarter = 0;
            int curQuarter  = 0; // 0 = Right Top, 1 = Right Bottom, 2 = Left Bottom, 3 = Left Top

            Console.WriteLine("Starting main loop!");

            while (true)
            {
                // Get the pose! For real now.
                OpenVR.System.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, pose);

                // In testing I found that I could use these values to find out what direction we're facing
                // M8 is essentially M2 but negative, but when building it I thought it would be good to
                // use it for some reason... Not sure why anymore. But it works!
                newCheckM2  = pose[0].mDeviceToAbsoluteTracking.m2;
                newCheckM8  = pose[0].mDeviceToAbsoluteTracking.m8;
                newCheckM10 = pose[0].mDeviceToAbsoluteTracking.m10;

                // Determine the quadrant we're in. You could even use V(a2*b2=c2) to calculate the actual degrees
                if (newCheckM2 > 0 && newCheckM8 < 0 && newCheckM10 < 0)
                {
                    curQuarter = 0;
                }
                if (newCheckM2 > 0 && newCheckM8 < 0 && newCheckM10 > 0)
                {
                    curQuarter = 1;
                }
                if (newCheckM2 < 0 && newCheckM8 > 0 && newCheckM10 > 0)
                {
                    curQuarter = 2;
                }
                if (newCheckM2 < 0 && newCheckM8 > 0 && newCheckM10 < 0)
                {
                    curQuarter = 3;
                }

                // If we've changed quadrant, check which way we're spinning.
                if (curQuarter != prevQuarter)
                {
                    // Yay, we know stuff! Lets add it to the number of rotations (or subtract).
                    if (curQuarter == 1 && prevQuarter == 2)
                    {
                        numSpin++;
                    }

                    if (curQuarter == 2 && prevQuarter == 1)
                    {
                        numSpin--;
                    }

                    // Determine the string to be shown

                    if (numSpin < 0)
                    {
                        drawString = "Spin left " + Math.Abs(numSpin).ToString() + " times!";
                    }
                    if (numSpin > 0)
                    {
                        drawString = "Spin right " + Math.Abs(numSpin).ToString() + " times!";
                    }
                    if (numSpin == 0)
                    {
                        drawString = "You're untangled!";
                    }

                    // Okay, so I have no clue how OpenGL works (for now) apart from the fact that I need to
                    // generate a texture I don't know how. Fonts are also a challenge, from what I've read.

                    // SO! Simply hackity hack, generate a PNG that we can use with the SetOverlayFromFile funciton
                    // provided by OpenVR.

                    // I sorta stole this from StackExchange, but adapted it for my needs. Sigh, I feel dirty.
                    Bitmap   bmp = new Bitmap(260, 60);
                    Graphics g   = Graphics.FromImage(bmp);
                    g.FillRectangle(Brushes.Black, 0, 0, 260, 60);
                    RectangleF rectf = new RectangleF(20, 10, 240, 50);
                    g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    g.DrawString(drawString, new Font("Tahoma", 20), Brushes.White, rectf);
                    g.Flush();

                    // Save it, as I'm not sure if I can pass along the Bitmap as itself.
                    bmp.Save($"{ResourcePath}/spin.png", System.Drawing.Imaging.ImageFormat.Png);

                    // Update the 'last' quadrant.
                    prevQuarter = curQuarter;

                    // Set the overlay.
                    if (overlay.IsOverlayVisible(overlayHandle))
                    {
                        overlay.SetOverlayFromFile(overlayHandle, $"{ResourcePath}/spin.png");
                    }
                    // HOORAY!
                }
            }
        }
Example #28
0
    public static bool GetBounds(Size size, ref HmdQuad_t pRect)
    {
        if (size == Size.Calibrated)
        {
            var error = HmdError.None;
            if (!SteamVR.active)
            {
                OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);
                if (error != HmdError.None)
                {
                    return(false);
                }
            }

            var pChaperone = OpenVR.GetGenericInterface(OpenVR.IVRChaperone_Version, ref error);
            if (pChaperone == System.IntPtr.Zero || error != HmdError.None)
            {
                if (!SteamVR.active)
                {
                    OpenVR.Shutdown();
                }
                return(false);
            }

            var chaperone = new CVRChaperone(pChaperone);

            bool success = chaperone.GetPlayAreaRect(ref pRect);
            if (!success)
            {
                Debug.LogWarning("Failed to get Calibrated Play Area bounds!  Make sure you have tracking first, and that your space is calibrated.");
            }

            if (!SteamVR.active)
            {
                OpenVR.Shutdown();
            }

            return(success);
        }
        else
        {
            try
            {
                var str = size.ToString().Substring(1);
                var arr = str.Split(new char[] { 'x' }, 2);
                // convert to half size in meters (from cm)
                var x = float.Parse(arr[0]) / 200;
                var z = float.Parse(arr[1]) / 200;
                pRect.vCorners      = new HmdVector3_t[4];
                pRect.vCorners[0].v = new float[3] {
                    x, 0, z
                };
                pRect.vCorners[1].v = new float[3] {
                    x, 0, -z
                };
                pRect.vCorners[2].v = new float[3] {
                    -x, 0, -z
                };
                pRect.vCorners[3].v = new float[3] {
                    -x, 0, z
                };
                return(true);
            }
            catch {}
        }

        return(false);
    }
        private void VRInit()
        {
            // init
            var error = EVRInitError.None;

            system = OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVRSystem_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            TrackedDevicePose_t[] m_rTrackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
            TrackedDevicePose_t   TrackedDevicePose    = new TrackedDevicePose_t();
            VRControllerState_t   controllerState      = new VRControllerState_t();

            while (true)
            {
                system.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, m_rTrackedDevicePose);

                for (uint unDevice = 0; unDevice < OpenVR.k_unMaxTrackedDeviceCount; unDevice++)
                {
                    if (!system.IsTrackedDeviceConnected(unDevice))
                    {
                        continue;
                    }

                    HmdVector3_t    position;
                    HmdQuaternion_t quaternion;

                    // Get what type of device it is and work with its data
                    ETrackedDeviceClass    trackedDeviceClass    = system.GetTrackedDeviceClass(unDevice);
                    ETrackedControllerRole trackedControllerRole = system.GetControllerRoleForTrackedDeviceIndex(unDevice);
                    ETrackingResult        eTrackingResult;

                    switch (trackedDeviceClass)
                    {
                    case ETrackedDeviceClass.HMD:

                        // get the position and rotation
                        position   = GetPosition(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);
                        quaternion = GetRotation(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);

                        // for printing some more info to the user about the state of the device/pose
                        eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult;

                        // print the tracking data
                        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                            HmdIndex.Text       = String.Format("{0}", unDevice);
                            HmdVectorX.Text     = String.Format("{0:F4}", position.v0);
                            HmdVectorY.Text     = String.Format("{0:F4}", position.v1);
                            HmdVectorZ.Text     = String.Format("{0:F4}", position.v2);
                            HmdQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                            HmdQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                            HmdQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                            HmdQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                            HmdState.Text       = GetDeviceState(eTrackingResult);
                        }));
                        break;

                    case ETrackedDeviceClass.Controller:

                        // get the position and rotation
                        position   = GetPosition(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);
                        quaternion = GetRotation(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);

                        // for printing some more info to the user about the state of the device/pose
                        eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult;

                        // get Controllers info
                        system.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, unDevice, ref controllerState, (uint)Marshal.SizeOf(controllerState), ref TrackedDevicePose);

                        switch (trackedControllerRole)
                        {
                        case ETrackedControllerRole.LeftHand:

                            // print the tracking data
                            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                                CLIndex.Text       = String.Format("{0}", unDevice);
                                CLVectorX.Text     = String.Format("{0:F4}", position.v0);
                                CLVectorY.Text     = String.Format("{0:F4}", position.v1);
                                CLVectorZ.Text     = String.Format("{0:F4}", position.v2);
                                CLQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                                CLQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                                CLQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                                CLQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                                CLState.Text       = GetDeviceState(eTrackingResult);
                                CLulPressed.Text   = String.Format("{0}", controllerState.ulButtonPressed);
                                CLulTouched.Text   = String.Format("{0}", controllerState.ulButtonTouched);
                                CLAxis0X.Text      = String.Format("{0:F4}", controllerState.rAxis0.x);
                                CLAxis0Y.Text      = String.Format("{0:F4}", controllerState.rAxis0.y);
                                CLAxis1X.Text      = String.Format("{0:F4}", controllerState.rAxis1.x);
                                CLAxis1Y.Text      = String.Format("{0:F4}", controllerState.rAxis1.y);
                                CLAxis2X.Text      = String.Format("{0:F4}", controllerState.rAxis2.x);
                                CLAxis2Y.Text      = String.Format("{0:F4}", controllerState.rAxis2.y);
                                CLAxis3X.Text      = String.Format("{0:F4}", controllerState.rAxis3.x);
                                CLAxis3Y.Text      = String.Format("{0:F4}", controllerState.rAxis3.y);
                                CLAxis4X.Text      = String.Format("{0:F4}", controllerState.rAxis4.x);
                                CLAxis4Y.Text      = String.Format("{0:F4}", controllerState.rAxis4.y);
                            }));
                            break;

                        case ETrackedControllerRole.RightHand:

                            // print the tracking data
                            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                                CRIndex.Text       = String.Format("{0}", unDevice);
                                CRVectorX.Text     = String.Format("{0:F4}", position.v0);
                                CRVectorY.Text     = String.Format("{0:F4}", position.v1);
                                CRVectorZ.Text     = String.Format("{0:F4}", position.v2);
                                CRQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                                CRQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                                CRQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                                CRQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                                CRState.Text       = GetDeviceState(eTrackingResult);
                                CRulPressed.Text   = String.Format("{0}", controllerState.ulButtonPressed);
                                CRulTouched.Text   = String.Format("{0}", controllerState.ulButtonTouched);
                                CRAxis0X.Text      = String.Format("{0:F4}", controllerState.rAxis0.x);
                                CRAxis0Y.Text      = String.Format("{0:F4}", controllerState.rAxis0.y);
                                CRAxis1X.Text      = String.Format("{0:F4}", controllerState.rAxis1.x);
                                CRAxis1Y.Text      = String.Format("{0:F4}", controllerState.rAxis1.y);
                                CRAxis2X.Text      = String.Format("{0:F4}", controllerState.rAxis2.x);
                                CRAxis2Y.Text      = String.Format("{0:F4}", controllerState.rAxis2.y);
                                CRAxis3X.Text      = String.Format("{0:F4}", controllerState.rAxis3.x);
                                CRAxis3Y.Text      = String.Format("{0:F4}", controllerState.rAxis3.y);
                                CRAxis4X.Text      = String.Format("{0:F4}", controllerState.rAxis4.x);
                                CRAxis4Y.Text      = String.Format("{0:F4}", controllerState.rAxis4.y);
                            }));
                            break;
                        }


                        break;

                    case ETrackedDeviceClass.GenericTracker:

                        system.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, unDevice, ref controllerState, (uint)Marshal.SizeOf(controllerState), ref TrackedDevicePose);
                        // get the position and rotation
                        position   = GetPosition(TrackedDevicePose.mDeviceToAbsoluteTracking);
                        quaternion = GetRotation(TrackedDevicePose.mDeviceToAbsoluteTracking);

                        // for printing some more info to the user about the state of the device/pose
                        eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult;

                        // print the tracking data
                        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                            TrackerIndex.Text       = String.Format("{0}", unDevice);
                            TrackerVectorX.Text     = String.Format("{0:F4}", position.v0);
                            TrackerVectorY.Text     = String.Format("{0:F4}", position.v1);
                            TrackerVectorZ.Text     = String.Format("{0:F4}", position.v2);
                            TrackerQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                            TrackerQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                            TrackerQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                            TrackerQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                            TrackerState.Text       = GetDeviceState(eTrackingResult);
                        }));
                        break;
                    }
                    Thread.Sleep(10);
                }
            }
        }
Example #30
0
        static void Main(string[] args)
        {
            Thread.Sleep(100);
            bool vrmodStarted = false;

            Console.TreatControlCAsInput = false;
            string ResourcePath = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName + "/Resources/";

            // init
            var error = EVRInitError.None;

            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }


            // create overlay, ...
            var overlay = OpenVR.Overlay;

            ulong overlayHandle = 0, thumbnailHandle = 0;

            overlay.CreateDashboardOverlay("VRModOverlay" + new Random().Next(1, 4096), "Start VRMod", ref overlayHandle, ref thumbnailHandle);
            overlay.SetOverlayFromFile(thumbnailHandle, $"{ResourcePath}/vrmod_icon.png");

            overlay.SetOverlayWidthInMeters(overlayHandle, 2.5f);
            overlay.SetOverlayInputMethod(overlayHandle, VROverlayInputMethod.Mouse);
            Console.CancelKeyPress += (s, e) => overlay.DestroyOverlay(overlayHandle);

            bool gmodActive = (Process.GetProcessesByName("hl2") != null || Process.GetProcessesByName("gmod") != null);

            Console.WriteLine(gmodActive ? "Found Garry's Mod." : "Could not find Garry's Mod.");

            Console.WriteLine("Ready to launch VRMod.\nOnce your game has loaded, select the 'Start VRMod' button inside your SteamVR dashboard.");

            while (true)
            {
                if (overlay.IsOverlayVisible(overlayHandle))
                {
                    overlay.SetOverlayFromFile(overlayHandle, $"{ResourcePath}/conceptbackground.jpg");
                    Thread.Sleep(200);
                    if (!vrmodStarted)
                    {
                        Thread launchVRMod = new Thread(StartVRMod);
                        StartVRMod();
                        System.Environment.Exit(0);
                        vrmodStarted = true;
                    }
                }
                vrmodStarted = !overlay.IsOverlayVisible(overlayHandle);
            }
        }