Exemple #1
0
    void Start()
    {
        OVRPlugin.SystemHeadset headset = OVRPlugin.GetSystemHeadsetType();
        switch (headset)
        {
        case OVRPlugin.SystemHeadset.Oculus_Go:
            activeControllerType = ControllerType.Go;
            break;

        case OVRPlugin.SystemHeadset.Oculus_Quest:
            activeControllerType = ControllerType.QuestAndRiftS;
            break;

        case OVRPlugin.SystemHeadset.Rift_CV1:
            activeControllerType = ControllerType.Rift;
            break;

        case OVRPlugin.SystemHeadset.Rift_S:
            activeControllerType = ControllerType.QuestAndRiftS;
            break;

        case OVRPlugin.SystemHeadset.GearVR_R320:
        case OVRPlugin.SystemHeadset.GearVR_R321:
        case OVRPlugin.SystemHeadset.GearVR_R322:
        case OVRPlugin.SystemHeadset.GearVR_R323:
        case OVRPlugin.SystemHeadset.GearVR_R324:
        case OVRPlugin.SystemHeadset.GearVR_R325:
            activeControllerType = ControllerType.GearVR;
            break;

        default:
#if UNITY_EDITOR || !UNITY_ANDROID
            activeControllerType = ControllerType.Rift;
#else
            activeControllerType = ControllerType.GearVR;
#endif
            break;
        }

        //Debug.LogFormat("OVRControllerHelp: Active controller type: {0} for product {1}", activeControllerType, OVRPlugin.productName);
        if ((activeControllerType != ControllerType.GearVR) && (activeControllerType != ControllerType.Go))
        {
            if (m_controller == OVRInput.Controller.LTrackedRemote)
            {
                m_controller = OVRInput.Controller.LTouch;
            }
            else if (m_controller == OVRInput.Controller.RTrackedRemote)
            {
                m_controller = OVRInput.Controller.RTouch;
            }
        }
        else
        {
            if (m_controller == OVRInput.Controller.LTouch)
            {
                m_controller = OVRInput.Controller.LTrackedRemote;
            }
            else if (m_controller == OVRInput.Controller.RTouch)
            {
                m_controller = OVRInput.Controller.RTrackedRemote;
            }
        }
    }
Exemple #2
0
    private void Update()
    {
#if UNITY_EDITOR
        if (_scriptsReloaded)
        {
            _scriptsReloaded = false;
            instance         = this;
            Initialize();
        }
#endif

        if (OVRPlugin.shouldQuit)
        {
            Application.Quit();
        }

        if (OVRPlugin.shouldRecenter)
        {
            OVRManager.display.RecenterPose();
        }

        if (trackingOriginType != _trackingOriginType)
        {
            trackingOriginType = _trackingOriginType;
        }

        tracker.isEnabled = usePositionTracking;

        OVRPlugin.rotation = useRotationTracking;

        OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;

        // Dispatch HMD events.

        isHmdPresent = OVRPlugin.hmdPresent;

        if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
        {
            Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing +
                      ", but the recommended MSAA level is " + display.recommendedMSAALevel +
                      ". Switching to the recommended level.");

            QualitySettings.antiAliasing = display.recommendedMSAALevel;
        }

        if (_wasHmdPresent && !isHmdPresent)
        {
            try
            {
                if (HMDLost != null)
                {
                    HMDLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_wasHmdPresent && isHmdPresent)
        {
            try
            {
                if (HMDAcquired != null)
                {
                    HMDAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _wasHmdPresent = isHmdPresent;

        // Dispatch HMD mounted events.

        isUserPresent = OVRPlugin.userPresent;

        if (_wasUserPresent && !isUserPresent)
        {
            try
            {
                if (HMDUnmounted != null)
                {
                    HMDUnmounted();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_wasUserPresent && isUserPresent)
        {
            try
            {
                if (HMDMounted != null)
                {
                    HMDMounted();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _wasUserPresent = isUserPresent;

        // Dispatch XR Focus events.

        hasXRFocus = OVRPlugin.hasXRFocus;

        if (_hadXRFocus && !hasXRFocus)
        {
            try
            {
                if (XRFocusLost != null)
                {
                    XRFocusLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_hadXRFocus && hasXRFocus)
        {
            try
            {
                if (XRFocusAcquired != null)
                {
                    XRFocusAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _hadXRFocus = hasXRFocus;

        // Dispatch XR Input events.

        bool hasInputFocus = OVRPlugin.hasInputFocus;

        if (_hadInputFocus && !hasInputFocus)
        {
            try
            {
                if (InputFocusLost != null)
                {
                    InputFocusLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_hadInputFocus && hasInputFocus)
        {
            try
            {
                if (InputFocusAcquired != null)
                {
                    InputFocusAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _hadInputFocus = hasInputFocus;

        // Dispatch System Overlay present events.

        bool hasSystemOverlayPresent = OVRPlugin.hasSystemOverlayPresent;

        if (_hadSystemOverlayPresented && !hasSystemOverlayPresent)
        {
            try
            {
                if (SystemOverlayHide != null)
                {
                    SystemOverlayHide();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_hadSystemOverlayPresented && hasSystemOverlayPresent)
        {
            try
            {
                if (SystemOverlayPresented != null)
                {
                    SystemOverlayPresented();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _hadSystemOverlayPresented = hasSystemOverlayPresent;

        // Changing effective rendering resolution dynamically according performance
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5_4_OR_NEWER
        if (enableAdaptiveResolution)
        {
            if (XR.XRSettings.renderScale < maxRenderScale)
            {
                // Allocate renderScale to max to avoid re-allocation
                XR.XRSettings.renderScale = maxRenderScale;
            }
            else
            {
                // Adjusting maxRenderScale in case app started with a larger renderScale value
                maxRenderScale = Mathf.Max(maxRenderScale, XR.XRSettings.renderScale);
            }
            minRenderScale = Mathf.Min(minRenderScale, maxRenderScale);
            float minViewportScale         = minRenderScale / XR.XRSettings.renderScale;
            float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / XR.XRSettings.renderScale;
            recommendedViewportScale          = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
            XR.XRSettings.renderViewportScale = recommendedViewportScale;
        }
#endif

        // Dispatch Audio Device events.

        string audioOutId = OVRPlugin.audioOutId;
        if (!prevAudioOutIdIsCached)
        {
            prevAudioOutId         = audioOutId;
            prevAudioOutIdIsCached = true;
        }
        else if (audioOutId != prevAudioOutId)
        {
            try
            {
                if (AudioOutChanged != null)
                {
                    AudioOutChanged();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }

            prevAudioOutId = audioOutId;
        }

        string audioInId = OVRPlugin.audioInId;
        if (!prevAudioInIdIsCached)
        {
            prevAudioInId         = audioInId;
            prevAudioInIdIsCached = true;
        }
        else if (audioInId != prevAudioInId)
        {
            try
            {
                if (AudioInChanged != null)
                {
                    AudioInChanged();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }

            prevAudioInId = audioInId;
        }

        // Dispatch tracking events.

        if (wasPositionTracked && !tracker.isPositionTracked)
        {
            try
            {
                if (TrackingLost != null)
                {
                    TrackingLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!wasPositionTracked && tracker.isPositionTracked)
        {
            try
            {
                if (TrackingAcquired != null)
                {
                    TrackingAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        wasPositionTracked = tracker.isPositionTracked;

        display.Update();
        OVRInput.Update();

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
        if (enableMixedReality || prevEnableMixedReality)
        {
            Camera mainCamera = FindMainCamera();
            if (Camera.main != null)
            {
                suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false;

                if (enableMixedReality)
                {
                    OVRMixedReality.Update(this.gameObject, mainCamera, compositionMethod, useDynamicLighting, capturingCameraDevice, depthQuality);
                }

                if (prevEnableMixedReality && !enableMixedReality)
                {
                    OVRMixedReality.Cleanup();
                }

                prevEnableMixedReality = enableMixedReality;
            }
            else
            {
                if (!suppressDisableMixedRealityBecauseOfNoMainCameraWarning)
                {
                    Debug.LogWarning("Main Camera is not set, Mixed Reality disabled");
                    suppressDisableMixedRealityBecauseOfNoMainCameraWarning = true;
                }
            }
        }
#endif
    }
Exemple #3
0
 public Vector3 GetDimensions(OVRBoundary.BoundaryType boundaryType)
 {
     return(OVRPlugin.GetBoundaryDimensions((OVRPlugin.BoundaryType)boundaryType).FromVector3f());
 }
Exemple #4
0
 public void SetVisible(bool value)
 {
     OVRPlugin.SetBoundaryVisible(value);
 }
    // Update is called once per frame
    void Update()
    {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
        if (!inited)
        {
            Initialize();
            return;
        }

        if (!defaultExternalCamera)
        {
            return;
        }

#if OVR_ANDROID_MRC
        if (!OVRPlugin.Media.GetInitialized())
        {
            return;
        }
#else
        if (!OVRPlugin.IsMixedRealityInitialized())
        {
            return;
        }
#endif

        if (OVRInput.GetDown(OVRInput.Button.One))
        {
            if (currentMode == CameraMode.ThirdPerson)
            {
                currentMode = CameraMode.Normal;
            }
            else
            {
                currentMode = currentMode + 1;
            }

            Debug.LogFormat("Camera mode change to {0}", currentMode);
        }

        if (currentMode == CameraMode.Normal)
        {
            UpdateDefaultExternalCamera();
            OVRPlugin.OverrideExternalCameraFov(0, false, new OVRPlugin.Fovf());
            OVRPlugin.OverrideExternalCameraStaticPose(0, false, OVRPlugin.Posef.identity);
        }
        else if (currentMode == CameraMode.OverrideFov)
        {
            OVRPlugin.Fovf fov    = defaultFov;
            OVRPlugin.Fovf newFov = new OVRPlugin.Fovf();
            newFov.LeftTan  = fov.LeftTan * 2.0f;
            newFov.RightTan = fov.RightTan * 2.0f;
            newFov.UpTan    = fov.UpTan * 2.0f;
            newFov.DownTan  = fov.DownTan * 2.0f;

            OVRPlugin.OverrideExternalCameraFov(0, true, newFov);
            OVRPlugin.OverrideExternalCameraStaticPose(0, false, OVRPlugin.Posef.identity);

            if (!OVRPlugin.GetUseOverriddenExternalCameraFov(0))
            {
                Debug.LogWarning("FOV not overridden");
            }
        }
        else if (currentMode == CameraMode.ThirdPerson)
        {
            Camera camera = GetComponent <Camera>();
            if (camera == null)
            {
                return;
            }

            float          vFov = camera.fieldOfView * Mathf.Deg2Rad;
            float          hFov = Mathf.Atan(Mathf.Tan(vFov * 0.5f) * camera.aspect) * 2.0f;
            OVRPlugin.Fovf fov  = new OVRPlugin.Fovf();
            fov.UpTan   = fov.DownTan = Mathf.Tan(vFov * 0.5f);
            fov.LeftTan = fov.RightTan = Mathf.Tan(hFov * 0.5f);
            OVRPlugin.OverrideExternalCameraFov(0, true, fov);

            Camera       mainCamera = Camera.main;
            OVRCameraRig cameraRig  = mainCamera.GetComponentInParent <OVRCameraRig>();
            if (cameraRig)
            {
                Transform       trackingSpace     = cameraRig.trackingSpace;
                OVRPose         trackingSpacePose = trackingSpace.ToOVRPose(false);
                OVRPose         cameraPose        = transform.ToOVRPose(false);
                OVRPose         relativePose      = trackingSpacePose.Inverse() * cameraPose;
                OVRPlugin.Posef relativePosef     = relativePose.ToPosef();
                OVRPlugin.OverrideExternalCameraStaticPose(0, true, relativePosef);
            }
            else
            {
                OVRPlugin.OverrideExternalCameraStaticPose(0, false, OVRPlugin.Posef.identity);
            }

            if (!OVRPlugin.GetUseOverriddenExternalCameraFov(0))
            {
                Debug.LogWarning("FOV not overridden");
            }

            if (!OVRPlugin.GetUseOverriddenExternalCameraStaticPose(0))
            {
                Debug.LogWarning("StaticPose not overridden");
            }
        }
#endif
    }
Exemple #6
0
 public void ResetLookAndFeel()
 {
     OVRPlugin.ResetBoundaryLookAndFeel();
 }
Exemple #7
0
    private static bool BuildGradleProject()
    {
        gradleBuildProcess = new Process();
        string arguments = "-Xmx4096m -classpath \"" + gradlePath +
                           "\" org.gradle.launcher.GradleMain assembleDebug -x validateSigningDebug --profile";

#if UNITY_2019_3_OR_NEWER
        var gradleProjectPath = gradleExport;
#else
        var gradleProjectPath = Path.Combine(gradleExport, productName);
#endif

        var processInfo = new System.Diagnostics.ProcessStartInfo
        {
            WorkingDirectory       = gradleProjectPath,
            WindowStyle            = System.Diagnostics.ProcessWindowStyle.Normal,
            FileName               = jdkPath,
            Arguments              = arguments,
            RedirectStandardInput  = true,
            UseShellExecute        = false,
            CreateNoWindow         = true,
            RedirectStandardError  = true,
            RedirectStandardOutput = true,
        };

        gradleBuildProcess.StartInfo           = processInfo;
        gradleBuildProcess.EnableRaisingEvents = true;

        DateTime gradleStartTime = System.DateTime.Now;
        DateTime gradleEndTime   = System.DateTime.MinValue;

        gradleBuildProcess.Exited += new System.EventHandler(
            (s, e) =>
        {
            UnityEngine.Debug.Log("Gradle: Exited");
        }
            );

        gradleBuildProcess.OutputDataReceived += new DataReceivedEventHandler(
            (s, e) =>
        {
            if (e != null && e.Data != null &&
                e.Data.Length != 0 &&
                (e.Data.Contains("BUILD") || e.Data.StartsWith("See the profiling report at:")))
            {
                UnityEngine.Debug.LogFormat("Gradle: {0}", e.Data);
                if (e.Data.Contains("SUCCESSFUL"))
                {
                    UnityEngine.Debug.LogFormat("APK Build Completed: {0}",
                                                Path.Combine(Path.Combine(gradleProjectPath, "build\\outputs\\apk\\debug"), productName + "-debug.apk").Replace("/", "\\"));
                    if (!apkOutputSuccessful.HasValue)
                    {
                        apkOutputSuccessful = true;
                    }
                    gradleEndTime = System.DateTime.Now;
                }
                else if (e.Data.Contains("FAILED"))
                {
                    apkOutputSuccessful = false;
                }
            }
        }
            );

        gradleBuildProcess.ErrorDataReceived += new DataReceivedEventHandler(
            (s, e) =>
        {
            if (e != null && e.Data != null &&
                e.Data.Length != 0)
            {
                UnityEngine.Debug.LogErrorFormat("Gradle: {0}", e.Data);
            }
            apkOutputSuccessful = false;
        }
            );

        gradleBuildProcess.Start();
        gradleBuildProcess.BeginOutputReadLine();
        IncrementProgressBar("Building gradle project . . .");

        gradleBuildProcess.WaitForExit();

        // Add a timeout for if gradle unexpectedlly exits or errors out
        Stopwatch timeout = new Stopwatch();
        timeout.Start();
        while (apkOutputSuccessful == null)
        {
            if (timeout.ElapsedMilliseconds > 5000)
            {
                UnityEngine.Debug.LogError("Gradle has exited unexpectedly.");
                apkOutputSuccessful = false;
            }
            System.Threading.Thread.Sleep(100);
        }

        // Record time it takes to build gradle project only if we had a successful build
        double gradleTime = (gradleEndTime - gradleStartTime).TotalSeconds;
        if (gradleTime > 0)
        {
            OVRPlugin.SendEvent("build_step_building_gradle_project", gradleTime.ToString(), "ovrbuild");
            totalBuildTime += gradleTime;
        }

        return(apkOutputSuccessful.HasValue && apkOutputSuccessful.Value);
    }
Exemple #8
0
    void Update()
    {
        data.Length = 0;

        OVRInput.Controller activeController = OVRInput.GetActiveController();

        string activeControllerName = activeController.ToString();

        data.AppendFormat("Active: {0}\n", activeControllerName);

        string connectedControllerNames = OVRInput.GetConnectedControllers().ToString();

        data.AppendFormat("Connected: {0}\n", connectedControllerNames);

        data.AppendFormat("PrevConnected: {0}\n", prevConnected);

        controllers.Update();
        controllers.AppendToStringBuilder(ref data);
        prevConnected = connectedControllerNames;

        Vector3 pos = OVRInput.GetLocalControllerPosition(activeController);

        data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", pos.x, pos.y, pos.z);

        Quaternion rot = OVRInput.GetLocalControllerRotation(activeController);

        data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", rot.x, rot.y, rot.z, rot.w);

        data.AppendFormat("HandTrackingEnabled: {0}\n", OVRPlugin.GetHandTrackingEnabled());

        bool result_hs_LH = OVRPlugin.GetHandState(OVRPlugin.Step.Render, OVRPlugin.Hand.HandLeft, ref hs_LH);

        data.AppendFormat("LH HS Query Res: {0}\n", result_hs_LH);
        data.AppendFormat("LH HS Status: {0}\n", hs_LH.Status);
        data.AppendFormat("LH HS Pose: {0}\n", hs_LH.RootPose);
        data.AppendFormat("LH HS HandConf: {0}\n", hs_LH.HandConfidence);

        bool result_hs_RH = OVRPlugin.GetHandState(OVRPlugin.Step.Render, OVRPlugin.Hand.HandRight, ref hs_RH);

        data.AppendFormat("RH HS Query Res: {0}\n", result_hs_RH);
        data.AppendFormat("RH HS Status: {0}\n", hs_RH.Status);
        data.AppendFormat("RH HS Pose: {0}\n", hs_RH.RootPose);
        data.AppendFormat("RH HS HandConf: {0}\n", hs_RH.HandConfidence);

        data.AppendFormat("LH Skel Query Res: {0}\n", result_skel_LH);
        data.AppendFormat("LH Skel Type: {0}\n", skel_LH.Type);
        data.AppendFormat("LH Skel NumBones: {0}\n", skel_LH.NumBones);

        data.AppendFormat("RH Skel Query Res: {0}\n", result_skel_RH);
        data.AppendFormat("RH Skel Type: {0}\n", skel_RH.Type);
        data.AppendFormat("RH Skel NumBones: {0}\n", skel_RH.NumBones);

        data.AppendFormat("LH Mesh Query Res: {0}\n", result_mesh_LH);
        data.AppendFormat("LH Mesh Type: {0}\n", mesh_LH.Type);
        data.AppendFormat("LH Mesh NumVers: {0}\n", mesh_LH.NumVertices);

        data.AppendFormat("RH Mesh Query Res: {0}\n", result_mesh_RH);
        data.AppendFormat("RH Mesh Type: {0}\n", mesh_RH.Type);
        data.AppendFormat("RH Mesh NumVers: {0}\n", mesh_RH.NumVertices);

        for (int i = 0; i < monitors.Count; i++)
        {
            monitors[i].Update();
            monitors[i].AppendToStringBuilder(ref data);
        }

        if (uiText != null)
        {
            uiText.text = data.ToString();
        }
    }
    void Start()
    {
        OVRManager.display.RecenteredPose += Recentered;

        m_originalTrackerOrientation = OVRPlugin.GetNodePose(OVRPlugin.Node.TrackerZero, OVRPlugin.Step.Render).ToOVRPose().orientation;
    }
Exemple #10
0
    static void StartBuildAndRun()
    {
        EditorWindow.GetWindow(typeof(OculusBuildApp));

        showCancel     = false;
        buildFailed    = false;
        totalBuildTime = 0;

        InitializeProgressBar(NUM_BUILD_AND_RUN_STEPS);
        IncrementProgressBar("Exporting Unity Project . . .");

        OVRPlugin.SetDeveloperMode(OVRPlugin.Bool.True);
        OVRPlugin.AddCustomMetadata("build_type", "ovr_build_and_run");

        if (!CheckADBDevices())
        {
            buildFailed = true;
            return;
        }

        // Record OVR Build and Run start event
        OVRPlugin.SendEvent("ovr_build_and_run_start", "", "ovrbuild");

        apkOutputSuccessful = null;
        syncCancelToken     = null;
        gradleBuildProcess  = null;

        UnityEngine.Debug.Log("OVRBuild: Starting Unity build ...");

        SetupDirectories();

        // 1. Get scenes to build in Unity, and export gradle project
        var buildResult = UnityBuildPlayer();

        if (buildResult.summary.result == UnityEditor.Build.Reporting.BuildResult.Succeeded)
        {
            foreach (var step in buildResult.steps)
            {
                // Only log top level build steps & specific nested steps to reduce the number of events sent
                if (step.depth == 1 ||
                    (step.name.StartsWith("Packaging assets") && step.name.EndsWith(".assets")) ||
                    step.name.Equals("Managed Stripping: (Mono)") ||
                    step.name.Equals("Splitting assets") ||
                    step.name.Equals("IL2CPP") ||
                    step.name.Equals("Exporting project")
                    )
                {
                    OVRPlugin.SendEvent($"build_step_unity_build_player {step.name}", step.duration.TotalSeconds.ToString(), "ovrbuild");
                }
            }

            OVRPlugin.SendEvent("build_step_unity_export", buildResult.summary.totalTime.TotalSeconds.ToString(), "ovrbuild");
            totalBuildTime += buildResult.summary.totalTime.TotalSeconds;

            // Set static variables so build thread has updated data
            showCancel            = true;
            gradlePath            = OVRConfig.Instance.GetGradlePath();
            jdkPath               = OVRConfig.Instance.GetJDKPath();
            androidSdkPath        = OVRConfig.Instance.GetAndroidSDKPath();
            applicationIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android);
#if UNITY_2019_3_OR_NEWER
            productName = "launcher";
#else
            productName = Application.productName;
#endif
            dataPath = Application.dataPath;

            buildThread = new Thread(delegate()
            {
                OVRBuildRun();
            });
            buildThread.Start();
            return;
        }
        else if (buildResult.summary.result == UnityEditor.Build.Reporting.BuildResult.Cancelled)
        {
            UnityEngine.Debug.Log("Build cancelled.");
        }
        else
        {
            UnityEngine.Debug.Log("Build failed.");
        }
        buildFailed = true;
    }
Exemple #11
0
    private void Initialize()
    {
        var skeleton = new OVRPlugin.Skeleton();

        if (OVRPlugin.GetSkeleton((OVRPlugin.SkeletonType)_skeletonType, out skeleton))
        {
            if (!_bonesGO)
            {
                _bonesGO = new GameObject("Bones");
                _bonesGO.transform.SetParent(transform, false);
                _bonesGO.transform.localPosition = Vector3.zero;
                _bonesGO.transform.localRotation = Quaternion.identity;
            }

            if (!_bindPosesGO)
            {
                _bindPosesGO = new GameObject("BindPoses");
                _bindPosesGO.transform.SetParent(transform, false);
                _bindPosesGO.transform.localPosition = Vector3.zero;
                _bindPosesGO.transform.localRotation = Quaternion.identity;
            }

            if (_enablePhysicsCapsules)
            {
                if (!_capsulesGO)
                {
                    _capsulesGO = new GameObject("Capsules");
                    _capsulesGO.transform.SetParent(transform, false);
                    _capsulesGO.transform.localPosition = Vector3.zero;
                    _capsulesGO.transform.localRotation = Quaternion.identity;
                }
            }

            _bones = new List <OVRBone>(new OVRBone[skeleton.NumBones]);
            Bones  = _bones.AsReadOnly();

            _bindPoses = new List <OVRBone>(new OVRBone[skeleton.NumBones]);
            BindPoses  = _bindPoses.AsReadOnly();

            // pre-populate bones list before attempting to apply bone hierarchy
            for (int i = 0; i < skeleton.NumBones; ++i)
            {
                BoneId     id        = (OVRSkeleton.BoneId)skeleton.Bones[i].Id;
                short      parentIdx = skeleton.Bones[i].ParentBoneIndex;
                Vector3    pos       = skeleton.Bones[i].Pose.Position.FromFlippedZVector3f();
                Quaternion rot       = skeleton.Bones[i].Pose.Orientation.FromFlippedZQuatf();

                var boneGO = new GameObject(id.ToString());
                boneGO.transform.localPosition = pos;
                boneGO.transform.localRotation = rot;
                _bones[i] = new OVRBone(id, parentIdx, boneGO.transform);

                var bindPoseGO = new GameObject(id.ToString());
                bindPoseGO.transform.localPosition = pos;
                bindPoseGO.transform.localRotation = rot;
                _bindPoses[i] = new OVRBone(id, parentIdx, bindPoseGO.transform);
            }

            for (int i = 0; i < skeleton.NumBones; ++i)
            {
                if (((OVRPlugin.BoneId)skeleton.Bones[i].ParentBoneIndex) == OVRPlugin.BoneId.Invalid)
                {
                    _bones[i].Transform.SetParent(_bonesGO.transform, false);
                    _bindPoses[i].Transform.SetParent(_bindPosesGO.transform, false);
                }
                else
                {
                    _bones[i].Transform.SetParent(_bones[_bones[i].ParentBoneIndex].Transform, false);
                    _bindPoses[i].Transform.SetParent(_bindPoses[_bones[i].ParentBoneIndex].Transform, false);
                }
            }

            if (_enablePhysicsCapsules)
            {
                _capsules = new List <OVRBoneCapsule>(new OVRBoneCapsule[skeleton.NumBoneCapsules]);
                Capsules  = _capsules.AsReadOnly();

                for (int i = 0; i < skeleton.NumBoneCapsules; ++i)
                {
                    var       capsule = skeleton.BoneCapsules[i];
                    Transform bone    = Bones[capsule.BoneIndex].Transform;

                    var capsuleRigidBodyGO = new GameObject((_bones[capsule.BoneIndex].Id).ToString() + "_CapsuleRigidBody");
                    capsuleRigidBodyGO.transform.SetParent(_capsulesGO.transform, false);
                    capsuleRigidBodyGO.transform.localPosition = bone.position;
                    capsuleRigidBodyGO.transform.localRotation = bone.rotation;

                    var capsuleRigidBody = capsuleRigidBodyGO.AddComponent <Rigidbody>();
                    capsuleRigidBody.mass        = 1.0f;
                    capsuleRigidBody.isKinematic = true;
                    capsuleRigidBody.useGravity  = false;
#if UNITY_2018_3_OR_NEWER
                    capsuleRigidBody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
#else
                    capsuleRigidBody.collisionDetectionMode = CollisionDetectionMode.Continuous;
#endif

                    var capsuleColliderGO = new GameObject((_bones[capsule.BoneIndex].Id).ToString() + "_CapsuleCollider");
                    capsuleColliderGO.transform.SetParent(capsuleRigidBodyGO.transform, false);
                    var capsuleCollider = capsuleColliderGO.AddComponent <CapsuleCollider>();
                    var p0    = capsule.Points[0].FromFlippedZVector3f();
                    var p1    = capsule.Points[1].FromFlippedZVector3f();
                    var delta = p1 - p0;
                    var mag   = delta.magnitude;
                    var rot   = Quaternion.FromToRotation(capsuleRigidBodyGO.transform.localRotation * Vector3.right, delta);
                    capsuleCollider.radius    = capsule.Radius;
                    capsuleCollider.height    = mag + capsule.Radius * 2.0f;
                    capsuleCollider.isTrigger = false;
                    capsuleCollider.direction = 0;
                    capsuleColliderGO.transform.localPosition = p0;
                    capsuleColliderGO.transform.localRotation = rot;
                    capsuleCollider.center = Vector3.right * mag * 0.5f;

                    _capsules[i] = new OVRBoneCapsule(capsule.BoneIndex, capsuleRigidBody, capsuleCollider);
                }
            }

            _isInitialized = true;
        }
    }
Exemple #12
0
    // The actual window code goes here
    void OnGUI()
    {
        showAndroidOptions = EditorGUILayout.Foldout(showAndroidOptions, "Android Tools");

        if (showAndroidOptions)
        {
            GUILayout.BeginHorizontal();
            string newAndroidSdkRootPath = EditorGUILayout.DelayedTextField("Android SDK root path", androidSdkRootPath);
            if (newAndroidSdkRootPath != androidSdkRootPath)
            {
                androidSdkRootPath = newAndroidSdkRootPath;
                PlayerPrefs.SetString("OVRAndroidSdkRootPath", androidSdkRootPath);
            }
            GUILayout.EndHorizontal();
            if (!OVRADBTool.IsAndroidSdkRootValid(androidSdkRootPath))
            {
                GUILayout.Label("Invalid Android SDK. Please set it to the Android SDK path in Unity Preferences / External Tools");
            }

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Start Server"))
            {
                if (adbTool == null)
                {
                    adbTool = new OVRADBTool(androidSdkRootPath);
                }
                if (adbTool.isReady)
                {
                    int exitCode = adbTool.StartServer(null);
                    EditorUtility.DisplayDialog("ADB StartServer", (exitCode == 0 ? "Success" : "Failure. ExitCode = " + exitCode.ToString()), "Ok");
                }
                else
                {
                    EditorUtility.DisplayDialog("Can't locate ADBTool", adbTool.adbPath, "Ok");
                }
            }
            if (GUILayout.Button("Kill Server"))
            {
                if (adbTool == null)
                {
                    adbTool = new OVRADBTool(androidSdkRootPath);
                }
                if (adbTool.isReady)
                {
                    int exitCode = adbTool.KillServer(null);
                    EditorUtility.DisplayDialog("ADB KillServer", (exitCode == 0 ? "Success" : "Failure. ExitCode = " + exitCode.ToString()), "Ok");
                }
                else
                {
                    EditorUtility.DisplayDialog("Can't locate ADBTool", adbTool.adbPath, "Ok");
                }
            }
            if (GUILayout.Button("Forward Port"))
            {
                if (adbTool == null)
                {
                    adbTool = new OVRADBTool(androidSdkRootPath);
                }
                if (adbTool.isReady)
                {
                    int exitCode = adbTool.ForwardPort(remoteListeningPort, null);
                    EditorUtility.DisplayDialog("ADB ForwardPort", (exitCode == 0 ? "Success" : "Failure. ExitCode = " + exitCode.ToString()), "Ok");
                    OVRPlugin.SendEvent("device_metrics_profiler", (exitCode == 0 ? "adb_forward_success" : "adb_forward_failure"));
                }
                else
                {
                    EditorUtility.DisplayDialog("Can't locate ADBTool", adbTool.adbPath, "Ok");
                }
            }
            if (GUILayout.Button("Release Port"))
            {
                if (adbTool == null)
                {
                    adbTool = new OVRADBTool(androidSdkRootPath);
                }
                if (adbTool.isReady)
                {
                    int exitCode = adbTool.ReleasePort(remoteListeningPort, null);
                    EditorUtility.DisplayDialog("ADB ReleasePort", (exitCode == 0 ? "Success" : "Failure. ExitCode = " + exitCode.ToString()), "Ok");
                }
                else
                {
                    EditorUtility.DisplayDialog("Can't locate ADBTool", adbTool.adbPath, "Ok");
                }
            }
            GUILayout.EndHorizontal();
        }

        EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);

        GUILayout.BeginHorizontal();
        remoteListeningPort = EditorGUILayout.DelayedIntField("Remote Port", remoteListeningPort);

        if (tcpClient.connectionState == OVRNetwork.OVRNetworkTcpClient.ConnectionState.Disconnected)
        {
            if (GUILayout.Button("Connect"))
            {
                ConnectPerfMetricsTcpServer();
                pauseReceiveMetrics = false;
                OVRPlugin.SendEvent("device_metrics_profiler", "connect");
            }
        }
        else
        {
            if (tcpClient.connectionState == OVRNetwork.OVRNetworkTcpClient.ConnectionState.Connecting)
            {
                if (GUILayout.Button("Connecting ... Click again to Cancel"))
                {
                    DisconnectPerfMetricsTcpServer();
                    OVRPlugin.SendEvent("device_metrics_profiler", "cancel");
                }
            }
            else
            {
                if (GUILayout.Button("Disconnect"))
                {
                    DisconnectPerfMetricsTcpServer();
                    OVRPlugin.SendEvent("device_metrics_profiler", "disconnect");
                }

                if (GUILayout.Button(pauseReceiveMetrics ? "Continue" : "Pause"))
                {
                    pauseReceiveMetrics = !pauseReceiveMetrics;
                }
            }
        }
        GUILayout.EndHorizontal();

        EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);

        lock (receivedMetricsList)
        {
            PresentIntProperty("Frame Count", "frameCount");
            PresentIntProperty("Dropped Frame Count", "compositorDroppedFrameCount");

            float?avgFrameTime = GetAveragePerfValueFloat("deltaFrameTime");
            if (avgFrameTime.HasValue)
            {
                float fps = 1.0f / avgFrameTime.Value;
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("FPS", GUILayout.Width(labelWidth));
                EditorGUILayout.LabelField(string.Format("{0:F1}", fps));
                EditorGUILayout.EndHorizontal();
            }

            int?  deviceCpuClockLevel          = GetLatestPerfValueInt("deviceCpuClockLevel");
            int?  deviceGpuClockLevel          = GetLatestPerfValueInt("deviceGpuClockLevel");
            float?deviceCpuClockFrequencyInMHz = GetLatestPerfValueFloat("deviceCpuClockFrequencyInMHz");
            float?deviceGpuClockFrequencyInMHz = GetLatestPerfValueFloat("deviceGpuClockFrequencyInMHz");

            if (deviceCpuClockLevel.HasValue || deviceCpuClockFrequencyInMHz.HasValue)
            {
                string cpuLabel;
                string cpuText;
                if (deviceCpuClockLevel.HasValue && deviceCpuClockFrequencyInMHz.HasValue)
                {
                    cpuLabel = "CPU Level (Freq)";
                    cpuText  = string.Format("{0} ({1:F0} MHz)", deviceCpuClockLevel, deviceCpuClockFrequencyInMHz);
                }
                else if (deviceCpuClockLevel.HasValue)
                {
                    cpuLabel = "CPU Level";
                    cpuText  = string.Format("{0}", deviceCpuClockLevel);
                }
                else
                {
                    cpuLabel = "CPU Frequency";
                    cpuText  = string.Format("{0:F0} MHz", deviceCpuClockFrequencyInMHz);
                }
                PresentText(cpuLabel, cpuText);
            }

            if (deviceGpuClockLevel.HasValue || deviceGpuClockFrequencyInMHz.HasValue)
            {
                string cpuLabel;
                string cpuText;
                if (deviceGpuClockLevel.HasValue && deviceGpuClockFrequencyInMHz.HasValue)
                {
                    cpuLabel = "GPU Level (Freq)";
                    cpuText  = string.Format("{0} ({1:F0} MHz)", deviceGpuClockLevel, deviceGpuClockFrequencyInMHz);
                }
                else if (deviceGpuClockLevel.HasValue)
                {
                    cpuLabel = "GPU Level";
                    cpuText  = string.Format("{0}", deviceGpuClockLevel);
                }
                else
                {
                    cpuLabel = "GPU Frequency";
                    cpuText  = string.Format("{0:F0} MHz", deviceGpuClockFrequencyInMHz);
                }
                PresentText(cpuLabel, cpuText);
            }

            PresentColumnTitles("Current", "Average", "Peak");

            PresentFloatTimeInMs("Frame Time", "deltaFrameTime", 0.020f, true, true);
            PresentFloatTimeInMs("App CPU Time", "appCpuTime", 0.020f, true, true);
            PresentFloatTimeInMs("App GPU Time", "appGpuTime", 0.020f, true, true);
            PresentFloatTimeInMs("Compositor CPU Time", "compositorCpuTime", 0.020f, true, true);
            PresentFloatTimeInMs("Compositor GPU Time", "compositorGpuTime", 0.020f, true, true);
            PresentFloatPercentage("CPU Util (Average)", "systemCpuUtilAveragePercentage", false, false);
            PresentFloatPercentage("CPU Util (Worst Core)", "systemCpuUtilWorstPercentage", false, false);
            PresentFloatPercentage("GPU Util", "systemGpuUtilPercentage", false, false);
        }
    }
Exemple #13
0
 public static void ShowWindow()
 {
     EditorWindow.GetWindow(typeof(OVRSystemProfilerPanel), false, "Oculus Profiler");
     OVRPlugin.SendEvent("oculus_profiler_panel", "show_window");
 }
Exemple #14
0
    // Token: 0x060038F1 RID: 14577 RVA: 0x001225BC File Offset: 0x001209BC
    private void OnRenderObject()
    {
        if (!Camera.current.CompareTag("MainCamera") || Camera.current.cameraType != CameraType.Game || this.layerIndex == -1 || this.currentOverlayType == OVROverlay.OverlayType.None)
        {
            return;
        }
        if (this.currentOverlayShape == OVROverlay.OverlayShape.Cubemap || this.currentOverlayShape == OVROverlay.OverlayShape.Cylinder)
        {
            Debug.LogWarning("Overlay shape " + this.currentOverlayShape + " is not supported on current platform");
        }
        for (int i = 0; i < 2; i++)
        {
            if (i < this.textures.Length)
            {
                if (this.textures[i] != this.cachedTextures[i])
                {
                    this.cachedTextures[i] = this.textures[i];
                    if (this.cachedTextures[i] != null)
                    {
                        this.texNativePtrs[i] = this.cachedTextures[i].GetNativeTexturePtr();
                    }
                }
                if (this.currentOverlayShape == OVROverlay.OverlayShape.Cubemap && this.textures[i] != null && this.textures[i].GetType() != typeof(Cubemap))
                {
                    Debug.LogError("Need Cubemap texture for cube map overlay");
                    return;
                }
            }
        }
        if (this.cachedTextures[0] == null || this.texNativePtrs[0] == IntPtr.Zero)
        {
            return;
        }
        bool      onTop     = this.currentOverlayType == OVROverlay.OverlayType.Overlay;
        bool      flag      = false;
        Transform transform = base.transform;

        while (transform != null && !flag)
        {
            flag     |= (transform == Camera.current.transform);
            transform = transform.parent;
        }
        OVRPose ovrpose    = (!flag) ? base.transform.ToTrackingSpacePose() : base.transform.ToHeadSpacePose();
        Vector3 lossyScale = base.transform.lossyScale;

        for (int j = 0; j < 3; j++)
        {
            int index;
            lossyScale[index = j] = lossyScale[index] / Camera.current.transform.lossyScale[j];
        }
        if (this.currentOverlayShape == OVROverlay.OverlayShape.Cylinder)
        {
            float num = lossyScale.x / lossyScale.z / 3.14159274f * 180f;
            if (num > 180f)
            {
                Debug.LogError("Cylinder overlay's arc angle has to be below 180 degree, current arc angle is " + num + " degree.");
                return;
            }
        }
        bool flag2 = OVRPlugin.SetOverlayQuad(onTop, flag, this.texNativePtrs[0], this.texNativePtrs[1], IntPtr.Zero, ovrpose.flipZ().ToPosef(), lossyScale.ToVector3f(), this.layerIndex, (OVRPlugin.OverlayShape) this.currentOverlayShape);

        if (this.rend)
        {
            this.rend.enabled = !flag2;
        }
    }
Exemple #15
0
    public static bool DeployAPK()
    {
        // Create new instance of ADB Tool
        var adbTool = new OVRADBTool(androidSdkPath);

        if (adbTool.isReady)
        {
            string apkPathLocal;
            string gradleExportFolder = Path.Combine(Path.Combine(gradleExport, productName), "build\\outputs\\apk\\debug");

            // Check to see if gradle output directory exists
            gradleExportFolder = gradleExportFolder.Replace("/", "\\");
            if (!Directory.Exists(gradleExportFolder))
            {
                UnityEngine.Debug.LogError("Could not find the gradle project at the expected path: " + gradleExportFolder);
                return(false);
            }

            // Search for output APK in gradle output directory
            apkPathLocal = Path.Combine(gradleExportFolder, productName + "-debug.apk");
            if (!System.IO.File.Exists(apkPathLocal))
            {
                UnityEngine.Debug.LogError(string.Format("Could not find {0} in the gradle project.", productName + "-debug.apk"));
                return(false);
            }

            string   output, error;
            DateTime timerStart;

            // Ensure that the Oculus temp directory is on the device by making it
            IncrementProgressBar("Making Temp directory on device");
            string[] mkdirCommand = { "-d shell", "mkdir -p", REMOTE_APK_PATH };
            if (adbTool.RunCommand(mkdirCommand, null, out output, out error) != 0)
            {
                return(false);
            }

            // Push APK to device, also time how long it takes
            timerStart = System.DateTime.Now;
            IncrementProgressBar("Pushing APK to device . . .");
            string[] pushCommand = { "-d push", "\"" + apkPathLocal + "\"", REMOTE_APK_PATH };
            if (adbTool.RunCommand(pushCommand, null, out output, out error) != 0)
            {
                return(false);
            }

            // Calculate the transfer speed and determine if user is using USB 2.0 or 3.0
            TimeSpan pushTime      = System.DateTime.Now - timerStart;
            FileInfo apkInfo       = new System.IO.FileInfo(apkPathLocal);
            double   transferSpeed = (apkInfo.Length / pushTime.TotalSeconds) / BYTES_TO_MEGABYTES;
            bool     informLog     = transferSpeed < USB_TRANSFER_SPEED_THRES;
            UnityEngine.Debug.Log("OVRADBTool: Push Success");

            // Install the APK package on the device
            IncrementProgressBar("Installing APK . . .");
            string apkPath = REMOTE_APK_PATH + "/" + productName + "-debug.apk";
            apkPath = apkPath.Replace(" ", "\\ ");
            string[] installCommand = { "-d shell", "pm install -r", apkPath };

            timerStart = System.DateTime.Now;
            if (adbTool.RunCommand(installCommand, null, out output, out error) != 0)
            {
                return(false);
            }
            TimeSpan installTime = System.DateTime.Now - timerStart;
            UnityEngine.Debug.Log("OVRADBTool: Install Success");

            // Start the application on the device
            IncrementProgressBar("Launching application on device . . .");
#if UNITY_2019_3_OR_NEWER
            string playerActivityName = "\"" + applicationIdentifier + "/com.unity3d.player.UnityPlayerActivity\"";
#else
            string playerActivityName = "\"" + applicationIdentifier + "/" + applicationIdentifier + ".UnityPlayerActivity\"";
#endif
            string[] appStartCommand = { "-d shell", "am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -S -f 0x10200000 -n", playerActivityName };
            if (adbTool.RunCommand(appStartCommand, null, out output, out error) != 0)
            {
                return(false);
            }
            UnityEngine.Debug.Log("OVRADBTool: Application Start Success");

            // Send back metrics on push and install steps
            OVRPlugin.AddCustomMetadata("transfer_speed", transferSpeed.ToString());
            OVRPlugin.SendEvent("build_step_push_apk", pushTime.TotalSeconds.ToString(), "ovrbuild");
            OVRPlugin.SendEvent("build_step_install_apk", installTime.TotalSeconds.ToString(), "ovrbuild");

            IncrementProgressBar("Success!");

            // If the user is using a USB 2.0 cable, inform them about improved transfer speeds and estimate time saved
            if (informLog)
            {
                var usb3Time = apkInfo.Length / (USB_3_TRANSFER_SPEED * BYTES_TO_MEGABYTES);
                UnityEngine.Debug.Log(string.Format("OVRBuild has detected slow transfer speeds. A USB 3.0 cable is recommended to reduce the time it takes to deploy your project by approximatly {0:0.0} seconds", pushTime.TotalSeconds - usb3Time));
                return(true);
            }
        }
        else
        {
            UnityEngine.Debug.LogError("Could not find the ADB executable in the specified Android SDK directory.");
        }
        return(false);
    }
Exemple #16
0
    public override void Update(Camera mainCamera)
    {
        if (!hasCameraDeviceOpened)
        {
            return;
        }

        if (!OVRPlugin.SetHandNodePoseStateLatency(OVRManager.instance.handPoseStateLatency))
        {
            Debug.LogWarning("HandPoseStateLatency is invalid. Expect a value between 0.0 to 0.5, get " + OVRManager.instance.handPoseStateLatency);
        }

        directCompositionCamera.clearFlags      = mainCamera.clearFlags;
        directCompositionCamera.backgroundColor = mainCamera.backgroundColor;
        directCompositionCamera.cullingMask     = mainCamera.cullingMask & (~OVRManager.instance.extraHiddenLayers);
        directCompositionCamera.nearClipPlane   = mainCamera.nearClipPlane;
        directCompositionCamera.farClipPlane    = mainCamera.farClipPlane;

        if (OVRMixedReality.useFakeExternalCamera || OVRPlugin.GetExternalCameraCount() == 0)
        {
            OVRPose worldSpacePose    = new OVRPose();
            OVRPose trackingSpacePose = new OVRPose();
            trackingSpacePose.position    = OVRMixedReality.fakeCameraPositon;
            trackingSpacePose.orientation = OVRMixedReality.fakeCameraRotation;
            worldSpacePose = OVRExtensions.ToWorldSpacePose(trackingSpacePose);

            directCompositionCamera.fieldOfView = OVRMixedReality.fakeCameraFov;
            directCompositionCamera.aspect      = OVRMixedReality.fakeCameraAspect;
            directCompositionCamera.transform.FromOVRPose(worldSpacePose);
        }
        else
        {
            OVRPlugin.CameraExtrinsics extrinsics;
            OVRPlugin.CameraIntrinsics intrinsics;

            // So far, only support 1 camera for MR and always use camera index 0
            if (OVRPlugin.GetMixedRealityCameraInfo(0, out extrinsics, out intrinsics))
            {
                OVRPose worldSpacePose = ComputeCameraWorldSpacePose(extrinsics);

                float fovY   = Mathf.Atan(intrinsics.FOVPort.UpTan) * Mathf.Rad2Deg * 2;
                float aspect = intrinsics.FOVPort.LeftTan / intrinsics.FOVPort.UpTan;
                directCompositionCamera.fieldOfView = fovY;
                directCompositionCamera.aspect      = aspect;
                directCompositionCamera.transform.FromOVRPose(worldSpacePose);
            }
            else
            {
                Debug.LogWarning("Failed to get external camera information");
            }
        }

        if (hasCameraDeviceOpened)
        {
            if (boundaryMeshMaskTexture == null || boundaryMeshMaskTexture.width != Screen.width || boundaryMeshMaskTexture.height != Screen.height)
            {
                boundaryMeshMaskTexture = new RenderTexture(Screen.width, Screen.height, 0, RenderTextureFormat.R8);
                boundaryMeshMaskTexture.Create();
            }
            UpdateCameraFramePlaneObject(mainCamera, directCompositionCamera, boundaryMeshMaskTexture);
            directCompositionCamera.GetComponent <OVRCameraFrameCompositionManager>().boundaryMeshMaskTexture = boundaryMeshMaskTexture;
        }
    }
        public override void UpdateDeviceState(IVRModuleDeviceState[] prevState, IVRModuleDeviceStateRW[] currState)
        {
            for (uint i = 0; i < MAX_DEVICE_COUNT; ++i)
            {
                var node = s_index2node[i];
                if (node == OVRPlugin.Node.None)
                {
                    continue;
                }

                currState[i].isConnected = OVRPlugin.GetNodePresent(node);

                if (currState[i].isConnected)
                {
                    if (!prevState[i].isConnected)
                    {
                        var ovrProductName = OVRPlugin.productName;
                        var deviceClass    = s_node2class[(int)node];

                        switch (deviceClass)
                        {
                        case VRModuleDeviceClass.HMD:
                            currState[i].deviceModel = VRModuleDeviceModel.OculusHMD;
                            break;

                        case VRModuleDeviceClass.TrackingReference:
                            currState[i].deviceModel = VRModuleDeviceModel.OculusSensor;
                            break;

                        case VRModuleDeviceClass.Controller:
                            switch (ovrProductName)
                            {
                            case "Oculus Go":
                                currState[i].deviceModel = VRModuleDeviceModel.OculusGoController;
                                break;

                            case "Gear VR":
                                currState[i].deviceModel = VRModuleDeviceModel.OculusGearVrController;
                                break;

                            case "Oculus Rift":
                            default:
                                switch (node)
                                {
                                case OVRPlugin.Node.HandLeft:
                                    currState[i].deviceModel = VRModuleDeviceModel.OculusTouchLeft;
                                    break;

                                case OVRPlugin.Node.HandRight:
                                default:
                                    currState[i].deviceModel = VRModuleDeviceModel.OculusTouchRight;
                                    break;
                                }
                                break;
                            }
                            break;
                        }

                        currState[i].deviceClass = deviceClass;
                        // FIXME: how to get device id from OVRPlugin?
                        currState[i].modelNumber     = ovrProductName + " " + deviceClass;
                        currState[i].renderModelName = ovrProductName + " " + deviceClass;
                        currState[i].serialNumber    = ovrProductName + " " + deviceClass;
                    }

                    // update device status
                    currState[i].pose            = ToPose(OVRPlugin.GetNodePose(node, OVRPlugin.Step.Render));
                    currState[i].velocity        = OVRPlugin.GetNodeVelocity(node, OVRPlugin.Step.Render).FromFlippedZVector3f();
                    currState[i].angularVelocity = OVRPlugin.GetNodeAngularVelocity(node, OVRPlugin.Step.Render).FromFlippedZVector3f();

                    currState[i].isPoseValid = currState[i].pose != RigidPose.identity;

                    // update device input
                    switch (currState[i].deviceModel)
                    {
                    case VRModuleDeviceModel.OculusTouchLeft:
                    {
                        var ctrlState = OVRPlugin.GetControllerState((uint)OVRPlugin.Controller.LTouch);

                        currState[i].SetButtonPress(VRModuleRawButton.ApplicationMenu, (ctrlState.Buttons & (uint)OVRInput.RawButton.Y) != 0u);
                        currState[i].SetButtonPress(VRModuleRawButton.A, (ctrlState.Buttons & (uint)OVRInput.RawButton.X) != 0u);
                        currState[i].SetButtonPress(VRModuleRawButton.Touchpad, (ctrlState.Buttons & (uint)OVRInput.RawButton.LThumbstick) != 0u);
                        currState[i].SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(currState[i].GetButtonPress(VRModuleRawButton.Trigger), ctrlState.LIndexTrigger, 0.55f, 0.45f));
                        currState[i].SetButtonPress(VRModuleRawButton.Grip, AxisToPress(currState[i].GetButtonPress(VRModuleRawButton.Grip), ctrlState.LHandTrigger, 0.55f, 0.45f));
                        currState[i].SetButtonPress(VRModuleRawButton.CapSenseGrip, AxisToPress(currState[i].GetButtonPress(VRModuleRawButton.CapSenseGrip), ctrlState.LHandTrigger, 0.55f, 0.45f));

                        currState[i].SetButtonTouch(VRModuleRawButton.ApplicationMenu, (ctrlState.Touches & (uint)OVRInput.RawTouch.Y) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.A, (ctrlState.Touches & (uint)OVRInput.RawTouch.X) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.Touchpad, (ctrlState.Touches & (uint)OVRInput.RawTouch.LThumbstick) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.Trigger, (ctrlState.Touches & (uint)OVRInput.RawTouch.LIndexTrigger) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.CapSenseGrip, AxisToPress(currState[i].GetButtonTouch(VRModuleRawButton.CapSenseGrip), ctrlState.LHandTrigger, 0.25f, 0.20f));

                        currState[i].SetAxisValue(VRModuleRawAxis.TouchpadX, ctrlState.LThumbstick.x);
                        currState[i].SetAxisValue(VRModuleRawAxis.TouchpadY, ctrlState.LThumbstick.y);
                        currState[i].SetAxisValue(VRModuleRawAxis.Trigger, ctrlState.LIndexTrigger);
                        currState[i].SetAxisValue(VRModuleRawAxis.CapSenseGrip, ctrlState.LHandTrigger);
                        break;
                    }

                    case VRModuleDeviceModel.OculusTouchRight:
                    {
                        var ctrlState = OVRPlugin.GetControllerState((uint)OVRPlugin.Controller.RTouch);

                        currState[i].SetButtonPress(VRModuleRawButton.ApplicationMenu, (ctrlState.Buttons & (uint)OVRInput.RawButton.B) != 0u);
                        currState[i].SetButtonPress(VRModuleRawButton.A, (ctrlState.Buttons & (uint)OVRInput.RawButton.A) != 0u);
                        currState[i].SetButtonPress(VRModuleRawButton.Touchpad, (ctrlState.Buttons & (uint)OVRInput.RawButton.RThumbstick) != 0u);
                        currState[i].SetButtonPress(VRModuleRawButton.Trigger, AxisToPress(currState[i].GetButtonPress(VRModuleRawButton.Trigger), ctrlState.RIndexTrigger, 0.55f, 0.45f));
                        currState[i].SetButtonPress(VRModuleRawButton.Grip, AxisToPress(currState[i].GetButtonPress(VRModuleRawButton.Grip), ctrlState.RHandTrigger, 0.55f, 0.45f));
                        currState[i].SetButtonPress(VRModuleRawButton.CapSenseGrip, AxisToPress(currState[i].GetButtonPress(VRModuleRawButton.CapSenseGrip), ctrlState.RHandTrigger, 0.55f, 0.45f));

                        currState[i].SetButtonTouch(VRModuleRawButton.ApplicationMenu, (ctrlState.Touches & (uint)OVRInput.RawTouch.B) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.A, (ctrlState.Touches & (uint)OVRInput.RawTouch.A) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.Touchpad, (ctrlState.Touches & (uint)OVRInput.RawTouch.RThumbstick) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.Trigger, (ctrlState.Touches & (uint)OVRInput.RawTouch.RIndexTrigger) != 0u);
                        currState[i].SetButtonTouch(VRModuleRawButton.CapSenseGrip, AxisToPress(currState[i].GetButtonTouch(VRModuleRawButton.CapSenseGrip), ctrlState.RHandTrigger, 0.25f, 0.20f));

                        currState[i].SetAxisValue(VRModuleRawAxis.TouchpadX, ctrlState.RThumbstick.x);
                        currState[i].SetAxisValue(VRModuleRawAxis.TouchpadY, ctrlState.RThumbstick.y);
                        currState[i].SetAxisValue(VRModuleRawAxis.Trigger, ctrlState.RIndexTrigger);
                        currState[i].SetAxisValue(VRModuleRawAxis.CapSenseGrip, ctrlState.RHandTrigger);
                        break;
                    }

                    case VRModuleDeviceModel.OculusGoController:
                    case VRModuleDeviceModel.OculusGearVrController:
                        switch (node)
                        {
                        case OVRPlugin.Node.HandLeft:
                        {
                            var ctrlState = OVRPlugin.GetControllerState((uint)OVRPlugin.Controller.LTrackedRemote);

                            currState[i].SetButtonPress(VRModuleRawButton.Touchpad, (ctrlState.Buttons & (uint)OVRInput.RawButton.LTouchpad) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.ApplicationMenu, (ctrlState.Buttons & (uint)OVRInput.RawButton.Back) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.Trigger, (ctrlState.Buttons & (uint)(OVRInput.RawButton.A | OVRInput.RawButton.LIndexTrigger)) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadLeft, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadLeft) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadUp, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadUp) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadRight, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadRight) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadDown, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadDown) != 0u);

                            currState[i].SetButtonTouch(VRModuleRawButton.Touchpad, (ctrlState.Touches & (uint)OVRInput.RawTouch.LTouchpad) != 0u);
                        }
                        break;

                        case OVRPlugin.Node.HandRight:
                        default:
                        {
                            var ctrlState = OVRPlugin.GetControllerState((uint)OVRPlugin.Controller.RTrackedRemote);

                            currState[i].SetButtonPress(VRModuleRawButton.Touchpad, (ctrlState.Buttons & unchecked ((uint)OVRInput.RawButton.RTouchpad)) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.ApplicationMenu, (ctrlState.Buttons & (uint)OVRInput.RawButton.Back) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.Trigger, (ctrlState.Buttons & (uint)(OVRInput.RawButton.A | OVRInput.RawButton.RIndexTrigger)) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadLeft, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadLeft) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadUp, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadUp) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadRight, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadRight) != 0u);
                            currState[i].SetButtonPress(VRModuleRawButton.DPadDown, (ctrlState.Buttons & (uint)OVRInput.RawButton.DpadDown) != 0u);

                            currState[i].SetButtonTouch(VRModuleRawButton.Touchpad, (ctrlState.Touches & unchecked ((uint)OVRInput.RawTouch.RTouchpad)) != 0u);
                        }
                        break;
                        }
                        break;
                    }
                }
                else
                {
                    if (prevState[i].isConnected)
                    {
                        currState[i].Reset();
                    }
                }
            }
        }
Exemple #18
0
    private void Update()
    {
        if (OVRPlugin.shouldQuit)
        {
            Application.Quit();
        }

        if (OVRPlugin.shouldRecenter)
        {
            OVRManager.display.RecenterPose();
        }

        if (trackingOriginType != _trackingOriginType)
        {
            trackingOriginType = _trackingOriginType;
        }

        tracker.isEnabled = usePositionTracking;

        OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;

        // Dispatch HMD events.

        isHmdPresent = OVRPlugin.hmdPresent;

        if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
        {
            Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing +
                      ", but the recommended MSAA level is " + display.recommendedMSAALevel +
                      ". Switching to the recommended level.");

            QualitySettings.antiAliasing = display.recommendedMSAALevel;
        }

        if (_wasHmdPresent && !isHmdPresent)
        {
            try
            {
                if (HMDLost != null)
                {
                    HMDLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_wasHmdPresent && isHmdPresent)
        {
            try
            {
                if (HMDAcquired != null)
                {
                    HMDAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _wasHmdPresent = isHmdPresent;

        // Dispatch HMD mounted events.

        isUserPresent = OVRPlugin.userPresent;

        if (_wasUserPresent && !isUserPresent)
        {
            try
            {
                if (HMDUnmounted != null)
                {
                    HMDUnmounted();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_wasUserPresent && isUserPresent)
        {
            try
            {
                if (HMDMounted != null)
                {
                    HMDMounted();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _wasUserPresent = isUserPresent;

        // Dispatch VR Focus events.

        hasVrFocus = OVRPlugin.hasVrFocus;

        if (_hadVrFocus && !hasVrFocus)
        {
            try
            {
                if (VrFocusLost != null)
                {
                    VrFocusLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!_hadVrFocus && hasVrFocus)
        {
            try
            {
                if (VrFocusAcquired != null)
                {
                    VrFocusAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        _hadVrFocus = hasVrFocus;


        // Changing effective rendering resolution dynamically according performance
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5 && !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
        if (enableAdaptiveResolution)
        {
            if (VR.VRSettings.renderScale < maxRenderScale)
            {
                // Allocate renderScale to max to avoid re-allocation
                VR.VRSettings.renderScale = maxRenderScale;
            }
            else
            {
                // Adjusting maxRenderScale in case app started with a larger renderScale value
                maxRenderScale = Mathf.Max(maxRenderScale, VR.VRSettings.renderScale);
            }
            float minViewportScale         = minRenderScale / VR.VRSettings.renderScale;
            float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / VR.VRSettings.renderScale;
            recommendedViewportScale          = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
            VR.VRSettings.renderViewportScale = recommendedViewportScale;
        }
#endif

        // Dispatch Audio Device events.

        string audioOutId = OVRPlugin.audioOutId;
        if (!prevAudioOutIdIsCached)
        {
            prevAudioOutId         = audioOutId;
            prevAudioOutIdIsCached = true;
        }
        else if (audioOutId != prevAudioOutId)
        {
            try
            {
                if (AudioOutChanged != null)
                {
                    AudioOutChanged();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }

            prevAudioOutId = audioOutId;
        }

        string audioInId = OVRPlugin.audioInId;
        if (!prevAudioInIdIsCached)
        {
            prevAudioInId         = audioInId;
            prevAudioInIdIsCached = true;
        }
        else if (audioInId != prevAudioInId)
        {
            try
            {
                if (AudioInChanged != null)
                {
                    AudioInChanged();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }

            prevAudioInId = audioInId;
        }

        // Dispatch tracking events.

        if (wasPositionTracked && !tracker.isPositionTracked)
        {
            try
            {
                if (TrackingLost != null)
                {
                    TrackingLost();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        if (!wasPositionTracked && tracker.isPositionTracked)
        {
            try
            {
                if (TrackingAcquired != null)
                {
                    TrackingAcquired();
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught Exception: " + e);
            }
        }

        wasPositionTracked = tracker.isPositionTracked;

        display.Update();
        OVRInput.Update();
    }
 public override void OnActivated()
 {
     m_prevTrackingSpace = OVRPlugin.GetTrackingOriginType();
     UpdateTrackingSpaceType();
 }
    void Initialize()
    {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
        if (inited)
        {
            return;
        }

#if OVR_ANDROID_MRC
        if (!OVRPlugin.Media.GetInitialized())
        {
            return;
        }
#else
        if (!OVRPlugin.IsMixedRealityInitialized())
        {
            return;
        }
#endif

        OVRPlugin.ResetDefaultExternalCamera();
        Debug.LogFormat("GetExternalCameraCount before adding manual external camera {0}", OVRPlugin.GetExternalCameraCount());
        UpdateDefaultExternalCamera();
        Debug.LogFormat("GetExternalCameraCount after adding manual external camera {0}", OVRPlugin.GetExternalCameraCount());

        // obtain default FOV
        {
            OVRPlugin.CameraIntrinsics cameraIntrinsics;
            OVRPlugin.CameraExtrinsics cameraExtrinsics;
            OVRPlugin.Posef            calibrationRawPose;
            OVRPlugin.GetMixedRealityCameraInfo(0, out cameraExtrinsics, out cameraIntrinsics, out calibrationRawPose);
            defaultFov = cameraIntrinsics.FOVPort;
        }

        inited = true;
#endif
    }
 public override void OnDeactivated()
 {
     OVRPlugin.SetTrackingOriginType(m_prevTrackingSpace);
 }
Exemple #22
0
 public bool GetConfigured()
 {
     return(OVRPlugin.GetBoundaryConfigured());
 }
    void Update()
    {
        OVRInput.Controller activeController = OVRInput.GetActiveController();

        data.Length = 0;
        byte recenterCount = OVRInput.GetControllerRecenterCount();

        data.AppendFormat("RecenterCount: {0}\n", recenterCount);

        byte battery = OVRInput.GetControllerBatteryPercentRemaining();

        data.AppendFormat("Battery: {0}\n", battery);

        float framerate = OVRPlugin.GetAppFramerate();

        data.AppendFormat("Framerate: {0:F2}\n", framerate);

        string activeControllerName = activeController.ToString();

        data.AppendFormat("Active: {0}\n", activeControllerName);

        string connectedControllerNames = OVRInput.GetConnectedControllers().ToString();

        data.AppendFormat("Connected: {0}\n", connectedControllerNames);

        data.AppendFormat("PrevConnected: {0}\n", prevConnected);

        controllers.Update();
        controllers.AppendToStringBuilder(ref data);

        prevConnected = connectedControllerNames;

        Quaternion rot = OVRInput.GetLocalControllerRotation(activeController);

        data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", rot.x, rot.y, rot.z, rot.w);

        Vector3 angVel = OVRInput.GetLocalControllerAngularVelocity(activeController);

        data.AppendFormat("AngVel: ({0:F2}, {1:F2}, {2:F2})\n", angVel.x, angVel.y, angVel.z);

        Vector3 angAcc = OVRInput.GetLocalControllerAngularAcceleration(activeController);

        data.AppendFormat("AngAcc: ({0:F2}, {1:F2}, {2:F2})\n", angAcc.x, angAcc.y, angAcc.z);

        Vector3 pos = OVRInput.GetLocalControllerPosition(activeController);

        data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", pos.x, pos.y, pos.z);

        Vector3 vel = OVRInput.GetLocalControllerVelocity(activeController);

        data.AppendFormat("Vel: ({0:F2}, {1:F2}, {2:F2})\n", vel.x, vel.y, vel.z);

        Vector3 acc = OVRInput.GetLocalControllerAcceleration(activeController);

        data.AppendFormat("Acc: ({0:F2}, {1:F2}, {2:F2})\n", acc.x, acc.y, acc.z);

        Vector2 primaryTouchpad = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad);

        data.AppendFormat("PrimaryTouchpad: ({0:F2}, {1:F2})\n", primaryTouchpad.x, primaryTouchpad.y);

        Vector2 secondaryTouchpad = OVRInput.Get(OVRInput.Axis2D.SecondaryTouchpad);

        data.AppendFormat("SecondaryTouchpad: ({0:F2}, {1:F2})\n", secondaryTouchpad.x, secondaryTouchpad.y);

        float indexTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);

        data.AppendFormat("PrimaryIndexTriggerAxis1D: ({0:F2})\n", indexTrigger);

        float handTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger);

        data.AppendFormat("PrimaryHandTriggerAxis1D: ({0:F2})\n", handTrigger);

        for (int i = 0; i < monitors.Count; i++)
        {
            monitors[i].Update();
            monitors[i].AppendToStringBuilder(ref data);
        }

        if (uiText != null)
        {
            uiText.text = data.ToString();
        }
    }
Exemple #24
0
 public bool GetVisible()
 {
     return(OVRPlugin.GetBoundaryVisible());
 }
Exemple #25
0
    void Start()
    {
        if (OvrAvatarSDKManager.Instance == null)
        {
            return;
        }
#if !UNITY_ANDROID
        if (CombineMeshes)
        {
            CombineMeshes = false;
            AvatarLogger.Log("Combined Meshes currently only supported on mobile");
        }
#endif
#if !UNITY_5_5_OR_NEWER
        if (CombineMeshes)
        {
            CombineMeshes = false;
            AvatarLogger.LogWarning("Combined Meshes requires Unity 5.5.0+");
        }
#endif
        materialManager = gameObject.AddComponent <OvrAvatarMaterialManager>();

        try
        {
            oculusUserIDInternal = UInt64.Parse(oculusUserID);
        }
        catch (Exception)
        {
            oculusUserIDInternal = 0;
            AvatarLogger.LogWarning("Invalid Oculus User ID Format");
        }

        // If no oculus ID is supplied then turn off combine meshes to prevent the texture arrays
        // being populated by invalid textures.
        if (oculusUserIDInternal == 0)
        {
            AvatarLogger.LogWarning("Oculus User ID set to 0. Provide actual user ID: " + gameObject.name);
            CombineMeshes = false;
        }

        AvatarLogger.Log("Starting OvrAvatar " + gameObject.name);
        AvatarLogger.Log(AvatarLogger.Tab + "LOD: " + LevelOfDetail.ToString());
        AvatarLogger.Log(AvatarLogger.Tab + "Combine Meshes: " + CombineMeshes);
        AvatarLogger.Log(AvatarLogger.Tab + "Force Mobile Textures: " + USE_MOBILE_TEXTURE_FORMAT);
        AvatarLogger.Log(AvatarLogger.Tab + "Oculus User ID: " + oculusUserIDInternal);

        Capabilities = 0;

        bool is3Dof      = false;
        var  headsetType = OVRPlugin.GetSystemHeadsetType();
        switch (headsetType)
        {
        case OVRPlugin.SystemHeadset.GearVR_R320:
        case OVRPlugin.SystemHeadset.GearVR_R321:
        case OVRPlugin.SystemHeadset.GearVR_R322:
        case OVRPlugin.SystemHeadset.GearVR_R323:
        case OVRPlugin.SystemHeadset.GearVR_R324:
        case OVRPlugin.SystemHeadset.GearVR_R325:
        case OVRPlugin.SystemHeadset.Oculus_Go:
            is3Dof = true;
            break;

        case OVRPlugin.SystemHeadset.Oculus_Quest:
        case OVRPlugin.SystemHeadset.Rift_S:
        case OVRPlugin.SystemHeadset.Rift_DK1:
        case OVRPlugin.SystemHeadset.Rift_DK2:
        case OVRPlugin.SystemHeadset.Rift_CV1:
        default:
            break;
        }

        // The SDK 3 DOF Arm Model requires the body skeleton to pose itself. It will crash without it
        // The likely use case here is trying to have an invisible body.
        // T45010595
        if (is3Dof && !EnableBody)
        {
            AvatarLogger.Log("Forcing the Body component for 3Dof hand tracking, and setting the visibility to 1st person");
            EnableBody      = true;
            ShowFirstPerson = true;
            ShowThirdPerson = false;
        }

        if (EnableBody)
        {
            Capabilities |= ovrAvatarCapabilities.Body;
        }
        if (EnableHands)
        {
            Capabilities |= ovrAvatarCapabilities.Hands;
        }
        if (EnableBase && EnableBody)
        {
            Capabilities |= ovrAvatarCapabilities.Base;
        }
        if (EnableExpressive)
        {
            Capabilities |= ovrAvatarCapabilities.Expressive;
        }

        // Enable body tilt on 6dof devices
        if (OVRPlugin.positionSupported)
        {
            Capabilities |= ovrAvatarCapabilities.BodyTilt;
        }

        ShowLeftController(StartWithControllers);
        ShowRightController(StartWithControllers);

        OvrAvatarSDKManager.AvatarSpecRequestParams avatarSpecRequest = new OvrAvatarSDKManager.AvatarSpecRequestParams(
            oculusUserIDInternal,
            this.AvatarSpecificationCallback,
            CombineMeshes,
            LevelOfDetail,
            USE_MOBILE_TEXTURE_FORMAT,
            LookAndFeelVersion,
            FallbackLookAndFeelVersion,
            EnableExpressive);

        OvrAvatarSDKManager.Instance.RequestAvatarSpecification(avatarSpecRequest);
        OvrAvatarSDKManager.Instance.AddLoadingAvatar(GetInstanceID());

        waitingForCombinedMesh = CombineMeshes;
        if (Driver != null)
        {
            Driver.Mode = UseSDKPackets ? OvrAvatarDriver.PacketMode.SDK : OvrAvatarDriver.PacketMode.Unity;
        }
    }
        public void Process()
        {
            var hapticsState = OVRPlugin.GetControllerHapticsState(m_controller);

            float elapsedTime = Time.realtimeSinceStartup - m_prevSamplesQueuedTime;

            if (m_prevSamplesQueued > 0)
            {
                int expectedSamples = m_prevSamplesQueued - (int)(elapsedTime * OVRHaptics.Config.SampleRateHz + 0.5f);
                if (expectedSamples < 0)
                {
                    expectedSamples = 0;
                }

                if ((hapticsState.SamplesQueued - expectedSamples) == 0)
                {
                    m_numPredictionHits++;
                }
                else
                {
                    m_numPredictionMisses++;
                }

                //Debug.Log(hapticsState.SamplesAvailable + "a " + hapticsState.SamplesQueued + "q " + expectedSamples + "e "
                //+ "Prediction Accuracy: " + m_numPredictionHits / (float)(m_numPredictionMisses + m_numPredictionHits));

                if ((expectedSamples > 0) && (hapticsState.SamplesQueued == 0))
                {
                    m_numUnderruns++;
                    //Debug.LogError("Samples Underrun (" + m_controller + " #" + m_numUnderruns + ") -"
                    //        + " Expected: " + expectedSamples
                    //        + " Actual: " + hapticsState.SamplesQueued);
                }

                m_prevSamplesQueued     = hapticsState.SamplesQueued;
                m_prevSamplesQueuedTime = Time.realtimeSinceStartup;
            }

            int desiredSamplesCount = OVRHaptics.Config.OptimalBufferSamplesCount;

            if (m_lowLatencyMode)
            {
                float sampleRateMs           = 1000.0f / (float)OVRHaptics.Config.SampleRateHz;
                float elapsedMs              = elapsedTime * 1000.0f;
                int   samplesNeededPerFrame  = (int)Mathf.Ceil(elapsedMs / sampleRateMs);
                int   lowLatencySamplesCount = OVRHaptics.Config.MinimumSafeSamplesQueued + samplesNeededPerFrame;

                if (lowLatencySamplesCount < desiredSamplesCount)
                {
                    desiredSamplesCount = lowLatencySamplesCount;
                }
            }

            if (hapticsState.SamplesQueued > desiredSamplesCount)
            {
                return;
            }

            if (desiredSamplesCount > OVRHaptics.Config.MaximumBufferSamplesCount)
            {
                desiredSamplesCount = OVRHaptics.Config.MaximumBufferSamplesCount;
            }
            if (desiredSamplesCount > hapticsState.SamplesAvailable)
            {
                desiredSamplesCount = hapticsState.SamplesAvailable;
            }

            int acquiredSamplesCount = 0;
            int clipIndex            = 0;

            while (acquiredSamplesCount < desiredSamplesCount && clipIndex < m_pendingClips.Count)
            {
                int numSamplesToCopy       = desiredSamplesCount - acquiredSamplesCount;
                int remainingSamplesInClip = m_pendingClips[clipIndex].Clip.Count - m_pendingClips[clipIndex].ReadCount;
                if (numSamplesToCopy > remainingSamplesInClip)
                {
                    numSamplesToCopy = remainingSamplesInClip;
                }

                if (numSamplesToCopy > 0)
                {
                    int numBytes  = numSamplesToCopy * OVRHaptics.Config.SampleSizeInBytes;
                    int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes;
                    int srcOffset = m_pendingClips[clipIndex].ReadCount * OVRHaptics.Config.SampleSizeInBytes;
                    Marshal.Copy(m_pendingClips[clipIndex].Clip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes);

                    m_pendingClips[clipIndex].ReadCount += numSamplesToCopy;
                    acquiredSamplesCount += numSamplesToCopy;
                }

                clipIndex++;
            }

            for (int i = m_pendingClips.Count - 1; i >= 0 && m_pendingClips.Count > 0; i--)
            {
                if (m_pendingClips[i].ReadCount >= m_pendingClips[i].Clip.Count)
                {
                    m_pendingClips.RemoveAt(i);
                }
            }

            int desiredPadding = desiredSamplesCount - (hapticsState.SamplesQueued + acquiredSamplesCount);

            if (desiredPadding < (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount))
            {
                desiredPadding = (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount);
            }
            if (desiredPadding > hapticsState.SamplesAvailable)
            {
                desiredPadding = hapticsState.SamplesAvailable;
            }

            if (desiredPadding > 0)
            {
                int numBytes  = desiredPadding * OVRHaptics.Config.SampleSizeInBytes;
                int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes;
                int srcOffset = 0;
                Marshal.Copy(m_paddingClip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes);

                acquiredSamplesCount += desiredPadding;
            }

            if (acquiredSamplesCount > 0)
            {
                OVRPlugin.HapticsBuffer hapticsBuffer;
                hapticsBuffer.Samples      = m_nativeBuffer.GetPointer();
                hapticsBuffer.SamplesCount = acquiredSamplesCount;

                OVRPlugin.SetControllerHaptics(m_controller, hapticsBuffer);

                hapticsState            = OVRPlugin.GetControllerHapticsState(m_controller);
                m_prevSamplesQueued     = hapticsState.SamplesQueued;
                m_prevSamplesQueuedTime = Time.realtimeSinceStartup;
            }
        }
    private bool CreateLayerTextures(bool useMipmaps, OVRPlugin.Sizei size, bool isHdr)
    {
        bool needsCopy = false;

        if (stageCount <= 0)
        {
            return(false);
        }

        // For newer SDKs, blit directly to the surface that will be used in compositing.

        if (layerTextures == null)
        {
            frameIndex    = 0;
            layerTextures = new LayerTexture[texturesPerStage];
        }

        for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
        {
            if (layerTextures[eyeId].swapChain == null)
            {
                layerTextures[eyeId].swapChain = new Texture[stageCount];
            }

            if (layerTextures[eyeId].swapChainPtr == null)
            {
                layerTextures[eyeId].swapChainPtr = new IntPtr[stageCount];
            }

            for (int stage = 0; stage < stageCount; ++stage)
            {
                Texture sc    = layerTextures[eyeId].swapChain[stage];
                IntPtr  scPtr = layerTextures[eyeId].swapChainPtr[stage];

                if (sc != null && scPtr != IntPtr.Zero)
                {
                    continue;
                }

                if (scPtr == IntPtr.Zero)
                {
                    scPtr = OVRPlugin.GetLayerTexture(layerId, stage, (OVRPlugin.Eye)eyeId);
                }

                if (scPtr == IntPtr.Zero)
                {
                    continue;
                }

                var txFormat = (isHdr) ? TextureFormat.RGBAHalf : TextureFormat.RGBA32;

                if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                {
                    sc = Texture2D.CreateExternalTexture(size.w, size.h, txFormat, useMipmaps, true, scPtr);
                }
#if UNITY_2017_1_OR_NEWER
                else
                {
                    sc = Cubemap.CreateExternalTexture(size.w, txFormat, useMipmaps, scPtr);
                }
#endif

                layerTextures[eyeId].swapChain[stage]    = sc;
                layerTextures[eyeId].swapChainPtr[stage] = scPtr;

                needsCopy = true;
            }
        }

        return(needsCopy);
    }
    public override void Update(Camera mainCamera)
    {
        if (!hasCameraDeviceOpened)
        {
            return;
        }

        frameRealtime = Time.realtimeSinceStartup;

        ++historyRecordCursorIndex;
        if (historyRecordCursorIndex >= historyRecordCount)
        {
            historyRecordCursorIndex = 0;
        }

        if (!OVRPlugin.SetHandNodePoseStateLatency(OVRManager.instance.handPoseStateLatency))
        {
            Debug.LogWarning("HandPoseStateLatency is invalid. Expect a value between 0.0 to 0.5, get " + OVRManager.instance.handPoseStateLatency);
        }

        RefreshRenderTextures(mainCamera);

        bgCamera.clearFlags      = mainCamera.clearFlags;
        bgCamera.backgroundColor = mainCamera.backgroundColor;
        bgCamera.cullingMask     = mainCamera.cullingMask & (~OVRManager.instance.extraHiddenLayers);

        fgCamera.cullingMask = mainCamera.cullingMask & (~OVRManager.instance.extraHiddenLayers);

        if (OVRMixedReality.useFakeExternalCamera || OVRPlugin.GetExternalCameraCount() == 0)
        {
            OVRPose worldSpacePose    = new OVRPose();
            OVRPose trackingSpacePose = new OVRPose();
            trackingSpacePose.position    = OVRMixedReality.fakeCameraPositon;
            trackingSpacePose.orientation = OVRMixedReality.fakeCameraRotation;
            worldSpacePose = OVRExtensions.ToWorldSpacePose(trackingSpacePose);

            RefreshCameraPoses(OVRMixedReality.fakeCameraFov, OVRMixedReality.fakeCameraAspect, worldSpacePose);
        }
        else
        {
            OVRPlugin.CameraExtrinsics extrinsics;
            OVRPlugin.CameraIntrinsics intrinsics;

            // So far, only support 1 camera for MR and always use camera index 0
            if (OVRPlugin.GetMixedRealityCameraInfo(0, out extrinsics, out intrinsics))
            {
                OVRPose worldSpacePose = ComputeCameraWorldSpacePose(extrinsics);

                float fovY   = Mathf.Atan(intrinsics.FOVPort.UpTan) * Mathf.Rad2Deg * 2;
                float aspect = intrinsics.FOVPort.LeftTan / intrinsics.FOVPort.UpTan;

                RefreshCameraPoses(fovY, aspect, worldSpacePose);
            }
            else
            {
                Debug.LogWarning("Failed to get external camera information");
            }
        }

        compositionCamera.GetComponent <OVRCameraFrameCompositionManager>().boundaryMeshMaskTexture = historyRecordArray[historyRecordCursorIndex].boundaryMeshMaskTexture;
        HistoryRecord record = GetHistoryRecordForComposition();

        UpdateCameraFramePlaneObject(mainCamera, compositionCamera, record.boundaryMeshMaskTexture);
        OVRSandwichCompositionManager compositionManager = compositionCamera.gameObject.GetComponent <OVRSandwichCompositionManager>();

        compositionManager.fgTexture = record.fgRenderTexture;
        compositionManager.bgTexture = record.bgRenderTexture;

        cameraProxyPlane.transform.position = fgCamera.transform.position + fgCamera.transform.forward * cameraFramePlaneDistance;
        cameraProxyPlane.transform.LookAt(cameraProxyPlane.transform.position + fgCamera.transform.forward);
    }
Exemple #29
0
    private static void AttemptPluginUpdate(bool triggeredByAutoUpdate)
    {
        OVRPlugin.SendEvent("attempt_plugin_update_auto", triggeredByAutoUpdate.ToString());

        PluginPackage        bundledPluginPkg   = GetBundledPluginPackage();
        List <PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();

        PluginPackage enabledUtilsPluginPkg = null;
        PluginPackage newestUtilsPluginPkg  = null;

        foreach (PluginPackage pluginPkg in allUtilsPluginPkgs)
        {
            if ((newestUtilsPluginPkg == null) || (pluginPkg.Version > newestUtilsPluginPkg.Version))
            {
                newestUtilsPluginPkg = pluginPkg;
            }

            if (pluginPkg.IsEnabled())
            {
                if ((enabledUtilsPluginPkg == null) || (pluginPkg.Version > enabledUtilsPluginPkg.Version))
                {
                    enabledUtilsPluginPkg = pluginPkg;
                }
            }
        }

        bool          reenableCurrentPluginPkg = false;
        PluginPackage targetPluginPkg          = null;

        if ((newestUtilsPluginPkg != null) && (newestUtilsPluginPkg.Version > bundledPluginPkg.Version))
        {
            if ((enabledUtilsPluginPkg == null) || (enabledUtilsPluginPkg.Version != newestUtilsPluginPkg.Version))
            {
                targetPluginPkg = newestUtilsPluginPkg;
            }
        }
        else if ((enabledUtilsPluginPkg != null) && (enabledUtilsPluginPkg.Version < bundledPluginPkg.Version))
        {
            targetPluginPkg = bundledPluginPkg;
        }

        PluginPackage currentPluginPkg = (enabledUtilsPluginPkg != null) ? enabledUtilsPluginPkg : bundledPluginPkg;

        if ((targetPluginPkg == null) && !UnitySupportsEnabledAndroidPlugin())
        {
            // Force reenabling the current package to configure the correct android plugin for this unity version.
            reenableCurrentPluginPkg = true;
            targetPluginPkg          = currentPluginPkg;
        }

        if (targetPluginPkg == null)
        {
            if (!triggeredByAutoUpdate && !unityRunningInBatchmode)
            {
                EditorUtility.DisplayDialog("Update Oculus Utilities Plugin",
                                            "OVRPlugin is already up to date.\n\nCurrent version: "
                                            + GetVersionDescription(currentPluginPkg.Version),
                                            "Ok",
                                            "");
            }

            return;             // No update necessary.
        }

        System.Version targetVersion = targetPluginPkg.Version;

        bool userAcceptsUpdate = false;

        if (unityRunningInBatchmode)
        {
            userAcceptsUpdate = true;
        }
        else
        {
            string dialogBody = "Oculus Utilities has detected that a newer OVRPlugin is available."
                                + " Using the newest version is recommended. Do you want to enable it?\n\n"
                                + "Current version: "
                                + GetVersionDescription(currentPluginPkg.Version)
                                + "\nAvailable version: "
                                + targetVersion;

            if (reenableCurrentPluginPkg)
            {
                dialogBody = "Oculus Utilities has detected a configuration change that requires re-enabling the current OVRPlugin."
                             + " Do you want to proceed?\n\nCurrent version: "
                             + GetVersionDescription(currentPluginPkg.Version);
            }

            int dialogResult = EditorUtility.DisplayDialogComplex("Update Oculus Utilities Plugin", dialogBody, "Yes", "No, Don't Ask Again", "No");

            switch (dialogResult)
            {
            case 0:                     // "Yes"
                userAcceptsUpdate = true;
                break;

            case 1:                     // "No, Don't Ask Again"
                autoUpdateEnabled = false;

                EditorUtility.DisplayDialog("Oculus Utilities OVRPlugin",
                                            "To manually update in the future, use the following menu option:\n\n"
                                            + "[Oculus -> Tools -> Update OVR Utilities Plugin]",
                                            "Ok",
                                            "");
                return;

            case 2:                     // "No"
                return;
            }
        }

        if (userAcceptsUpdate)
        {
            DisableAllUtilitiesPluginPackages();

            if (!targetPluginPkg.IsBundledPluginPackage())
            {
                EnablePluginPackage(targetPluginPkg);
            }

            if (unityRunningInBatchmode ||
                EditorUtility.DisplayDialog("Restart Unity",
                                            "OVRPlugin has been updated to "
                                            + GetVersionDescription(targetPluginPkg.Version)
                                            + ".\n\nPlease restart the Unity Editor to complete the update process."
                                            ,
                                            "Restart",
                                            "Not Now"))
            {
                RestartUnityEditor();
            }
        }
    }
Exemple #30
0
	private Transform ConfigureHandAnchor(Transform root, OVRPlugin.Node hand)
	{
		string handName = (hand == OVRPlugin.Node.LeftHand) ? "Left" : "Right";
		string name = handName + handAnchorName;
		Transform anchor = transform.Find(root.name + "/" + name);

		if (anchor == null)
		{
			anchor = transform.Find(name);
		}

		if (anchor == null)
		{
			anchor = new GameObject(name).transform;
		}

		anchor.name = name;
		anchor.parent = root;
		anchor.localScale = Vector3.one;
		anchor.localPosition = Vector3.zero;
		anchor.localRotation = Quaternion.identity;

		return anchor;
	}
    void Awake()
    {
        Debug.Log("Overlay Awake");

        if (premultiplyMaterial == null)
        {
            premultiplyMaterial = new Material(Shader.Find("Oculus/Alpha Premultiply"));
        }

        rend = GetComponent <Renderer>();

        if (textures.Length == 0)
        {
            textures = new Texture[] { null }
        }
        ;

        // Backward compatibility
        if (rend != null && textures[0] == null)
        {
            textures[0] = rend.material.mainTexture;
        }

        if (textures[0] != null)
        {
            cachedTextures[0] = textures[0];
            texNativePtrs[0]  = textures[0].GetNativeTexturePtr();
        }

#if UNITY_ANDROID && !UNITY_EDITOR
        if (textures.Length == 2 && textures[1] != null)
        {
            layout = (isMultiviewEnabled) ? OVRPlugin.LayerLayout.Array : OVRPlugin.LayerLayout.Stereo;
        }
        texturesPerStage = (layout == OVRPlugin.LayerLayout.Stereo) ? 2 : 1;
#endif
    }

    void OnEnable()
    {
        if (!OVRManager.isHmdPresent)
        {
            enabled = false;
            return;
        }

        OnDisable();

        for (int i = 0; i < maxInstances; ++i)
        {
            if (instances[i] == null || instances[i] == this)
            {
                layerIndex   = i;
                instances[i] = this;
                break;
            }
        }

        layerIdHandle = GCHandle.Alloc(layerId, GCHandleType.Pinned);
        layerIdPtr    = layerIdHandle.AddrOfPinnedObject();
    }

    void OnDisable()
    {
        if (layerIndex != -1)
        {
            // Turn off the overlay if it was on.
            OVRPlugin.EnqueueSubmitLayer(true, false, IntPtr.Zero, IntPtr.Zero, -1, 0, OVRPose.identity.ToPosef(), Vector3.one.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)_prevOverlayShape);
            instances[layerIndex] = null;
        }

        if (layerIdPtr != IntPtr.Zero)
        {
            OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
            layerIdPtr = IntPtr.Zero;
            layerIdHandle.Free();
        }

        layerIndex = -1;
    }

    int prevFrameIndex = -1;

    void OnRenderObject()
    {
        // The overlay must be specified every eye frame, because it is positioned relative to the
        // current head location.  If frames are dropped, it will be time warped appropriately,
        // just like the eye buffers.
        if (!Camera.current.CompareTag("MainCamera") || Camera.current.cameraType != CameraType.Game || layerIndex == -1 || currentOverlayType == OverlayType.None || textures.Length < texturesPerStage)
        {
            return;
        }


        // Don't submit the same frame twice.
        if (Time.frameCount <= prevFrameIndex)
        {
            return;
        }
        prevFrameIndex = Time.frameCount;

#if !UNITY_ANDROID || UNITY_EDITOR
        if (currentOverlayShape == OverlayShape.OffcenterCubemap)
        {
            Debug.LogWarning("Overlay shape " + currentOverlayShape + " is not supported on current platform");
        }
#endif

        for (int i = 0; i < texturesPerStage; ++i)
        {
            if (textures[i] != cachedTextures[i])
            {
                cachedTextures[i] = textures[i];
                if (cachedTextures[i] != null)
                {
                    texNativePtrs[i] = cachedTextures[i].GetNativeTexturePtr();
                }
            }

            if (currentOverlayShape == OverlayShape.Cubemap)
            {
                if (textures[i] != null && textures[i].GetType() != typeof(Cubemap))
                {
                    Debug.LogError("Need Cubemap texture for cube map overlay");
                    return;
                }
            }
        }

        if (cachedTextures[0] == null || texNativePtrs[0] == IntPtr.Zero)
        {
            return;
        }

        bool overlay    = (currentOverlayType == OverlayType.Overlay);
        bool headLocked = false;
        for (var t = transform; t != null && !headLocked; t = t.parent)
        {
            headLocked |= (t == Camera.current.transform);
        }

        OVRPose pose  = (headLocked) ? transform.ToHeadSpacePose() : transform.ToTrackingSpacePose();
        Vector3 scale = transform.lossyScale;
        for (int i = 0; i < 3; ++i)
        {
            scale[i] /= Camera.current.transform.lossyScale[i];
        }
#if !UNITY_ANDROID
        if (currentOverlayShape == OverlayShape.Cubemap)
        {
            pose.position = Camera.current.transform.position;
        }
#endif
        // Pack the offsetCenter directly into pose.position for offcenterCubemap
        if (currentOverlayShape == OverlayShape.OffcenterCubemap)
        {
            pose.position = transform.position;
            if (pose.position.magnitude > 1.0f)
            {
                Debug.LogWarning("your cube map center offset's magnitude is greater than 1, which will cause some cube map pixel always invisible .");
            }
        }
        // Cylinder overlay sanity checking
        if (currentOverlayShape == OverlayShape.Cylinder)
        {
            float arcAngle = scale.x / scale.z / (float)Math.PI * 180.0f;
            if (arcAngle > 180.0f)
            {
                Debug.LogError("Cylinder overlay's arc angle has to be below 180 degree, current arc angle is " + arcAngle + " degree.");
                return;
            }
        }

        OVRPlugin.Sizei size = new OVRPlugin.Sizei()
        {
            w = textures[0].width, h = textures[0].height
        };
        int           flags                 = (int)OVRPlugin.LayerFlags.TextureOriginAtBottomLeft;
        int           mipLevels             = 1;
        int           sampleCount           = 1;
        TextureFormat txFormat              = TextureFormat.BGRA32;
        OVRPlugin.EyeTextureFormat etFormat = OVRPlugin.EyeTextureFormat.B8G8R8A8_sRGB;
        RenderTextureFormat        rtFormat = RenderTextureFormat.BGRA32;

        var tex2D = textures[0] as Texture2D;
        if (tex2D != null)
        {
            if (tex2D.format == TextureFormat.RGBAHalf || tex2D.format == TextureFormat.RGBAFloat)
            {
                txFormat = TextureFormat.RGBAHalf;
                etFormat = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
                rtFormat = RenderTextureFormat.ARGBHalf;
            }
        }

        var rt = textures[0] as RenderTexture;
        if (rt != null)
        {
            sampleCount = rt.antiAliasing;

            if (rt.format == RenderTextureFormat.ARGBHalf)
            {
                txFormat = TextureFormat.RGBAHalf;
                etFormat = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
                rtFormat = RenderTextureFormat.ARGBHalf;
            }
        }

        bool needsSetup = (
            !layerDesc.TextureSize.Equals(size) ||
            layerDesc.SampleCount != sampleCount ||
            layerDesc.LayerFlags != flags ||
            layerDesc.Shape != (OVRPlugin.OverlayShape)currentOverlayShape ||
            layerDesc.Layout != layout ||
            layerDesc.Format != etFormat);

        OVRPlugin.LayerDesc desc = new OVRPlugin.LayerDesc();

        if (layerIdPtr != IntPtr.Zero && needsSetup)
        {
            if ((int)layerIdHandle.Target != 0)
            {
                OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
            }

            desc = OVRPlugin.CalculateLayerDesc((OVRPlugin.OverlayShape)currentOverlayShape, layout, size, mipLevels, sampleCount, etFormat, flags);
            OVRPlugin.EnqueueSetupLayer(desc, layerIdPtr);
            layerId = (int)layerIdHandle.Target;

            if (layerId > 0)
            {
                layerDesc = desc;
            }
        }

        if (layerId > 0)
        {
            // For newer SDKs, blit directly to the surface that will be used in compositing.

            int stageCount = OVRPlugin.GetLayerTextureStageCount(layerId);

            if (externalTextures == null)
            {
                frameIndex       = 0;
                externalTextures = new Texture[texturesPerStage][];
            }

            for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
            {
                if (externalTextures[eyeId] == null)
                {
                    externalTextures[eyeId] = new Texture[stageCount];
                }

                int stage = frameIndex % stageCount;

                IntPtr externalTex = OVRPlugin.GetLayerTexture(layerId, stage, (OVRPlugin.Eye)eyeId);

                if (externalTex == IntPtr.Zero)
                {
                    continue;
                }

                bool needsCopy = isDynamic;

                Texture et = externalTextures[eyeId][stage];
                if (et == null)
                {
                    bool isSrgb = (etFormat == OVRPlugin.EyeTextureFormat.B8G8R8A8_sRGB || etFormat == OVRPlugin.EyeTextureFormat.R8G8B8A8_sRGB);

                    if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                    {
                        et = Texture2D.CreateExternalTexture(size.w, size.h, txFormat, mipLevels > 1, isSrgb, externalTex);
                    }
#if UNITY_2017_1_OR_NEWER
                    else
                    {
                        et = Cubemap.CreateExternalTexture(size.w, txFormat, mipLevels > 1, externalTex);
                    }
#endif

                    externalTextures[eyeId][stage] = et;
                    needsCopy = true;
                }

                if (needsCopy)
                {
                    // The compositor uses premultiplied alpha, so multiply it here.
                    if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                    {
                        var tempRT = RenderTexture.GetTemporary(size.w, size.h, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount);
#if UNITY_ANDROID && !UNITY_EDITOR
                        Graphics.Blit(textures[eyeId], tempRT);                         //Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
#else
                        Graphics.Blit(textures[eyeId], tempRT, premultiplyMaterial);
#endif
                        Graphics.CopyTexture(tempRT, 0, 0, et, 0, 0);
                        RenderTexture.ReleaseTemporary(tempRT);
                    }
#if UNITY_2017_1_OR_NEWER
                    else
                    {
                        var tempRTSrc = RenderTexture.GetTemporary(size.w, size.h, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount);
                        var tempRTDst = RenderTexture.GetTemporary(size.w, size.h, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount);

                        for (int face = 0; face < 6; ++face)
                        {
                            //HACK: It would be much more efficient to blit directly from textures[eyeId] to et, but Unity's API doesn't support that.
                            //Suggest using a native plugin to render directly to a cubemap layer for 360 video, etc.
                            Graphics.CopyTexture(textures[eyeId], face, 0, tempRTSrc, 0, 0);
                            Graphics.Blit(tempRTSrc, tempRTDst, premultiplyMaterial);
                            Graphics.CopyTexture(tempRTDst, 0, 0, et, face, 0);
                        }
                        RenderTexture.ReleaseTemporary(tempRTSrc);
                        RenderTexture.ReleaseTemporary(tempRTDst);
                    }
#endif
                }
            }

            bool isOverlayVisible = OVRPlugin.EnqueueSubmitLayer(overlay, headLocked, texNativePtrs[0], texNativePtrs[1], layerId, frameIndex, pose.flipZ().ToPosef(), scale.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)currentOverlayShape);
            if (isDynamic)
            {
                ++frameIndex;
            }
            _prevOverlayShape = currentOverlayShape;
            if (rend)
            {
                rend.enabled = !isOverlayVisible;
            }
        }
    }
}