Exemplo n.º 1
0
        public void InitOpenVR()
        {
            ExtenFunctions.SetDllDirectory(OpenVRDllPath);

            if (!OpenVR.IsHmdPresent())
            {
                throw new InvalidOperationException("Could not find vr headset");
            }

            if (!OpenVR.IsRuntimeInstalled())
            {
                throw new InvalidOperationException("Could not find openVr runtime");
            }

            EVRInitError hmdInitErrorCode = EVRInitError.None;

            OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);
            if (hmdInitErrorCode != EVRInitError.None)
            {
                throw new Exception("OpenVR error: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
            }

            OpenVR.System.ResetSeatedZeroPose();

            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            OpenVR.System.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);

            VRManager.Instance.InitEyeTextures((int)renderTextureWidth, (int)renderTextureHeight);
        }
Exemplo n.º 2
0
        public static void Main()
        {
            Console.WriteLine("Is Runtime Installed: {0}", OpenVR.IsRuntimeInstalled());
            var isHmdPresent = OpenVR.IsHmdPresent();

            Console.WriteLine("Is HMD Present: {0}", isHmdPresent);
            if (isHmdPresent)
            {
                try
                {
                    var err = EVRInitError.None;
                    var sys = OpenVR.Init(ref err, EVRApplicationType.VRApplication_Scene);
                    if (err != EVRInitError.None)
                    {
                        Console.WriteLine("Err {0}", err);
                    }
                    else
                    {
                        Console.WriteLine("Runtime version: {0}", sys.GetRuntimeVersion());
                        Console.WriteLine("Is display on desktop: {0}", sys.IsDisplayOnDesktop());
                        Console.WriteLine("Is input available: {0}", sys.IsInputAvailable());
                        Console.WriteLine("Is SteamVR drawing controllers: {0}", sys.IsSteamVRDrawingControllers());
                        Console.WriteLine("Should application pause: {0}", sys.ShouldApplicationPause());
                        Console.WriteLine("Should application reduce rendering work: {0}", sys.ShouldApplicationReduceRenderingWork());
                        sys.GetRecommendedRenderTargetSize(out var width, out var height);
                        Console.WriteLine("Recommended render target size: {0}x{1}", width, height);
                        Console.WriteLine("Button Name: {0}", sys.GetButtonIdNameFromEnum(EVRButtonId.k_EButton_A));
                    }
                }
                finally
                {
                    OpenVR.Shutdown();
                }
            }
        }
Exemplo n.º 3
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);
             */
        }
Exemplo n.º 4
0
    internal static bool DetectSteamVR()
    {
        Process[] vrServer  = Process.GetProcessesByName("vrserver");
        Process[] vrMonitor = Process.GetProcessesByName("vrmonitor");
        if ((vrServer.Length == 0) || (vrMonitor.Length == 0))
        {
            return(false);
        }
        if (!OpenVR.IsRuntimeInstalled())
        {
            return(false);
        }

        return(true);
    }
        public override void InstallBindings()
        {
            // logging
            Container.Bind(typeof(ILogger <>)).FromMethodUntyped(CreateLogger).AsTransient().When(ShouldCreateLogger);

            // settings
            Container.BindInterfacesAndSelfTo <SettingsManager>().AsSingle();
            Container.Bind <Settings>().FromMethod((context) => context.Container.Resolve <SettingsManager>().settings);
            Container.BindInterfacesAndSelfTo <CalibrationData>().AsSingle();

            if (XRSettings.loadedDeviceName.Equals("openvr", StringComparison.InvariantCultureIgnoreCase) &&
                OpenVR.IsRuntimeInstalled() &&
                !Environment.GetCommandLineArgs().Contains("--force-xr"))
            {
                Container.Bind <OpenVRFacade>().AsTransient();
                Container.BindInterfacesAndSelfTo <OpenVRDeviceProvider>().AsSingle();
            }
            else
            {
                Container.BindInterfacesTo <UnityXRDeviceProvider>().AsSingle();
            }

            // managers
            Container.BindInterfacesAndSelfTo <PlayerAvatarManager>().AsSingle().NonLazy();
            Container.BindInterfacesAndSelfTo <ShaderLoader>().AsSingle().NonLazy();
            Container.BindInterfacesAndSelfTo <DeviceManager>().AsSingle().NonLazy();

            // this prevents a race condition when registering components in AvatarSpawner
            Container.BindExecutionOrder <PlayerAvatarManager>(kPlayerAvatarManagerExecutionOrder);

            Container.Bind <AvatarLoader>().AsSingle();
            Container.Bind <AvatarSpawner>().AsSingle();
            Container.BindInterfacesAndSelfTo <VRPlayerInput>().AsSingle();
            Container.Bind(typeof(VRPlayerInputInternal), typeof(IInitializable), typeof(IDisposable)).To <VRPlayerInputInternal>().AsSingle();
            Container.BindInterfacesAndSelfTo <LightingQualityController>().AsSingle();
            Container.BindInterfacesAndSelfTo <BeatSaberUtilities>().AsSingle();

            #pragma warning disable CS0612
            Container.BindInterfacesAndSelfTo <FloorController>().AsSingle();
            #pragma warning restore CS0612

            // helper classes
            Container.Bind <MirrorHelper>().AsTransient();
            Container.Bind <IKHelper>().AsTransient();
            Container.Bind <TrackingHelper>().AsTransient();

            Container.Bind <MainSettingsModelSO>().FromInstance(_pcAppInit.GetField <MainSettingsModelSO, PCAppInit>("_mainSettingsModel")).IfNotBound();
        }
Exemplo n.º 6
0
        public override void InstallBindings()
        {
            // logging
            Container.Bind <ILoggerProvider>().To <IPALoggerProvider>().AsTransient().WithArguments(new object[] { _logger });

            // settings
            Container.BindInterfacesAndSelfTo <SettingsManager>().AsSingle();
            Container.Bind <Settings>().FromMethod((context) => context.Container.Resolve <SettingsManager>().settings);
            Container.BindInterfacesAndSelfTo <CalibrationData>().AsSingle();

            if (XRSettings.loadedDeviceName.Equals("openvr", StringComparison.InvariantCultureIgnoreCase) &&
                OpenVR.IsRuntimeInstalled() &&
                !Environment.GetCommandLineArgs().Contains("--force-xr"))
            {
                Container.Bind <OpenVRFacade>().AsTransient();
                Container.BindInterfacesAndSelfTo <OpenVRDeviceProvider>().AsSingle();
            }
            else
            {
                Container.BindInterfacesTo <UnityXRDeviceProvider>().AsSingle();
            }

            // managers
            Container.BindInterfacesAndSelfTo <PlayerAvatarManager>().AsSingle().NonLazy();
            Container.BindInterfacesAndSelfTo <MainCameraController>().AsSingle().NonLazy();
            Container.BindInterfacesAndSelfTo <ShaderLoader>().AsSingle().NonLazy();
            Container.BindInterfacesAndSelfTo <DeviceManager>().AsSingle().NonLazy();

            Container.Bind <AvatarLoader>().AsSingle();
            Container.BindInterfacesAndSelfTo <VRPlayerInput>().AsSingle();
            Container.BindInterfacesAndSelfTo <FloorController>().AsSingle();
            Container.BindInterfacesAndSelfTo <LightingQualityController>().AsSingle();

            // helper classes
            Container.Bind <MirrorHelper>().AsTransient();
            Container.Bind <AvatarSpawner>().AsTransient();
            Container.Bind <IKHelper>().AsTransient();
            Container.BindInterfacesAndSelfTo <BeatSaberUtilities>().AsTransient();
            Container.Bind <TrackingHelper>().AsTransient();

            // not sure if this is a great idea but w/e
            if (!Container.HasBinding <MainSettingsModelSO>())
            {
                Container.Bind <MainSettingsModelSO>().FromInstance(Resources.FindObjectsOfTypeAll <MainSettingsModelSO>().First());
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on successful initialization, false otherwise.</returns>
        private static void InitializeOpenVR()
        {
            // return if HMD has already been initialized
            if (hmdState == HmdState.Initialized)
            {
                return;
            }

            // set the location of the OpenVR DLL
            SetDllDirectory(Globals.OpenVRDllPath);

            // check if HMD is connected on the system
            if (!OpenVR.IsHmdPresent())
            {
                throw new InvalidOperationException("HMD not found on this system");
            }

            // check if SteamVR runtime is installed
            if (!OpenVR.IsRuntimeInstalled())
            {
                throw new InvalidOperationException("SteamVR runtime not found on this system");
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);
            if (hmdInitErrorCode != EVRInitError.None)
            {
                throw new Exception("OpenVR error: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
            }

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

            // get HMD render target size
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            OpenVR.System.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);

            // at the moment, only Direct3D12 is working with Kerbal Space Program
            ETextureType textureType = ETextureType.DirectX;

            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                textureType = ETextureType.OpenGL;
                throw new InvalidOperationException(SystemInfo.graphicsDeviceType.ToString() + " does not support VR. You must use -force-d3d12");

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
                throw new InvalidOperationException(SystemInfo.graphicsDeviceType.ToString() + " does not support VR. You must use -force-d3d12");

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                textureType = ETextureType.DirectX;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D12:
                textureType = ETextureType.DirectX;
                break;

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

            // initialize render textures (for displaying on HMD)
            for (int i = 0; i < 2; i++)
            {
                hmdEyeRenderTexture[i] = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
                hmdEyeRenderTexture[i].Create();
                hmdEyeTexture[i].handle      = hmdEyeRenderTexture[i].GetNativeTexturePtr();
                hmdEyeTexture[i].eColorSpace = EColorSpace.Auto;
                hmdEyeTexture[i].eType       = textureType;
            }

            // set rendering bounds on texture to render
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 1.0f; // flip the vertical coordinate for some reason
            hmdTextureBounds.vMax = 0.0f;
        }
Exemplo n.º 8
0
 public static bool vrAvailable()
 {
     return(OpenVR.IsRuntimeInstalled());
 }
Exemplo n.º 9
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        bool InitHMD()
        {
            bool retVal = false;

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

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

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

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

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

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

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

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

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

            ResetInitialHmdPosition();

            // initialize Compositor
            vrCompositor = OpenVR.Compositor;

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

            initTmr.Start();

            return(retVal);
        }
Exemplo n.º 10
0
        public void Initialize()
        {
            try
            {
                _isOpenVRRunning = XRSettings.loadedDeviceName.Equals("openvr", StringComparison.InvariantCultureIgnoreCase) && OpenVR.IsRuntimeInstalled();
            }
            catch (Exception ex)
            {
                _logger.Error("Failed to check if SteamVR is running; assuming it is not");
                _logger.Error(ex);
            }

            InputDevices.deviceConnected     += OnInputDevicesUpdated;
            InputDevices.deviceDisconnected  += OnInputDevicesUpdated;
            InputDevices.deviceConfigChanged += OnInputDevicesUpdated;

            UpdateInputDevices();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        private bool InitHMD()
        {
            bool retVal = false;

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

            // set the location of the OpenVR DLL
            SetDllDirectory(Globals.OpenVRDllPath);

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

            // check if SteamVR runtime is installed
            retVal = OpenVR.IsRuntimeInstalled();
            if (!retVal)
            {
                Utils.LogError("SteamVR runtime not found on this system.");
                return(retVal);
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);
            retVal = (hmdInitErrorCode == EVRInitError.None);
            if (!retVal)
            {
                Utils.LogError("Failed to initialize HMD. Init returned: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
                return(retVal);
            }

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

            // get HMD render target size
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            OpenVR.System.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);

            // at the moment, only Direct3D12 is working with Kerbal Space Program
            ETextureType textureType = ETextureType.DirectX;

            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                textureType = ETextureType.OpenGL;
                break;     // doesn't work

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                textureType = ETextureType.DirectX;
                break;     // doesn't work

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D12:
                textureType = ETextureType.DirectX;     // do not use DirectX12
                break;

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

            openvrTexture             = new Texture_t();
            openvrTexture.eType       = textureType;
            openvrTexture.eColorSpace = EColorSpace.Auto;

            Debug.Log("Graphics Type: " + SystemInfo.graphicsDeviceType);

            // initialize render textures (for displaying on HMD)

            rightEyeRenderTextures[0] = new Texture2D((int)(renderTextureWidth * 1.5), (int)(renderTextureHeight * 1.5), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[0]  = new Texture2D((int)(renderTextureWidth * 1.5), (int)(renderTextureHeight * 1.5), TextureFormat.ARGB32, false);
            renderTextures[0]         = new RenderTexture((int)(renderTextureWidth * 1.5), (int)(renderTextureHeight * 1.5), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[1] = new Texture2D((int)(renderTextureWidth), (int)(renderTextureHeight), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[1]  = new Texture2D((int)(renderTextureWidth), (int)(renderTextureHeight), TextureFormat.ARGB32, false);
            renderTextures[1]         = new RenderTexture((int)(renderTextureWidth), (int)(renderTextureHeight), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[2] = new Texture2D((int)(renderTextureWidth * .75), (int)(renderTextureHeight * .75), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[2]  = new Texture2D((int)(renderTextureWidth * .75), (int)(renderTextureHeight * .75), TextureFormat.ARGB32, false);
            renderTextures[2]         = new RenderTexture((int)(renderTextureWidth * .75), (int)(renderTextureHeight * .75), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[3] = new Texture2D((int)(renderTextureWidth * .5), (int)(renderTextureHeight * .5), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[3]  = new Texture2D((int)(renderTextureWidth * .5), (int)(renderTextureHeight * .5), TextureFormat.ARGB32, false);
            renderTextures[3]         = new RenderTexture((int)(renderTextureWidth * .5), (int)(renderTextureHeight * .5), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[4] = new Texture2D((int)(renderTextureWidth * .25), (int)(renderTextureHeight * .25), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[4]  = new Texture2D((int)(renderTextureWidth * .25), (int)(renderTextureHeight * .25), TextureFormat.ARGB32, false);
            renderTextures[4]         = new RenderTexture((int)(renderTextureWidth * .25), (int)(renderTextureHeight * .25), 24, RenderTextureFormat.ARGB32);

            // set rendering bounds on texture to render
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 1.0f; // flip the vertical coordinate for some reason
            hmdTextureBounds.vMax = 0.0f;


            hmdIsInitialized = true;

            return(retVal);
        }
Exemplo n.º 12
0
 internal static bool IsRuntimeInstalled()
 {
     return(OpenVR.IsRuntimeInstalled());
 }
Exemplo n.º 13
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        bool InitHMD()
        {
            bool retVal = false;

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

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

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

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

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

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

            // reset "seated position" and capture initial position. this means you should hold the HMD in
            // the position you would like to consider "seated", before running this code.
            hmdIsInitialized = true;
            ResetInitialHmdPosition();

            // initialize Compositor
            vrCompositor = OpenVR.Compositor;

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

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

            Debug.Log("[KerbalVR] Render Texture size: " + renderTextureWidth + " x " + renderTextureHeight);

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

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

            hmdLeftEyeTexture.handle = hmdLeftEyeRenderTexture.GetNativeTexturePtr();
            hmdLeftEyeTexture.eType  = EGraphicsAPIConvention.API_OpenGL;
            //hmdLeftEyeTexture.eType = EGraphicsAPIConvention.API_DirectX; // this doesn't seem to work
            hmdLeftEyeTexture.eColorSpace = EColorSpace.Auto;

            hmdRightEyeTexture.handle = hmdRightEyeRenderTexture.GetNativeTexturePtr();
            hmdRightEyeTexture.eType  = EGraphicsAPIConvention.API_OpenGL;
            //hmdRightEyeTexture.eType = EGraphicsAPIConvention.API_DirectX; // this doesn't seem to work
            hmdRightEyeTexture.eColorSpace = EColorSpace.Auto;

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

            // create the hidden area mask meshes
            HiddenAreaMesh_t vrHiddenAreaMesh = vrSystem.GetHiddenAreaMesh(EVREye.Eye_Left);

            hmdHiddenAreaMeshLeft  = SteamVR_Utils.CreateHiddenAreaMesh(vrHiddenAreaMesh, hmdTextureBounds);
            vrHiddenAreaMesh       = vrSystem.GetHiddenAreaMesh(EVREye.Eye_Right);
            hmdHiddenAreaMeshRight = SteamVR_Utils.CreateHiddenAreaMesh(vrHiddenAreaMesh, hmdTextureBounds);

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

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

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

            foreach (Camera camera in Camera.allCameras)
            {
                if (cameraNames[5].Equals(camera.name))
                {
                    uiCamera = camera;
                }
            }

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

            if (!ctrlFocusCaptured)
            {
                Debug.LogWarning("[KerbalVR] Controller input focus was not captured");
            }

            return(retVal);
        }