initial commit

This commit is contained in:
Jo 2025-01-07 02:06:59 +01:00
parent 6715289efe
commit 788c3389af
37645 changed files with 2526849 additions and 80 deletions

View file

@ -0,0 +1,21 @@
#if UNITY_EDITOR
using UnityEditor;
namespace UnityEngine.XR.Management
{
/// <summary>
/// XRLoader interface for retrieving the XR PreInit library name from an XRLoader instance
/// </summary>
public interface IXRLoaderPreInit
{
/// <summary>
/// Get the library name, if any, to use for XR PreInit.
/// </summary>
///
/// <param name="buildTarget">An enum specifying which platform this build is for.</param>
/// <param name="buildTargetGroup">An enum specifying which platform group this build is for.</param>
/// <returns>A string specifying the library name used for XR PreInit.</returns>
string GetPreInitLibraryName(BuildTarget buildTarget, BuildTargetGroup buildTargetGroup);
}
}
#endif

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fdb1d409e9083354e829d5669fe6f6ad
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,19 @@
{
"name": "Unity.XR.Management",
"references": [],
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"versionDefines": [
{
"name": "com.unity.modules.unityanalytics",
"expression": "1.0.0",
"define": "UNITY_ANALYTICS"
}
],
"defineConstraints": []
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e40ba710768534012815d3193fa296cb
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,45 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEngine.XR.Management
{
/// <summary>
/// This attribute is used to tag classes as providing build settings support for an XR provider. The unified setting system
/// will present the settings as an inspectable object in the Unified Settings window using the built-in inspector UI.
///
/// The implementor of the settings is able to create their own custom UI and the Unified Settings system will use that UI in
/// place of the build in inspector. See the &lt;a href="https://docs.unity3d.com/Manual/ExtendingTheEditor.html">&gt;Extending the Editor&lt;/a&gt;
/// portion of the Unity documentation for information and instructions on doing this.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class XRConfigurationDataAttribute : Attribute
{
/// <summary>
/// The display name to be presented to the user in the Unified Settings window.
/// </summary>
public string displayName { get; set; }
/// <summary>
/// The key that will be used to store the singleton instance of these settings within EditorBuildSettings.
///
/// See &lt;a href="https://docs.unity3d.com/ScriptReference/EditorBuildSettings.html"&gt;EditorBuildSettings&lt;/a&gt; scripting
/// API documentation on how this is beign done.
/// </summary>
public string buildSettingsKey { get; set; }
private XRConfigurationDataAttribute() {}
/// <summary>Constructor for attribute</summary>
/// <param name="displayName">The display name to use in the Project Settings window.</param>
/// <param name="buildSettingsKey">The key to use to get/set build settings with.</param>
public XRConfigurationDataAttribute(string displayName, string buildSettingsKey)
{
this.displayName = displayName;
this.buildSettingsKey = buildSettingsKey;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4f9b2b17cfd02430b99d104616f45273
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,208 @@
using System;
using System.Collections;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.XR.Management
{
/// <summary>General settings container used to house the instance of the active settings as well as the manager
/// instance used to load the loaders with.
/// </summary>
public class XRGeneralSettings : ScriptableObject
{
/// <summary>The key used to query to get the current loader settings.</summary>
public static string k_SettingsKey = "com.unity.xr.management.loader_settings";
internal static XRGeneralSettings s_RuntimeSettingsInstance = null;
[SerializeField]
internal XRManagerSettings m_LoaderManagerInstance = null;
[SerializeField]
[Tooltip("Toggling this on/off will enable/disable the automatic startup of XR at run time.")]
internal bool m_InitManagerOnStart = true;
/// <summary>The current active manager used to manage XR lifetime.</summary>
public XRManagerSettings Manager
{
get { return m_LoaderManagerInstance; }
set { m_LoaderManagerInstance = value; }
}
private XRManagerSettings m_XRManager = null;
#pragma warning disable 414 // Suppress warning for needed variables.
private bool m_ProviderIntialized = false;
private bool m_ProviderStarted = false;
#pragma warning restore 414
/// <summary>The current settings instance.</summary>
public static XRGeneralSettings Instance
{
get
{
return s_RuntimeSettingsInstance;
}
#if UNITY_EDITOR
set
{
s_RuntimeSettingsInstance = value;
}
#endif
}
/// <summary>The current active manager used to manage XR lifetime.</summary>
public XRManagerSettings AssignedSettings
{
get
{
return m_LoaderManagerInstance;
}
#if UNITY_EDITOR
set
{
m_LoaderManagerInstance = value;
}
#endif
}
/// <summary>Used to set if the manager is activated and initialized on startup.</summary>
public bool InitManagerOnStart
{
get
{
return m_InitManagerOnStart;
}
#if UNITY_EDITOR
set
{
m_InitManagerOnStart = value;
}
#endif
}
#if !UNITY_EDITOR
void Awake()
{
Debug.Log("XRGeneral Settings awakening...");
s_RuntimeSettingsInstance = this;
Application.quitting += Quit;
DontDestroyOnLoad(s_RuntimeSettingsInstance);
}
#endif
#if UNITY_EDITOR
/// <summary>For internal use only.</summary>
[System.Obsolete("Deprecating internal only API.")]
public void InternalPauseStateChanged(PauseState state)
{
throw new NotImplementedException();
}
/// <summary>For internal use only.</summary>
public void InternalPlayModeStateChanged(PlayModeStateChange state)
{
switch (state)
{
case PlayModeStateChange.ExitingPlayMode:
Quit();
break;
case PlayModeStateChange.ExitingEditMode:
case PlayModeStateChange.EnteredPlayMode:
case PlayModeStateChange.EnteredEditMode:
break;
}
}
#endif
static void Quit()
{
XRGeneralSettings instance = XRGeneralSettings.Instance;
if (instance == null)
return;
instance.DeInitXRSDK();
}
void Start()
{
StartXRSDK();
}
void OnDestroy()
{
DeInitXRSDK();
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
internal static void AttemptInitializeXRSDKOnLoad()
{
XRGeneralSettings instance = XRGeneralSettings.Instance;
if (instance == null || !instance.InitManagerOnStart)
return;
instance.InitXRSDK();
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
internal static void AttemptStartXRSDKOnBeforeSplashScreen()
{
XRGeneralSettings instance = XRGeneralSettings.Instance;
if (instance == null || !instance.InitManagerOnStart)
return;
instance.StartXRSDK();
}
private void InitXRSDK()
{
if (XRGeneralSettings.Instance == null || XRGeneralSettings.Instance.m_LoaderManagerInstance == null || XRGeneralSettings.Instance.m_InitManagerOnStart == false)
return;
m_XRManager = XRGeneralSettings.Instance.m_LoaderManagerInstance;
if (m_XRManager == null)
{
Debug.LogError("Assigned GameObject for XR Management loading is invalid. No XR Providers will be automatically loaded.");
return;
}
m_XRManager.automaticLoading = false;
m_XRManager.automaticRunning = false;
m_XRManager.InitializeLoaderSync();
m_ProviderIntialized = true;
}
private void StartXRSDK()
{
if (m_XRManager != null && m_XRManager.activeLoader != null)
{
m_XRManager.StartSubsystems();
m_ProviderStarted = true;
}
}
private void StopXRSDK()
{
if (m_XRManager != null && m_XRManager.activeLoader != null)
{
m_XRManager.StopSubsystems();
m_ProviderStarted = false;
}
}
private void DeInitXRSDK()
{
if (m_XRManager != null && m_XRManager.activeLoader != null)
{
m_XRManager.DeinitializeLoader();
m_XRManager = null;
m_ProviderIntialized = false;
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d236b7d11115f2143951f1e14045df39
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,71 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEngine.XR.Management
{
/// <summary>
/// XR Loader abstract class used as a base class for specific provider implementations. Providers should implement
/// subclasses of this to provide specific initialization and management implementations that make sense for their supported
/// scenarios and needs.
/// </summary>
public abstract class XRLoader : ScriptableObject
{
/// <summary>
/// Initialize the loader. This should initialize all subsystems to support the desired runtime setup this
/// loader represents.
///
/// This is the only method on XRLoader that Management uses to determine the active loader to use. If this
/// method returns true, Management locks this loader as the <see cref="XRManagerSettings.activeLoader"/>
/// and and stops fall through processing on the <see cref="XRManagerSettings.loaders"/> list of current loaders.
///
/// If this method returns false, <see cref="XRManagerSettings"/> continues to process the next loader
/// in the <see cref="XRManagerSettings.loaders"/> list, or fails completely when the list is exhausted.
/// </summary>
///
/// <returns>Whether or not initialization succeeded.</returns>
public virtual bool Initialize() { return true; }
/// <summary>
/// Ask loader to start all initialized subsystems.
/// </summary>
///
/// <returns>Whether or not all subsystems were successfully started.</returns>
public virtual bool Start() { return true; }
/// <summary>
/// Ask loader to stop all initialized subsystems.
/// </summary>
///
/// <returns>Whether or not all subsystems were successfully stopped.</returns>
public virtual bool Stop() { return true; }
/// <summary>
/// Ask loader to deinitialize all initialized subsystems.
/// </summary>
///
/// <returns>Whether or not deinitialization succeeded.</returns>
public virtual bool Deinitialize() { return true; }
/// <summary>
/// Gets the loaded subsystem of the specified type. Implementation dependent as only implemetnations
/// know what they have loaded and how best to get it..
/// </summary>
///
/// <typeparam name="T">Type of the subsystem to get</typeparam>
///
/// <returns>The loaded subsystem or null if not found.</returns>
public abstract T GetLoadedSubsystem<T>() where T : class, ISubsystem;
/// <summary>
/// Gets the loader's supported graphics device types. If the list is empty, it is assumed that it supports all graphics device types.
/// </summary>
///
/// <param name="buildingPlayer">True if the player is being built. You may want to include or exclude graphics apis if the player is being built or not.</param>
/// <returns>Returns the loader's supported graphics device types.</returns>
public virtual List<GraphicsDeviceType> GetSupportedGraphicsDeviceTypes(bool buildingPlayer)
{
return new List<GraphicsDeviceType>();
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 61ff693bbf35149d684ae1e0be75e26f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 0eda7b875264842c7ac58d1267518728, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,192 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.XR;
namespace UnityEngine.XR.Management
{
/// <summary>
/// XR Loader abstract subclass used as a base class for specific provider implementations. Class provides some
/// helper logic that can be used to handle subsystem handling in a typesafe manner, reducing potential boilerplate
/// code.
/// </summary>
public abstract class XRLoaderHelper : XRLoader
{
/// <summary>
/// Map of loaded susbsystems. Used so we don't always have to fo to XRSubsystemManger and do a manual
/// search to find the instance we loaded.
/// </summary>
protected Dictionary<Type, ISubsystem> m_SubsystemInstanceMap = new Dictionary<Type, ISubsystem>();
/// <summary>
/// Gets the loaded subsystem of the specified type. Implementation dependent as only implemetnations
/// know what they have loaded and how best to get it..
/// </summary>
///
/// <typeparam name="T">Type of the subsystem to get.</typeparam>
///
/// <returns>The loaded subsystem or null if not found.</returns>
public override T GetLoadedSubsystem<T>()
{
Type subsystemType = typeof(T);
ISubsystem subsystem;
m_SubsystemInstanceMap.TryGetValue(subsystemType, out subsystem);
return subsystem as T;
}
/// <summary>
/// Start a subsystem instance of a given type. Subsystem assumed to already be loaded from
/// a previous call to CreateSubsystem
/// </summary>
///
/// <typeparam name="T">A subclass of <see cref="ISubsystem"/></typeparam>
protected void StartSubsystem<T>() where T : class, ISubsystem
{
T subsystem = GetLoadedSubsystem<T>();
if (subsystem != null)
subsystem.Start();
}
/// <summary>
/// Stop a subsystem instance of a given type. Subsystem assumed to already be loaded from
/// a previous call to CreateSubsystem
/// </summary>
///
/// <typeparam name="T">A subclass of <see cref="ISubsystem"/></typeparam>
protected void StopSubsystem<T>() where T : class, ISubsystem
{
T subsystem = GetLoadedSubsystem<T>();
if (subsystem != null)
subsystem.Stop();
}
/// <summary>
/// Destroy a subsystem instance of a given type. Subsystem assumed to already be loaded from
/// a previous call to CreateSubsystem
/// </summary>
///
/// <typeparam name="T">A subclass of <see cref="ISubsystem"/></typeparam>
protected void DestroySubsystem<T>() where T : class, ISubsystem
{
T subsystem = GetLoadedSubsystem<T>();
if (subsystem != null)
{
var subsystemType = typeof(T);
if (m_SubsystemInstanceMap.ContainsKey(subsystemType))
m_SubsystemInstanceMap.Remove(subsystemType);
subsystem.Destroy();
}
}
/// <summary>
/// Creates a subsystem given a list of descriptors and a specific subsystem id.
///
/// You should make sure to destroy any subsystem that you created so that resources
/// acquired by your subsystems are correctly cleaned up and released. This is especially important
/// if you create them during initialization, but initialization fails. If that happens,
/// you should clean up any subsystems created up to that point.
/// </summary>
///
/// <typeparam name="TDescriptor">The descriptor type being passed in.</typeparam>
/// <typeparam name="TSubsystem">The subsystem type being requested</typeparam>
/// <param name="descriptors">List of TDescriptor instances to use for subsystem matching.</param>
/// <param name="id">The identifier key of the particualr subsystem implementation being requested.</param>
protected void CreateSubsystem<TDescriptor, TSubsystem>(List<TDescriptor> descriptors, string id)
where TDescriptor : ISubsystemDescriptor
where TSubsystem : ISubsystem
{
if (descriptors == null)
throw new ArgumentNullException("descriptors");
SubsystemManager.GetSubsystemDescriptors<TDescriptor>(descriptors);
if (descriptors.Count > 0)
{
foreach (var descriptor in descriptors)
{
ISubsystem subsys = null;
if (String.Compare(descriptor.id, id, true) == 0)
{
subsys = descriptor.Create();
}
if (subsys != null)
{
m_SubsystemInstanceMap[typeof(TSubsystem)] = subsys;
break;
}
}
}
}
/// <summary>
/// Creates a native, integrated subsystem given a list of descriptors and a specific subsystem id.
/// DEPRECATED: Please use the geenric CreateSubsystem method. This method is soley retained for
/// backwards compatibility and will be removed in a future release.
/// </summary>
///
/// <typeparam name="TDescriptor">The descriptor type being passed in.</typeparam>
/// <typeparam name="TSubsystem">The subsystem type being requested</typeparam>
/// <param name="descriptors">List of TDescriptor instances to use for subsystem matching.</param>
/// <param name="id">The identifier key of the particualr subsystem implementation being requested.</param>
[Obsolete("This method is obsolete. Please use the geenric CreateSubsystem method.", false)]
protected void CreateIntegratedSubsystem<TDescriptor, TSubsystem>(List<TDescriptor> descriptors, string id)
where TDescriptor : IntegratedSubsystemDescriptor
where TSubsystem : IntegratedSubsystem
{
CreateSubsystem<TDescriptor, TSubsystem>(descriptors, id);
}
/// <summary>
/// Creates a managed, standalone subsystem given a list of descriptors and a specific subsystem id.
/// DEPRECATED: Please use the geenric CreateSubsystem method. This method is soley retained for
/// backwards compatibility and will be removed in a future release.
/// </summary>
///
/// <typeparam name="TDescriptor">The descriptor type being passed in.</typeparam>
/// <typeparam name="TSubsystem">The subsystem type being requested</typeparam>
/// <param name="descriptors">List of TDescriptor instances to use for subsystem matching.</param>
/// <param name="id">The identifier key of the particualr subsystem implementation being requested.</param>
[Obsolete("This method is obsolete. Please use the generic CreateSubsystem method.", false)]
protected void CreateStandaloneSubsystem<TDescriptor, TSubsystem>(List<TDescriptor> descriptors, string id)
where TDescriptor : SubsystemDescriptor
where TSubsystem : Subsystem
{
CreateSubsystem<TDescriptor, TSubsystem>(descriptors, id);
}
/// <summary>
/// Override of <see cref="XRLoader.Deinitialize"/> to provide for clearing the instance map.true
///
/// If you override this method in your subclass, you must call the base
/// implementation to allow the instance map tp be cleaned up correctly.
/// </summary>
///
/// <returns>True if de-initialization was successful.</returns>
public override bool Deinitialize()
{
m_SubsystemInstanceMap.Clear();
return base.Deinitialize();
}
#if UNITY_EDITOR
virtual public void WasAssignedToBuildTarget(BuildTargetGroup buildTargetGroup)
{
}
virtual public void WasUnassignedFromBuildTarget(BuildTargetGroup buildTargetGroup)
{
}
#endif
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8d28a628911c34c58a40cb9ef2ea4b31
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,89 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if UNITY_ANALYTICS && ENABLE_CLOUD_SERVICES_ANALYTICS
using UnityEngine.Analytics;
#endif //UNITY_ANALYTICS && ENABLE_CLOUD_SERVICES_ANALYTICS
[assembly:InternalsVisibleTo("Unity.XR.Management.Editor")]
namespace UnityEngine.XR.Management
{
internal static class XRManagementAnalytics
{
private const int kMaxEventsPerHour = 1000;
private const int kMaxNumberOfElements = 1000;
private const string kVendorKey = "unity.xrmanagement";
private const string kEventBuild = "xrmanagment_build";
#if ENABLE_CLOUD_SERVICES_ANALYTICS && UNITY_ANALYTICS
private static bool s_Initialized = false;
#endif //ENABLE_CLOUD_SERVICES_ANALYTICS && UNITY_ANALYTICS
[Serializable]
private struct BuildEvent
{
public string buildGuid;
public string buildTarget;
public string buildTargetGroup;
public string[] assigned_loaders;
}
private static bool Initialize()
{
#if ENABLE_TEST_SUPPORT || !ENABLE_CLOUD_SERVICES_ANALYTICS || !UNITY_ANALYTICS
return false;
#else
#if UNITY_EDITOR
if (!EditorAnalytics.enabled)
return false;
if(AnalyticsResult.Ok != EditorAnalytics.RegisterEventWithLimit(kEventBuild, kMaxEventsPerHour, kMaxNumberOfElements, kVendorKey))
return false;
s_Initialized = true;
#endif //UNITY_EDITOR
return s_Initialized;
#endif //ENABLE_TEST_SUPPORT || !ENABLE_CLOUD_SERVICES_ANALYTICS || !UNITY_ANALYTICS
}
#if UNITY_EDITOR
public static void SendBuildEvent(GUID guid, BuildTarget buildTarget, BuildTargetGroup buildTargetGroup, IEnumerable<XRLoader> loaders)
{
#if UNITY_ANALYTICS && ENABLE_CLOUD_SERVICES_ANALYTICS
if (!s_Initialized && !Initialize())
{
return;
}
List<string> loaderTypeNames = new List<string>();
foreach (var loader in loaders)
{
loaderTypeNames.Add(loader.GetType().Name);
}
var data = new BuildEvent
{
buildGuid = guid.ToString(),
buildTarget = buildTarget.ToString(),
buildTargetGroup = buildTargetGroup.ToString(),
assigned_loaders = loaderTypeNames.ToArray(),
};
EditorAnalytics.SendEventWithLimit(kEventBuild, data);
#endif //UNITY_ANALYTICS && ENABLE_CLOUD_SERVICES_ANALYTICS
}
#endif //UNITY_EDITOR
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a65c6d9b4fa97644c896e9382fe5226f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,497 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
using UnityEngine.Serialization;
using UnityEngine.XR.Management;
[assembly: InternalsVisibleTo("Unity.XR.Management.Tests")]
[assembly: InternalsVisibleTo("Unity.XR.Management.EditorTests")]
namespace UnityEngine.XR.Management
{
/// <summary>
/// Class to handle active loader and subsystem management for XR. This class is to be added as a
/// ScriptableObject asset in your project and should only be referenced by the <see cref="XRGeneralSettings"/>
/// instance for its use.
///
/// Given a list of loaders, it will attempt to load each loader in the given order. The first
/// loader that is successful wins and all remaining loaders are ignored. The loader
/// that succeeds is accessible through the <see cref="activeLoader"/> property on the manager.
///
/// Depending on configuration the <see cref="XRManagerSettings"/> instance will automatically manage the active loader
/// at correct points in the application lifecycle. The user can override certain points in the active loader lifecycle
/// and manually manage them by toggling the <see cref="automaticLoading"/> and <see cref="automaticRunning"/>
/// properties. Disabling <see cref="automaticLoading"/> implies the the user is responsible for the full lifecycle
/// of the XR session normally handled by the <see cref="XRManagerSettings"/> instance. Toggling this to false also toggles
/// <see cref="automaticRunning"/> false.
///
/// Disabling <see cref="automaticRunning"/> only implies that the user is responsible for starting and stopping
/// the <see cref="activeLoader"/> through the <see cref="StartSubsystems"/> and <see cref="StopSubsystems"/> APIs.
///
/// Automatic lifecycle management is executed as follows
///
/// * Runtime Initialize -> <see cref="InitializeLoader"/>. The loader list will be iterated over and the first successful loader will be set as the active loader.
/// * Start -> <see cref="StartSubsystems"/>. Ask the active loader to start all subsystems.
/// * OnDisable -> <see cref="StopSubsystems"/>. Ask the active loader to stop all subsystems.
/// * OnDestroy -> <see cref="DeinitializeLoader"/>. Deinitialize and remove the active loader.
/// </summary>
public sealed class XRManagerSettings : ScriptableObject
{
[HideInInspector]
bool m_InitializationComplete = false;
#pragma warning disable 414
// This property is only used by the scriptable object editing part of the system and as such no one
// directly references it. Have to manually disable the console warning here so that we can
// get a clean console report.
[HideInInspector]
[SerializeField]
bool m_RequiresSettingsUpdate = false;
#pragma warning restore 414
[SerializeField]
[Tooltip("Determines if the XR Manager instance is responsible for creating and destroying the appropriate loader instance.")]
[FormerlySerializedAs("AutomaticLoading")]
bool m_AutomaticLoading = false;
/// <summary>
/// Get and set Automatic Loading state for this manager. When this is true, the manager will automatically call
/// <see cref="InitializeLoader"/> and <see cref="DeinitializeLoader"/> for you. When false <see cref="automaticRunning"/>
/// is also set to false and remains that way. This means that disabling automatic loading disables all automatic behavior
/// for the manager.
/// </summary>
public bool automaticLoading
{
get { return m_AutomaticLoading; }
set { m_AutomaticLoading = value; }
}
[SerializeField]
[Tooltip("Determines if the XR Manager instance is responsible for starting and stopping subsystems for the active loader instance.")]
[FormerlySerializedAs("AutomaticRunning")]
bool m_AutomaticRunning = false;
/// <summary>
/// Get and set automatic running state for this manager. When set to true the manager will call <see cref="StartSubsystems"/>
/// and <see cref="StopSubsystems"/> APIs at appropriate times. When set to false, or when <see cref="automaticLoading"/> is false
/// then it is up to the user of the manager to handle that same functionality.
/// </summary>
public bool automaticRunning
{
get { return m_AutomaticRunning; }
set { m_AutomaticRunning = value; }
}
[SerializeField]
[Tooltip("List of XR Loader instances arranged in desired load order.")]
[FormerlySerializedAs("Loaders")]
List<XRLoader> m_Loaders = new List<XRLoader>();
// Maintains a list of registered loaders that is immutable at runtime.
[SerializeField]
[HideInInspector]
HashSet<XRLoader> m_RegisteredLoaders = new HashSet<XRLoader>();
/// <summary>
/// List of loaders currently managed by this XR Manager instance.
/// </summary>
/// <remarks>
/// Modifying the list of loaders at runtime is undefined behavior and could result in a crash or memory leak.
/// Use <see cref="activeLoaders"/> to retrieve the currently ordered list of loaders. If you need to mutate
/// the list at runtime, use <see cref="TryAddLoader"/>, <see cref="TryRemoveLoader"/>, and
/// <see cref="TrySetLoaders"/>.
/// </remarks>
[Obsolete("'XRManagerSettings.loaders' property is obsolete. Use 'XRManagerSettings.activeLoaders' instead to get a list of the current loaders.")]
public List<XRLoader> loaders
{
get { return m_Loaders; }
#if UNITY_EDITOR
set { m_Loaders = value; }
#endif
}
/// <summary>
/// A shallow copy of the list of loaders currently managed by this XR Manager instance.
/// </summary>
/// <remarks>
/// This property returns a read only list. Any changes made to the list itself will not affect the list
/// used by this XR Manager instance. To mutate the list of loaders currently managed by this instance,
/// use <see cref="TryAddLoader"/>, <see cref="TryRemoveLoader"/>, and/or <see cref="TrySetLoaders"/>.
/// </remarks>
public IReadOnlyList<XRLoader> activeLoaders => m_Loaders;
/// <summary>
/// Read only boolean letting us know if initialization is completed. Because initialization is
/// handled as a Coroutine, people taking advantage of the auto-lifecycle management of XRManager
/// will need to wait for init to complete before checking for an ActiveLoader and calling StartSubsystems.
/// </summary>
public bool isInitializationComplete
{
get { return m_InitializationComplete; }
}
///<summary>
/// Return the current singleton active loader instance.
///</summary>
[HideInInspector]
public XRLoader activeLoader { get; private set; }
/// <summary>
/// Return the current active loader, cast to the requested type. Useful shortcut when you need
/// to get the active loader as something less generic than XRLoader.
/// </summary>
///
/// <typeparam name="T">Requested type of the loader</typeparam>
///
/// <returns>The active loader as requested type, or null.</returns>
public T ActiveLoaderAs<T>() where T : XRLoader
{
return activeLoader as T;
}
/// <summary>
/// Iterate over the configured list of loaders and attempt to initialize each one. The first one
/// that succeeds is set as the active loader and initialization immediately terminates.
///
/// When complete <see cref="isInitializationComplete"/> will be set to true. This will mark that it is safe to
/// call other parts of the API. This does not guarantee that init successfully created a loader. For that
/// you need to check that ActiveLoader is not null.
///
/// Note that there can only be one active loader. Any attempt to initialize a new active loader with one
/// already set will cause a warning to be logged and immediate exit of this function.
///
/// This method is synchronous and on return all state should be immediately checkable.
///
/// <b>If manual initialization of XR is being done, this method can not be called before Start completes
/// as it depends on graphics initialization within Unity completing.</b>
/// </summary>
public void InitializeLoaderSync()
{
if (activeLoader != null)
{
Debug.LogWarning(
"XR Management has already initialized an active loader in this scene." +
" Please make sure to stop all subsystems and deinitialize the active loader before initializing a new one.");
return;
}
foreach (var loader in currentLoaders)
{
if (loader != null)
{
if (CheckGraphicsAPICompatibility(loader) && loader.Initialize())
{
activeLoader = loader;
m_InitializationComplete = true;
return;
}
}
}
activeLoader = null;
}
/// <summary>
/// Iterate over the configured list of loaders and attempt to initialize each one. The first one
/// that succeeds is set as the active loader and initialization immediately terminates.
///
/// When complete <see cref="isInitializationComplete"/> will be set to true. This will mark that it is safe to
/// call other parts of the API. This does not guarantee that init successfully created a loader. For that
/// you need to check that ActiveLoader is not null.
///
/// Note that there can only be one active loader. Any attempt to initialize a new active loader with one
/// already set will cause a warning to be logged and immediate exit of this function.
///
/// Iteration is done asynchronously and this method must be called within the context of a Coroutine.
///
/// <b>If manual initialization of XR is being done, this method can not be called before Start completes
/// as it depends on graphics initialization within Unity completing.</b>
/// </summary>
///
/// <returns>Enumerator marking the next spot to continue execution at.</returns>
public IEnumerator InitializeLoader()
{
if (activeLoader != null)
{
Debug.LogWarning(
"XR Management has already initialized an active loader in this scene." +
" Please make sure to stop all subsystems and deinitialize the active loader before initializing a new one.");
yield break;
}
foreach (var loader in currentLoaders)
{
if (loader != null)
{
if (CheckGraphicsAPICompatibility(loader) && loader.Initialize())
{
activeLoader = loader;
m_InitializationComplete = true;
yield break;
}
}
yield return null;
}
activeLoader = null;
}
/// <summary>
/// Attempts to append the given loader to the list of loaders at the given index.
/// </summary>
/// <param name="loader">
/// The <see cref="XRLoader"/> to be added to this manager's instance of loaders.
/// </param>
/// <param name="index">
/// The index at which the given <see cref="XRLoader"/> should be added. If you set a negative or otherwise
/// invalid index, the loader will be appended to the end of the list.
/// </param>
/// <returns>
/// <c>true</c> if the loader is not a duplicate and was added to the list successfully, <c>false</c>
/// otherwise.
/// </returns>
/// <remarks>
/// This method behaves differently in the Editor and during runtime/Play mode. While your app runs in the Editor and not in
/// Play mode, attempting to add an <see cref="XRLoader"/> will always succeed and register that loader's type
/// internally. Attempting to add a loader during runtime/Play mode will trigger a check to see whether a loader of
/// that type was registered. If the check is successful, the loader is added. If not, the loader is not added and the method
/// returns <c>false</c>.
/// </remarks>
public bool TryAddLoader(XRLoader loader, int index = -1)
{
if (loader == null || currentLoaders.Contains(loader))
return false;
#if UNITY_EDITOR
if (!EditorApplication.isPlaying && !m_RegisteredLoaders.Contains(loader))
m_RegisteredLoaders.Add(loader);
#endif
if (!m_RegisteredLoaders.Contains(loader))
return false;
if (index < 0 || index >= currentLoaders.Count)
currentLoaders.Add(loader);
else
currentLoaders.Insert(index, loader);
return true;
}
/// <summary>
/// Attempts to remove the first instance of a given loader from the list of loaders.
/// </summary>
/// <param name="loader">
/// The <see cref="XRLoader"/> to be removed from this manager's instance of loaders.
/// </param>
/// <returns>
/// <c>true</c> if the loader was successfully removed from the list, <c>false</c> otherwise.
/// </returns>
/// <remarks>
/// This method behaves differently in the Editor and during runtime/Play mode. During runtime/Play mode, the loader
/// will be removed with no additional side effects if it is in the list managed by this instance. While in the
/// Editor and not in Play mode, the loader will be removed if it exists and
/// it will be unregistered from this instance and any attempts to add it during
/// runtime/Play mode will fail. You can re-add the loader in the Editor while not in Play mode.
/// </remarks>
public bool TryRemoveLoader(XRLoader loader)
{
var removedLoader = true;
if (currentLoaders.Contains(loader))
removedLoader = currentLoaders.Remove(loader);
#if UNITY_EDITOR
if (!EditorApplication.isPlaying && !currentLoaders.Contains(loader))
m_RegisteredLoaders.Remove(loader);
#endif
return removedLoader;
}
/// <summary>
/// Attempts to set the given loader list as the list of loaders managed by this instance.
/// </summary>
/// <param name="reorderedLoaders">
/// The list of <see cref="XRLoader"/>s to be managed by this manager instance.
/// </param>
/// <returns>
/// <c>true</c> if the loader list was set successfully, <c>false</c> otherwise.
/// </returns>
/// <remarks>
/// This method behaves differently in the Editor and during runtime/Play mode. While in the Editor and not in
/// Play mode, any attempts to set the list of loaders will succeed without any additional checks. During
/// runtime/Play mode, the new loader list will be validated against the registered <see cref="XRLoader"/> types.
/// If any loaders exist in the list that were not registered at startup, the attempt will fail.
/// </remarks>
public bool TrySetLoaders(List<XRLoader> reorderedLoaders)
{
var originalLoaders = new List<XRLoader>(activeLoaders);
#if UNITY_EDITOR
if (!EditorApplication.isPlaying)
{
registeredLoaders.Clear();
currentLoaders.Clear();
foreach (var loader in reorderedLoaders)
{
if (!TryAddLoader(loader))
{
TrySetLoaders(originalLoaders);
return false;
}
}
return true;
}
#endif
currentLoaders.Clear();
foreach (var loader in reorderedLoaders)
{
if (!TryAddLoader(loader))
{
currentLoaders = originalLoaders;
return false;
}
}
return true;
}
private bool CheckGraphicsAPICompatibility(XRLoader loader)
{
GraphicsDeviceType deviceType = SystemInfo.graphicsDeviceType;
List<GraphicsDeviceType> supportedDeviceTypes = loader.GetSupportedGraphicsDeviceTypes(false);
// To help with backward compatibility, if the compatibility list is empty we assume that it does not implement the GetSupportedGraphicsDeviceTypes method
// Therefore we revert to the previous behavior of building or starting the loader regardless of gfx api settings.
if (supportedDeviceTypes.Count > 0 && !supportedDeviceTypes.Contains(deviceType))
{
Debug.LogWarning(String.Format("The {0} does not support the initialized graphics device, {1}. Please change the preffered Graphics API in PlayerSettings. Attempting to start the next XR loader.", loader.name, deviceType.ToString()));
return false;
}
return true;
}
/// <summary>
/// If there is an active loader, this will request the loader to start all the subsystems that it
/// is managing.
///
/// You must wait for <see cref="isInitializationComplete"/> to be set to true prior to calling this API.
/// </summary>
public void StartSubsystems()
{
if (!m_InitializationComplete)
{
Debug.LogWarning(
"Call to StartSubsystems without an initialized manager." +
"Please make sure wait for initialization to complete before calling this API.");
return;
}
if (activeLoader != null)
{
activeLoader.Start();
}
}
/// <summary>
/// If there is an active loader, this will request the loader to stop all the subsystems that it
/// is managing.
///
/// You must wait for <see cref="isInitializationComplete"/> to be set to tru prior to calling this API.
/// </summary>
public void StopSubsystems()
{
if (!m_InitializationComplete)
{
Debug.LogWarning(
"Call to StopSubsystems without an initialized manager." +
"Please make sure wait for initialization to complete before calling this API.");
return;
}
if (activeLoader != null)
{
activeLoader.Stop();
}
}
/// <summary>
/// If there is an active loader, this function will deinitialize it and remove the active loader instance from
/// management. We will automatically call <see cref="StopSubsystems"/> prior to deinitialization to make sure
/// that things are cleaned up appropriately.
///
/// You must wait for <see cref="isInitializationComplete"/> to be set to tru prior to calling this API.
///
/// Upon return <see cref="isInitializationComplete"/> will be rest to false;
/// </summary>
public void DeinitializeLoader()
{
if (!m_InitializationComplete)
{
Debug.LogWarning(
"Call to DeinitializeLoader without an initialized manager." +
"Please make sure wait for initialization to complete before calling this API.");
return;
}
StopSubsystems();
if (activeLoader != null)
{
activeLoader.Deinitialize();
activeLoader = null;
}
m_InitializationComplete = false;
}
// Use this for initialization
void Start()
{
if (automaticLoading && automaticRunning)
{
StartSubsystems();
}
}
void OnDisable()
{
if (automaticLoading && automaticRunning)
{
StopSubsystems();
}
}
void OnDestroy()
{
if (automaticLoading)
{
DeinitializeLoader();
}
}
// To modify the list of loaders internally use `currentLoaders` as it will return a list reference rather
// than a shallow copy.
// TODO @davidmo 10/12/2020: remove this in next major version bump and make 'loaders' internal.
internal List<XRLoader> currentLoaders
{
get { return m_Loaders; }
set { m_Loaders = value; }
}
// To modify the set of registered loaders use `registeredLoaders` as it will return a reference to the
// hashset of loaders.
internal HashSet<XRLoader> registeredLoaders
{
get { return m_RegisteredLoaders; }
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f4c3631f5e58749a59194e0cf6baf6d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: