using System;
using System.Runtime.InteropServices;
using UnityEngine.Assertions;
using UnityEngine.XR.Management;
using UnityEngine.XR.OpenXR.Features.Mock;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.XR.OpenXR;
using UnityEditor.XR.OpenXR.Features;
#endif
namespace UnityEngine.XR.OpenXR.TestTooling
{
///
/// Sets up and manages a mock XR environment used for testing,
/// using the OpenXR Mock Runtime feature.
///
///
///
/// Use this class for testing low-level OpenXR features, such as OpenXR-based loaders,
/// performing calls to the Mock Runtime, or testing lifecycle events.
///
///
/// Note that only one MockOpenXREnvironment instance should be created and started at a time, otherwise settings and resources may conflict.
///
///
public class MockOpenXREnvironment : IDisposable
{
bool m_MockRuntimeIsRunning = false;
#if UNITY_EDITOR && OPENXR_USE_KHRONOS_LOADER
private const string k_RuntimeJsonEnvKey = "XR_RUNTIME_JSON";
private string m_BackupXRRuntimeJsonPath = null;
#endif
///
/// Resources and settings used by this environment to run the Mock Runtime.
///
///
/// Use this object to add or remove features and extensions to be used by the environment.
///
public readonly MockOpenXREnvironmentSettings Settings;
static bool AnyLoaderIsRunning => OpenXRLoaderBase.Instance != null;
MockOpenXREnvironment(MockOpenXREnvironmentSettings settings)
{
Settings = settings;
}
///
/// Builds a new MockOpenXREnvironment instance and sets it up for testing.
///
///
///
/// This method stops any running loader instances and initializes the Mock Runtime, to make a clean and stable environment for running.
///
///
/// The method runs automatically if the environment is built with a statement or declaration.
///
///
/// When calling this method while running the tests in the Editor, any open Project Settings window will be closed
/// to avoid changes in the settings, which may result in the settings files receiving unitnended changes
/// and tests failing.
///
///
///
///
/// Example of creating a new environment for testing with a statement:
///
///
///
///
///
/// A new instance.
public static MockOpenXREnvironment CreateEnvironment()
{
if (AnyLoaderIsRunning)
{
StopSubsystems();
DeinitializeLoader();
}
// Prevents settings being edited while the tests are running in Editor.
if (!Application.isBatchMode)
{
CloseProjectSettingsWindow();
}
var settings = new MockOpenXREnvironmentSettings();
var newMockRuntimeEnvironment = new MockOpenXREnvironment(settings);
MockRuntime.Instance.AddTestHookGetInstanceProcAddr(InstallMockRuntimeFunctionInterceptor);
return newMockRuntimeEnvironment;
}
///
/// Tears down the environment and its resources.
///
///
/// This method stops the Mock Runtime and disposes of the environment settings.
/// After calling this method, the environment object is in a disposed state and can't be used anymore.
///
public void Dispose()
{
if (m_MockRuntimeIsRunning)
{
Stop();
}
MockRuntime.Instance.ClearTestHookGetInstanceProcAddr();
Settings.Dispose();
NativeApi.Cleanup();
}
///
/// Starts the Mock Runtime and initializes the XR subsystems for testing.
///
///
/// The method does nothing if the environment has been disposed.
///
/// If the Mock Runtime is already running, the method calls
/// before restarting and reinitializing it.
///
public void Start()
{
if (m_MockRuntimeIsRunning)
{
Stop();
}
PrepareBeforeTest();
InitializeLoader();
StartSubsystems();
m_MockRuntimeIsRunning = true;
}
///
/// Stops the Mock Runtime and deinitializes the XR subsystems.
///
///
/// The method does nothing if the environment has been disposed.
///
public void Stop()
{
if (m_MockRuntimeIsRunning)
{
StopSubsystems();
DeinitializeLoader();
AfterTest();
m_MockRuntimeIsRunning = false;
}
}
///
/// Adds an extension to the set of underlying mock runtime extensions that are provided by the runtime
/// when the OpenXR xrEnumerateInstanceExtensionProperties() call is made.
/// Throws an 'InvalidOperationException' if this is called while the MockOpenXREnvironment is running.
/// NOTE: Any added mocked extension will *not* work when writing tests which rely on the generic Khronos
/// loader for the mock runtime when executing on device.
///
/// The name of the extension to add.
/// For example 'XR_FB_spatial_entity'.
/// The version number of the extension to mock, usually defined in openxr.h
/// For example, XR_FB_spatial_entity_SPEC_VERSION.
public void AddSupportedExtension(string extensionName, uint extensionVersion)
{
if (m_MockRuntimeIsRunning)
throw new InvalidOperationException("Call AddSupportedExtension() prior to calling Start() on the MockOpenXREnvironment.");
NativeApi.AddSupportedExtension(extensionName, extensionVersion);
}
///
/// Passes a mocked C# function that to the native Mock Runtime for handling the retrieval of system properties
/// for an extension-specific/type-specific system properties structure.
///
/// An OpenXR structure type ID which identifies the actual structure definition type.
///
/// A pointer to a C# mock function capable of modifying the typed system properties structure.
/// Note: if IntPtr.Zero is passed, then that means to disregard usage of a mock function for the provided type.
///
public void SetSysPropertiesFunctionForXrStructureType(uint type, IntPtr function) =>
NativeApi.SetSysPropertiesFunctionForXrStructureType(type, function);
///
/// Binds a C# mock function to a function name that corresponds with an extension-specific and
/// platform-specific function.
///
/// The name of the OpenXR function to bind to the mock function.
/// The C# mock function to call for the function name. Use null to remove it.
public void SetFunctionForInterceptor(string methodName, IntPtr function) =>
NativeApi.SetFunctionForInterceptor(methodName, function);
///
/// Places a mocked C# event structure converted to a marshaled native pointer into
/// the mock runtime's event queue that will be polled through xrPollEvent.
///
/// The marshaled event structure data.
public void EnqueueMockEventData(IntPtr eventData) =>
NativeApi.EnqueueMockEventData(eventData);
///
/// Processes events on the event queue by virtue of calling xrPollEvent until the event
/// queue is empty
///
public void ProcessEventQueue() =>
NativeApi.ProcessEventQueue();
static IntPtr InstallMockRuntimeFunctionInterceptor(IntPtr oldGetProcAddrFunc) =>
NativeApi.InstallGetInstanceProcAddrInterceptor(oldGetProcAddrFunc);
static class NativeApi
{
const string k_MockApiNativeLibName = "mock_api";
const string k_OpenXrNativeLibName = "UnityOpenXR";
///
/// Cleans up the underlying native current instance of the test fixture.
///
[DllImport(k_MockApiNativeLibName, EntryPoint = "MockRuntimeTestApi_Cleanup")]
internal static extern void Cleanup();
///
/// Installs the native mock function interceptor for allowing C# mock functions to serve as
/// real OpenXR functions that are extension-specific/platform-specific.
///
/// The function to retain and call in the xrGetInstanceProcAddr call chain.
///
[DllImport(k_MockApiNativeLibName, EntryPoint = "MockRuntimeTestApi_InstallGetInstanceProcAddrInterceptor")]
internal static extern IntPtr InstallGetInstanceProcAddrInterceptor(IntPtr oldFunc);
///
/// Adds an extension to the set of underlying mock runtime extensions that are provided by the runtime
/// when the OpenXR xrEnumerateInstanceExtensionProperties() call is made.
///
/// The name of the extension to add.
/// For example 'XR_FB_spatial_entity'.
/// The version number of the extension to mock, usually defined in openxr.h
/// For example, XR_FB_spatial_entity_SPEC_VERSION.
[DllImport(k_MockApiNativeLibName, EntryPoint = "MockRuntimeTestApi_AddSupportedExtension")]
internal static extern void AddSupportedExtension(string extensionName, uint extensionVersion);
///
/// Passes a mocked C# function that to the native Mock Runtime for handling the retrieval of system properties
/// for an extension-specific/type-specific system properties structure.
///
/// An OpenXR structure type ID which identifies the actual structure definition type.
///
/// A pointer to a C# mock function capable of modifying the typed system properties structure.
/// Note: if IntPtr.Zero is passed, then that means to disregard usage of a mock function for the provided type.
///
[DllImport(k_MockApiNativeLibName, EntryPoint = "MockRuntimeTestApi_SetSysPropertiesFunctionForXrStructureType")]
internal static extern void SetSysPropertiesFunctionForXrStructureType(uint type, IntPtr function);
///
/// Binds a C# mock function to a function name that corresponds with an extension-specific and
/// platform-specific function.
///
/// The name of the OpenXR function to bind to the mock function.
/// The C# mock function to call for the function name. Use null to remove it.
[DllImport(k_MockApiNativeLibName, EntryPoint = "MockRuntimeTestApi_SetFunctionForInterceptor")]
internal static extern void SetFunctionForInterceptor(string methodName, IntPtr function);
///
/// Places a mocked C# event structure converted to a marshaled native pointer into
/// the mock runtime's event queue that will be polled through xrPollEvent.
///
/// The marshaled event structure data.
[DllImport(k_MockApiNativeLibName, EntryPoint = "MockRuntimeTestApi_EnqueueMockEventData")]
internal static extern void EnqueueMockEventData(IntPtr eventData);
///
/// Processes events on the event queue by virtue of calling xrPollEvent until the event
/// queue is empty
///
[DllImport(k_OpenXrNativeLibName, EntryPoint = "messagepump_PumpMessageLoop")]
internal static extern void ProcessEventQueue();
}
static bool SetMockRuntimeEnabled(bool enable)
{
var feature = MockRuntime.Instance;
if (null == feature)
return false;
if (feature.enabled == enable)
return true;
feature.enabled = enable;
if (enable)
{
feature.priority = 0;
feature.required = false;
feature.ignoreValidationErrors = true;
MockRuntime.ResetDefaults();
}
return true;
}
void PrepareBeforeTest()
{
// Enable the mock runtime and reset it back to default state
Assert.IsTrue(SetMockRuntimeEnabled(true));
#if UNITY_INCLUDE_TESTS
OpenXRRuntime.ClearEvents();
#endif
OpenXRRestarter.Instance.ResetCallbacks();
#if UNITY_EDITOR && OPENXR_USE_KHRONOS_LOADER
var features = FeatureHelpersInternal.GetAllFeatureInfo(BuildTargetGroup.Standalone);
foreach (var f in features.Features)
{
if (String.Compare(f.Feature.featureIdInternal, MockRuntime.featureId, true) == 0)
{
m_BackupXRRuntimeJsonPath = Environment.GetEnvironmentVariable(k_RuntimeJsonEnvKey);
var path = System.IO.Path.GetFullPath(f.PluginPath + "/unity-mock-runtime.json");
Environment.SetEnvironmentVariable(k_RuntimeJsonEnvKey, path);
}
}
#endif
}
static void InitializeLoader()
{
if (TryGetXRManagerSettings(out var manager))
{
manager.InitializeLoaderSync();
}
}
static void StartSubsystems()
{
if (TryGetXRManagerSettings(out var manager) && manager.activeLoader != null)
{
manager.StartSubsystems();
}
}
static void StopSubsystems()
{
if (TryGetXRManagerSettings(out var manager) && manager.activeLoader != null)
{
manager.StopSubsystems();
}
}
static void DeinitializeLoader()
{
if (TryGetXRManagerSettings(out var manager) && manager.activeLoader != null)
{
manager.DeinitializeLoader();
}
}
static bool TryGetXRManagerSettings(out XRManagerSettings settings)
{
settings = XRGeneralSettings.Instance != null ? XRGeneralSettings.Instance.Manager : null;
return settings != null;
}
void AfterTest()
{
OpenXRRestarter.Instance.ResetCallbacks();
#if UNITY_INCLUDE_TESTS
MockRuntime.Instance.TestCallback = (methodName, param) => true;
MockRuntime.KeepFunctionCallbacks = false;
#endif
MockRuntime.ClearFunctionCallbacks();
#if UNITY_EDITOR && OPENXR_USE_KHRONOS_LOADER
if (m_BackupXRRuntimeJsonPath != null)
{
Environment.SetEnvironmentVariable(k_RuntimeJsonEnvKey, m_BackupXRRuntimeJsonPath);
m_BackupXRRuntimeJsonPath = null;
}
#endif
}
static void CloseProjectSettingsWindow()
{
#if UNITY_EDITOR
var windowTypes = TypeCache.GetTypesDerivedFrom(typeof(EditorWindow));
foreach (var wt in windowTypes)
{
if (wt.Name.Contains("ProjectSettingsWindow"))
{
var projectSettingsWindow = EditorWindow.GetWindow(wt);
if (projectSettingsWindow != null)
{
Debug.Log($"{nameof(MockOpenXREnvironment)} is closing the Project Settings window to run tests.");
projectSettingsWindow.Close();
}
}
}
#endif
}
}
}