// %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%
namespace UnityEngine.XR.MagicLeap
{
using System;
using System.Reflection;
///
/// Place this attribute on a child of MLAutoAPISingleton to prevent its initialization
/// until the Magic Leap XR package is loaded.
///
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class RequireXRLoader : Attribute { }
///
/// MLAutoAPISingleton class contains a template for singleton APIs
///
/// The type of the class to create a singleton for.
public abstract class MLAutoAPISingleton : MLLazySingleton where T : MLAutoAPISingleton, new()
{
///
/// The native handle ID for this API instance. Will be invalid until the API is started.
///
protected ulong Handle = Native.MagicLeapNativeBindings.InvalidHandle;
///
/// Lock used to keep api calls synchronous.
///
protected readonly object APILock = new object();
private static readonly bool requiresXRLoader = typeof(T).GetCustomAttribute() != null;
///
/// This is the only way to initialize this class.
///
sealed protected override void Initialize()
{
if (requiresXRLoader && !MLDevice.IsReady())
{
MLPluginLog.Error($"Magic Leap XR Loader is not initialized, and the {typeof(T).Name} API must be started afterwards.");
return;
}
else
{
Instance.StartInternal();
#if !UNITY_OPENXR_1_9_0_OR_NEWER
MagicLeapXrProviderNativeBindings.InputSetOnPerceptionShutdownCallback(OnPerceptionShutdown);
#endif
}
}
///
/// Indicates if the API has started successfully.
///
public static bool IsStarted { get; private set; } = false;
protected readonly string DllNotFoundError = $"Failed to start {typeof(T).Name} API. This API is only available on device or when running inside the Unity editor with Magic Leap App Simulator enabled.";
///
/// Do API-specific creation/initialization of ML resources for this API, such as
/// creating trackers, etc. Called automatically the first time Instance is accessed.
/// Error checking on the return value is performed in the base class.
///
protected abstract MLResult.Code StartAPI();
///
/// API-specific cleanup. Will be called whenever MLDevice is destroyed
/// (at the latest, when the application is shutting down).
/// Error checking on the return value is performed in the base class.
///
protected abstract MLResult.Code StopAPI();
///
/// Update function that will run once per Unity frame.
///
protected virtual void Update() { }
///
/// Callback sent to all MagicLeap APIs on application pause.
///
/// True if the application is paused, else False.
protected virtual void OnApplicationPause(bool pauseStatus) { }
///
/// Callback sent to all MagicLeap APIs on application focus event.
///
/// True if the application has focus, else False.
protected virtual void OnApplicationFocus(bool hasFocus) { }
///
/// Callback sent to all MagicLeap APIs when device enters standby mode.
///
protected virtual void OnDeviceStandby() { }
///
/// Callback sent to all MagicLeap APIs when device enters reality mode.
///
protected virtual void OnDeviceReality() { }
///
/// Callback sent to all MagicLeap APIs when device enters active mode.
///
protected virtual void OnDeviceActive() { }
[AOT.MonoPInvokeCallback(typeof(MagicLeapXrProviderNativeBindings.CallOnPerceptionShutdownDelegate))]
private static void OnPerceptionShutdown() => Instance.StopInternal();
private void StartInternal()
{
MLPluginLog.Debug($"Initializing {typeof(T).Name} API...");
if (MLResult.DidNativeCallSucceed(StartAPI(), $"{typeof(T).Name} Start"))
{
IsStarted = true;
MLDevice.RegisterUpdate(Instance.Update);
MLDevice.RegisterApplicationPause(Instance.OnApplicationPause);
MLDevice.RegisterApplicationFocus(Instance.OnApplicationFocus);
MLDevice.RegisterDestroy(Instance.StopInternal);
MLPluginLog.Debug($"{typeof(T).Name} API initialized.");
}
}
private void StopInternal()
{
if (IsStarted)
{
MLDevice.UnregisterUpdate(Instance.Update);
MLDevice.UnregisterApplicationPause(Instance.OnApplicationPause);
MLDevice.UnregisterApplicationFocus(Instance.OnApplicationFocus);
MLDevice.UnregisterDestroy(Instance.StopInternal);
MLResult.Code resultCode = Instance.StopAPI();
if (MLResult.DidNativeCallSucceed(resultCode, $"{typeof(T).Name} Stop"))
MLPluginLog.Debug($"{typeof(T).Name} API stopped successfully");
IsStarted = false;
}
}
}
}