BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VR / Scripts / OVRManager.cs

OVRManager.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
OVRManager.cs 51.9 KiB Download Raw
1/************************************************************************************
2Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
3
4Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
5the Utilities SDK except in compliance with the License, which is provided at the time of installation
6or download, or which otherwise accompanies this software in either electronic or hard copy form.
7
8You may obtain a copy of the License at
9https://developer.oculus.com/licenses/utilities-1.31
10
11Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
12under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13ANY KIND, either express or implied. See the License for the specific language governing
14permissions and limitations under the License.
15************************************************************************************/
16
17#if UNITY_ANDROID && !UNITY_EDITOR
18#define OVR_ANDROID_MRC
19#endif
20
21#if !UNITY_5_6_OR_NEWER
22#error Oculus Utilities require Unity 5.6 or higher.
23#endif
24
25using System;
26using System.Collections.Generic;
27using UnityEngine;
28#if UNITY_EDITOR
29using UnityEditor;
30#endif
31
32#if USING_XR_SDK
33using UnityEngine.Experimental.XR;
34#endif
35
36#if UNITY_2017_2_OR_NEWER
37using Settings = UnityEngine.XR.XRSettings;
38using Node = UnityEngine.XR.XRNode;
39#else
40using Settings = UnityEngine.VR.VRSettings;
41using Node = UnityEngine.VR.VRNode;
42#endif
43
44/// <summary>
45/// Configuration data for Oculus virtual reality.
46/// </summary>
47public class OVRManager : MonoBehaviour
48{
49 public enum TrackingOrigin
50 {
51 EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel,
52 FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel,
53 Stage = OVRPlugin.TrackingOrigin.Stage,
54 }
55
56 public enum EyeTextureFormat
57 {
58 Default = OVRPlugin.EyeTextureFormat.Default,
59 R16G16B16A16_FP = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP,
60 R11G11B10_FP = OVRPlugin.EyeTextureFormat.R11G11B10_FP,
61 }
62
63 public enum FixedFoveatedRenderingLevel
64 {
65 Off = OVRPlugin.FixedFoveatedRenderingLevel.Off,
66 Low = OVRPlugin.FixedFoveatedRenderingLevel.Low,
67 Medium = OVRPlugin.FixedFoveatedRenderingLevel.Medium,
68 High = OVRPlugin.FixedFoveatedRenderingLevel.High,
69 HighTop = OVRPlugin.FixedFoveatedRenderingLevel.HighTop,
70 }
71
72 [Obsolete("Please use FixedFoveatedRenderingLevel instead")]
73 public enum TiledMultiResLevel
74 {
75 Off = OVRPlugin.TiledMultiResLevel.Off,
76 LMSLow = OVRPlugin.TiledMultiResLevel.LMSLow,
77 LMSMedium = OVRPlugin.TiledMultiResLevel.LMSMedium,
78 LMSHigh = OVRPlugin.TiledMultiResLevel.LMSHigh,
79 LMSHighTop = OVRPlugin.TiledMultiResLevel.LMSHighTop,
80 }
81
82 public enum XRDevice
83 {
84 Unknown = 0,
85 Oculus = 1,
86 OpenVR = 2,
87 }
88
89 /// <summary>
90 /// Gets the singleton instance.
91 /// </summary>
92 public static OVRManager instance { get; private set; }
93
94 /// <summary>
95 /// Gets a reference to the active display.
96 /// </summary>
97 public static OVRDisplay display { get; private set; }
98
99 /// <summary>
100 /// Gets a reference to the active sensor.
101 /// </summary>
102 public static OVRTracker tracker { get; private set; }
103
104 /// <summary>
105 /// Gets a reference to the active boundary system.
106 /// </summary>
107 public static OVRBoundary boundary { get; private set; }
108
109 private static OVRProfile _profile;
110 /// <summary>
111 /// Gets the current profile, which contains information about the user's settings and body dimensions.
112 /// </summary>
113 public static OVRProfile profile
114 {
115 get {
116 if (_profile == null)
117 _profile = new OVRProfile();
118
119 return _profile;
120 }
121 }
122
123 private IEnumerable<Camera> disabledCameras;
124 float prevTimeScale;
125
126 /// <summary>
127 /// Occurs when an HMD attached.
128 /// </summary>
129 public static event Action HMDAcquired;
130
131 /// <summary>
132 /// Occurs when an HMD detached.
133 /// </summary>
134 public static event Action HMDLost;
135
136 /// <summary>
137 /// Occurs when an HMD is put on the user's head.
138 /// </summary>
139 public static event Action HMDMounted;
140
141 /// <summary>
142 /// Occurs when an HMD is taken off the user's head.
143 /// </summary>
144 public static event Action HMDUnmounted;
145
146 /// <summary>
147 /// Occurs when VR Focus is acquired.
148 /// </summary>
149 public static event Action VrFocusAcquired;
150
151 /// <summary>
152 /// Occurs when VR Focus is lost.
153 /// </summary>
154 public static event Action VrFocusLost;
155
156 /// <summary>
157 /// Occurs when Input Focus is acquired.
158 /// </summary>
159 public static event Action InputFocusAcquired;
160
161 /// <summary>
162 /// Occurs when Input Focus is lost.
163 /// </summary>
164 public static event Action InputFocusLost;
165
166 /// <summary>
167 /// Occurs when the active Audio Out device has changed and a restart is needed.
168 /// </summary>
169 public static event Action AudioOutChanged;
170
171 /// <summary>
172 /// Occurs when the active Audio In device has changed and a restart is needed.
173 /// </summary>
174 public static event Action AudioInChanged;
175
176 /// <summary>
177 /// Occurs when the sensor gained tracking.
178 /// </summary>
179 public static event Action TrackingAcquired;
180
181 /// <summary>
182 /// Occurs when the sensor lost tracking.
183 /// </summary>
184 public static event Action TrackingLost;
185
186 /// <summary>
187 /// Occurs when Health & Safety Warning is dismissed.
188 /// </summary>
189 //Disable the warning about it being unused. It's deprecated.
190 #pragma warning disable 0067
191 [Obsolete]
192 public static event Action HSWDismissed;
193 #pragma warning restore
194
195 private static bool _isHmdPresentCached = false;
196 private static bool _isHmdPresent = false;
197 private static bool _wasHmdPresent = false;
198 /// <summary>
199 /// If true, a head-mounted display is connected and present.
200 /// </summary>
201 public static bool isHmdPresent
202 {
203 get {
204 if (!_isHmdPresentCached)
205 {
206 _isHmdPresentCached = true;
207 _isHmdPresent = OVRNodeStateProperties.IsHmdPresent();
208 }
209
210 return _isHmdPresent;
211 }
212
213 private set {
214 _isHmdPresentCached = true;
215 _isHmdPresent = value;
216 }
217 }
218
219 /// <summary>
220 /// Gets the audio output device identifier.
221 /// </summary>
222 /// <description>
223 /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
224 /// </description>
225 public static string audioOutId
226 {
227 get { return OVRPlugin.audioOutId; }
228 }
229
230 /// <summary>
231 /// Gets the audio input device identifier.
232 /// </summary>
233 /// <description>
234 /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
235 /// </description>
236 public static string audioInId
237 {
238 get { return OVRPlugin.audioInId; }
239 }
240
241 private static bool _hasVrFocusCached = false;
242 private static bool _hasVrFocus = false;
243 private static bool _hadVrFocus = false;
244 /// <summary>
245 /// If true, the app has VR Focus.
246 /// </summary>
247 public static bool hasVrFocus
248 {
249 get {
250 if (!_hasVrFocusCached)
251 {
252 _hasVrFocusCached = true;
253 _hasVrFocus = OVRPlugin.hasVrFocus;
254 }
255
256 return _hasVrFocus;
257 }
258
259 private set {
260 _hasVrFocusCached = true;
261 _hasVrFocus = value;
262 }
263 }
264
265 private static bool _hadInputFocus = true;
266 /// <summary>
267 /// If true, the app has Input Focus.
268 /// </summary>
269 public static bool hasInputFocus
270 {
271 get
272 {
273 return OVRPlugin.hasInputFocus;
274 }
275 }
276
277 /// <summary>
278 /// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth.
279 /// </summary>
280 public bool chromatic
281 {
282 get {
283 if (!isHmdPresent)
284 return false;
285
286 return OVRPlugin.chromatic;
287 }
288
289 set {
290 if (!isHmdPresent)
291 return;
292
293 OVRPlugin.chromatic = value;
294 }
295 }
296
297 [Header("Performance/Quality")]
298 /// <summary>
299 /// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.
300 /// </summary>
301 [Tooltip("If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.")]
302 public bool queueAhead = true;
303
304 /// <summary>
305 /// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.
306 /// </summary>
307 [Tooltip("If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.")]
308 public bool useRecommendedMSAALevel = true;
309
310 /// <summary>
311 /// If true, both eyes will see the same image, rendered from the center eye pose, saving performance.
312 /// </summary>
313 [SerializeField]
314 [Tooltip("If true, both eyes will see the same image, rendered from the center eye pose, saving performance.")]
315 private bool _monoscopic = false;
316
317 public bool monoscopic
318 {
319 get
320 {
321 if (!isHmdPresent)
322 return _monoscopic;
323
324 return OVRPlugin.monoscopic;
325 }
326
327 set
328 {
329 if (!isHmdPresent)
330 return;
331
332 OVRPlugin.monoscopic = value;
333 _monoscopic = value;
334 }
335 }
336
337 /// <summary>
338 /// If true, dynamic resolution will be enabled
339 /// </summary>
340 [Tooltip("If true, dynamic resolution will be enabled On PC")]
341 public bool enableAdaptiveResolution = false;
342
343 /// <summary>
344 /// Adaptive Resolution is based on Unity engine's renderViewportScale/eyeTextureResolutionScale feature
345 /// But renderViewportScale was broken in an array of Unity engines, this function help to filter out those broken engines
346 /// </summary>
347 public static bool IsAdaptiveResSupportedByEngine()
348 {
349#if UNITY_2017_1_OR_NEWER
350 return Application.unityVersion != "2017.1.0f1";
351#else
352 return false;
353#endif
354 }
355
356 /// <summary>
357 /// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true );
358 /// </summary>
359 [RangeAttribute(0.5f, 2.0f)]
360 [Tooltip("Min RenderScale the app can reach under adaptive resolution mode")]
361 public float minRenderScale = 0.7f;
362
363 /// <summary>
364 /// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true );
365 /// </summary>
366 [RangeAttribute(0.5f, 2.0f)]
367 [Tooltip("Max RenderScale the app can reach under adaptive resolution mode")]
368 public float maxRenderScale = 1.0f;
369
370 /// <summary>
371 /// Set the relative offset rotation of head poses
372 /// </summary>
373 [SerializeField]
374 [Tooltip("Set the relative offset rotation of head poses")]
375 private Vector3 _headPoseRelativeOffsetRotation;
376 public Vector3 headPoseRelativeOffsetRotation
377 {
378 get
379 {
380 return _headPoseRelativeOffsetRotation;
381 }
382 set
383 {
384 OVRPlugin.Quatf rotation;
385 OVRPlugin.Vector3f translation;
386 if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation))
387 {
388 Quaternion finalRotation = Quaternion.Euler(value);
389 rotation = finalRotation.ToQuatf();
390 OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation);
391 }
392 _headPoseRelativeOffsetRotation = value;
393 }
394 }
395
396 /// <summary>
397 /// Set the relative offset translation of head poses
398 /// </summary>
399 [SerializeField]
400 [Tooltip("Set the relative offset translation of head poses")]
401 private Vector3 _headPoseRelativeOffsetTranslation;
402 public Vector3 headPoseRelativeOffsetTranslation
403 {
404 get
405 {
406 return _headPoseRelativeOffsetTranslation;
407 }
408 set
409 {
410 OVRPlugin.Quatf rotation;
411 OVRPlugin.Vector3f translation;
412 if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation))
413 {
414 if (translation.FromFlippedZVector3f() != value)
415 {
416 translation = value.ToFlippedZVector3f();
417 OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation);
418 }
419 }
420 _headPoseRelativeOffsetTranslation = value;
421 }
422 }
423
424 /// <summary>
425 /// The TCP listening port of Oculus Profiler Service, which will be activated in Debug/Developerment builds
426 /// When the app is running on editor or device, open "Tools/Oculus/Oculus Profiler Panel" to view the realtime system metrics
427 /// </summary>
428 public int profilerTcpPort = OVRSystemPerfMetrics.TcpListeningPort;
429
430#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
431 /// <summary>
432 /// If true, the MixedRealityCapture properties will be displayed
433 /// </summary>
434 [HideInInspector]
435 public bool expandMixedRealityCapturePropertySheet = false;
436
437
438 /// <summary>
439 /// If true, Mixed Reality mode will be enabled
440 /// </summary>
441 [HideInInspector, Tooltip("If true, Mixed Reality mode will be enabled. It would be always set to false when the game is launching without editor")]
442 public bool enableMixedReality = false;
443
444 public enum CompositionMethod
445 {
446 External,
447 Direct,
448 Sandwich
449 }
450
451 /// <summary>
452 /// Composition method
453 /// </summary>
454 [HideInInspector]
455 public CompositionMethod compositionMethod = CompositionMethod.External;
456
457 /// <summary>
458 /// Extra hidden layers
459 /// </summary>
460 [HideInInspector, Tooltip("Extra hidden layers")]
461 public LayerMask extraHiddenLayers;
462
463 /// <summary>
464 /// The backdrop color will be used when rendering the foreground frames. It only applies to External Composition.
465 /// </summary>
466 [HideInInspector, Tooltip("Backdrop color (External Compositon)")]
467 public Color externalCompositionBackdropColor = Color.clear;
468
469 /// <summary>
470 /// If true, Mixed Reality mode will use direct composition from the first web camera
471 /// </summary>
472
473 public enum CameraDevice
474 {
475 WebCamera0,
476 WebCamera1,
477 ZEDCamera
478 }
479
480 /// <summary>
481 /// The camera device for direct composition
482 /// </summary>
483 [HideInInspector, Tooltip("The camera device for direct composition")]
484 public CameraDevice capturingCameraDevice = CameraDevice.WebCamera0;
485
486 /// <summary>
487 /// Flip the camera frame horizontally
488 /// </summary>
489 [HideInInspector, Tooltip("Flip the camera frame horizontally")]
490 public bool flipCameraFrameHorizontally = false;
491
492 /// <summary>
493 /// Flip the camera frame vertically
494 /// </summary>
495 [HideInInspector, Tooltip("Flip the camera frame vertically")]
496 public bool flipCameraFrameVertically = false;
497
498 /// <summary>
499 /// Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency
500 /// </summary>
501 [HideInInspector, Tooltip("Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency")]
502 public float handPoseStateLatency = 0.0f;
503
504 /// <summary>
505 /// Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS}
506 /// </summary>
507 [HideInInspector, Tooltip("Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS}")]
508 public float sandwichCompositionRenderLatency = 0.0f;
509
510 /// <summary>
511 /// The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume.
512 /// </summary>
513 [HideInInspector, Tooltip("The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume.")]
514 public int sandwichCompositionBufferedFrames = 8;
515
516
517 /// <summary>
518 /// Chroma Key Color
519 /// </summary>
520 [HideInInspector, Tooltip("Chroma Key Color")]
521 public Color chromaKeyColor = Color.green;
522
523 /// <summary>
524 /// Chroma Key Similarity
525 /// </summary>
526 [HideInInspector, Tooltip("Chroma Key Similarity")]
527 public float chromaKeySimilarity = 0.60f;
528
529 /// <summary>
530 /// Chroma Key Smooth Range
531 /// </summary>
532 [HideInInspector, Tooltip("Chroma Key Smooth Range")]
533 public float chromaKeySmoothRange = 0.03f;
534
535 /// <summary>
536 /// Chroma Key Spill Range
537 /// </summary>
538 [HideInInspector, Tooltip("Chroma Key Spill Range")]
539 public float chromaKeySpillRange = 0.06f;
540
541 /// <summary>
542 /// Use dynamic lighting (Depth sensor required)
543 /// </summary>
544 [HideInInspector, Tooltip("Use dynamic lighting (Depth sensor required)")]
545 public bool useDynamicLighting = false;
546
547 public enum DepthQuality
548 {
549 Low,
550 Medium,
551 High
552 }
553 /// <summary>
554 /// The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance.
555 /// </summary>
556 [HideInInspector, Tooltip("The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance.")]
557 public DepthQuality depthQuality = DepthQuality.Medium;
558
559 /// <summary>
560 /// Smooth factor in dynamic lighting. Larger is smoother
561 /// </summary>
562 [HideInInspector, Tooltip("Smooth factor in dynamic lighting. Larger is smoother")]
563 public float dynamicLightingSmoothFactor = 8.0f;
564
565 /// <summary>
566 /// The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges.
567 /// </summary>
568 [HideInInspector, Tooltip("The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges.")]
569 public float dynamicLightingDepthVariationClampingValue = 0.001f;
570
571 public enum VirtualGreenScreenType
572 {
573 Off,
574 OuterBoundary,
575 PlayArea
576 }
577
578 /// <summary>
579 /// Set the current type of the virtual green screen
580 /// </summary>
581 [HideInInspector, Tooltip("Type of virutal green screen ")]
582 public VirtualGreenScreenType virtualGreenScreenType = VirtualGreenScreenType.Off;
583
584 /// <summary>
585 /// Top Y of virtual screen
586 /// </summary>
587 [HideInInspector, Tooltip("Top Y of virtual green screen")]
588 public float virtualGreenScreenTopY = 10.0f;
589
590 /// <summary>
591 /// Bottom Y of virtual screen
592 /// </summary>
593 [HideInInspector, Tooltip("Bottom Y of virtual green screen")]
594 public float virtualGreenScreenBottomY = -10.0f;
595
596 /// <summary>
597 /// When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling.
598 /// </summary>
599 [HideInInspector, Tooltip("When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling.")]
600 public bool virtualGreenScreenApplyDepthCulling = false;
601
602 /// <summary>
603 /// The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly.
604 /// </summary>
605 [HideInInspector, Tooltip("The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly.")]
606 public float virtualGreenScreenDepthTolerance = 0.2f;
607
608 public enum MrcActivationMode
609 {
610 Automatic,
611 Disabled
612 }
613
614 /// <summary>
615 /// (Quest-only) control if the mixed reality capture mode can be activated automatically through remote network connection.
616 /// </summary>
617 [HideInInspector, Tooltip("(Quest-only) control if the mixed reality capture mode can be activated automatically through remote network connection.")]
618 public MrcActivationMode mrcActivationMode;
619#endif
620
621 /// <summary>
622 /// The number of expected display frames per rendered frame.
623 /// </summary>
624 public int vsyncCount
625 {
626 get {
627 if (!isHmdPresent)
628 return 1;
629
630 return OVRPlugin.vsyncCount;
631 }
632
633 set {
634 if (!isHmdPresent)
635 return;
636
637 OVRPlugin.vsyncCount = value;
638 }
639 }
640
641 public static string OCULUS_UNITY_NAME_STR = "Oculus";
642 public static string OPENVR_UNITY_NAME_STR = "OpenVR";
643
644 public static XRDevice loadedXRDevice;
645
646 /// <summary>
647 /// Gets the current battery level.
648 /// </summary>
649 /// <returns><c>battery level in the range [0.0,1.0]</c>
650 /// <param name="batteryLevel">Battery level.</param>
651 public static float batteryLevel
652 {
653 get {
654 if (!isHmdPresent)
655 return 1f;
656
657 return OVRPlugin.batteryLevel;
658 }
659 }
660
661 /// <summary>
662 /// Gets the current battery temperature.
663 /// </summary>
664 /// <returns><c>battery temperature in Celsius</c>
665 /// <param name="batteryTemperature">Battery temperature.</param>
666 public static float batteryTemperature
667 {
668 get {
669 if (!isHmdPresent)
670 return 0f;
671
672 return OVRPlugin.batteryTemperature;
673 }
674 }
675
676 /// <summary>
677 /// Gets the current battery status.
678 /// </summary>
679 /// <returns><c>battery status</c>
680 /// <param name="batteryStatus">Battery status.</param>
681 public static int batteryStatus
682 {
683 get {
684 if (!isHmdPresent)
685 return -1;
686
687 return (int)OVRPlugin.batteryStatus;
688 }
689 }
690
691 /// <summary>
692 /// Gets the current volume level.
693 /// </summary>
694 /// <returns><c>volume level in the range [0,1].</c>
695 public static float volumeLevel
696 {
697 get {
698 if (!isHmdPresent)
699 return 0f;
700
701 return OVRPlugin.systemVolume;
702 }
703 }
704
705 /// <summary>
706 /// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power.
707 /// </summary>
708 public static int cpuLevel
709 {
710 get {
711 if (!isHmdPresent)
712 return 2;
713
714 return OVRPlugin.cpuLevel;
715 }
716
717 set {
718 if (!isHmdPresent)
719 return;
720
721 OVRPlugin.cpuLevel = value;
722 }
723 }
724
725 /// <summary>
726 /// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power.
727 /// </summary>
728 public static int gpuLevel
729 {
730 get {
731 if (!isHmdPresent)
732 return 2;
733
734 return OVRPlugin.gpuLevel;
735 }
736
737 set {
738 if (!isHmdPresent)
739 return;
740
741 OVRPlugin.gpuLevel = value;
742 }
743 }
744
745 /// <summary>
746 /// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature.
747 /// </summary>
748 public static bool isPowerSavingActive
749 {
750 get {
751 if (!isHmdPresent)
752 return false;
753
754 return OVRPlugin.powerSaving;
755 }
756 }
757
758 /// <summary>
759 /// Gets or sets the eye texture format.
760 /// </summary>
761 public static EyeTextureFormat eyeTextureFormat
762 {
763 get
764 {
765 return (OVRManager.EyeTextureFormat)OVRPlugin.GetDesiredEyeTextureFormat();
766 }
767
768 set
769 {
770 OVRPlugin.SetDesiredEyeTextureFormat((OVRPlugin.EyeTextureFormat)value);
771 }
772 }
773
774 /// <summary>
775 /// Gets if tiled-based multi-resolution technique is supported
776 /// This feature is only supported on QCOMM-based Android devices
777 /// </summary>
778 public static bool fixedFoveatedRenderingSupported
779 {
780 get
781 {
782 return OVRPlugin.fixedFoveatedRenderingSupported;
783 }
784 }
785
786 /// <summary>
787 /// Gets or sets the tiled-based multi-resolution level
788 /// This feature is only supported on QCOMM-based Android devices
789 /// </summary>
790 public static FixedFoveatedRenderingLevel fixedFoveatedRenderingLevel
791 {
792 get
793 {
794 if (!OVRPlugin.fixedFoveatedRenderingSupported)
795 {
796 Debug.LogWarning("Fixed Foveated Rendering feature is not supported");
797 }
798 return (FixedFoveatedRenderingLevel)OVRPlugin.fixedFoveatedRenderingLevel;
799 }
800 set
801 {
802 if (!OVRPlugin.fixedFoveatedRenderingSupported)
803 {
804 Debug.LogWarning("Fixed Foveated Rendering feature is not supported");
805 }
806 OVRPlugin.fixedFoveatedRenderingLevel = (OVRPlugin.FixedFoveatedRenderingLevel)value;
807 }
808 }
809
810 [Obsolete("Please use fixedFoveatedRenderingSupported instead", false)]
811 public static bool tiledMultiResSupported
812 {
813 get
814 {
815 return OVRPlugin.tiledMultiResSupported;
816 }
817 }
818
819 [Obsolete("Please use fixedFoveatedRenderingLevel instead", false)]
820 public static TiledMultiResLevel tiledMultiResLevel
821 {
822 get
823 {
824 if (!OVRPlugin.tiledMultiResSupported)
825 {
826 Debug.LogWarning("Tiled-based Multi-resolution feature is not supported");
827 }
828 return (TiledMultiResLevel)OVRPlugin.tiledMultiResLevel;
829 }
830 set
831 {
832 if (!OVRPlugin.tiledMultiResSupported)
833 {
834 Debug.LogWarning("Tiled-based Multi-resolution feature is not supported");
835 }
836 OVRPlugin.tiledMultiResLevel = (OVRPlugin.TiledMultiResLevel)value;
837 }
838 }
839
840 /// <summary>
841 /// Gets if the GPU Utility is supported
842 /// This feature is only supported on QCOMM-based Android devices
843 /// </summary>
844 public static bool gpuUtilSupported
845 {
846 get
847 {
848 return OVRPlugin.gpuUtilSupported;
849 }
850 }
851
852 /// <summary>
853 /// Gets the GPU Utilised Level (0.0 - 1.0)
854 /// This feature is only supported on QCOMM-based Android devices
855 /// </summary>
856 public static float gpuUtilLevel
857 {
858 get
859 {
860 if (!OVRPlugin.gpuUtilSupported)
861 {
862 Debug.LogWarning("GPU Util is not supported");
863 }
864 return OVRPlugin.gpuUtilLevel;
865 }
866 }
867
868 /// <summary>
869 /// Sets the Color Scale and Offset which is commonly used for effects like fade-to-black.
870 /// In our compositor, once a given frame is rendered, warped, and ready to be displayed, we then multiply
871 /// each pixel by colorScale and add it to colorOffset, whereby newPixel = oldPixel * colorScale + colorOffset.
872 /// Note that for mobile devices (Quest, Go, etc.), colorOffset is not supported, so colorScale is all that can
873 /// be used. A colorScale of (1, 1, 1, 1) and colorOffset of (0, 0, 0, 0) will lead to an identity multiplication
874 /// and have no effect.
875 /// </summary>
876 public static void SetColorScaleAndOffset(Vector4 colorScale, Vector4 colorOffset, bool applyToAllLayers)
877 {
878 OVRPlugin.SetColorScaleAndOffset(colorScale, colorOffset, applyToAllLayers);
879 }
880
881 /// <summary>
882 /// Specifies OpenVR pose local to tracking space
883 /// </summary>
884 public static void SetOpenVRLocalPose(Vector3 leftPos, Vector3 rightPos, Quaternion leftRot, Quaternion rightRot)
885 {
886 if (loadedXRDevice == XRDevice.OpenVR)
887 OVRInput.SetOpenVRLocalPose(leftPos, rightPos, leftRot, rightRot);
888 }
889
890 //Series of offsets that line up the virtual controllers to the phsyical world.
891 private static Vector3 OpenVRTouchRotationOffsetEulerLeft = new Vector3(40.0f, 0.0f, 0.0f);
892 private static Vector3 OpenVRTouchRotationOffsetEulerRight = new Vector3(40.0f, 0.0f, 0.0f);
893 private static Vector3 OpenVRTouchPositionOffsetLeft = new Vector3(0.0075f, -0.005f, -0.0525f);
894 private static Vector3 OpenVRTouchPositionOffsetRight = new Vector3(-0.0075f, -0.005f, -0.0525f);
895
896 /// <summary>
897 /// Specifies the pose offset required to make an OpenVR controller's reported pose match the virtual pose.
898 /// Currently we only specify this offset for Oculus Touch on OpenVR.
899 /// </summary>
900 public static OVRPose GetOpenVRControllerOffset(Node hand)
901 {
902 OVRPose poseOffset = OVRPose.identity;
903 if ((hand == Node.LeftHand || hand == Node.RightHand) && loadedXRDevice == XRDevice.OpenVR)
904 {
905 int index = (hand == Node.LeftHand) ? 0 : 1;
906 if (OVRInput.openVRControllerDetails[index].controllerType == OVRInput.OpenVRController.OculusTouch)
907 {
908 Vector3 offsetOrientation = (hand == Node.LeftHand) ? OpenVRTouchRotationOffsetEulerLeft : OpenVRTouchRotationOffsetEulerRight;
909 poseOffset.orientation = Quaternion.Euler(offsetOrientation.x, offsetOrientation.y, offsetOrientation.z);
910 poseOffset.position = (hand == Node.LeftHand) ? OpenVRTouchPositionOffsetLeft : OpenVRTouchPositionOffsetRight;
911 }
912 }
913 return poseOffset;
914 }
915
916
917 [Header("Tracking")]
918 [SerializeField]
919 [Tooltip("Defines the current tracking origin type.")]
920 private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel;
921 /// <summary>
922 /// Defines the current tracking origin type.
923 /// </summary>
924 public OVRManager.TrackingOrigin trackingOriginType
925 {
926 get {
927 if (!isHmdPresent)
928 return _trackingOriginType;
929
930 return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType();
931 }
932
933 set {
934 if (!isHmdPresent)
935 return;
936
937 if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value))
938 {
939 // Keep the field exposed in the Unity Editor synchronized with any changes.
940 _trackingOriginType = value;
941 }
942 }
943 }
944
945 /// <summary>
946 /// If true, head tracking will affect the position of each OVRCameraRig's cameras.
947 /// </summary>
948 [Tooltip("If true, head tracking will affect the position of each OVRCameraRig's cameras.")]
949 public bool usePositionTracking = true;
950
951 /// <summary>
952 /// If true, head tracking will affect the rotation of each OVRCameraRig's cameras.
953 /// </summary>
954 [HideInInspector]
955 public bool useRotationTracking = true;
956
957 /// <summary>
958 /// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.
959 /// </summary>
960 [Tooltip("If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.")]
961 public bool useIPDInPositionTracking = true;
962
963 /// <summary>
964 /// If true, each scene load will cause the head pose to reset.
965 /// </summary>
966 [Tooltip("If true, each scene load will cause the head pose to reset.")]
967 public bool resetTrackerOnLoad = false;
968
969 /// <summary>
970 /// If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be
971 /// enabled for applications with a stationary position in the virtual world and will allow the View Reset
972 /// command to place the person back to a predefined location (such as a cockpit seat).
973 /// Set this to false if you have a locomotion system because resetting the view would effectively teleport
974 /// the player to potentially invalid locations.
975 /// </summary>
976 [Tooltip("If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be enabled for applications with a stationary position in the virtual world and will allow the View Reset command to place the person back to a predefined location (such as a cockpit seat). Set this to false if you have a locomotion system because resetting the view would effectively teleport the player to potentially invalid locations.")]
977 public bool AllowRecenter = true;
978
979 [SerializeField]
980 [Tooltip("Specifies HMD recentering behavior when controller recenter is performed. True recenters the HMD as well, false does not.")]
981 private bool _reorientHMDOnControllerRecenter = true;
982 /// <summary>
983 /// Defines the recentering mode specified in the tooltip above.
984 /// </summary>
985 public bool reorientHMDOnControllerRecenter
986 {
987 get
988 {
989 if (!isHmdPresent)
990 return false;
991
992 return OVRPlugin.GetReorientHMDOnControllerRecenter();
993 }
994
995 set
996 {
997 if (!isHmdPresent)
998 return;
999
1000 OVRPlugin.SetReorientHMDOnControllerRecenter(value);
1001
1002 }
1003 }
1004
1005 /// <summary>
1006 /// If true, a lower-latency update will occur right before rendering. If false, the only controller pose update will occur at the start of simulation for a given frame.
1007 /// Selecting this option lowers rendered latency for controllers and is often a net positive; however, it also creates a slight disconnect between rendered and simulated controller poses.
1008 /// Visit online Oculus documentation to learn more.
1009 /// </summary>
1010 [Tooltip("If true, rendered controller latency is reduced by several ms, as the left/right controllers will have their positions updated right before rendering.")]
1011 public bool LateControllerUpdate = true;
1012
1013 /// <summary>
1014 /// True if the current platform supports virtual reality.
1015 /// </summary>
1016 public bool isSupportedPlatform { get; private set; }
1017
1018 private static bool _isUserPresentCached = false;
1019 private static bool _isUserPresent = false;
1020 private static bool _wasUserPresent = false;
1021 /// <summary>
1022 /// True if the user is currently wearing the display.
1023 /// </summary>
1024 public bool isUserPresent
1025 {
1026 get {
1027 if (!_isUserPresentCached)
1028 {
1029 _isUserPresentCached = true;
1030 _isUserPresent = OVRPlugin.userPresent;
1031 }
1032
1033 return _isUserPresent;
1034 }
1035
1036 private set {
1037 _isUserPresentCached = true;
1038 _isUserPresent = value;
1039 }
1040 }
1041
1042 private static bool prevAudioOutIdIsCached = false;
1043 private static bool prevAudioInIdIsCached = false;
1044 private static string prevAudioOutId = string.Empty;
1045 private static string prevAudioInId = string.Empty;
1046 private static bool wasPositionTracked = false;
1047
1048 public static System.Version utilitiesVersion
1049 {
1050 get { return OVRPlugin.wrapperVersion; }
1051 }
1052
1053 public static System.Version pluginVersion
1054 {
1055 get { return OVRPlugin.version; }
1056 }
1057
1058 public static System.Version sdkVersion
1059 {
1060 get { return OVRPlugin.nativeSDKVersion; }
1061 }
1062
1063#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
1064 private static bool prevEnableMixedReality = false;
1065 private static bool MixedRealityEnabledFromCmd()
1066 {
1067 var args = System.Environment.GetCommandLineArgs();
1068 for (int i = 0; i < args.Length; i++)
1069 {
1070 if (args[i].ToLower() == "-mixedreality")
1071 return true;
1072 }
1073 return false;
1074 }
1075
1076 private static bool UseDirectCompositionFromCmd()
1077 {
1078 var args = System.Environment.GetCommandLineArgs();
1079 for (int i = 0; i < args.Length; i++)
1080 {
1081 if (args[i].ToLower() == "-directcomposition")
1082 return true;
1083 }
1084 return false;
1085 }
1086
1087 private static bool UseExternalCompositionFromCmd()
1088 {
1089 var args = System.Environment.GetCommandLineArgs();
1090 for (int i = 0; i < args.Length; i++)
1091 {
1092 if (args[i].ToLower() == "-externalcomposition")
1093 return true;
1094 }
1095 return false;
1096 }
1097
1098 private static bool CreateMixedRealityCaptureConfigurationFileFromCmd()
1099 {
1100 var args = System.Environment.GetCommandLineArgs();
1101 for (int i = 0; i < args.Length; i++)
1102 {
1103 if (args[i].ToLower() == "-create_mrc_config")
1104 return true;
1105 }
1106 return false;
1107 }
1108
1109 private static bool LoadMixedRealityCaptureConfigurationFileFromCmd()
1110 {
1111 var args = System.Environment.GetCommandLineArgs();
1112 for (int i = 0; i < args.Length; i++)
1113 {
1114 if (args[i].ToLower() == "-load_mrc_config")
1115 return true;
1116 }
1117 return false;
1118 }
1119#endif
1120
1121 public static bool IsUnityAlphaOrBetaVersion()
1122 {
1123 string ver = Application.unityVersion;
1124 int pos = ver.Length - 1;
1125
1126 while (pos >= 0 && ver[pos] >= '0' && ver[pos] <= '9')
1127 {
1128 --pos;
1129 }
1130
1131 if (pos >= 0 && (ver[pos] == 'a' || ver[pos] == 'b'))
1132 return true;
1133
1134 return false;
1135 }
1136
1137 public static string UnityAlphaOrBetaVersionWarningMessage = "WARNING: It's not recommended to use Unity alpha/beta release in Oculus development. Use a stable release if you encounter any issue.";
1138
1139#region Unity Messages
1140
1141 public static bool OVRManagerinitialized = false;
1142 private void InitOVRManager()
1143 {
1144 // Only allow one instance at runtime.
1145 if (instance != null)
1146 {
1147 enabled = false;
1148 DestroyImmediate(this);
1149 return;
1150 }
1151
1152 instance = this;
1153
1154 // uncomment the following line to disable the callstack printed to log
1155 //Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None); // TEMPORARY
1156
1157 Debug.Log("Unity v" + Application.unityVersion + ", " +
1158 "Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " +
1159 "OVRPlugin v" + OVRPlugin.version + ", " +
1160 "SDK v" + OVRPlugin.nativeSDKVersion + ".");
1161
1162#if !UNITY_EDITOR
1163 if (IsUnityAlphaOrBetaVersion())
1164 {
1165 Debug.LogWarning(UnityAlphaOrBetaVersionWarningMessage);
1166 }
1167#endif
1168
1169#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
1170 var supportedTypes =
1171 UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " +
1172 UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString();
1173
1174 if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString()))
1175 Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString());
1176#endif
1177
1178 // Detect whether this platform is a supported platform
1179 RuntimePlatform currPlatform = Application.platform;
1180 if (currPlatform == RuntimePlatform.Android ||
1181 // currPlatform == RuntimePlatform.LinuxPlayer ||
1182 currPlatform == RuntimePlatform.OSXEditor ||
1183 currPlatform == RuntimePlatform.OSXPlayer ||
1184 currPlatform == RuntimePlatform.WindowsEditor ||
1185 currPlatform == RuntimePlatform.WindowsPlayer)
1186 {
1187 isSupportedPlatform = true;
1188 }
1189 else
1190 {
1191 isSupportedPlatform = false;
1192 }
1193 if (!isSupportedPlatform)
1194 {
1195 Debug.LogWarning("This platform is unsupported");
1196 return;
1197 }
1198
1199#if UNITY_ANDROID && !UNITY_EDITOR
1200 // Turn off chromatic aberration by default to save texture bandwidth.
1201 chromatic = false;
1202#endif
1203
1204#if (UNITY_STANDALONE_WIN || UNITY_ANDROID) && !UNITY_EDITOR
1205 enableMixedReality = false; // we should never start the standalone game in MxR mode, unless the command-line parameter is provided
1206#endif
1207
1208#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
1209 bool loadMrcConfig = LoadMixedRealityCaptureConfigurationFileFromCmd();
1210 bool createMrcConfig = CreateMixedRealityCaptureConfigurationFileFromCmd();
1211
1212 if (loadMrcConfig || createMrcConfig)
1213 {
1214 OVRMixedRealityCaptureSettings mrcSettings = ScriptableObject.CreateInstance<OVRMixedRealityCaptureSettings>();
1215 mrcSettings.ReadFrom(this);
1216 if (loadMrcConfig)
1217 {
1218 mrcSettings.CombineWithConfigurationFile();
1219 mrcSettings.ApplyTo(this);
1220 }
1221 if (createMrcConfig)
1222 {
1223 mrcSettings.WriteToConfigurationFile();
1224 }
1225 ScriptableObject.Destroy(mrcSettings);
1226 }
1227
1228 if (MixedRealityEnabledFromCmd())
1229 {
1230 enableMixedReality = true;
1231 }
1232
1233 if (enableMixedReality)
1234 {
1235 Debug.Log("OVR: Mixed Reality mode enabled");
1236 if (UseDirectCompositionFromCmd())
1237 {
1238 compositionMethod = CompositionMethod.Direct;
1239 }
1240 if (UseExternalCompositionFromCmd())
1241 {
1242 compositionMethod = CompositionMethod.External;
1243 }
1244 Debug.Log("OVR: CompositionMethod : " + compositionMethod);
1245 }
1246#endif
1247
1248#if OVR_ANDROID_MRC
1249 bool mediaInitialized = OVRPlugin.Media.Initialize();
1250 Debug.Log(mediaInitialized ? "OVRPlugin.Media initialized" : "OVRPlugin.Media not initialized");
1251 if (mediaInitialized)
1252 {
1253 OVRPlugin.Media.SetMrcAudioSampleRate(AudioSettings.outputSampleRate);
1254 Debug.LogFormat("[MRC] SetMrcAudioSampleRate({0})", AudioSettings.outputSampleRate);
1255 OVRPlugin.Media.SetMrcInputVideoBufferType(OVRPlugin.Media.InputVideoBufferType.TextureHandle);
1256 Debug.LogFormat("[MRC] Active InputVideoBufferType:{0}", OVRPlugin.Media.GetMrcInputVideoBufferType());
1257 if (mrcActivationMode == MrcActivationMode.Automatic)
1258 {
1259 OVRPlugin.Media.SetMrcActivationMode(OVRPlugin.Media.MrcActivationMode.Automatic);
1260 Debug.LogFormat("[MRC] ActivateMode: Automatic");
1261 }
1262 else if (mrcActivationMode == MrcActivationMode.Disabled)
1263 {
1264 OVRPlugin.Media.SetMrcActivationMode(OVRPlugin.Media.MrcActivationMode.Disabled);
1265 Debug.LogFormat("[MRC] ActivateMode: Disabled");
1266 }
1267 }
1268#endif
1269
1270#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
1271 if (enableAdaptiveResolution && !OVRManager.IsAdaptiveResSupportedByEngine())
1272 {
1273 enableAdaptiveResolution = false;
1274 UnityEngine.Debug.LogError("Your current Unity Engine " + Application.unityVersion + " might have issues to support adaptive resolution, please disable it under OVRManager");
1275 }
1276#endif
1277
1278 Initialize();
1279
1280 if (resetTrackerOnLoad)
1281 display.RecenterPose();
1282
1283 if (Debug.isDebugBuild)
1284 {
1285 // Activate system metrics collection in Debug/Developerment build
1286 if (GetComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>() == null)
1287 {
1288 gameObject.AddComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>();
1289 }
1290 OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer perfTcpServer = GetComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>();
1291 perfTcpServer.listeningPort = profilerTcpPort;
1292 if (!perfTcpServer.enabled)
1293 {
1294 perfTcpServer.enabled = true;
1295 }
1296 }
1297
1298#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
1299 // Force OcculusionMesh on all the time, you can change the value to false if you really need it be off for some reasons,
1300 // be aware there are performance drops if you don't use occlusionMesh.
1301 OVRPlugin.occlusionMesh = true;
1302#endif
1303 OVRManagerinitialized = true;
1304
1305 }
1306
1307 private void Awake()
1308 {
1309#if !USING_XR_SDK
1310 //For legacy, we can safely InitOVRManager on Awake(), as OVRPlugin is already initialized.
1311 InitOVRManager();
1312#endif
1313 }
1314
1315#if UNITY_EDITOR
1316 private static bool _scriptsReloaded;
1317
1318 [UnityEditor.Callbacks.DidReloadScripts]
1319 static void ScriptsReloaded()
1320 {
1321 _scriptsReloaded = true;
1322 }
1323#endif
1324
1325 void SetCurrentXRDevice()
1326 {
1327#if USING_XR_SDK
1328 XRDisplaySubsystem currentDisplaySubsystem = GetCurrentDisplaySubsystem();
1329 XRDisplaySubsystemDescriptor currentDisplaySubsystemDescriptor = GetCurrentDisplaySubsystemDescriptor();
1330#endif
1331 if (OVRPlugin.initialized)
1332 {
1333 loadedXRDevice = XRDevice.Oculus;
1334 }
1335#if USING_XR_SDK
1336 else if (currentDisplaySubsystem != null && currentDisplaySubsystemDescriptor != null && currentDisplaySubsystem.running)
1337#else
1338 else if (Settings.enabled)
1339#endif
1340 {
1341#if USING_XR_SDK
1342 string loadedXRDeviceName = currentDisplaySubsystemDescriptor.id;
1343#else
1344 string loadedXRDeviceName = Settings.loadedDeviceName;
1345#endif
1346 if (loadedXRDeviceName == OPENVR_UNITY_NAME_STR)
1347 loadedXRDevice = XRDevice.OpenVR;
1348 else
1349 loadedXRDevice = XRDevice.Unknown;
1350 }
1351 else
1352 {
1353 loadedXRDevice = XRDevice.Unknown;
1354 }
1355 }
1356
1357#if USING_XR_SDK
1358
1359 public static XRDisplaySubsystem GetCurrentDisplaySubsystem()
1360 {
1361 List<XRDisplaySubsystem> displaySubsystems = new List<XRDisplaySubsystem>();
1362 SubsystemManager.GetInstances(displaySubsystems);
1363 //Note: Here we are making the assumption that there will always be one valid display subsystem. If there is not, then submitFrame isn't being called,
1364 //so for now this is a fine assumption to make.
1365 if (displaySubsystems.Count > 0)
1366 return displaySubsystems[0];
1367 return null;
1368 }
1369
1370 public static XRDisplaySubsystemDescriptor GetCurrentDisplaySubsystemDescriptor()
1371 {
1372 List<XRDisplaySubsystemDescriptor> displaySubsystemDescriptors = new List<XRDisplaySubsystemDescriptor>();
1373 SubsystemManager.GetSubsystemDescriptors(displaySubsystemDescriptors);
1374 if (displaySubsystemDescriptors.Count > 0)
1375 return displaySubsystemDescriptors[0];
1376 return null;
1377 }
1378#endif
1379
1380
1381
1382
1383 void Initialize()
1384 {
1385 if (display == null)
1386 display = new OVRDisplay();
1387 if (tracker == null)
1388 tracker = new OVRTracker();
1389 if (boundary == null)
1390 boundary = new OVRBoundary();
1391
1392 reorientHMDOnControllerRecenter = _reorientHMDOnControllerRecenter;
1393 SetCurrentXRDevice();
1394
1395 }
1396
1397#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
1398 private bool suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false;
1399#endif
1400
1401 private void Update()
1402 {
1403 //Only if we're using the XR SDK do we have to check if OVRManager isn't yet initialized, and init it.
1404 //If we're on legacy, we know initialization occurred properly in Awake()
1405#if USING_XR_SDK
1406 if (!OVRManagerinitialized)
1407 {
1408 XRDisplaySubsystem currentDisplaySubsystem = GetCurrentDisplaySubsystem();
1409 XRDisplaySubsystemDescriptor currentDisplaySubsystemDescriptor = GetCurrentDisplaySubsystemDescriptor();
1410 if (currentDisplaySubsystem == null || currentDisplaySubsystemDescriptor == null || !OVRPlugin.initialized)
1411 return;
1412 //If we're using the XR SDK and the display subsystem is present, and OVRPlugin is initialized, we can init OVRManager
1413 InitOVRManager();
1414 }
1415#endif
1416
1417#if UNITY_EDITOR
1418 if (_scriptsReloaded)
1419 {
1420 _scriptsReloaded = false;
1421 instance = this;
1422 Initialize();
1423 }
1424#endif
1425
1426 SetCurrentXRDevice();
1427
1428 if (OVRPlugin.shouldQuit)
1429 {
1430 Debug.Log("[OVRManager] OVRPlugin.shouldQuit detected");
1431 Application.Quit();
1432 }
1433
1434 if (AllowRecenter && OVRPlugin.shouldRecenter)
1435 {
1436 OVRManager.display.RecenterPose();
1437 }
1438
1439 if (trackingOriginType != _trackingOriginType)
1440 trackingOriginType = _trackingOriginType;
1441
1442 tracker.isEnabled = usePositionTracking;
1443
1444 OVRPlugin.rotation = useRotationTracking;
1445
1446 OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;
1447
1448 // Dispatch HMD events.
1449
1450 isHmdPresent = OVRNodeStateProperties.IsHmdPresent();
1451
1452 if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
1453 {
1454 Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing +
1455 ", but the recommended MSAA level is " + display.recommendedMSAALevel +
1456 ". Switching to the recommended level.");
1457
1458 QualitySettings.antiAliasing = display.recommendedMSAALevel;
1459 }
1460
1461 if (monoscopic != _monoscopic)
1462 {
1463 monoscopic = _monoscopic;
1464 }
1465
1466 if (headPoseRelativeOffsetRotation != _headPoseRelativeOffsetRotation)
1467 {
1468 headPoseRelativeOffsetRotation = _headPoseRelativeOffsetRotation;
1469 }
1470
1471 if (headPoseRelativeOffsetTranslation != _headPoseRelativeOffsetTranslation)
1472 {
1473 headPoseRelativeOffsetTranslation = _headPoseRelativeOffsetTranslation;
1474 }
1475
1476 if (_wasHmdPresent && !isHmdPresent)
1477 {
1478 try
1479 {
1480 Debug.Log("[OVRManager] HMDLost event");
1481 if (HMDLost != null)
1482 HMDLost();
1483 }
1484 catch (Exception e)
1485 {
1486 Debug.LogError("Caught Exception: " + e);
1487 }
1488 }
1489
1490 if (!_wasHmdPresent && isHmdPresent)
1491 {
1492 try
1493 {
1494 Debug.Log("[OVRManager] HMDAcquired event");
1495 if (HMDAcquired != null)
1496 HMDAcquired();
1497 }
1498 catch (Exception e)
1499 {
1500 Debug.LogError("Caught Exception: " + e);
1501 }
1502 }
1503
1504 _wasHmdPresent = isHmdPresent;
1505
1506 // Dispatch HMD mounted events.
1507
1508 isUserPresent = OVRPlugin.userPresent;
1509
1510 if (_wasUserPresent && !isUserPresent)
1511 {
1512 try
1513 {
1514 Debug.Log("[OVRManager] HMDUnmounted event");
1515 if (HMDUnmounted != null)
1516 HMDUnmounted();
1517 }
1518 catch (Exception e)
1519 {
1520 Debug.LogError("Caught Exception: " + e);
1521 }
1522 }
1523
1524 if (!_wasUserPresent && isUserPresent)
1525 {
1526 try
1527 {
1528 Debug.Log("[OVRManager] HMDMounted event");
1529 if (HMDMounted != null)
1530 HMDMounted();
1531 }
1532 catch (Exception e)
1533 {
1534 Debug.LogError("Caught Exception: " + e);
1535 }
1536 }
1537
1538 _wasUserPresent = isUserPresent;
1539
1540 // Dispatch VR Focus events.
1541
1542 hasVrFocus = OVRPlugin.hasVrFocus;
1543
1544 if (_hadVrFocus && !hasVrFocus)
1545 {
1546 try
1547 {
1548 Debug.Log("[OVRManager] VrFocusLost event");
1549 if (VrFocusLost != null)
1550 VrFocusLost();
1551 }
1552 catch (Exception e)
1553 {
1554 Debug.LogError("Caught Exception: " + e);
1555 }
1556 }
1557
1558 if (!_hadVrFocus && hasVrFocus)
1559 {
1560 try
1561 {
1562 Debug.Log("[OVRManager] VrFocusAcquired event");
1563 if (VrFocusAcquired != null)
1564 VrFocusAcquired();
1565 }
1566 catch (Exception e)
1567 {
1568 Debug.LogError("Caught Exception: " + e);
1569 }
1570 }
1571
1572 _hadVrFocus = hasVrFocus;
1573
1574 // Dispatch VR Input events.
1575
1576 bool hasInputFocus = OVRPlugin.hasInputFocus;
1577
1578 if (_hadInputFocus && !hasInputFocus)
1579 {
1580 try
1581 {
1582 Debug.Log("[OVRManager] InputFocusLost event");
1583 if (InputFocusLost != null)
1584 InputFocusLost();
1585 }
1586 catch (Exception e)
1587 {
1588 Debug.LogError("Caught Exception: " + e);
1589 }
1590 }
1591
1592 if (!_hadInputFocus && hasInputFocus)
1593 {
1594 try
1595 {
1596 Debug.Log("[OVRManager] InputFocusAcquired event");
1597 if (InputFocusAcquired != null)
1598 InputFocusAcquired();
1599 }
1600 catch (Exception e)
1601 {
1602 Debug.LogError("Caught Exception: " + e);
1603 }
1604 }
1605
1606 _hadInputFocus = hasInputFocus;
1607
1608 // Changing effective rendering resolution dynamically according performance
1609#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN)
1610
1611 if (enableAdaptiveResolution)
1612 {
1613#if UNITY_2017_2_OR_NEWER
1614 if (UnityEngine.XR.XRSettings.eyeTextureResolutionScale < maxRenderScale)
1615 {
1616 // Allocate renderScale to max to avoid re-allocation
1617 UnityEngine.XR.XRSettings.eyeTextureResolutionScale = maxRenderScale;
1618 }
1619 else
1620 {
1621 // Adjusting maxRenderScale in case app started with a larger renderScale value
1622 maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.XR.XRSettings.eyeTextureResolutionScale);
1623 }
1624 minRenderScale = Mathf.Min(minRenderScale, maxRenderScale);
1625 float minViewportScale = minRenderScale / UnityEngine.XR.XRSettings.eyeTextureResolutionScale;
1626 float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.XR.XRSettings.eyeTextureResolutionScale;
1627 recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
1628 UnityEngine.XR.XRSettings.renderViewportScale = recommendedViewportScale;
1629#else
1630 if (UnityEngine.VR.VRSettings.renderScale < maxRenderScale)
1631 {
1632 // Allocate renderScale to max to avoid re-allocation
1633 UnityEngine.VR.VRSettings.renderScale = maxRenderScale;
1634 }
1635 else
1636 {
1637 // Adjusting maxRenderScale in case app started with a larger renderScale value
1638 maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.VR.VRSettings.renderScale);
1639 }
1640 minRenderScale = Mathf.Min(minRenderScale, maxRenderScale);
1641 float minViewportScale = minRenderScale / UnityEngine.VR.VRSettings.renderScale;
1642 float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.VR.VRSettings.renderScale;
1643 recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
1644 UnityEngine.VR.VRSettings.renderViewportScale = recommendedViewportScale;
1645#endif
1646 }
1647#endif
1648
1649 // Dispatch Audio Device events.
1650
1651 string audioOutId = OVRPlugin.audioOutId;
1652 if (!prevAudioOutIdIsCached)
1653 {
1654 prevAudioOutId = audioOutId;
1655 prevAudioOutIdIsCached = true;
1656 }
1657 else if (audioOutId != prevAudioOutId)
1658 {
1659 try
1660 {
1661 Debug.Log("[OVRManager] AudioOutChanged event");
1662 if (AudioOutChanged != null)
1663 AudioOutChanged();
1664 }
1665 catch (Exception e)
1666 {
1667 Debug.LogError("Caught Exception: " + e);
1668 }
1669
1670 prevAudioOutId = audioOutId;
1671 }
1672
1673 string audioInId = OVRPlugin.audioInId;
1674 if (!prevAudioInIdIsCached)
1675 {
1676 prevAudioInId = audioInId;
1677 prevAudioInIdIsCached = true;
1678 }
1679 else if (audioInId != prevAudioInId)
1680 {
1681 try
1682 {
1683 Debug.Log("[OVRManager] AudioInChanged event");
1684 if (AudioInChanged != null)
1685 AudioInChanged();
1686 }
1687 catch (Exception e)
1688 {
1689 Debug.LogError("Caught Exception: " + e);
1690 }
1691
1692 prevAudioInId = audioInId;
1693 }
1694
1695 // Dispatch tracking events.
1696
1697 if (wasPositionTracked && !tracker.isPositionTracked)
1698 {
1699 try
1700 {
1701 Debug.Log("[OVRManager] TrackingLost event");
1702 if (TrackingLost != null)
1703 TrackingLost();
1704 }
1705 catch (Exception e)
1706 {
1707 Debug.LogError("Caught Exception: " + e);
1708 }
1709 }
1710
1711 if (!wasPositionTracked && tracker.isPositionTracked)
1712 {
1713 try
1714 {
1715 Debug.Log("[OVRManager] TrackingAcquired event");
1716 if (TrackingAcquired != null)
1717 TrackingAcquired();
1718 }
1719 catch (Exception e)
1720 {
1721 Debug.LogError("Caught Exception: " + e);
1722 }
1723 }
1724
1725 wasPositionTracked = tracker.isPositionTracked;
1726
1727 display.Update();
1728 OVRInput.Update();
1729
1730#if OVR_ANDROID_MRC
1731 enableMixedReality = OVRPlugin.Media.GetInitialized() && OVRPlugin.Media.IsMrcActivated();
1732 compositionMethod = CompositionMethod.External; // force external composition on Android MRC
1733
1734 if (OVRPlugin.Media.GetInitialized())
1735 {
1736 OVRPlugin.Media.Update();
1737 }
1738#endif
1739
1740#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
1741 if (enableMixedReality && !prevEnableMixedReality)
1742 {
1743 OVRPlugin.SendEvent("mixed_reality_capture", "activated");
1744 Debug.Log("MixedRealityCapture: activate");
1745 }
1746
1747 if (!enableMixedReality && prevEnableMixedReality)
1748 {
1749 Debug.Log("MixedRealityCapture: deactivate");
1750 }
1751
1752 if (enableMixedReality || prevEnableMixedReality)
1753 {
1754 Camera mainCamera = FindMainCamera();
1755 if (Camera.main != null)
1756 {
1757 suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false;
1758
1759 if (enableMixedReality)
1760 {
1761 OVRMixedReality.Update(this.gameObject, mainCamera, compositionMethod, useDynamicLighting, capturingCameraDevice, depthQuality);
1762 }
1763
1764 if (prevEnableMixedReality && !enableMixedReality)
1765 {
1766 OVRMixedReality.Cleanup();
1767 }
1768
1769 prevEnableMixedReality = enableMixedReality;
1770 }
1771 else
1772 {
1773 if (!suppressDisableMixedRealityBecauseOfNoMainCameraWarning)
1774 {
1775 Debug.LogWarning("Main Camera is not set, Mixed Reality disabled");
1776 suppressDisableMixedRealityBecauseOfNoMainCameraWarning = true;
1777 }
1778 }
1779 }
1780#endif
1781 }
1782
1783 private bool multipleMainCameraWarningPresented = false;
1784 private Camera FindMainCamera()
1785 {
1786 GameObject[] objects = GameObject.FindGameObjectsWithTag("MainCamera");
1787 List<Camera> cameras = new List<Camera>(4);
1788 foreach (GameObject obj in objects)
1789 {
1790 Camera camera = obj.GetComponent<Camera>();
1791 if (camera != null && camera.enabled)
1792 {
1793 OVRCameraRig cameraRig = camera.GetComponentInParent<OVRCameraRig>();
1794 if (cameraRig != null && cameraRig.trackingSpace != null)
1795 {
1796 cameras.Add(camera);
1797 }
1798 }
1799 }
1800 if (cameras.Count == 0)
1801 {
1802 return Camera.main; // pick one of the cameras which tagged as "MainCamera"
1803 }
1804 else if (cameras.Count == 1)
1805 {
1806 return cameras[0];
1807 }
1808 else
1809 {
1810 if (!multipleMainCameraWarningPresented)
1811 {
1812 Debug.LogWarning("Multiple MainCamera found. Assume the real MainCamera is the camera with the least depth");
1813 multipleMainCameraWarningPresented = true;
1814 }
1815 // return the camera with least depth
1816 cameras.Sort((Camera c0, Camera c1) => { return c0.depth < c1.depth ? -1 : (c0.depth > c1.depth ? 1 : 0); });
1817 return cameras[0];
1818 }
1819 }
1820
1821 private void OnDisable()
1822 {
1823 OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer perfTcpServer = GetComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>();
1824 if (perfTcpServer != null)
1825 {
1826 perfTcpServer.enabled = false;
1827 }
1828
1829#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
1830 OVRMixedReality.Cleanup();
1831#endif
1832
1833#if UNITY_ANDROID && !UNITY_EDITOR
1834 if (OVRPlugin.Media.GetInitialized())
1835 {
1836 OVRPlugin.Media.Shutdown();
1837 }
1838#endif
1839 }
1840
1841 private void LateUpdate()
1842 {
1843 OVRHaptics.Process();
1844 }
1845
1846 private void FixedUpdate()
1847 {
1848 OVRInput.FixedUpdate();
1849 }
1850
1851 private void OnDestroy()
1852 {
1853 Debug.Log("[OVRManager] OnDestroy");
1854 OVRManagerinitialized = false;
1855 }
1856
1857 private void OnApplicationPause(bool pause)
1858 {
1859 if (pause)
1860 {
1861 Debug.Log("[OVRManager] OnApplicationPause(true)");
1862 }
1863 else
1864 {
1865 Debug.Log("[OVRManager] OnApplicationPause(false)");
1866 }
1867 }
1868
1869 private void OnApplicationFocus(bool focus)
1870 {
1871 if (focus)
1872 {
1873 Debug.Log("[OVRManager] OnApplicationFocus(true)");
1874 }
1875 else
1876 {
1877 Debug.Log("[OVRManager] OnApplicationFocus(false)");
1878 }
1879 }
1880
1881 private void OnApplicationQuit()
1882 {
1883 Debug.Log("[OVRManager] OnApplicationQuit");
1884 }
1885
1886#endregion // Unity Messages
1887
1888 /// <summary>
1889 /// Leaves the application/game and returns to the launcher/dashboard
1890 /// </summary>
1891 public void ReturnToLauncher()
1892 {
1893 // show the platform UI quit prompt
1894 OVRManager.PlatformUIConfirmQuit();
1895 }
1896
1897 public static void PlatformUIConfirmQuit()
1898 {
1899 if (!isHmdPresent)
1900 return;
1901
1902 OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit);
1903 }
1904}