// %BANNER_BEGIN%
// ---------------------------------------------------------------------
// %COPYRIGHT_BEGIN%
// Copyright (c) (2018-2022) Magic Leap, Inc. All Rights Reserved.
// Use of this file is governed by the Software License Agreement, located here: https://www.magicleap.com/software-license-agreement-ml2
// Terms and conditions applicable to third-party materials accompanying this distribution may also be found in the top-level NOTICE file appearing herein.
// %COPYRIGHT_END%
// ---------------------------------------------------------------------
// %BANNER_END%
using System;
using System.Collections;
using System.Collections.Generic;
using MagicLeap.OpenXR;
using MagicLeap.OpenXR.Features;
using UnityEngine.XR.MagicLeap.Native;
using UnityEngine.XR.Management;
using Utils = MagicLeap.OpenXR.Utils;
#if UNITY_OPENXR_1_9_0_OR_NEWER
using UnityEngine.XR.OpenXR;
#endif
namespace UnityEngine.XR.MagicLeap
{
///
/// MagicLeap device class responsible for updating all trackers when they register and are enabled.
///
[DefaultExecutionOrder(ScriptOrder)]
public class MLDevice : MonoBehaviour
{
///
/// Ensures this MonoBehavior runs its event methods very early before all other scripts.
///
private const int ScriptOrder = -15001;
///
/// Create the MLDevice instance object on application startup from the main thread
/// This avoids race conditions and situations where worker threads need to access it
///
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void InstantiateSingleton()
{
if (instance == null)
{
GameObject go = new GameObject("(MLDevice Singleton)");
instance = go.AddComponent();
#if DEBUG
MLPluginLog.Debug("Creating MLDevice");
#endif
if (Application.isPlaying)
{
DontDestroyOnLoad(instance.gameObject);
}
}
}
///
/// Hardcoded value approximating minimum near clip plane distance allowed by the platform.
///
public const float MinimumNearClipDistance = 0.37f;
///
/// Hardcoded value with the default near clip plane distance to use.
///
public const float DefaultNearClipDistance = 0.37f;
///
/// MagicLeap platform Unity name.
///
public const string MagicLeapDeviceName = "MagicLeap";
///
/// Reference to the active MLDevice instance.
///
private static MLDevice instance = null;
///
/// Reference to the active XR MagicLeap gestures subsystem.
///
private GestureSubsystemComponent gestureSubsystemComponent = null;
///
/// Contains the value that specifies if the underlying Unity XR MagicLeap subsystem is initialized.
///
private bool isReady = false;
///
/// Count of XR MagicLeap gestures subsystem start calls.
///
private uint gestureSubsystemStartCount = 0;
///
/// Platform API level.
///
private uint? platformLevel = null;
///
/// List of callbacks to trigger at the end of the frame.
///
private List endOfFrameCallbacks = new List();
///
/// Coroutine used to get the end of frame.
///
private Coroutine endOfFrameCoroutine = null;
///
/// Delegate to handle Update calls.
///
public delegate void OnStartEventDelegate();
///
/// Delegate to handle Update calls.
///
public delegate void OnUpdateEventDelegate();
///
/// Delegate to handle Update calls.
///
public delegate void OnDestroyEventDelegate();
///
/// Delegate to handle application pause events.
///
/// Whether app is paused or resumed.
public delegate void OnPauseEventDelegate(bool paused);
///
/// Delegate to handle application focus events.
///
/// Whether app is focus gained or lost.
public delegate void OnFocusEventDelegate(bool hasFocus);
///
/// Delegate to handle application quit events.
///
public delegate void OnQuitEventDelegate();
///
/// Triggered every Unity Update.
///
private event OnStartEventDelegate OnStartEvent = delegate { };
///
/// Triggered every Unity Update.
///
private event OnUpdateEventDelegate OnUpdateEvent = delegate { };
///
/// Triggered when Unity's OnDestroy is called.
///
private event OnDestroyEventDelegate OnDestroyEvent = delegate { };
///
/// Triggered on application pause and resume.
///
private event OnPauseEventDelegate OnPauseEvent = delegate { };
///
/// Triggered on application focus gained and lost.
///
private event OnFocusEventDelegate OnFocusEvent = delegate { };
///
/// Triggered on application quit.
///
private event OnQuitEventDelegate OnQuitEvent = delegate { };
private int mainThreadId = -1;
private Camera unityCamera;
#if UNITY_OPENXR_1_9_0_OR_NEWER
private MagicLeapFeature mlOpenXrFeature;
#endif
///
/// Gets the platform API level that the OS supports.
///
public static uint PlatformLevel
{
get
{
if (Instance.platformLevel == null)
{
Instance.GetPlatformLevel();
}
return Instance.platformLevel.Value;
}
}
///
/// Gets the active XR MagicLeap gestures subsystem.
///
public static GestureSubsystemComponent GestureSubsystemComponent
{
get => Instance.gestureSubsystemComponent;
}
public static int MainThreadId => Instance.mainThreadId;
public static bool UnityVideoPlayerSupported =>
#if UNITY_2022_3_10_OR_NEWER
true;
#else
false;
#endif
///
/// Gets the MLDevice singleton instance.
///
public static MLDevice Instance
{
get { return instance; }
private set { instance = value; }
}
///
/// Check if the underlying Unity XR MagicLeap subsystem is initialized.
///
/// Value indicating whether the XR MagicLeap subsystem is initialized.
public static bool IsReady()
{
return UnityEngine.XR.XRSettings.enabled && (IsMagicLeapLoaderActive() || IsOpenXRLoaderActive());
}
public static bool IsMagicLeapLoaderActive()
{
#if UNITY_XR_MAGICLEAP_PROVIDER
if (XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null)
{
return XRGeneralSettings.Instance.Manager.ActiveLoaderAs() != null;
}
#endif
return false;
}
public static bool IsOpenXRLoaderActive()
{
#if UNITY_OPENXR_1_9_0_OR_NEWER
return Utils.TryGetOpenXRLoader(out _);
#endif
#pragma warning disable CS0162
return false;
#pragma warning restore CS0162
}
public static bool IsMagicLeapOrOpenXRLoaderActive()
{
if (XRGeneralSettings.Instance != null && XRGeneralSettings.Instance.Manager != null)
{
bool isOpenXRLoaderActive = IsOpenXRLoaderActive();
bool isXRSDKLoaderActive = IsMagicLeapLoaderActive();
return isOpenXRLoaderActive || isXRSDKLoaderActive;
}
return false;
}
///
/// Register a MagicLeap API Update callback to be called on Start of this behavior.
///
/// Callback to register.
public static void RegisterStart(OnStartEventDelegate callback)
{
Instance.OnStartEvent += callback;
}
///
/// Register a MagicLeap API Update callback to be called on Update of this behavior.
///
/// Callback to register.
public static void RegisterUpdate(OnUpdateEventDelegate callback)
{
Instance.OnUpdateEvent += callback;
}
///
/// Register a MagicLeap API Update callback to be called on Destroy of this behavior.
///
/// Callback to register.
public static void RegisterDestroy(OnDestroyEventDelegate callback)
{
Instance.OnDestroyEvent += callback;
}
///
/// Unrgister a MagicLeap API application pause callback to be called OnApplicationPause of this behavior.
///
/// Callback to register.
public static void RegisterApplicationPause(OnPauseEventDelegate callback)
{
Instance.OnPauseEvent += callback;
}
///
/// Unrgister a MagicLeap API application focus callback to be called OnApplicationFocus of this behavior.
///
/// Callback to register.
public static void RegisterApplicationFocus(OnFocusEventDelegate callback)
{
Instance.OnFocusEvent += callback;
}
///
/// Register a MagicLeap API application quit callback to be called on OnApplicationQuit of this behavior.
///
/// Callback to register
public static void RegisterApplicationQuit(OnQuitEventDelegate callback)
{
Instance.OnQuitEvent += callback;
}
///
/// Unregister a previously registered MagicLeap API Update callback.
///
/// Callback to unregister.
public static void UnregisterStart(OnStartEventDelegate callback)
{
Instance.OnStartEvent -= callback;
}
///
/// Unregister a previously registered MagicLeap API Update callback.
///
/// Callback to unregister.
public static void UnregisterUpdate(OnUpdateEventDelegate callback)
{
// Check instance instead of the Instance property to prevent
// creating an instance to unregister something that won't be there.
if (instance != null)
{
instance.OnUpdateEvent -= callback;
}
}
///
/// Unregister a MagicLeap API from being called when OnDestroy for this behavior is called.
///
/// Callback to register.
public static void UnregisterDestroy(OnDestroyEventDelegate callback)
{
// Check instance instead of the Instance property to prevent
// creating an instance to unregister something that won't be there.
if (instance != null)
{
instance.OnDestroyEvent -= callback;
}
}
///
/// Unregister a previously registered MagicLeap API application pause callback.
///
/// Callback to unregister.
public static void UnregisterApplicationPause(OnPauseEventDelegate callback)
{
// Check instance instead of the Instance property to prevent
// creating an instance to unregister something that won't be there.
if (instance != null)
{
instance.OnPauseEvent -= callback;
}
}
///
/// Unregister a previously registered MagicLeap API application focus callback.
///
/// Callback to unregister.
public static void UnregisterApplicationFocus(OnFocusEventDelegate callback)
{
// Check instance instead of the Instance property to prevent
// creating an instance to unregister something that won't be there.
if (instance != null)
{
instance.OnFocusEvent -= callback;
}
}
///
/// Unregister a previously registered MagicLeapAPI application quit callback.
///
/// Callback to unregister
public static void UnregisterApplicationQuit(OnQuitEventDelegate callback)
{
// Check instance instead of the Instance property to prevent
// creating an instance to unregister something that won't be there.
if (instance != null)
{
instance.OnQuitEvent -= callback;
}
}
///
/// Attempts to register the Unity GestureSubsystem.
///
public static void RegisterGestureSubsystem()
{
// Instance is used on register, to ensure we have a valid instance.
Instance.gestureSubsystemStartCount++;
if (instance != null && instance.gestureSubsystemComponent == null)
{
instance.gestureSubsystemComponent = instance.gameObject.AddComponent();
}
}
///
/// Attempts to unregister the GestureSubsystem.
///
public static void UnregisterGestureSubsystem()
{
if (instance == null)
{
return;
}
if (instance.gestureSubsystemStartCount > 0)
{
instance.gestureSubsystemStartCount--;
// Only destroy the component when all instances have been removed.
if (instance.gestureSubsystemStartCount == 0)
{
if (instance.gestureSubsystemComponent != null)
{
Destroy(instance.gestureSubsystemComponent);
instance.gestureSubsystemComponent = null;
}
}
}
}
///
/// Register a function to be executed per frame at the end of every frame, after all cameras and GUI is rendered
/// but before displaying the frame on screen
///
/// The function.
public static void RegisterEndOfFrameUpdate(Action endOfFrameFunction)
{
if (endOfFrameFunction != null)
{
Instance.endOfFrameCallbacks.Add(endOfFrameFunction);
}
}
///
/// Unregister a function to no longer be executed at the end of the frame
///
/// The function.
public static void UnregisterEndOfFrameUpdate(Action endOfFrameFunction)
{
if (instance != null && endOfFrameFunction != null)
{
instance.endOfFrameCallbacks.Remove(endOfFrameFunction);
}
}
///
/// Initializes the Magic Leap device state.
///
protected void Awake()
{
this.mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
#if UNITY_XR_MAGICLEAP_PROVIDER
if (!Application.isEditor)
{
using (var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
var context = actClass.GetStatic("currentActivity");
AndroidJavaClass systemGlobal = new AndroidJavaClass("android.provider.Settings$Secure");
var setting = systemGlobal.CallStatic("getFloat", context.Call("getContentResolver"), "clipping_plane_distance", 0f);
if (setting != 0f)
{
// if we got something other than 0 that means the setting is available and we should disable the cumbersome enforcement in the XR plugin
Rendering.RenderingSettings.enforceNearClip = false;
Debug.Log("System setting clipping_plane_distance found, disabling Unity XR enforcement.");
}
else
{
Rendering.RenderingSettings.enforceNearClip = true;
Debug.LogWarning("System setting clipping_plane_distance could not be found. Unity XR will enforce constant value.");
}
}
}
#endif
#if UNITY_OPENXR_1_9_0_OR_NEWER
if (IsOpenXRLoaderActive())
{
mlOpenXrFeature = OpenXRSettings.Instance.GetFeature();
}
#endif
}
///
/// Cleans up any resources the object has open.
///
protected void OnDestroy()
{
if (this.endOfFrameCoroutine != null)
{
this.StopCoroutine(this.endOfFrameCoroutine);
}
OnDestroyEvent?.Invoke();
}
///
/// Calls OnUpdateActions event and dispatches all queued callbacks.
///
protected void Update()
{
if (!this.isReady && !(this.isReady = MLDevice.IsReady()))
{
return;
}
this.OnUpdateEvent?.Invoke();
MLThreadDispatch.DispatchAll();
}
///
/// Starts the EndOfFrameUpdate coroutine and dispatches the Start event.
///
protected void Start()
{
this.endOfFrameCoroutine = this.StartCoroutine(this.EndOfFrameUpdate());
OnStartEvent();
}
///
/// Callback sent to all game objects when the player pauses.
///
/// The pause state of the application.
private void OnApplicationPause(bool pauseStatus)
{
this.OnPauseEvent?.Invoke(pauseStatus);
MLThreadDispatch.DispatchAll();
}
///
/// Callback sent to all game objects when the player loses or gains focus.
///
/// The focus state of the application.
private void OnApplicationFocus(bool hasFocus)
{
this.OnFocusEvent?.Invoke(hasFocus);
MLThreadDispatch.DispatchAll();
}
///
/// Callback sent to all game objects when the player quits.
///
private void OnApplicationQuit()
{
this.OnQuitEvent?.Invoke();
}
///
/// Retrieves the platform API level that the OS supports.
///
private void GetPlatformLevel()
{
try
{
uint level = 0;
MLResult.Code resultCode = MagicLeapNativeBindings.MLPlatformGetAPILevel(ref level);
if (resultCode != MLResult.Code.Ok)
{
MLPluginLog.ErrorFormat("MLDevice.GetPlatformLevel failed to get platform level. Reason: {0}", resultCode);
}
else
{
this.platformLevel = level;
}
}
catch (DllNotFoundException)
{
MLPluginLog.ErrorFormat("MLDevice.GetPlatformLevel failed. Reason: {0} library not found", MagicLeapNativeBindings.MLPlatformDll);
}
if (this.platformLevel == null)
{
this.platformLevel = 0;
}
}
///
/// Update function that gets called at the end of frame.
///
/// End of frame IEnumetaor
private IEnumerator EndOfFrameUpdate()
{
while (true)
{
yield return new WaitForEndOfFrame();
foreach (Action callback in this.endOfFrameCallbacks)
{
callback?.Invoke();
}
}
}
}
}