Decompiled source of MIMESIS VR v0.1.51

Mods/MimesisVR.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Bifrost.Cooked;
using HarmonyLib;
using MelonLoader;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using Mimic;
using Mimic.Actors;
using Mimic.Animation;
using Mimic.InputSystem;
using ReluProtocol;
using TMPro;
using Unity.Collections;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityVRMod;
using UnityVRMod.Cfg;
using UnityVRMod.Config;
using UnityVRMod.Core;
using UnityVRMod.Features.Debug;
using UnityVRMod.Features.Shared;
using UnityVRMod.Features.Util;
using UnityVRMod.Features.VRVisualization.OpenXR;
using UnityVRMod.Features.VrVisualization;
using UnityVRMod.Loader;
using UnityVRMod.Loader.ML;
using UnityVRMod.Mimesis;
using UniverseLib;
using UniverseLib.Config;
using UniverseLib.Input;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Unity VR Mod")]
[assembly: AssemblyDescription("Universal VR Mod with some extra functionality for visualization")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("New Unity Modder")]
[assembly: AssemblyProduct("Unity VR Mod")]
[assembly: AssemblyCopyright("Copyright (C) 2025 NewUnityModder")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("7CBC39BC-3F69-42B4-BA3D-18ED937BA3E3")]
[assembly: AssemblyFileVersion("0.1.51")]
[assembly: MelonInfo(typeof(VRModMelon), "MIMESIS VR", "0.1.51", "Palmmass", null)]
[assembly: MelonGame("ReLUGames", "MIMESIS")]
[assembly: MelonPriority(-100)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.51.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace UnityVRMod
{
	public class VRModMelon : MelonMod, IVRModLoader
	{
		private FileConfigHandler _configHandler;

		public static VRModMelon Instance { get; private set; }

		public string InteropAssembliesPath => Path.Combine(MelonEnvironment.GameRootDirectory, "MelonLoader", "Il2CppAssemblies");

		public ConfigHandler ConfigHandler => _configHandler;

		public Action<object> LogMessage => delegate(object o)
		{
			((MelonBase)this).LoggerInstance.Msg(o?.ToString());
		};

		public Action<object> LogWarning => delegate(object o)
		{
			((MelonBase)this).LoggerInstance.Warning(o?.ToString());
		};

		public Action<object> LogError => delegate(object o)
		{
			((MelonBase)this).LoggerInstance.Error(o?.ToString());
		};

		public override void OnInitializeMelon()
		{
			Instance = this;
			string text = Path.Combine(MelonEnvironment.UserDataDirectory, "MimesisVR");
			Directory.CreateDirectory(text);
			MvrPaths.LoaderName = "MelonLoader";
			MvrPaths.ConfigDir = text;
			MvrPaths.DataDir = text;
			MvrPaths.NativeDir = FindNativeDir(text);
			TakeOverBepInExSettings(text);
			_configHandler = new FileConfigHandler(Path.Combine(text, "com.newunitymodder.unityvrmod.cfg"));
			VRModCore.Init(this);
		}

		private string FindNativeDir(string data)
		{
			List<string> list = new List<string> { Path.Combine(data, "Native") };
			try
			{
				string[] directories = Directory.GetDirectories(MelonEnvironment.UserDataDirectory);
				foreach (string path in directories)
				{
					list.Add(Path.Combine(path, "MimesisVR", "Native"));
					list.Add(Path.Combine(path, "Native"));
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("UserData scan: " + ex.Message);
			}
			try
			{
				string directoryName = Path.GetDirectoryName(typeof(VRModMelon).Assembly.Location);
				if (!string.IsNullOrEmpty(directoryName))
				{
					list.Add(directoryName);
					list.Add(Path.Combine(directoryName, "Native"));
					list.Add(Path.Combine(Path.GetDirectoryName(directoryName) ?? directoryName, "Native"));
				}
			}
			catch
			{
			}
			foreach (string item in list)
			{
				try
				{
					if (File.Exists(Path.Combine(item, "openxr_loader.dll")))
					{
						if (item != list[0])
						{
							((MelonBase)this).LoggerInstance.Msg("Native files found in " + item);
						}
						return item;
					}
				}
				catch
				{
				}
			}
			((MelonBase)this).LoggerInstance.Warning("Native files (openxr_loader.dll etc.) not found - expected in " + list[0] + ". VR will not start.");
			return list[0];
		}

		private void TakeOverBepInExSettings(string data)
		{
			string path = Path.Combine(MelonEnvironment.GameRootDirectory, "BepInEx", "config");
			string[] array = new string[3] { "MimesisVR.cfg", "com.newunitymodder.unityvrmod.cfg", "Unity VR Mod.Internal.cfg" };
			foreach (string text in array)
			{
				try
				{
					string text2 = Path.Combine(path, text);
					string text3 = Path.Combine(data, text);
					if (!File.Exists(text3) && File.Exists(text2))
					{
						File.Copy(text2, text3);
						((MelonBase)this).LoggerInstance.Msg("Settings taken over from BepInEx: " + text);
					}
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning("Settings " + text + " not taken over: " + ex.Message);
				}
			}
		}
	}
}
namespace UnityVRMod.Features.Shared
{
	public static class SharedVrApi
	{
		private static class NativeMethods
		{
			[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
			internal static extern IntPtr GetModuleHandle(string lpModuleName);
		}

		private static bool _nativeVrChecked;

		private static bool _isNativeOpenXr;

		private static bool _isNativeOpenVr;

		public static Camera GetCurrentVrCamera()
		{
			if (ConfigManager.EnableVrInjection.Value)
			{
				VrVisualizationManager vrVisualizationFeature = VRModCore.VrVisualizationFeature;
				if (vrVisualizationFeature != null)
				{
					Camera vrCameraForUIParenting = vrVisualizationFeature.VrCameraForUIParenting;
					if ((Object)(object)vrCameraForUIParenting != (Object)null)
					{
						return vrCameraForUIParenting;
					}
				}
				VRModCore.LogError("EnableVrInjection is true, but the VR Visualization Feature is not available or has no active camera. This may indicate a mod initialization failure.", null, "GetCurrentVrCamera", "MimesisVR/Features/Shared/SharedVrApi.cs", 40);
				return null;
			}
			Camera val = FindCameraByOverride();
			if ((Object)(object)val != (Object)null)
			{
				VRModCore.LogRuntimeDebug("Found native VR camera via AssertedCameraOverrides: '" + ((Object)val).name + "'", "GetCurrentVrCamera", "MimesisVR/Features/Shared/SharedVrApi.cs", 49);
				return val;
			}
			if (!_nativeVrChecked)
			{
				_isNativeOpenXr = NativeMethods.GetModuleHandle("openxr_loader.dll") != IntPtr.Zero;
				_isNativeOpenVr = NativeMethods.GetModuleHandle("openvr_api.dll") != IntPtr.Zero;
				_nativeVrChecked = true;
				if (_isNativeOpenXr || _isNativeOpenVr)
				{
					VRModCore.LogRuntimeDebug($"Native VR check complete: OpenXR active = {_isNativeOpenXr}, OpenVR active = {_isNativeOpenVr}", "GetCurrentVrCamera", "MimesisVR/Features/Shared/SharedVrApi.cs", 60);
				}
			}
			if (_isNativeOpenXr || _isNativeOpenVr)
			{
				Camera main = Camera.main;
				if ((Object)(object)main != (Object)null && ((Behaviour)main).enabled && IsLikelyVrCamera(main))
				{
					VRModCore.LogRuntimeDebug("Found likely native VR camera via Camera.main.", "GetCurrentVrCamera", "MimesisVR/Features/Shared/SharedVrApi.cs", 69);
					return main;
				}
				Camera[] allCameras = Camera.allCameras;
				foreach (Camera val2 in allCameras)
				{
					if ((Object)(object)val2 != (Object)null && ((Behaviour)val2).enabled && IsLikelyVrCamera(val2))
					{
						VRModCore.LogRuntimeDebug("Found likely native VR camera via heuristic search: '" + ((Object)val2).name + "'.", "GetCurrentVrCamera", "MimesisVR/Features/Shared/SharedVrApi.cs", 78);
						return val2;
					}
				}
			}
			return null;
		}

		private static Camera FindCameraByOverride()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			List<CameraIdentifier> list = CameraIdentifierHelper.Parse(ConfigManager.AssertedCameraOverrides.Value);
			if (list.Count == 0)
			{
				return null;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			string name = ((Scene)(ref activeScene)).name;
			foreach (CameraIdentifier item in list)
			{
				if (!string.IsNullOrEmpty(item.Scene) && !item.Scene.Equals(name, StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				GameObject val = GameObject.Find(item.Path);
				if ((Object)(object)val != (Object)null)
				{
					Camera component = val.GetComponent<Camera>();
					if ((Object)(object)component != (Object)null && ((Behaviour)component).enabled)
					{
						return component;
					}
				}
			}
			return null;
		}

		private static bool IsLikelyVrCamera(Camera cam)
		{
			if ((Object)(object)((Component)cam).GetComponent("UnityEngine.XR.TrackedPoseDriver") != (Object)null)
			{
				return true;
			}
			string text = ((Object)cam).name.ToLowerInvariant();
			Transform parent = ((Component)cam).transform.parent;
			string text2 = ((parent != null) ? ((Object)parent).name.ToLowerInvariant() : null) ?? "";
			string[] array = new string[6] { "vr", "head", "hmd", "stereo", "eye", "ovr" };
			foreach (string value in array)
			{
				if (text.Contains(value) || text2.Contains(value))
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace UnityVRMod.Features.Debug
{
	internal static class TemporaryLiveReloadTester
	{
		private static readonly List<IConfigElement> _reloadableSettings = new List<IConfigElement>();

		private static int _selectedSettingIndex = -1;

		private static string _displayMessage = "";

		private static float _messageClearTime = 0f;

		private const KeyCode NEXT_SETTING_KEY = (KeyCode)281;

		private const KeyCode PREV_SETTING_KEY = (KeyCode)280;

		private const KeyCode INCREMENT_KEY = (KeyCode)270;

		private const KeyCode DECREMENT_KEY = (KeyCode)269;

		private const KeyCode TOGGLE_BOOL_KEY = (KeyCode)271;

		private const KeyCode TEST_API_KEY = (KeyCode)291;

		private const float FLOAT_STEP = 0.1f;

		private const int INT_STEP = 1;

		public static void Initialize()
		{
			_reloadableSettings.Clear();
			VRModCore.Log("Initializing and scanning for reloadable settings...", "Initialize", "MimesisVR/Features/Debug/TemporaryLiveReloadTester.cs", 30);
			if (ConfigManager.ConfigElements != null && ConfigManager.ConfigElements.Count > 0)
			{
				foreach (KeyValuePair<string, IConfigElement> configElement in ConfigManager.ConfigElements)
				{
					IConfigElement value = configElement.Value;
					if (value.ElementType != typeof(KeyCode) && !value.IsInternal && (value.ElementType == typeof(float) || value.ElementType == typeof(int) || value.ElementType == typeof(bool) || value.ElementType.IsEnum))
					{
						_reloadableSettings.Add(value);
						VRModCore.LogRuntimeDebug("Added '" + value.Name + "' (Type: " + value.ElementType.Name + ") to testable list.", "Initialize", "MimesisVR/Features/Debug/TemporaryLiveReloadTester.cs", 45);
					}
				}
			}
			_reloadableSettings.Sort((IConfigElement a, IConfigElement b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
			_selectedSettingIndex = ((_reloadableSettings.Count <= 0) ? (-1) : 0);
			if (_selectedSettingIndex != -1)
			{
				DisplaySelectedSetting();
			}
			else
			{
				VRModCore.Log("No suitable non-internal, non-KeyCode settings found to test with inc/dec/toggle.", "Initialize", "MimesisVR/Features/Debug/TemporaryLiveReloadTester.cs", 60);
			}
		}

		public static void Update()
		{
			if (Time.time > _messageClearTime && !string.IsNullOrEmpty(_displayMessage))
			{
				_displayMessage = "";
				if (_selectedSettingIndex != -1)
				{
					DisplaySelectedSetting();
				}
			}
			if (InputManager.GetKeyDown((KeyCode)291))
			{
				TestSharedVrApi();
			}
			else if (_selectedSettingIndex != -1 && _reloadableSettings.Count != 0)
			{
				IConfigElement configElement = _reloadableSettings[_selectedSettingIndex];
				if (InputManager.GetKeyDown((KeyCode)281))
				{
					_selectedSettingIndex = (_selectedSettingIndex + 1) % _reloadableSettings.Count;
					DisplaySelectedSetting();
				}
				else if (InputManager.GetKeyDown((KeyCode)280))
				{
					_selectedSettingIndex = (_selectedSettingIndex - 1 + _reloadableSettings.Count) % _reloadableSettings.Count;
					DisplaySelectedSetting();
				}
				else if (InputManager.GetKeyDown((KeyCode)270))
				{
					ModifyValue(configElement, increment: true);
					DisplaySelectedSetting();
				}
				else if (InputManager.GetKeyDown((KeyCode)269))
				{
					ModifyValue(configElement, increment: false);
					DisplaySelectedSetting();
				}
				else if (InputManager.GetKeyDown((KeyCode)271) && configElement.ElementType == typeof(bool))
				{
					ConfigElement<bool> configElement2 = (ConfigElement<bool>)configElement;
					configElement2.Value = !configElement2.Value;
					SetDisplayMessage($"Toggled [{configElement.Name}] to {configElement2.Value}");
					DisplaySelectedSetting();
				}
			}
		}

		private static void TestSharedVrApi()
		{
			VRModCore.Log("--- Running SharedVrApi.GetCurrentVrCamera() Test ---", "TestSharedVrApi", "MimesisVR/Features/Debug/TemporaryLiveReloadTester.cs", 117);
			Camera currentVrCamera = SharedVrApi.GetCurrentVrCamera();
			if ((Object)(object)currentVrCamera != (Object)null)
			{
				SetDisplayMessage("SUCCESS: Found VR Camera: '" + ((Object)currentVrCamera).name + "'");
			}
			else
			{
				SetDisplayMessage("FAILURE: GetCurrentVrCamera() returned NULL.");
			}
			VRModCore.Log("--- Test Complete ---", "TestSharedVrApi", "MimesisVR/Features/Debug/TemporaryLiveReloadTester.cs", 127);
		}

		private static void ModifyValue(IConfigElement element, bool increment)
		{
			if (element.ElementType == typeof(float))
			{
				ConfigElement<float> configElement = (ConfigElement<float>)element;
				float num = configElement.Value + (increment ? 0.1f : (-0.1f));
				configElement.Value = (float)Math.Round(num, 4);
				SetDisplayMessage($"Adjusted [{element.Name}] to {configElement.Value}");
			}
			else if (element.ElementType == typeof(int))
			{
				ConfigElement<int> configElement2 = (ConfigElement<int>)element;
				configElement2.Value += (increment ? 1 : (-1));
				SetDisplayMessage($"Adjusted [{element.Name}] to {configElement2.Value}");
			}
			else if (element.ElementType.IsEnum)
			{
				Array values = Enum.GetValues(element.ElementType);
				int num2 = Array.IndexOf(values, element.BoxedValue) + (increment ? 1 : (-1));
				if (num2 >= values.Length)
				{
					num2 = 0;
				}
				if (num2 < 0)
				{
					num2 = values.Length - 1;
				}
				element.BoxedValue = values.GetValue(num2);
				SetDisplayMessage($"Set [{element.Name}] to {element.BoxedValue}");
			}
		}

		private static void SetDisplayMessage(string message, float duration = 2f)
		{
			_displayMessage = message;
			VRModCore.Log(message ?? "", "SetDisplayMessage", "MimesisVR/Features/Debug/TemporaryLiveReloadTester.cs", 160);
			_messageClearTime = Time.time + duration;
		}

		private static void DisplaySelectedSetting()
		{
			if (_selectedSettingIndex != -1)
			{
				IConfigElement configElement = _reloadableSettings[_selectedSettingIndex];
				string arg = (configElement.ElementType.IsEnum ? "Enum" : configElement.ElementType.Name);
				SetDisplayMessage($"Selected: [{configElement.Name}] (Type: {arg}, Current: {configElement.BoxedValue}) | +/- or Enter (for bool)");
			}
		}
	}
}
namespace UnityVRMod.Features.VRVisualization.OpenXR
{
	internal static class NativeBridge
	{
		private const string NativeHelperDll = "UnityGraphicsHelper";

		[DllImport("UnityGraphicsHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "DirectCopyResource")]
		public static extern void DirectCopyResource_Internal(IntPtr pDest, IntPtr pSrc);

		[DllImport("UnityGraphicsHelper", CallingConvention = CallingConvention.Cdecl)]
		public static extern void SetDevicePointerFromCSharp(IntPtr d3d11DevicePtr);

		[DllImport("UnityGraphicsHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "CreateAndRegisterSRV")]
		public static extern int CreateAndRegisterSRV_Internal(IntPtr pTextureResource, int srvFormatDXGI, out IntPtr ppSRV);

		[DllImport("UnityGraphicsHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ReleaseNativeObject")]
		public static extern void ReleaseNativeObject_Internal(IntPtr pObject);

		[DllImport("UnityGraphicsHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetD3D11Device")]
		private static extern IntPtr GetCachedD3D11Device_Internal();

		[DllImport("UnityGraphicsHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetDeviceFromResource")]
		private static extern IntPtr GetDeviceFromResource_Internal(IntPtr pResource);

		public static IntPtr GetD3D11DevicePointer(Texture textureForFallback)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			if ((int)SystemInfo.graphicsDeviceType != 2)
			{
				VRModCore.LogWarning("Graphics device is not Direct3D 11.", "GetD3D11DevicePointer", "MimesisVR/Features/VRVisualization/OpenXR/NativeBridge.cs", 32);
				return IntPtr.Zero;
			}
			try
			{
				IntPtr cachedD3D11Device_Internal = GetCachedD3D11Device_Internal();
				if (cachedD3D11Device_Internal != IntPtr.Zero)
				{
					return cachedD3D11Device_Internal;
				}
			}
			catch
			{
			}
			if ((Object)(object)textureForFallback == (Object)null)
			{
				return IntPtr.Zero;
			}
			try
			{
				IntPtr nativeTexturePtr = textureForFallback.GetNativeTexturePtr();
				if (nativeTexturePtr == IntPtr.Zero)
				{
					return IntPtr.Zero;
				}
				return GetDeviceFromResource_Internal(nativeTexturePtr);
			}
			catch
			{
			}
			return IntPtr.Zero;
		}
	}
	public enum XrResult
	{
		XR_SUCCESS = 0,
		XR_TIMEOUT_EXPIRED = 1,
		XR_SESSION_LOSS_PENDING = 3,
		XR_EVENT_UNAVAILABLE = 4,
		XR_SPACE_BOUNDS_UNAVAILABLE = 7,
		XR_SESSION_NOT_FOCUSED = 8,
		XR_FRAME_DISCARDED = 9,
		XR_ERROR_VALIDATION_FAILURE = -1,
		XR_ERROR_RUNTIME_FAILURE = -2,
		XR_ERROR_OUT_OF_MEMORY = -3,
		XR_ERROR_API_VERSION_UNSUPPORTED = -4,
		XR_ERROR_INITIALIZATION_FAILED = -6,
		XR_ERROR_FUNCTION_UNSUPPORTED = -7,
		XR_ERROR_FEATURE_UNSUPPORTED = -8,
		XR_ERROR_EXTENSION_NOT_PRESENT = -9,
		XR_ERROR_LIMIT_REACHED = -10,
		XR_ERROR_SIZE_INSUFFICIENT = -11,
		XR_ERROR_HANDLE_INVALID = -12,
		XR_ERROR_INSTANCE_LOST = -13,
		XR_ERROR_SESSION_RUNNING = -14,
		XR_ERROR_SESSION_NOT_RUNNING = -16,
		XR_ERROR_SESSION_LOST = -17,
		XR_ERROR_SYSTEM_INVALID = -18,
		XR_ERROR_PATH_INVALID = -19,
		XR_ERROR_PATH_COUNT_EXCEEDED = -20,
		XR_ERROR_PATH_FORMAT_INVALID = -21,
		XR_ERROR_PATH_UNSUPPORTED = -22,
		XR_ERROR_LAYER_INVALID = -23,
		XR_ERROR_LAYER_LIMIT_EXCEEDED = -24,
		XR_ERROR_SWAPCHAIN_RECT_INVALID = -25,
		XR_ERROR_SWAPCHAIN_FORMAT_UNSUPPORTED = -26,
		XR_ERROR_ACTION_TYPE_MISMATCH = -27,
		XR_ERROR_SESSION_NOT_READY = -28,
		XR_ERROR_SESSION_NOT_STOPPING = -29,
		XR_ERROR_TIME_INVALID = -30,
		XR_ERROR_REFERENCE_SPACE_UNSUPPORTED = -31,
		XR_ERROR_FILE_ACCESS_ERROR = -32,
		XR_ERROR_FILE_CONTENTS_INVALID = -33,
		XR_ERROR_FORM_FACTOR_UNSUPPORTED = -34,
		XR_ERROR_FORM_FACTOR_UNAVAILABLE = -35,
		XR_ERROR_API_LAYER_NOT_PRESENT = -36,
		XR_ERROR_CALL_ORDER_INVALID = -37,
		XR_ERROR_GRAPHICS_DEVICE_INVALID = -38,
		XR_ERROR_POSE_INVALID = -39,
		XR_ERROR_INDEX_OUT_OF_RANGE = -40,
		XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED = -41,
		XR_ERROR_ENVIRONMENT_BLEND_MODE_UNSUPPORTED = -42,
		XR_ERROR_NAME_DUPLICATED = -44,
		XR_ERROR_NAME_INVALID = -45,
		XR_ERROR_ACTIONSET_NOT_ATTACHED = -46,
		XR_ERROR_ACTIONSETS_ALREADY_ATTACHED = -47,
		XR_ERROR_LOCALIZED_NAME_DUPLICATED = -48,
		XR_ERROR_LOCALIZED_NAME_INVALID = -49,
		XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING = -50,
		XR_ERROR_RUNTIME_UNAVAILABLE = -51,
		XR_ERROR_EXTENSION_DEPENDENCY_NOT_ENABLED = -1000710001,
		XR_ERROR_PERMISSION_INSUFFICIENT = -1000710000
	}
	public enum XrStructureType
	{
		XR_TYPE_UNKNOWN = 0,
		XR_TYPE_API_LAYER_PROPERTIES = 1,
		XR_TYPE_EXTENSION_PROPERTIES = 2,
		XR_TYPE_INSTANCE_CREATE_INFO = 3,
		XR_TYPE_SYSTEM_GET_INFO = 4,
		XR_TYPE_SYSTEM_PROPERTIES = 5,
		XR_TYPE_VIEW_LOCATE_INFO = 6,
		XR_TYPE_VIEW = 7,
		XR_TYPE_SESSION_CREATE_INFO = 8,
		XR_TYPE_SWAPCHAIN_CREATE_INFO = 9,
		XR_TYPE_SESSION_BEGIN_INFO = 10,
		XR_TYPE_VIEW_STATE = 11,
		XR_TYPE_FRAME_END_INFO = 12,
		XR_TYPE_EVENT_DATA_BUFFER = 16,
		XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING = 17,
		XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED = 18,
		XR_TYPE_FRAME_WAIT_INFO = 33,
		XR_TYPE_COMPOSITION_LAYER_PROJECTION = 35,
		XR_TYPE_REFERENCE_SPACE_CREATE_INFO = 37,
		XR_TYPE_FRAME_STATE = 44,
		XR_TYPE_FRAME_BEGIN_INFO = 46,
		XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW = 48,
		XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO = 55,
		XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO = 56,
		XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO = 57,
		XR_TYPE_VIEW_CONFIGURATION_VIEW = 41,
		XR_TYPE_GRAPHICS_BINDING_D3D11_KHR = 1000027000,
		XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR = 1000027001,
		XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR = 1000027002
	}
	public enum XrFormFactor
	{
		XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY = 1
	}
	public enum XrEnvironmentBlendMode
	{
		XR_ENVIRONMENT_BLEND_MODE_OPAQUE = 1,
		XR_ENVIRONMENT_BLEND_MODE_ADDITIVE,
		XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND
	}
	public enum D3D_FEATURE_LEVEL
	{
		D3D_FEATURE_LEVEL_11_0 = 45056,
		D3D_FEATURE_LEVEL_11_1 = 45312
	}
	public enum XrViewConfigurationType
	{
		XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO = 2
	}
	public enum XrSessionState
	{
		XR_SESSION_STATE_UNKNOWN,
		XR_SESSION_STATE_IDLE,
		XR_SESSION_STATE_READY,
		XR_SESSION_STATE_SYNCHRONIZED,
		XR_SESSION_STATE_VISIBLE,
		XR_SESSION_STATE_FOCUSED,
		XR_SESSION_STATE_STOPPING,
		XR_SESSION_STATE_LOSS_PENDING,
		XR_SESSION_STATE_EXITING
	}
	public enum XrReferenceSpaceType
	{
		XR_REFERENCE_SPACE_TYPE_VIEW = 1,
		XR_REFERENCE_SPACE_TYPE_LOCAL,
		XR_REFERENCE_SPACE_TYPE_STAGE
	}
	[Flags]
	public enum XrSwapchainCreateFlags : ulong
	{
		None = 0uL
	}
	[Flags]
	public enum XrSwapchainUsageFlags : ulong
	{
		XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT = 1uL,
		XR_SWAPCHAIN_USAGE_SAMPLED_BIT = 0x20uL
	}
	[Flags]
	public enum XrViewStateFlags : ulong
	{
		XR_VIEW_STATE_ORIENTATION_VALID_BIT = 1uL,
		XR_VIEW_STATE_POSITION_VALID_BIT = 2uL
	}
	[Flags]
	public enum XrCompositionLayerFlags : ulong
	{
		None = 0uL
	}
	public static class OpenXRConstants
	{
		public const ulong XR_NULL_HANDLE = 0uL;

		public const ulong XR_NULL_SYSTEM_ID = 0uL;

		public const long XR_INFINITE_DURATION = long.MaxValue;

		public const int XR_MAX_APPLICATION_NAME_SIZE = 128;

		public const int XR_MAX_ENGINE_NAME_SIZE = 128;

		public const int XR_MAX_SYSTEM_NAME_SIZE = 256;

		public const int XR_MAX_EXTENSION_NAME_SIZE = 128;

		public static ulong XR_API_VERSION_1_1 = 281474976710656uL;

		public const string XR_KHR_D3D11_ENABLE_EXTENSION_NAME = "XR_KHR_D3D11_enable";
	}
	public static class XrBool32
	{
		public const uint XR_FALSE = 0u;

		public const uint XR_TRUE = 1u;
	}
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetInstanceProcAddr(ulong instance, [MarshalAs(UnmanagedType.LPStr)] string name, out IntPtr function);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEnumerateInstanceExtensionProperties(string layerName, uint propertyCapacityInput, out uint propertyCountOutput, IntPtr properties);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateInstance(in XrInstanceCreateInfo createInfo, out ulong instance);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrDestroyInstance(ulong instance);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetSystem(ulong instance, in XrSystemGetInfo getInfo, out ulong systemId);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetSystemProperties(ulong instance, ulong systemId, ref XrSystemProperties properties);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetD3D11GraphicsRequirementsKHR(ulong instance, ulong systemId, out XrGraphicsRequirementsD3D11KHR graphicsRequirements);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateSession(ulong instance, in XrSessionCreateInfo createInfo, out ulong session);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrDestroySession(ulong session);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrWaitFrame(ulong session, in XrFrameWaitInfo frameWaitInfo, out XrFrameState frameState);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrBeginFrame(ulong session, in XrFrameBeginInfo frameBeginInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEndFrame(ulong session, in XrFrameEndInfo frameEndInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrBeginSession(ulong session, in XrSessionBeginInfo beginInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrPollEvent(ulong instance, IntPtr eventDataBuffer);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEnumerateViewConfigurations(ulong instance, ulong systemId, uint viewConfigurationTypeCapacityInput, out uint viewConfigurationTypeCountOutput, IntPtr viewConfigurationTypes);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEnumerateViewConfigurationViews(ulong instance, ulong systemId, XrViewConfigurationType viewConfigurationType, uint viewCapacityInput, out uint viewCountOutput, IntPtr views);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEnumerateSwapchainFormats(ulong session, uint formatCapacityInput, out uint formatCountOutput, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] long[] formats);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateSwapchain(ulong session, in XrSwapchainCreateInfo createInfo, out ulong swapchain);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrDestroySwapchain(ulong swapchain);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEnumerateSwapchainImages(ulong swapchain, uint imageCapacityInput, out uint imageCountOutput, IntPtr imagesBuffer);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrLocateViews(ulong session, in XrViewLocateInfo viewLocateInfo, out XrViewState viewState, uint viewCapacityInput, out uint viewCountOutput, IntPtr viewsBuffer);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateReferenceSpace(ulong session, in XrReferenceSpaceCreateInfo createInfo, out ulong space);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrDestroySpace(ulong space);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrAcquireSwapchainImage(ulong swapchain, in XrSwapchainImageAcquireInfo acquireInfo, out uint index);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrWaitSwapchainImage(ulong swapchain, in XrSwapchainImageWaitInfo waitInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrReleaseSwapchainImage(ulong swapchain, in XrSwapchainImageReleaseInfo releaseInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrEndSession(ulong session);
	public static class OpenXRNativeLoader
	{
		private static class Kernel32NativeMethods
		{
			[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
			public static extern IntPtr LoadLibrary(string lpFileName);

			[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
			public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

			[DllImport("kernel32.dll", SetLastError = true)]
			public static extern bool FreeLibrary(IntPtr hModule);
		}

		private static IntPtr openxrLibHandle = IntPtr.Zero;

		public static PFN_xrGetInstanceProcAddr xrGetInstanceProcAddr_ptr_delegate;

		public static bool LoadOpenXRLibrary()
		{
			if (openxrLibHandle != IntPtr.Zero)
			{
				return true;
			}
			try
			{
				string obj = ((!string.IsNullOrEmpty(MvrPaths.NativeDir)) ? MvrPaths.NativeDir : Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
				if (string.IsNullOrEmpty(obj))
				{
					throw new Exception("Failed to get mod assembly directory.");
				}
				string text = Path.Combine(obj, "openxr_loader.dll");
				if (!File.Exists(text))
				{
					throw new FileNotFoundException("openxr_loader.dll not found in mod directory.", text);
				}
				openxrLibHandle = Kernel32NativeMethods.LoadLibrary(text);
				if (openxrLibHandle == IntPtr.Zero)
				{
					throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to load openxr_loader.dll.");
				}
				IntPtr procAddress = Kernel32NativeMethods.GetProcAddress(openxrLibHandle, "xrGetInstanceProcAddr");
				if (procAddress == IntPtr.Zero)
				{
					throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to get address of xrGetInstanceProcAddr.");
				}
				xrGetInstanceProcAddr_ptr_delegate = Marshal.GetDelegateForFunctionPointer<PFN_xrGetInstanceProcAddr>(procAddress);
				return true;
			}
			catch (Exception exception)
			{
				VRModCore.LogError("Exception during OpenXR library loading:", exception, "LoadOpenXRLibrary", "MimesisVR/Features/VRVisualization/OpenXR/OpenXR.cs", 201);
				FreeOpenXRLibrary();
				return false;
			}
		}

		public static void FreeOpenXRLibrary()
		{
			if (openxrLibHandle != IntPtr.Zero)
			{
				Kernel32NativeMethods.FreeLibrary(openxrLibHandle);
				openxrLibHandle = IntPtr.Zero;
				xrGetInstanceProcAddr_ptr_delegate = null;
			}
		}
	}
	public static class OpenXRAPI
	{
		private static PFN_xrGetInstanceProcAddr xrGetInstanceProcAddr_func_ptr;

		public static PFN_xrCreateInstance xrCreateInstance;

		public static PFN_xrDestroyInstance xrDestroyInstance;

		public static PFN_xrGetSystem xrGetSystem;

		public static PFN_xrGetD3D11GraphicsRequirementsKHR xrGetD3D11GraphicsRequirementsKHR;

		public static PFN_xrCreateSession xrCreateSession;

		public static PFN_xrDestroySession xrDestroySession;

		public static PFN_xrWaitFrame xrWaitFrame;

		public static PFN_xrBeginFrame xrBeginFrame;

		public static PFN_xrEndFrame xrEndFrame;

		public static PFN_xrBeginSession xrBeginSession;

		public static PFN_xrPollEvent xrPollEvent;

		public static PFN_xrEnumerateViewConfigurations xrEnumerateViewConfigurations;

		public static PFN_xrEnumerateViewConfigurationViews xrEnumerateViewConfigurationViews;

		public static PFN_xrEnumerateSwapchainFormats xrEnumerateSwapchainFormats;

		public static PFN_xrCreateSwapchain xrCreateSwapchain;

		public static PFN_xrDestroySwapchain xrDestroySwapchain;

		public static PFN_xrEnumerateSwapchainImages xrEnumerateSwapchainImages;

		public static PFN_xrLocateViews xrLocateViews;

		public static PFN_xrCreateReferenceSpace xrCreateReferenceSpace;

		public static PFN_xrDestroySpace xrDestroySpace;

		public static PFN_xrAcquireSwapchainImage xrAcquireSwapchainImage;

		public static PFN_xrWaitSwapchainImage xrWaitSwapchainImage;

		public static PFN_xrReleaseSwapchainImage xrReleaseSwapchainImage;

		public static PFN_xrEndSession xrEndSession;

		public static bool InitializeCoreFunctions(PFN_xrGetInstanceProcAddr getInstanceProcAddrEntry)
		{
			xrGetInstanceProcAddr_func_ptr = getInstanceProcAddrEntry ?? throw new ArgumentNullException("getInstanceProcAddrEntry");
			xrCreateInstance = GetXrFunction<PFN_xrCreateInstance>(0uL, xrGetInstanceProcAddr_func_ptr);
			return true;
		}

		public static bool InitializeInstanceFunctions(ulong instanceHandle)
		{
			if (instanceHandle == 0L || xrGetInstanceProcAddr_func_ptr == null)
			{
				return false;
			}
			try
			{
				xrDestroyInstance = GetXrFunction<PFN_xrDestroyInstance>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrGetSystem = GetXrFunction<PFN_xrGetSystem>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrGetD3D11GraphicsRequirementsKHR = GetXrFunction<PFN_xrGetD3D11GraphicsRequirementsKHR>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrCreateSession = GetXrFunction<PFN_xrCreateSession>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrDestroySession = GetXrFunction<PFN_xrDestroySession>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrWaitFrame = GetXrFunction<PFN_xrWaitFrame>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrBeginFrame = GetXrFunction<PFN_xrBeginFrame>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrEndFrame = GetXrFunction<PFN_xrEndFrame>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrBeginSession = GetXrFunction<PFN_xrBeginSession>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrPollEvent = GetXrFunction<PFN_xrPollEvent>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrEnumerateViewConfigurations = GetXrFunction<PFN_xrEnumerateViewConfigurations>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrEnumerateViewConfigurationViews = GetXrFunction<PFN_xrEnumerateViewConfigurationViews>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrEnumerateSwapchainFormats = GetXrFunction<PFN_xrEnumerateSwapchainFormats>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrCreateSwapchain = GetXrFunction<PFN_xrCreateSwapchain>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrDestroySwapchain = GetXrFunction<PFN_xrDestroySwapchain>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrEnumerateSwapchainImages = GetXrFunction<PFN_xrEnumerateSwapchainImages>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrLocateViews = GetXrFunction<PFN_xrLocateViews>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrCreateReferenceSpace = GetXrFunction<PFN_xrCreateReferenceSpace>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrDestroySpace = GetXrFunction<PFN_xrDestroySpace>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrAcquireSwapchainImage = GetXrFunction<PFN_xrAcquireSwapchainImage>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrWaitSwapchainImage = GetXrFunction<PFN_xrWaitSwapchainImage>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrReleaseSwapchainImage = GetXrFunction<PFN_xrReleaseSwapchainImage>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				xrEndSession = GetXrFunction<PFN_xrEndSession>(instanceHandle, xrGetInstanceProcAddr_func_ptr);
				return true;
			}
			catch (Exception exception)
			{
				VRModCore.LogError("Error initializing instance-specific OpenXR functions:", exception, "InitializeInstanceFunctions", "MimesisVR/Features/VRVisualization/OpenXR/OpenXR.cs", 287);
				return false;
			}
		}

		private static TDelegate GetXrFunction<TDelegate>(ulong instanceHandle, PFN_xrGetInstanceProcAddr getInstanceProcAddrFunc) where TDelegate : Delegate
		{
			string text = typeof(TDelegate).Name.Substring("PFN_".Length);
			IntPtr function;
			XrResult xrResult = getInstanceProcAddrFunc(instanceHandle, text, out function);
			if (xrResult != XrResult.XR_SUCCESS || function == IntPtr.Zero)
			{
				throw new EntryPointNotFoundException($"Failed to load OpenXR function '{text}'. Result: {xrResult}");
			}
			return Marshal.GetDelegateForFunctionPointer<TDelegate>(function);
		}
	}
	public static class OpenXRHelper
	{
		public static void CheckResult(XrResult result, string originatingFunction, bool throwOnError = true)
		{
			if (result < XrResult.XR_SUCCESS)
			{
				VRModCore.LogError($"OpenXR Error: Function '{originatingFunction}' failed with result: {result} ({(int)result})", null, "CheckResult", "MimesisVR/Features/VRVisualization/OpenXR/OpenXR.cs", 311);
				if (throwOnError)
				{
					throw new OpenXRException(result, originatingFunction);
				}
			}
		}

		public static bool CheckResultAndLog(XrResult result, string originatingFunction, string context, bool throwOnError)
		{
			if (result >= XrResult.XR_SUCCESS)
			{
				if (result != XrResult.XR_SUCCESS)
				{
					VRModCore.LogRuntimeDebug($"OpenXR Info ({context}): Function '{originatingFunction}' completed with status: {result}", "CheckResultAndLog", "MimesisVR/Features/VRVisualization/OpenXR/OpenXR.cs", 321);
				}
				return true;
			}
			VRModCore.LogError($"OpenXR Error ({context}): Function '{originatingFunction}' failed with result: {result}", null, "CheckResultAndLog", "MimesisVR/Features/VRVisualization/OpenXR/OpenXR.cs", 327);
			if (throwOnError)
			{
				throw new OpenXRException(result, context + " - " + originatingFunction);
			}
			return false;
		}
	}
	public class OpenXRException : Exception
	{
		public XrResult ResultCode { get; private set; }

		public OpenXRException(XrResult result, string message)
		{
			ResultCode = result;
			base..ctor($"OpenXR Error in {message}: {result} ({(int)result})");
		}
	}
	public struct XrApplicationInfo
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string applicationName;

		public uint applicationVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string engineName;

		public uint engineVersion;

		public ulong apiVersion;
	}
	public struct XrExtensionProperties
	{
		public XrStructureType type;

		public IntPtr next;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string extensionName;

		public uint extensionVersion;
	}
	public struct XrInstanceCreateInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public ulong createFlags;

		public XrApplicationInfo applicationInfo;

		public uint enabledApiLayerCount;

		public IntPtr enabledApiLayerNames;

		public uint enabledExtensionCount;

		public IntPtr enabledExtensionNames;
	}
	public struct XrSystemGetInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public XrFormFactor formFactor;
	}
	public struct XrSystemGraphicsProperties
	{
		public uint maxSwapchainImageHeight;

		public uint maxSwapchainImageWidth;

		public uint maxLayerCount;
	}
	public struct XrSystemTrackingProperties
	{
		public uint orientationTracking;

		public uint positionTracking;
	}
	public struct XrSystemProperties
	{
		public XrStructureType type;

		public IntPtr next;

		public ulong systemId;

		public uint vendorId;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
		public byte[] systemName;

		public XrSystemGraphicsProperties graphicsProperties;

		public XrSystemTrackingProperties trackingProperties;
	}
	public struct LUID
	{
		public uint LowPart;

		public int HighPart;
	}
	public struct XrGraphicsRequirementsD3D11KHR
	{
		public XrStructureType type;

		public IntPtr next;

		public LUID adapterLuid;

		public D3D_FEATURE_LEVEL minFeatureLevel;
	}
	public struct XrGraphicsBindingD3D11KHR
	{
		public XrStructureType type;

		public IntPtr next;

		public IntPtr device;
	}
	public struct XrSessionCreateInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public ulong createFlags;

		public ulong systemId;
	}
	public struct XrFrameWaitInfo
	{
		public XrStructureType type;

		public IntPtr next;
	}
	public struct XrFrameBeginInfo
	{
		public XrStructureType type;

		public IntPtr next;
	}
	public struct XrSessionBeginInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public XrViewConfigurationType primaryViewConfigurationType;
	}
	public struct XrEventDataBaseHeader
	{
		public XrStructureType type;

		public IntPtr next;
	}
	public struct XrEventDataSessionStateChanged
	{
		public XrStructureType type;

		public IntPtr next;

		public ulong session;

		public XrSessionState state;

		public long time;
	}
	public struct XrFrameState
	{
		public XrStructureType type;

		public IntPtr next;

		public long predictedDisplayTime;

		public long predictedDisplayPeriod;

		public uint shouldRender;
	}
	public struct XrViewConfigurationView
	{
		public XrStructureType type;

		public IntPtr next;

		public uint recommendedImageRectWidth;

		public uint maxImageRectWidth;

		public uint recommendedImageRectHeight;

		public uint maxImageRectHeight;

		public uint recommendedSwapchainSampleCount;

		public uint maxSwapchainSampleCount;
	}
	public struct XrSwapchainCreateInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public XrSwapchainCreateFlags createFlags;

		public XrSwapchainUsageFlags usageFlags;

		public long format;

		public uint sampleCount;

		public uint width;

		public uint height;

		public uint faceCount;

		public uint arraySize;

		public uint mipCount;
	}
	public struct XrSwapchainImageD3D11KHR
	{
		public XrStructureType type;

		public IntPtr next;

		public IntPtr texture;
	}
	public struct XrViewLocateInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public XrViewConfigurationType viewConfigurationType;

		public long displayTime;

		public ulong space;
	}
	public struct XrViewState
	{
		public XrStructureType type;

		public IntPtr next;

		public XrViewStateFlags viewStateFlags;
	}
	public struct XrFovf
	{
		public float angleLeft;

		public float angleRight;

		public float angleUp;

		public float angleDown;
	}
	public struct XrQuaternionf
	{
		public float x;

		public float y;

		public float z;

		public float w;
	}
	public struct XrVector3f
	{
		public float x;

		public float y;

		public float z;
	}
	public struct XrPosef
	{
		public XrQuaternionf orientation;

		public XrVector3f position;
	}
	public struct XrView
	{
		public XrStructureType type;

		public IntPtr next;

		public XrPosef pose;

		public XrFovf fov;
	}
	public struct XrReferenceSpaceCreateInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public XrReferenceSpaceType referenceSpaceType;

		public XrPosef poseInReferenceSpace;
	}
	public struct XrOffset2Di
	{
		public int x;

		public int y;
	}
	public struct XrExtent2Di
	{
		public int width;

		public int height;
	}
	public struct XrRect2Di
	{
		public XrOffset2Di offset;

		public XrExtent2Di extent;
	}
	public struct XrSwapchainSubImage
	{
		public ulong swapchain;

		public XrRect2Di imageRect;

		public uint imageArrayIndex;
	}
	public struct XrCompositionLayerProjectionView
	{
		public XrStructureType type;

		public IntPtr next;

		public XrPosef pose;

		public XrFovf fov;

		public XrSwapchainSubImage subImage;
	}
	public struct XrCompositionLayerProjection
	{
		public XrStructureType type;

		public IntPtr next;

		public XrCompositionLayerFlags layerFlags;

		public ulong space;

		public uint viewCount;

		public IntPtr views;
	}
	public struct XrFrameEndInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public long displayTime;

		public XrEnvironmentBlendMode environmentBlendMode;

		public uint layerCount;

		public IntPtr layers;
	}
	public struct XrSwapchainImageAcquireInfo
	{
		public XrStructureType type;

		public IntPtr next;
	}
	public struct XrSwapchainImageWaitInfo
	{
		public XrStructureType type;

		public IntPtr next;

		public long timeout;
	}
	public struct XrSwapchainImageReleaseInfo
	{
		public XrStructureType type;

		public IntPtr next;
	}
	public struct XrEventDataBuffer
	{
		public XrStructureType type;

		public IntPtr next;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4000)]
		public byte[] varying;

		public static int GetSize()
		{
			return Marshal.SizeOf(typeof(XrEventDataBuffer));
		}
	}
	public static class MarshallStringUtils
	{
		public static IntPtr MarshalStringArrayToAnsi(string[] strings)
		{
			if (strings == null || strings.Length == 0)
			{
				return IntPtr.Zero;
			}
			IntPtr[] array = new IntPtr[strings.Length];
			IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<IntPtr>() * strings.Length);
			try
			{
				for (int i = 0; i < strings.Length; i++)
				{
					byte[] bytes = Encoding.UTF8.GetBytes(strings[i] + "\0");
					array[i] = Marshal.AllocHGlobal(bytes.Length);
					Marshal.Copy(bytes, 0, array[i], bytes.Length);
				}
				Marshal.Copy(array, 0, intPtr, strings.Length);
				return intPtr;
			}
			catch (Exception exception)
			{
				VRModCore.LogError("Exception during string array marshalling:", exception, "MarshalStringArrayToAnsi", "MimesisVR/Features/VRVisualization/OpenXR/OpenXR.cs", 419);
				FreeMarshalledStringArray(intPtr, array.Length);
				throw;
			}
		}

		public static void FreeMarshalledStringArray(IntPtr pointerArray, int numStrings)
		{
			if (pointerArray == IntPtr.Zero)
			{
				return;
			}
			IntPtr[] array = new IntPtr[numStrings];
			Marshal.Copy(pointerArray, array, 0, numStrings);
			for (int i = 0; i < numStrings; i++)
			{
				if (array[i] != IntPtr.Zero)
				{
					Marshal.FreeHGlobal(array[i]);
				}
			}
			Marshal.FreeHGlobal(pointerArray);
		}
	}
	public enum XrActionType
	{
		BOOLEAN_INPUT = 1,
		FLOAT_INPUT = 2,
		VECTOR2F_INPUT = 3,
		POSE_INPUT = 4,
		VIBRATION_OUTPUT = 100
	}
	internal static class XrInputTypes
	{
		public const int ACTION_STATE_BOOLEAN = 23;

		public const int ACTION_STATE_FLOAT = 24;

		public const int ACTION_STATE_VECTOR2F = 25;

		public const int ACTION_STATE_POSE = 27;

		public const int ACTION_SET_CREATE_INFO = 28;

		public const int ACTION_CREATE_INFO = 29;

		public const int ACTION_SPACE_CREATE_INFO = 38;

		public const int SPACE_LOCATION = 42;

		public const int INTERACTION_PROFILE_SUGGESTED_BINDING = 51;

		public const int ACTION_STATE_GET_INFO = 58;

		public const int SESSION_ACTION_SETS_ATTACH_INFO = 60;

		public const int ACTIONS_SYNC_INFO = 61;

		public const int HAPTIC_ACTION_INFO = 59;

		public const int HAPTIC_VIBRATION = 13;
	}
	public struct XrActionSetCreateInfo
	{
		public int type;

		public IntPtr next;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
		public string actionSetName;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string localizedActionSetName;

		public uint priority;
	}
	public struct XrActionCreateInfo
	{
		public int type;

		public IntPtr next;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
		public string actionName;

		public XrActionType actionType;

		public uint countSubactionPaths;

		public IntPtr subactionPaths;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string localizedActionName;
	}
	public struct XrActionSuggestedBinding
	{
		public ulong action;

		public ulong binding;
	}
	public struct XrInteractionProfileSuggestedBinding
	{
		public int type;

		public IntPtr next;

		public ulong interactionProfile;

		public uint countSuggestedBindings;

		public IntPtr suggestedBindings;
	}
	public struct XrSessionActionSetsAttachInfo
	{
		public int type;

		public IntPtr next;

		public uint countActionSets;

		public IntPtr actionSets;
	}
	public struct XrActiveActionSet
	{
		public ulong actionSet;

		public ulong subactionPath;
	}
	public struct XrActionsSyncInfo
	{
		public int type;

		public IntPtr next;

		public uint countActiveActionSets;

		public IntPtr activeActionSets;
	}
	public struct XrActionStateGetInfo
	{
		public int type;

		public IntPtr next;

		public ulong action;

		public ulong subactionPath;
	}
	public struct XrActionStateBoolean
	{
		public int type;

		public IntPtr next;

		public uint currentState;

		public uint changedSinceLastSync;

		public long lastChangeTime;

		public uint isActive;
	}
	public struct XrActionStateFloat
	{
		public int type;

		public IntPtr next;

		public float currentState;

		public uint changedSinceLastSync;

		public long lastChangeTime;

		public uint isActive;
	}
	public struct XrVector2f
	{
		public float x;

		public float y;
	}
	public struct XrActionStateVector2f
	{
		public int type;

		public IntPtr next;

		public XrVector2f currentState;

		public uint changedSinceLastSync;

		public long lastChangeTime;

		public uint isActive;
	}
	public struct XrActionSpaceCreateInfo
	{
		public int type;

		public IntPtr next;

		public ulong action;

		public ulong subactionPath;

		public XrPosef poseInActionSpace;
	}
	public struct XrExtent2Df
	{
		public float width;

		public float height;
	}
	public struct XrCompositionLayerQuad
	{
		public int type;

		public IntPtr next;

		public ulong layerFlags;

		public ulong space;

		public int eyeVisibility;

		public XrSwapchainSubImage subImage;

		public XrPosef pose;

		public XrExtent2Df size;
	}
	public struct XrSpaceLocation
	{
		public int type;

		public IntPtr next;

		public ulong locationFlags;

		public XrPosef pose;
	}
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrStringToPath(ulong instance, [MarshalAs(UnmanagedType.LPStr)] string pathString, out ulong path);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateActionSet(ulong instance, in XrActionSetCreateInfo createInfo, out ulong actionSet);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateAction(ulong actionSet, in XrActionCreateInfo createInfo, out ulong action);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrSuggestInteractionProfileBindings(ulong instance, in XrInteractionProfileSuggestedBinding suggestedBindings);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrAttachSessionActionSets(ulong session, in XrSessionActionSetsAttachInfo attachInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrSyncActions(ulong session, in XrActionsSyncInfo syncInfo);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetActionStateBoolean(ulong session, in XrActionStateGetInfo getInfo, ref XrActionStateBoolean state);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetActionStateFloat(ulong session, in XrActionStateGetInfo getInfo, ref XrActionStateFloat state);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrGetActionStateVector2f(ulong session, in XrActionStateGetInfo getInfo, ref XrActionStateVector2f state);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrCreateActionSpace(ulong session, in XrActionSpaceCreateInfo createInfo, out ulong space);
	public struct XrHapticActionInfo
	{
		public int type;

		public IntPtr next;

		public ulong action;

		public ulong subactionPath;
	}
	public struct XrHapticVibration
	{
		public int type;

		public IntPtr next;

		public long duration;

		public float frequency;

		public float amplitude;
	}
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrApplyHapticFeedback(ulong session, in XrHapticActionInfo hapticActionInfo, in XrHapticVibration hapticFeedback);
	[UnmanagedFunctionPointer(CallingConvention.StdCall)]
	public delegate XrResult PFN_xrLocateSpace(ulong space, ulong baseSpace, long time, ref XrSpaceLocation location);
	internal sealed class XrControllerInput
	{
		public enum B
		{
			A,
			B,
			X,
			Y,
			LStick,
			RStick,
			Menu,
			LThumbTouch,
			RThumbTouch,
			LIndexTouch,
			RIndexTouch,
			Count
		}

		public enum F
		{
			LTrigger,
			RTrigger,
			LGrip,
			RGrip,
			Count
		}

		private PFN_xrStringToPath _toPath;

		private PFN_xrCreateActionSet _createActionSet;

		private PFN_xrCreateAction _createAction;

		private PFN_xrSuggestInteractionProfileBindings _suggest;

		private PFN_xrAttachSessionActionSets _attach;

		private PFN_xrSyncActions _sync;

		private PFN_xrGetActionStateBoolean _getBool;

		private PFN_xrGetActionStateFloat _getFloat;

		private PFN_xrGetActionStateVector2f _getVec2;

		private PFN_xrCreateActionSpace _createActionSpace;

		private PFN_xrLocateSpace _locateSpace;

		private PFN_xrApplyHapticFeedback _haptic;

		private ulong _leftHaptic;

		private ulong _rightHaptic;

		internal int _hapticLogged;

		public static float HapticFrequency;

		private ulong _instance;

		private ulong _session;

		private ulong _actionSet;

		private readonly ulong[] _bool = new ulong[11];

		private readonly ulong[] _float = new ulong[4];

		private ulong _leftStick;

		private ulong _rightStick;

		private ulong _leftPose;

		private ulong _rightPose;

		private ulong _leftAim;

		private ulong _rightAim;

		private ulong _leftPoseSpace;

		private ulong _rightPoseSpace;

		private ulong _leftAimSpace;

		private ulong _rightAimSpace;

		public readonly bool[] Buttons = new bool[11];

		public readonly float[] Axes = new float[4];

		public Vector2 LeftStick;

		public Vector2 RightStick;

		public bool LeftPoseValid;

		public bool RightPoseValid;

		public Vector3 LeftPos;

		public Vector3 RightPos;

		public Vector3 LeftAimPos;

		public Vector3 RightAimPos;

		public Quaternion LeftRot = Quaternion.identity;

		public Quaternion RightRot = Quaternion.identity;

		public Quaternion LeftAimRot = Quaternion.identity;

		public Quaternion RightAimRot = Quaternion.identity;

		private long _failCount;

		public bool HapticsBound { get; private set; }

		public bool Ready { get; private set; }

		public bool TouchBound { get; private set; }

		public void Vibrate(bool right, float seconds, float amplitude)
		{
			Vibrate(right, seconds, amplitude, HapticFrequency);
		}

		public void Vibrate(bool right, float seconds, float amplitude, float frequency)
		{
			if (!HapticsBound || _haptic == null || _session == 0L)
			{
				return;
			}
			try
			{
				XrHapticActionInfo hapticActionInfo = new XrHapticActionInfo
				{
					type = 59,
					action = (right ? _rightHaptic : _leftHaptic)
				};
				XrHapticVibration hapticFeedback = new XrHapticVibration
				{
					type = 13,
					duration = ((seconds < 0f) ? (-1) : ((long)((double)Mathf.Max(0.005f, seconds) * 1000000000.0))),
					frequency = frequency,
					amplitude = Mathf.Clamp01(amplitude)
				};
				XrResult xrResult = _haptic(_session, in hapticActionInfo, in hapticFeedback);
				if (_hapticLogged < 30)
				{
					_hapticLogged++;
					VRModCore.Log(string.Format("[MimesisVR] Vibration {0} {1:F2}s x{2:F2} {3:0}Hz -> {4}", right ? "right" : "left", seconds, amplitude, frequency, xrResult), "Vibrate", "MimesisVR/Features/VRVisualization/OpenXR/OpenXRInput.cs", 114);
				}
			}
			catch (Exception ex)
			{
				if (_hapticLogged < 6)
				{
					_hapticLogged++;
					VRModCore.LogWarning("[MimesisVR] Vibration failed: " + ex.Message, "Vibrate", "MimesisVR/Features/VRVisualization/OpenXR/OpenXRInput.cs", 116);
				}
			}
		}

		private static T Load<T>(ulong instance) where T : Delegate
		{
			string text = typeof(T).Name.Substring("PFN_".Length);
			IntPtr function;
			XrResult xrResult = OpenXRNativeLoader.xrGetInstanceProcAddr_ptr_delegate(instance, text, out function);
			if (xrResult != XrResult.XR_SUCCESS || function == IntPtr.Zero)
			{
				throw new EntryPointNotFoundException($"OpenXR function {text}: {xrResult}");
			}
			return Marshal.GetDelegateForFunctionPointer<T>(function);
		}

		private ulong P(string s)
		{
			ulong path;
			XrResult xrResult = _toPath(_instance, s, out path);
			if (xrResult != XrResult.XR_SUCCESS)
			{
				throw new Exception($"xrStringToPath('{s}') -> {xrResult}");
			}
			return path;
		}

		private XrResult Suggest(ulong instance, List<XrActionSuggestedBinding> b)
		{
			int num = Marshal.SizeOf<XrActionSuggestedBinding>();
			IntPtr intPtr = Marshal.AllocHGlobal(num * b.Count);
			try
			{
				for (int i = 0; i < b.Count; i++)
				{
					Marshal.StructureToPtr(b[i], intPtr + i * num, fDeleteOld: false);
				}
				XrInteractionProfileSuggestedBinding suggestedBindings = new XrInteractionProfileSuggestedBinding
				{
					type = 51,
					interactionProfile = P("/interaction_profiles/oculus/touch_controller"),
					countSuggestedBindings = (uint)b.Count,
					suggestedBindings = intPtr
				};
				return _suggest(instance, in suggestedBindings);
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}

		private ulong MakeAction(string name, XrActionType type)
		{
			XrActionCreateInfo createInfo = new XrActionCreateInfo
			{
				type = 29,
				actionName = name,
				localizedActionName = name,
				actionType = type
			};
			ulong action;
			XrResult xrResult = _createAction(_actionSet, in createInfo, out action);
			if (xrResult != XrResult.XR_SUCCESS)
			{
				throw new Exception($"xrCreateAction('{name}') -> {xrResult}");
			}
			return action;
		}

		public bool Initialize(ulong instance, ulong session)
		{
			try
			{
				_instance = instance;
				_session = session;
				_toPath = Load<PFN_xrStringToPath>(instance);
				_createActionSet = Load<PFN_xrCreateActionSet>(instance);
				_createAction = Load<PFN_xrCreateAction>(instance);
				_suggest = Load<PFN_xrSuggestInteractionProfileBindings>(instance);
				_attach = Load<PFN_xrAttachSessionActionSets>(instance);
				_sync = Load<PFN_xrSyncActions>(instance);
				_getBool = Load<PFN_xrGetActionStateBoolean>(instance);
				_getFloat = Load<PFN_xrGetActionStateFloat>(instance);
				_getVec2 = Load<PFN_xrGetActionStateVector2f>(instance);
				_createActionSpace = Load<PFN_xrCreateActionSpace>(instance);
				_locateSpace = Load<PFN_xrLocateSpace>(instance);
				try
				{
					_haptic = Load<PFN_xrApplyHapticFeedback>(instance);
				}
				catch
				{
					_haptic = null;
				}
				XrActionSetCreateInfo createInfo = new XrActionSetCreateInfo
				{
					type = 28,
					actionSetName = "mimesisvr",
					localizedActionSetName = "MIMESIS VR",
					priority = 0u
				};
				XrResult xrResult = _createActionSet(instance, in createInfo, out _actionSet);
				if (xrResult != XrResult.XR_SUCCESS)
				{
					throw new Exception($"xrCreateActionSet -> {xrResult}");
				}
				_bool[0] = MakeAction("button_a", XrActionType.BOOLEAN_INPUT);
				_bool[1] = MakeAction("button_b", XrActionType.BOOLEAN_INPUT);
				_bool[2] = MakeAction("button_x", XrActionType.BOOLEAN_INPUT);
				_bool[3] = MakeAction("button_y", XrActionType.BOOLEAN_INPUT);
				_bool[4] = MakeAction("left_stick_click", XrActionType.BOOLEAN_INPUT);
				_bool[5] = MakeAction("right_stick_click", XrActionType.BOOLEAN_INPUT);
				_bool[6] = MakeAction("menu", XrActionType.BOOLEAN_INPUT);
				_bool[7] = MakeAction("left_thumb_touch", XrActionType.BOOLEAN_INPUT);
				_bool[8] = MakeAction("right_thumb_touch", XrActionType.BOOLEAN_INPUT);
				_bool[9] = MakeAction("left_index_touch", XrActionType.BOOLEAN_INPUT);
				_bool[10] = MakeAction("right_index_touch", XrActionType.BOOLEAN_INPUT);
				_leftHaptic = MakeAction("left_haptic", XrActionType.VIBRATION_OUTPUT);
				_rightHaptic = MakeAction("right_haptic", XrActionType.VIBRATION_OUTPUT);
				_float[0] = MakeAction("left_trigger", XrActionType.FLOAT_INPUT);
				_float[1] = MakeAction("right_trigger", XrActionType.FLOAT_INPUT);
				_float[2] = MakeAction("left_grip", XrActionType.FLOAT_INPUT);
				_float[3] = MakeAction("right_grip", XrActionType.FLOAT_INPUT);
				_leftStick = MakeAction("left_stick", XrActionType.VECTOR2F_INPUT);
				_rightStick = MakeAction("right_stick", XrActionType.VECTOR2F_INPUT);
				_leftPose = MakeAction("left_grip_pose", XrActionType.POSE_INPUT);
				_rightPose = MakeAction("right_grip_pose", XrActionType.POSE_INPUT);
				_leftAim = MakeAction("left_aim_pose", XrActionType.POSE_INPUT);
				_rightAim = MakeAction("right_aim_pose", XrActionType.POSE_INPUT);
				List<XrActionSuggestedBinding> list = new List<XrActionSuggestedBinding>
				{
					new XrActionSuggestedBinding
					{
						action = _bool[0],
						binding = P("/user/hand/right/input/a/click")
					},
					new XrActionSuggestedBinding
					{
						action = _bool[1],
						binding = P("/user/hand/right/input/b/click")
					},
					new XrActionSuggestedBinding
					{
						action = _bool[2],
						binding = P("/user/hand/left/input/x/click")
					},
					new XrActionSuggestedBinding
					{
						action = _bool[3],
						binding = P("/user/hand/left/input/y/click")
					},
					new XrActionSuggestedBinding
					{
						action = _bool[4],
						binding = P("/user/hand/left/input/thumbstick/click")
					},
					new XrActionSuggestedBinding
					{
						action = _bool[5],
						binding = P("/user/hand/right/input/thumbstick/click")
					},
					new XrActionSuggestedBinding
					{
						action = _bool[6],
						binding = P("/user/hand/left/input/menu/click")
					},
					new XrActionSuggestedBinding
					{
						action = _float[0],
						binding = P("/user/hand/left/input/trigger/value")
					},
					new XrActionSuggestedBinding
					{
						action = _float[1],
						binding = P("/user/hand/right/input/trigger/value")
					},
					new XrActionSuggestedBinding
					{
						action = _float[2],
						binding = P("/user/hand/left/input/squeeze/value")
					},
					new XrActionSuggestedBinding
					{
						action = _float[3],
						binding = P("/user/hand/right/input/squeeze/value")
					},
					new XrActionSuggestedBinding
					{
						action = _leftStick,
						binding = P("/user/hand/left/input/thumbstick")
					},
					new XrActionSuggestedBinding
					{
						action = _rightStick,
						binding = P("/user/hand/right/input/thumbstick")
					},
					new XrActionSuggestedBinding
					{
						action = _leftPose,
						binding = P("/user/hand/left/input/grip/pose")
					},
					new XrActionSuggestedBinding
					{
						action = _rightPose,
						binding = P("/user/hand/right/input/grip/pose")
					},
					new XrActionSuggestedBinding
					{
						action = _leftAim,
						binding = P("/user/hand/left/input/aim/pose")
					},
					new XrActionSuggestedBinding
					{
						action = _rightAim,
						binding = P("/user/hand/right/input/aim/pose")
					}
				};
				List<XrActionSuggestedBinding> touch = new List<XrActionSuggestedBinding>();
				T(B.RThumbTouch, "/user/hand/right/input/a/touch");
				T(B.RThumbTouch, "/user/hand/right/input/b/touch");
				T(B.RThumbTouch, "/user/hand/right/input/thumbstick/touch");
				T(B.RThumbTouch, "/user/hand/right/input/thumbrest/touch");
				T(B.LThumbTouch, "/user/hand/left/input/x/touch");
				T(B.LThumbTouch, "/user/hand/left/input/y/touch");
				T(B.LThumbTouch, "/user/hand/left/input/thumbstick/touch");
				T(B.LThumbTouch, "/user/hand/left/input/thumbrest/touch");
				T(B.RIndexTouch, "/user/hand/right/input/trigger/touch");
				T(B.LIndexTouch, "/user/hand/left/input/trigger/touch");
				touch.Add(new XrActionSuggestedBinding
				{
					action = _leftHaptic,
					binding = P("/user/hand/left/output/haptic")
				});
				touch.Add(new XrActionSuggestedBinding
				{
					action = _rightHaptic,
					binding = P("/user/hand/right/output/haptic")
				});
				List<XrActionSuggestedBinding> list2 = new List<XrActionSuggestedBinding>(list);
				list2.AddRange(touch);
				xrResult = Suggest(instance, list2);
				if (xrResult != XrResult.XR_SUCCESS)
				{
					VRModCore.LogWarning($"[MimesisVR] Touch bindings refused ({xrResult}) - fingers will not react to touch.", "Initialize", "MimesisVR/Features/VRVisualization/OpenXR/OpenXRInput.cs", 263);
					xrResult = Suggest(instance, list);
				}
				else
				{
					TouchBound = true;
					HapticsBound = _haptic != null;
				}
				if (xrResult != XrResult.XR_SUCCESS)
				{
					throw new Exception($"xrSuggestInteractionProfileBindings -> {xrResult}");
				}
				IntPtr intPtr = Marshal.AllocHGlobal(8);
				try
				{
					Marshal.WriteInt64(intPtr, (long)_actionSet);
					XrSessionActionSetsAttachInfo attachInfo = new XrSessionActionSetsAttachInfo
					{
						type = 60,
						countActionSets = 1u,
						actionSets = intPtr
					};
					xrResult = _attach(session, in attachInfo);
					if (xrResult != XrResult.XR_SUCCESS)
					{
						throw new Exception($"xrAttachSessionActionSets -> {xrResult}");
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
				_leftPoseSpace = MakeSpace(_leftPose);
				_rightPoseSpace = MakeSpace(_rightPose);
				_leftAimSpace = MakeSpace(_leftAim);
				_rightAimSpace = MakeSpace(_rightAim);
				Ready = true;
				VRModCore.Log("[MimesisVR] Controller actions ready (oculus/touch_controller), touch sensors " + (TouchBound ? "on" : "off") + ", vibration " + (HapticsBound ? "on" : "off") + ".", "Initialize", "MimesisVR/Features/VRVisualization/OpenXR/OpenXRInput.cs", 285);
				return true;
				void T(B a, string path)
				{
					touch.Add(new XrActionSuggestedBinding
					{
						action = _bool[(int)a],
						binding = P(path)
					});
				}
			}
			catch (Exception exception)
			{
				VRModCore.LogError("[MimesisVR] Controller input init failed:", exception, "Initialize", "MimesisVR/Features/VRVisualization/OpenXR/OpenXRInput.cs", 290);
				Ready = false;
				return false;
			}
		}

		private ulong MakeSpace(ulong action)
		{
			XrActionSpaceCreateInfo createInfo = new XrActionSpaceCreateInfo
			{
				type = 38,
				action = action,
				poseInActionSpace = new XrPosef
				{
					orientation = new XrQuaternionf
					{
						w = 1f
					}
				}
			};
			ulong space;
			XrResult xrResult = _createActionSpace(_session, in createInfo, out space);
			if (xrResult != XrResult.XR_SUCCESS)
			{
				throw new Exception($"xrCreateActionSpace -> {xrResult}");
			}
			return space;
		}

		private bool GetBool(ulong action)
		{
			XrActionStateGetInfo getInfo = new XrActionStateGetInfo
			{
				type = 58,
				action = action
			};
			XrActionStateBoolean state = new XrActionStateBoolean
			{
				type = 23
			};
			if (_getBool(_session, in getInfo, ref state) == XrResult.XR_SUCCESS && state.isActive != 0)
			{
				return state.currentState != 0;
			}
			return false;
		}

		private float GetFloat(ulong action)
		{
			XrActionStateGetInfo getInfo = new XrActionStateGetInfo
			{
				type = 58,
				action = action
			};
			XrActionStateFloat state = new XrActionStateFloat
			{
				type = 24
			};
			if (_getFloat(_session, in getInfo, ref state) != XrResult.XR_SUCCESS || state.isActive == 0)
			{
				return 0f;
			}
			return state.currentState;
		}

		private Vector2 GetVec2(ulong action)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			XrActionStateGetInfo getInfo = new XrActionStateGetInfo
			{
				type = 58,
				action = action
			};
			XrActionStateVector2f state = new XrActionStateVector2f
			{
				type = 25
			};
			if (_getVec2(_session, in getInfo, ref state) != XrResult.XR_SUCCESS || state.isActive == 0)
			{
				return Vector2.zero;
			}
			return new Vector2(state.currentState.x, state.currentState.y);
		}

		private bool Locate(ulong space, ulong baseSpace, long time, out Vector3 pos, out Quaternion rot)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			XrSpaceLocation location = new XrSpaceLocation
			{
				type = 42
			};
			pos = Vector3.zero;
			rot = Quaternion.identity;
			if (_locateSpace(space, baseSpace, time, ref location) != XrResult.XR_SUCCESS)
			{
				return false;
			}
			if ((location.locationFlags & 3) != 3)
			{
				return false;
			}
			pos = new Vector3(location.pose.position.x, location.pose.position.y, 0f - location.pose.position.z);
			rot = new Quaternion(location.pose.orientation.x, location.pose.orientation.y, 0f - location.pose.orientation.z, 0f - location.pose.orientation.w);
			return true;
		}

		public void Update(ulong baseSpace, long displayTime)
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			if (!Ready)
			{
				return;
			}
			IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<XrActiveActionSet>());
			try
			{
				Marshal.StructureToPtr(new XrActiveActionSet
				{
					actionSet = _actionSet,
					subactionPath = 0uL
				}, intPtr, fDeleteOld: false);
				XrActionsSyncInfo syncInfo = new XrActionsSyncInfo
				{
					type = 61,
					countActiveActionSets = 1u,
					activeActionSets = intPtr
				};
				XrResult xrResult = _sync(_session, in syncInfo);
				if (xrResult < XrResult.XR_SUCCESS)
				{
					if (_failCount++ % 300 == 0L)
					{
						VRModCore.LogWarning($"[MimesisVR] xrSyncActions -> {xrResult}", "Update", "MimesisVR/Features/VRVisualization/OpenXR/OpenXRInput.cs", 351);
					}
					return;
				}
				if (xrResult == XrResult.XR_SESSION_NOT_FOCUSED)
				{
					return;
				}
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			for (int i = 0; i < 11; i++)
			{
				Buttons[i] = GetBool(_bool[i]);
			}
			for (int j = 0; j < 4; j++)
			{
				Axes[j] = GetFloat(_float[j]);
			}
			LeftStick = GetVec2(_leftStick);
			RightStick = GetVec2(_rightStick);
			LeftPoseValid = Locate(_leftPoseSpace, baseSpace, displayTime, out LeftPos, out LeftRot);
			RightPoseValid = Locate(_rightPoseSpace, baseSpace, displayTime, out RightPos, out RightRot);
			Locate(_leftAimSpace, baseSpace, displayTime, out LeftAimPos, out LeftAimRot);
			Locate(_rightAimSpace, baseSpace, displayTime, out RightAimPos, out RightAimRot);
		}
	}
}
namespace UnityVRMod.Features.VrVisualization
{
	public enum SafeModeLevel
	{
		FastToggleOnly,
		RigReinitOnToggle,
		FullVrReinitOnToggle
	}
	internal class VrCameraSetup_CoreOpenXR : IVrCameraSetup
	{
		private ulong _xrInstance;

		private ulong _xrSystemId;

		private ulong _xrSession;

		private GameObject _vrRig;

		private float _currentAppliedRigScale = 1f;

		private XrFrameState _xrFrameState;

		private XrSessionState _currentSessionState;

		private readonly XrViewConfigurationType _viewConfigType = XrViewConfigurationType.XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;

		private readonly List<XrViewConfigurationView> _viewConfigViews = new List<XrViewConfigurationView>();

		private readonly List<long> _supportedSwapchainFormats = new List<long>();

		private long _selectedSwapchainFormat;

		private readonly List<ulong> _eyeSwapchains = new List<ulong>();

		private readonly List<List<IntPtr>> _eyeSwapchainImages = new List<List<IntPtr>>();

		private ulong _appSpace;

		private bool _isSessionRunning;

		private XrReferenceSpaceType _appSpaceType = XrReferenceSpaceType.XR_REFERENCE_SPACE_TYPE_LOCAL;

		private XrView[] _locatedViews;

		private XrViewState _locatedViewState;

		private Camera _leftVrCamera;

		private GameObject _leftVrCameraGO;

		private Camera _rightVrCamera;

		private GameObject _rightVrCameraGO;

		private RenderTexture _leftEyeIntermediateRT;

		private RenderTexture _rightEyeIntermediateRT;

		private IntPtr _d3d11Device = IntPtr.Zero;

		private XrCompositionLayerProjectionView[] _projectionLayerViews;

		private IntPtr _pProjectionLayerViews = IntPtr.Zero;

		private XrCompositionLayerProjection _projectionLayer;

		private IntPtr _pProjectionLayer = IntPtr.Zero;

		private IntPtr _pLayersForSubmit = IntPtr.Zero;

		private CameraClearFlags _mainCameraClearFlags;

		private Color _mainCameraBackgroundColor;

		private int _mainCameraCullingMask;

		private GameObject _currentlyTrackedOriginalCameraGO;

		private float _lastCalculatedVerticalOffset;

		private static CommandBuffer _flushCommandBuffer;

		private readonly List<List<IntPtr>> _eyeSwapchainSRVs = new List<List<IntPtr>>();

		private XrControllerInput _controllers;

		private RenderTexture _leftFlipRT;

		private RenderTexture _rightFlipRT;

		private bool _hasRecenter;

		private Vector3 _recenterHeadLocal;

		private float _recenterYaw;

		private XrQuadLayer _panelLayer;

		private XrQuadLayer _hudLayer;

		private XrQuadLayer _laserLayer;

		private XrQuadLayer _gearLayer;

		private XrQuadLayer _settingsLayer;

		private XrQuadLayer _fpsLayer;

		private XrQuadLayer _watchLayer;

		private readonly Dictionary<string, XrQuadLayer> _segLayers = new Dictionary<string, XrQuadLayer>();

		private static float _refFar;

		private static bool _gamePost = true;

		public bool IsVrAvailable { get; private set; }

		public XrControllerInput Controllers => _controllers;

		public Transform RigTransform
		{
			get
			{
				if (!((Object)(object)_vrRig != (Object)null))
				{
					return null;
				}
				return _vrRig.transform;
			}
		}

		public bool InitializeVr(string applicationKey)
		{
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_0528: Expected O, but got Unknown
			VRModCore.Log("Attempting to initialize OpenXR via P/Invoke...", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 66);
			try
			{
				if (!OpenXRNativeLoader.LoadOpenXRLibrary())
				{
					throw new Exception("Failed to load OpenXR native library (openxr_loader.dll).");
				}
				if (!OpenXRAPI.InitializeCoreFunctions(OpenXRNativeLoader.xrGetInstanceProcAddr_ptr_delegate))
				{
					throw new Exception("Failed to initialize core OpenXR functions.");
				}
				XrApplicationInfo applicationInfo = new XrApplicationInfo
				{
					applicationName = "UnityVRMod",
					applicationVersion = 1u,
					engineName = "Unity",
					engineVersion = 1u,
					apiVersion = OpenXRConstants.XR_API_VERSION_1_1
				};
				string[] array = new string[1] { "XR_KHR_D3D11_enable" };
				IntPtr intPtr = MarshallStringUtils.MarshalStringArrayToAnsi(array);
				XrInstanceCreateInfo createInfo = new XrInstanceCreateInfo
				{
					type = XrStructureType.XR_TYPE_INSTANCE_CREATE_INFO,
					applicationInfo = applicationInfo,
					enabledExtensionCount = (uint)array.Length,
					enabledExtensionNames = intPtr
				};
				OpenXRHelper.CheckResult(OpenXRAPI.xrCreateInstance(in createInfo, out _xrInstance), "xrCreateInstance");
				MarshallStringUtils.FreeMarshalledStringArray(intPtr, array.Length);
				if (_xrInstance == 0L)
				{
					throw new Exception("xrCreateInstance returned a null handle.");
				}
				VRModCore.Log($"OpenXR Instance created. Handle: {_xrInstance}", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 100);
				if (!OpenXRAPI.InitializeInstanceFunctions(_xrInstance))
				{
					throw new Exception("Failed to initialize instance-specific OpenXR functions.");
				}
				_d3d11Device = NativeBridge.GetD3D11DevicePointer((Texture)(object)Texture2D.whiteTexture);
				if (_d3d11Device == IntPtr.Zero)
				{
					throw new Exception("Failed to get D3D11 device pointer.");
				}
				NativeBridge.SetDevicePointerFromCSharp(_d3d11Device);
				RtSubmit.Init(_d3d11Device, _xrInstance);
				XrSystemGetInfo getInfo = new XrSystemGetInfo
				{
					type = XrStructureType.XR_TYPE_SYSTEM_GET_INFO,
					formFactor = XrFormFactor.XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY
				};
				OpenXRHelper.CheckResult(OpenXRAPI.xrGetSystem(_xrInstance, in getInfo, out _xrSystemId), "xrGetSystem");
				if (_xrSystemId == 0L)
				{
					throw new Exception("xrGetSystem failed for HMD.");
				}
				VRModCore.Log($"OpenXR SystemId obtained: {_xrSystemId}", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 115);
				XrGraphicsRequirementsD3D11KHR graphicsRequirements = new XrGraphicsRequirementsD3D11KHR
				{
					type = XrStructureType.XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR
				};
				OpenXRHelper.CheckResult(OpenXRAPI.xrGetD3D11GraphicsRequirementsKHR(_xrInstance, _xrSystemId, out graphicsRequirements), "xrGetD3D11GraphicsRequirementsKHR");
				XrGraphicsBindingD3D11KHR structure = new XrGraphicsBindingD3D11KHR
				{
					type = XrStructureType.XR_TYPE_GRAPHICS_BINDING_D3D11_KHR,
					device = _d3d11Device
				};
				IntPtr intPtr2 = Marshal.AllocHGlobal(Marshal.SizeOf(structure));
				Marshal.StructureToPtr(structure, intPtr2, fDeleteOld: false);
				XrSessionCreateInfo createInfo2 = new XrSessionCreateInfo
				{
					type = XrStructureType.XR_TYPE_SESSION_CREATE_INFO,
					next = intPtr2,
					systemId = _xrSystemId
				};
				OpenXRHelper.CheckResult(OpenXRAPI.xrCreateSession(_xrInstance, in createInfo2, out _xrSession), "xrCreateSession");
				Marshal.FreeHGlobal(intPtr2);
				if (_xrSession == 0L)
				{
					throw new Exception("xrCreateSession returned a null handle.");
				}
				VRModCore.Log($"OpenXR Session created. Handle: {_xrSession}", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 127);
				XrSessionBeginInfo beginInfo = new XrSessionBeginInfo
				{
					type = XrStructureType.XR_TYPE_SESSION_BEGIN_INFO,
					primaryViewConfigurationType = _viewConfigType
				};
				OpenXRHelper.CheckResult(OpenXRAPI.xrBeginSession(_xrSession, in beginInfo), "xrBeginSession");
				_currentSessionState = XrSessionState.XR_SESSION_STATE_READY;
				_isSessionRunning = true;
				VRModCore.Log("OpenXR Session begun.", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 133);
				_controllers = new XrControllerInput();
				if (_controllers.Initialize(_xrInstance, _xrSession))
				{
					MimesisInput.Controllers = _controllers;
				}
				XrReferenceSpaceCreateInfo createInfo3 = new XrReferenceSpaceCreateInfo
				{
					type = XrStructureType.XR_TYPE_REFERENCE_SPACE_CREATE_INFO,
					referenceSpaceType = XrReferenceSpaceType.XR_REFERENCE_SPACE_TYPE_STAGE,
					poseInReferenceSpace = new XrPosef
					{
						orientation = new XrQuaternionf
						{
							w = 1f
						}
					}
				};
				if (OpenXRAPI.xrCreateReferenceSpace(_xrSession, in createInfo3, out _appSpace) < XrResult.XR_SUCCESS)
				{
					VRModCore.LogWarning("Failed to create STAGE space. Trying LOCAL.", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 141);
					_appSpaceType = XrReferenceSpaceType.XR_REFERENCE_SPACE_TYPE_LOCAL;
					createInfo3.referenceSpaceType = _appSpaceType;
					OpenXRHelper.CheckResult(OpenXRAPI.xrCreateReferenceSpace(_xrSession, in createInfo3, out _appSpace), "xrCreateReferenceSpace_Fallback");
				}
				else
				{
					_appSpaceType = XrReferenceSpaceType.XR_REFERENCE_SPACE_TYPE_STAGE;
				}
				if (_appSpace == 0L)
				{
					throw new Exception("Failed to create any reference space.");
				}
				VRModCore.Log($"Created {_appSpaceType} space.", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 151);
				InitializeViews();
				InitializeSwapchains();
				if (_viewConfigViews.Count > 0)
				{
					_pProjectionLayerViews = Marshal.AllocHGlobal(Marshal.SizeOf<XrCompositionLayerProjectionView>() * _viewConfigViews.Count);
					_projectionLayer = new XrCompositionLayerProjection
					{
						type = XrStructureType.XR_TYPE_COMPOSITION_LAYER_PROJECTION
					};
					_pProjectionLayer = Marshal.AllocHGlobal(Marshal.SizeOf<XrCompositionLayerProjection>());
					_pLayersForSubmit = Marshal.AllocHGlobal(Marshal.SizeOf<IntPtr>() * 12);
					Marshal.WriteIntPtr(_pLayersForSubmit, _pProjectionLayer);
				}
				if (_flushCommandBuffer == null)
				{
					_flushCommandBuffer = new CommandBuffer
					{
						name = "VRModFlush"
					};
				}
				VRModCore.Log("OpenXR fully initialized.", "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 170);
				IsVrAvailable = true;
				return true;
			}
			catch (Exception exception)
			{
				VRModCore.LogError("Exception during OpenXR initialization:", exception, "InitializeVr", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 176);
				TeardownVr();
				return false;
			}
		}

		private void InitializeViews()
		{
			OpenXRAPI.xrEnumerateViewConfigurations(_xrInstance, _xrSystemId, 0u, out var viewConfigurationTypeCountOutput, IntPtr.Zero);
			if (viewConfigurationTypeCountOutput == 0)
			{
				throw new Exception("No view configurations available.");
			}
			OpenXRAPI.xrEnumerateViewConfigurationViews(_xrInstance, _xrSystemId, _viewConfigType, 0u, out var viewCountOutput, IntPtr.Zero);
			if (viewCountOutput == 0)
			{
				throw new Exception("No views for primary stereo config.");
			}
			_viewConfigViews.Clear();
			IntPtr intPtr = Marshal.AllocHGlobal((int)(viewCountOutput * Marshal.SizeOf<XrViewConfigurationView>()));
			try
			{
				for (int i = 0; i < viewCountOutput; i++)
				{
					Marshal.StructureToPtr(new XrViewConfigurationView
					{
						type = XrStructureType.XR_TYPE_VIEW_CONFIGURATION_VIEW
					}, intPtr + i * Marshal.SizeOf<XrViewConfigurationView>(), fDeleteOld: false);
				}
				OpenXRAPI.xrEnumerateViewConfigurationViews(_xrInstance, _xrSystemId, _viewConfigType, viewCountOutput, out viewCountOutput, intPtr);
				for (int j = 0; j < viewCountOutput; j++)
				{
					_viewConfigViews.Add(Marshal.PtrToStructure<XrViewConfigurationView>(intPtr + j * Marshal.SizeOf<XrViewConfigurationView>()));
				}
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			if (_viewConfigViews.Count > 0)
			{
				_locatedViews = new XrView[_viewConfigViews.Count];
				for (int k = 0; k < _locatedViews.Length; k++)
				{
					_locatedViews[k].type = XrStructureType.XR_TYPE_VIEW;
				}
				_projectionLayerViews = new XrCompositionLayerProjectionView[_viewConfigViews.Count];
				for (int l = 0; l < _projectionLayerViews.Length; l++)
				{
					_projectionLayerViews[l].type = XrStructureType.XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
				}
			}
			VRModCore.LogRuntimeDebug("View configurations enumerated.", "InitializeViews", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 208);
		}

		private void InitializeSwapchains()
		{
			OpenXRAPI.xrEnumerateSwapchainFormats(_xrSession, 0u, out var formatCountOutput, null);
			if (formatCountOutput == 0)
			{
				throw new Exception("No swapchain formats.");
			}
			long[] array = new long[formatCountOutput];
			OpenXRAPI.xrEnumerateSwapchainFormats(_xrSession, formatCountOutput, out formatCountOutput, array);
			_supportedSwapchainFormats.Clear();
			_supportedSwapchainFormats.AddRange(array);
			long num = 91L;
			if (_supportedSwapchainFormats.Contains(num))
			{
				_selectedSwapchainFormat = num;
			}
			else
			{
				if (_supportedSwapchainFormats.Count <= 0)
				{
					throw new Exception("No suitable swapchain format found.");
				}
				_selectedSwapchainFormat = _supportedSwapchainFormats[0];
			}
			VRModCore.Log($"Selected Swapchain Format (DXGI): {_selectedSwapchainFormat}", "InitializeSwapchains", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 228);
			_eyeSwapchains.Clear();
			_eyeSwapchainImages.Clear();
			_eyeSwapchainSRVs.Clear();
			for (int i = 0; i < _viewConfigViews.Count; i++)
			{
				XrViewConfigurationView xrViewConfigurationView = _viewConfigViews[i];
				XrSwapchainCreateInfo createInfo = new XrSwapchainCreateInfo
				{
					type = XrStructureType.XR_TYPE_SWAPCHAIN_CREATE_INFO,
					usageFlags = (XrSwapchainUsageFlags.XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XrSwapchainUsageFlags.XR_SWAPCHAIN_USAGE_SAMPLED_BIT),
					format = _selectedSwapchainFormat,
					sampleCount = xrViewConfigurationView.recommendedSwapchainSampleCount,
					width = xrViewConfigurationView.recommendedImageRectWidth,
					height = xrViewConfigurationView.recommendedImageRectHeight,
					faceCount = 1u,
					arraySize = 1u,
					mipCount = 1u
				};
				OpenXRHelper.CheckResult(OpenXRAPI.xrCreateSwapchain(_xrSession, in createInfo, out var swapchain), "xrCreateSwapchain");
				_eyeSwapchains.Add(swapchain);
				OpenXRAPI.xrEnumerateSwapchainImages(swapchain, 0u, out var imageCountOutput, IntPtr.Zero);
				IntPtr intPtr = Marshal.AllocHGlobal((int)(imageCountOutput * Marshal.SizeOf<XrSwapchainImageD3D11KHR>()));
				List<IntPtr> list = new List<IntPtr>();
				List<IntPtr> list2 = new List<IntPtr>();
				try
				{
					for (int j = 0; j < imageCountOutput; j++)
					{
						Marshal.StructureToPtr(new XrSwapchainImageD3D11KHR
						{
							type = XrStructureType.XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR
						}, intPtr + j * Marshal.SizeOf<XrSwapchainImageD3D11KHR>(), fDeleteOld: false);
					}
					OpenXRAPI.xrEnumerateSwapchainImages(swapchain, imageCountOutput, out imageCountOutput, intPtr);
					for (int k = 0; k < imageCountOutput; k++)
					{
						XrSwapchainImageD3D11KHR xrSwapchainImageD3D11KHR = Marshal.PtrToStructure<XrSwapchainImageD3D11KHR>(intPtr + k * Marshal.SizeOf<XrSwapchainImageD3D11KHR>());
						list.Add(xrSwapchainImageD3D11KHR.texture);
						if (NativeBridge.CreateAndRegisterSRV_Internal(xrSwapchainImageD3D11KHR.texture, (int)_selectedSwapchainFormat, out var ppSRV) == 0 && ppSRV != IntPtr.Zero)
						{
							list2.Add(ppSRV);
						}
						else
						{
							list2.Add(IntPtr.Zero);
						}
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
				_eyeSwapchainImages.Add(list);
				_eyeSwapchainSRVs.Add(list2);
				VRModCore.Log($"Swapchain for view {i} created. Images: {list.Count}", "InitializeSwapchains", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 275);
			}
		}

		public void UpdatePoses()
		{
			if (!IsVrAvailable || _xrSession == 0L)
			{
				return;
			}
			IntPtr intPtr = IntPtr.Zero;
			try
			{
				intPtr = Marshal.AllocHGlobal(XrEventDataBuffer.GetSize());
				while (true)
				{
					Marshal.StructureToPtr(new XrEventDataBaseHeader
					{
						type = XrStructureType.XR_TYPE_EVENT_DATA_BUFFER
					}, intPtr, fDeleteOld: false);
					XrResult xrResult = OpenXRAPI.xrPollEvent(_xrInstance, intPtr);
					if (xrResult == XrResult.XR_EVENT_UNAVAILABLE)
					{
						break;
					}
					if (xrResult < XrResult.XR_SUCCESS)
					{
						IsVrAvailable = false;
						break;
					}
					int num = Marshal.ReadInt32(intPtr);
					if (num == 40)
					{
						VRModCore.Log("[MimesisVR] Reference space change (system recenter) -> recentering.", "UpdatePoses", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 299);
						RequestRecenter();
					}
					if (num != 18)
					{
						continue;
					}
					XrEventDataSessionStateChanged xrEventDataSessionStateChanged = Marshal.PtrToStructure<XrEventDataSessionStateChanged>(intPtr);
					if (xrEventDataSessionStateChanged.state == _currentSessionState)
					{
						continue;
					}
					VRModCore.Log($"OpenXR Session State Changed: {_currentSessionState} -> {xrEventDataSessionStateChanged.state}", "UpdatePoses", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 305);
					_currentSessionState = xrEventDataSessionStateChanged.state;
					switch (_currentSessionState)
					{
					case XrSessionState.XR_SESSION_STATE_LOSS_PENDING:
					case XrSessionState.XR_SESSION_STATE_EXITING:
						_isSessionRunning = false;
						IsVrAvailable = false;
						break;
					case XrSessionState.XR_SESSION_STATE_STOPPING:
						if (_isSessionRunning)
						{
							VRModCore.Log("Session is stopping, calling xrEndSession.", "UpdatePoses", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 318);
							RtSubmit.WaitPrevious(500);
							RtSubmit.ResetFrame();
							OpenXRAPI.xrEndSession(_xrSession);
							_isSessionRunning = false;
						}
						break;
					case XrSessionState.XR_SESSION_STATE_READY:
						if (!_isSessionRunning)
						{
							VRModCore.Log("Session is ready, calling xrBeginSession to resume.", "UpdatePoses", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 328);
							XrSessionBeginInfo beginInfo = new XrSessionBeginInfo
							{
								type = XrStructureType.XR_TYPE_SESSION_BEGIN_INFO,
								primaryViewConfigurationType = _viewConfigType
							};
							if (OpenXRAPI.xrBeginSession(_xrSession, in beginInfo) == XrResult.XR_SUCCESS)
							{
								_isSessionRunning = true;
							}
						}
						break;
					}
				}
			}
			finally
			{
				if (intPtr != IntPtr.Zero)
				{
					Marshal.FreeHGlobal(intPtr);
				}
			}
			if (!_isSessionRunning)
			{
				return;
			}
			MimesisWatchdog.Start();
			MimesisWatchdog.Armed = true;
			MimesisWatchdog.MainStage = 1;
			Stopwatch stopwatch = Stopwatch.StartNew();
			RtSubmit.WaitPrevious();
			if (!RtSubmit.ReadyForNextFrame)
			{
				return;
			}
			MimesisWatchdog.MainStage = 2;
			if (RtSubmit.NativeActive)
			{
				if (!RtSubmit.FrameBegun)
				{
					RtSubmit.SubmitBootstrap(_xrSession);
					return;
				}
				_xrFrameState = RtSubmit.LastFrameState;
				MimesisWatchdog.MainStage = 3;
			}
			else
			{
				XrFrameWaitInfo frameWaitInfo = new XrFrameWaitInfo
				{
					type = XrStructureType.XR_TYPE_FRAME_WAIT_INFO
				};
				_xrFrameState.type = XrStructureType.XR_TYPE_FRAME_STATE;
				OpenXRAPI.xrWaitFrame(_xrSession, in frameWaitInfo, out _xrFrameState);
				MimesisWatchdog.MainStage = 3;
				XrFrameBeginInfo frameBeginInfo = new XrFrameBeginInfo
				{
					type = XrStructureType.XR_TYPE_FRAME_BEGIN_INFO
				};
				if (OpenXRAPI.xrBeginFrame(_xrSession, in frameBeginInfo) == XrResult.XR_FRAME_DISCARDED)
				{
					XrFrameEndInfo frameEndInfo = new XrFrameEndInfo
					{
						type = XrStructureType.XR_TYPE_FRAME_END_INFO,
						displayTime = _xrFrameState.predictedDisplayTime,
						layerCount = 0u,
						layers = IntPtr.Zero,
						environmentBlendMode = XrEnvironmentBlendMode.XR_ENVIRONMENT_BLEND_MODE_OPAQUE
					};
					OpenXRAPI.xrEndFrame(_xrSession, in frameEndInfo);
					return;
				}
			}
			XrFrameEndInfo endInfo = new XrFrameEndInfo
			{
				type = XrStructureType.XR_TYPE_FRAME_END_INFO,
				displayTime = _xrFrameState.predictedDisplayTime,
				environmentBlendMode = XrEnvironmentBlendMode.XR_ENVIRONMENT_BLEND_MODE_OPAQUE,
				layerCount = 0u,
				layers = IntPtr.Zero
			};
			if (_xrFrameState.shouldRender == 1)
			{
				MimesisWatchdog.MainStage = 4;
				XrViewLocateInfo viewLocateInfo = new XrViewLocateInfo
				{
					type = XrStructureType.XR_TYPE_VIEW_LOCATE_INFO,
					viewConfigurationType = _viewConfigType,
					displayTime = _xrFrameState.predictedDisplayTime,
					space = _appSpace
				};
				_locatedViewState.type = XrStructureType.XR_TYPE_VIEW_STATE;
				IntPtr intPtr2 = Marshal.AllocHGlobal(Marshal.SizeOf<XrView>() * _locatedViews.Length);
				try
				{
					for (int i = 0; i < _locatedViews.Length; i++)
					{
						Marshal.StructureToPtr(_locatedViews[i], intPtr2 + i * Marshal.SizeOf<XrView>(), fDeleteOld: false);
					}
					OpenXRAPI.xrLocateViews(_xrSession, in viewLocateInfo, out _locatedViewState, (uint)_locatedViews.Length, out var _, intPtr2);
					for (int j = 0; j < _locatedViews.Length; j++)
					{
						_locatedViews[j] = Marshal.PtrToStructure<XrView>(intPtr2 + j * Marshal.SizeOf<XrView>());
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr2);
				}
				bool num2 = (_locatedViewState.viewStateFlags & XrViewStateFlags.XR_VIEW_STATE_ORIENTATION_VALID_BIT) != 0;
				if (_controllers != null && _controllers.Ready && _currentSessionState == XrSessionState.XR_SESSION_STATE_FOCUSED)
				{
					_controllers.Update(_appSpace, _xrFrameState.predictedDisplayTime);
				}
				if (num2)
				{
					FollowGameCamera();
				}
				MimesisWatchdog.MainStage = 5;
				MimesisVrExtras.BeforeEyeRender(this);
				MimesisPerf.TPre = (float)stopwatch.Elapsed.TotalMilliseconds;
				if (num2)
				{
					uint index = 0u;
					uint index2 = 0u;
					if (!RtSubmit.NativeActive)
					{
						XrSwapchainImageAcquireInfo acquireInfo = new XrSwapchainImageAcquireInfo
						{
							type = XrStructureType.XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO
						};
						OpenXRAPI.xrAcquireSwapchainImage(_eyeSwapchains[0], in acquireInfo, out index);
						OpenXRAPI.xrAcquireSwapchainImage(_eyeSwapchains[1], in acquireInfo, out index2);
						XrSwapchainImageWaitInfo waitInfo = new XrSwapchainImageWaitInfo
						{
							type = XrStructureType.XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO,
							timeout = long.MaxValue
						};
						OpenXRAPI.xrWaitSwapchainImage(_eyeSwapchains[0], in waitInfo);
						OpenXRAPI.xrWaitSwapchainImage(_eyeSwapchains[1], in waitInfo);
					}
					MimesisVrExtras.PreEyes(_leftVrCamera, _rightVrCamera);
					try
					{
						MimesisWatchdog.MainStage = 6;
						RenderEye(0, index);
						MimesisPerf.TLeft = (float)stopwatch.Elapsed.TotalMilliseconds;
						MimesisWatchdog.MainStage = 7;
						RenderEye(1, index2);
						MimesisPerf.TRight = (float)stopwatch.Elapsed.TotalMilliseconds;
					}
					finally
					{
						MimesisVrExtras.PostEyes();
					}
					RtSubmit.AddRelease(_eyeSwapchains[0]);
					RtSubmit.AddRelease(_eyeSwapchains[1]);
					PopulateProjectionLayer();
					endInfo.layerCount = 1u;
					endInfo.layers = _pLayersForSubmit;
					MimesisWatchdog.MainStage = 8;
					endInfo.layerCount = SubmitQuadLayers();
					bool flag = MimesisVrExtras.MirrorRightEye && (Object)(object)_rightEyeIntermediateRT != (Object)null && (Object)(object)_rightVrCamera != (Object)null;
					MimesisVrExtras.MirrorToScreen(flag ? _rightEyeIntermediateRT : _leftEyeIntermediateRT, flag ? _rightVrCamera : _leftVrCamera, ((Object)(object)_vrRig != (Object)null) ? _vrRig.transform : null);
				}
			}
			MimesisWatchdog.MainStage = 9;
			RtSubmit.Submit(_xrSession, endInfo);
			MimesisWatchdog.MainStage = 10;
			MimesisWatchdog.Frames++;
			MimesisPerf.FrameDone((float)stopwatch.Elapsed.TotalMilliseconds, _xrFrameState.predictedDisplayPeriod);
		}

		private void RenderEye(int eyeIndex, uint swapchainImageIndex)
		{
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Invalid comparison between Unknown and I4
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Invalid comparison between Unknown and I4
			//IL_035f: Unknown result type (might be due to invalid IL or missing references)
			//IL_036c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Expected O, but got Unknown
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0491: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Expected O, but got Unknown
			//IL_04c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d1: Unknown result type (might be due to invalid IL or missing references)
			Camera val = ((eyeIndex == 0) ? _leftVrCamera : _rightVrCamera);
			float num = _refFar;
			Camera val2 = default(Camera);
			if (num <= 0f && (Object)(object)MimesisInput.GameCamera != (Object)null && ((Component)MimesisInput.GameCamera).TryGetComponent<Camera>(ref val2))
			{
				num = val2.farClipPlane;
			}
			if (num > 0f)
			{
				float num2 = ((MimesisImage.DrawDistance > 0f) ? Mathf.Min(num, MimesisImage.DrawDistance) : num);
				num2 = Mathf.Max(val.nearClipPlane * 20f, num2);
				if (!Mathf.Approximately(val.farClipPlane, num2))
				{
					val.farClipPlane = num2;
					if (eyeIndex == 0)
					{
						VRModCore.Log($"[MimesisVR] Eye far clip {num2:F0} m (game {num:F0} m)", "RenderEye", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 462);
					}
				}
			}
			UniversalAdditionalCameraData universalAdditionalCameraData = CameraExtensions.GetUniversalAdditionalCameraData(val);
			if ((Object)(object)universalAdditionalCameraData != (Object)null)
			{
				bool flag = _gamePost && MimesisImage.EyePost;
				if (universalAdditionalCameraData.renderPostProcessing != flag)
				{
					universalAdditionalCameraData.renderPostProcessing = flag;
				}
			}
			RenderTexture val3 = ((eyeIndex == 0) ? _leftEyeIntermediateRT : _rightEyeIntermediateRT);
			IntPtr intPtr = _eyeSwapchainImages[eyeIndex][(int)swapchainImageIndex];
			XrViewConfigurationView xrViewConfigurationView = _viewConfigViews[eyeIndex];
			int num3 = (MimesisVrExtras.LegacyFlip ? 1 : MimesisVrExtras.MsaaSamples);
			float num4 = (MimesisVrExtras.LegacyFlip ? 1f : Mathf.Clamp(MimesisImage.RenderScale, 0.4f, 1f));
			int recommendedImageRectWidth = (int)xrViewConfigurationView.recommendedImageRectWidth;
			int recommendedImageRectHeight = (int)xrViewConfigurationView.recommendedImageRectHeight;
			int num5 = Mathf.Max(64, Mathf.RoundToInt((float)recommendedImageRectWidth * num4));
			int num6 = Mathf.Max(64, Mathf.RoundToInt((float)recommendedImageRectHeight * num4));
			if ((Object)(object)val3 == (Object)null || !val3.IsCreated() || ((Texture)val3).width != num5 || ((Texture)val3).height != num6 || val3.antiAliasing != num3)
			{
				if ((Object)(object)val3 != (Object)null)
				{
					val3.Release();
					Object.Destroy((Object)(object)val3);
				}
				GraphicsFormat val4 = (GraphicsFormat)(((int)QualitySettings.activeColorSpace == 1) ? 57 : 59);
				val3 = new RenderTexture(num5, num6, 24, val4);
				val3.antiAliasing = num3;
				VRModCore.Log($"[MimesisVR] Eye {eyeIndex} RT {((Texture)val3).width}x{((Texture)val3).height}, MSAA x{num3}", "RenderEye", "MimesisVR/Features/VRVisualization/VrCameraSetup_CoreOpenXR.cs", 488);
				if (eyeIndex == 0)
				{
					_leftEyeIntermediateRT = val3;
				}
				else
				{
					_rightEyeIntermediateRT = val3;
				}
			}
			val.targetTexture = val3;
			val.clearFlags = _mainCameraClearFlags;
			if ((int)_mainCameraClearFlags == 2)
			{
				val.backgroundColor = _mainCameraBackgroundColor;
			}
			if (MimesisVrExtras.MenuBackdrop)
			{
				val.clearFlags = (CameraClearFlags)2;
				val.backgroundColor = new Color(0.035f, 0.035f, 0.045f, 1f);
			}
			val.cullingMask = _mainCameraCullingMask | MimesisVrExtras.VrOnlyLayerMask;
			((Behaviour)val).enabled = true;
			XrPosef pose = _locatedViews[eyeIndex].pose;
			Vector3 localPosition = default(Vector3);
			((Vector3)(ref localPosition))..ctor(pose.position.x, pose.position.y, 0f - pose.position.z);
			Quaternion localRotation = default(Quaternion);
			((Quaternion)(ref localRotation))..ctor(pose.orientation.x, pose.orientation.y, 0f - pose.orientation.z, 0f - pose.orientation.w);
			((Component)val).transform.localPosition = localPosition;
			((Component)val).transform.localRotation = localRotation;
			Matrix4x4 val5 = CreateProjectionMatrixFromFovUsingFrustum(_locatedViews[eyeIndex].fov, val.nearClipPlane, val.farClipPlane);
			bool legacyFlip = MimesisVrExtras.LegacyFlip;
			if (legacyFlip)
			{
				val5 = Matrix4x4.Scale(new Vector3(1f, -1f, 1f)) * val5;
			}
			val.projectionMatrix = val5;
			bool invertCulling = GL.invertCulling;
			if (legacyFlip)
			{
				GL.invertCulling = true;
			}
			val.Render();
			GL.invertCulling = invertCulling;
			if (!legacyFlip)
			{
				XrFovf fov = _locatedViews[eyeIndex].fov;
				MimesisHud.CompositeFx(val3, fov.angleLeft, fov.angleRight, fov.angleUp, fov.angleDown);
				MimesisWatches.CompositeDamage(val3);
			}
			RenderTexture val6 = val3;
			if (!legacyFlip && (Object)(object)val3 != (Object)null)
			{
				RenderTexture val7 = ((eyeIndex == 0) ? _leftFlipRT : _rightFlipRT);
				if ((Object)(object)val7 == (Object)null || ((Texture)val7).width != recommendedImageRectWidth || ((Texture)val7).height != recommendedImageRectHeight)
				{
					if ((Object)(object)val7 != (Object)null)
					{
						val7.Release();
						Object.Destroy((Object)(object)val7);
					}
					val7 = new RenderTexture(recommendedImageRectWidth, recommendedImageRectHeight, 0, val3.graphicsFormat);
					val7.Create();
					if (eyeIndex == 0)
					{
						_leftFlipRT = val7;
					}
					else
					{
						_rightFlipRT = val7;
					}
				}
				Graphics.Blit((Texture)(object)val3, val7, n

UserLibs/UniverseLib.Mono.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UniverseLib.Config;
using UniverseLib.Input;
using UniverseLib.Runtime;
using UniverseLib.Runtime.Mono;
using UniverseLib.UI;
using UniverseLib.UI.Models;
using UniverseLib.UI.ObjectPool;
using UniverseLib.UI.Panels;
using UniverseLib.UI.Widgets;
using UniverseLib.UI.Widgets.ScrollView;
using UniverseLib.Utility;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("UniverseLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sinai, yukieiji")]
[assembly: AssemblyProduct("UniverseLib")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b21dbde3-5d6f-4726-93ab-cc3cc68bae7d")]
[assembly: AssemblyFileVersion("1.5.11")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.11.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class MonoExtensions
{
	private static PropertyInfo p_childControlHeight = AccessTools.Property(typeof(HorizontalOrVerticalLayoutGroup), "childControlHeight");

	private static PropertyInfo p_childControlWidth = AccessTools.Property(typeof(HorizontalOrVerticalLayoutGroup), "childControlWidth");

	public static void AddListener(this UnityEvent _event, Action listener)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		_event.AddListener(new UnityAction(listener.Invoke));
	}

	public static void AddListener<T>(this UnityEvent<T> _event, Action<T> listener)
	{
		_event.AddListener((UnityAction<T>)listener.Invoke);
	}

	public static void RemoveListener(this UnityEvent _event, Action listener)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		_event.RemoveListener(new UnityAction(listener.Invoke));
	}

	public static void RemoveListener<T>(this UnityEvent<T> _event, Action<T> listener)
	{
		_event.RemoveListener((UnityAction<T>)listener.Invoke);
	}

	public static void Clear(this StringBuilder sb)
	{
		sb.Remove(0, sb.Length);
	}

	public static void SetChildControlHeight(this HorizontalOrVerticalLayoutGroup group, bool value)
	{
		p_childControlHeight?.SetValue(group, value, null);
	}

	public static void SetChildControlWidth(this HorizontalOrVerticalLayoutGroup group, bool value)
	{
		p_childControlWidth?.SetValue(group, value, null);
	}
}
namespace UniverseLib
{
	public static class ReflectionExtensions
	{
		public static Type GetActualType(this object obj)
		{
			return ReflectionUtility.Instance.Internal_GetActualType(obj);
		}

		public static object TryCast(this object obj)
		{
			return ReflectionUtility.Instance.Internal_TryCast(obj, ReflectionUtility.Instance.Internal_GetActualType(obj));
		}

		public static object TryCast(this object obj, Type castTo)
		{
			return ReflectionUtility.Instance.Internal_TryCast(obj, castTo);
		}

		public static T TryCast<T>(this object obj)
		{
			try
			{
				return (T)ReflectionUtility.Instance.Internal_TryCast(obj, typeof(T));
			}
			catch
			{
				return default(T);
			}
		}

		public static Type[] TryGetTypes(this Assembly asm)
		{
			try
			{
				return asm.GetTypes();
			}
			catch (ReflectionTypeLoadException e)
			{
				return ReflectionUtility.TryExtractTypesFromException(e);
			}
			catch
			{
				try
				{
					return asm.GetExportedTypes();
				}
				catch (ReflectionTypeLoadException e2)
				{
					return ReflectionUtility.TryExtractTypesFromException(e2);
				}
				catch
				{
					return ArgumentUtility.EmptyTypes;
				}
			}
		}

		public static bool ReferenceEqual(this object objA, object objB)
		{
			if (objA == objB)
			{
				return true;
			}
			Object val = (Object)((objA is Object) ? objA : null);
			if (val != null)
			{
				Object val2 = (Object)((objB is Object) ? objB : null);
				if (val2 != null && Object.op_Implicit(val) && Object.op_Implicit(val2) && val.m_CachedPtr == val2.m_CachedPtr)
				{
					return true;
				}
			}
			return false;
		}

		public static string ReflectionExToString(this Exception e, bool innerMost = true)
		{
			if (e == null)
			{
				return "The exception was null.";
			}
			if (innerMost)
			{
				e = e.GetInnerMostException();
			}
			return $"{e.GetType()}: {e.Message}";
		}

		public static Exception GetInnerMostException(this Exception e)
		{
			while (e != null && e.InnerException != null)
			{
				e = e.InnerException;
			}
			return e;
		}
	}
	public class ReflectionUtility
	{
		public static bool Initializing;

		public const BindingFlags FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public static readonly SortedDictionary<string, Type> AllTypes = new SortedDictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

		public static readonly List<string> AllNamespaces = new List<string>();

		private static readonly HashSet<string> uniqueNamespaces = new HashSet<string>();

		private static string[] allTypeNamesArray;

		private static readonly Dictionary<string, Type> shorthandToType = new Dictionary<string, Type>
		{
			{
				"object",
				typeof(object)
			},
			{
				"string",
				typeof(string)
			},
			{
				"bool",
				typeof(bool)
			},
			{
				"byte",
				typeof(byte)
			},
			{
				"sbyte",
				typeof(sbyte)
			},
			{
				"char",
				typeof(char)
			},
			{
				"decimal",
				typeof(decimal)
			},
			{
				"double",
				typeof(double)
			},
			{
				"float",
				typeof(float)
			},
			{
				"int",
				typeof(int)
			},
			{
				"uint",
				typeof(uint)
			},
			{
				"long",
				typeof(long)
			},
			{
				"ulong",
				typeof(ulong)
			},
			{
				"short",
				typeof(short)
			},
			{
				"ushort",
				typeof(ushort)
			},
			{
				"void",
				typeof(void)
			}
		};

		internal static readonly Dictionary<string, Type[]> baseTypes = new Dictionary<string, Type[]>();

		internal static ReflectionUtility Instance { get; private set; }

		public static event Action<Type> OnTypeLoaded;

		internal static void Init()
		{
			Instance = new ReflectionUtility();
			Instance.Initialize();
		}

		protected virtual void Initialize()
		{
			SetupTypeCache();
			Initializing = false;
		}

		public static string[] GetTypeNameArray()
		{
			if (allTypeNamesArray == null || allTypeNamesArray.Length != AllTypes.Count)
			{
				allTypeNamesArray = new string[AllTypes.Count];
				int num = 0;
				foreach (string key in AllTypes.Keys)
				{
					allTypeNamesArray[num] = key;
					num++;
				}
			}
			return allTypeNamesArray;
		}

		private static void SetupTypeCache()
		{
			if (!ConfigManager.Disable_Setup_Force_ReLoad_ManagedAssemblies && Universe.Context == RuntimeContext.Mono)
			{
				ForceLoadManagedAssemblies();
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				CacheTypes(assemblies[i]);
			}
			AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded;
		}

		private static void AssemblyLoaded(object sender, AssemblyLoadEventArgs args)
		{
			if ((object)args.LoadedAssembly != null && !(args.LoadedAssembly.GetName().Name == "completions"))
			{
				CacheTypes(args.LoadedAssembly);
			}
		}

		private static void ForceLoadManagedAssemblies()
		{
			string path = Path.Combine(Application.dataPath, "Managed");
			if (!Directory.Exists(path))
			{
				return;
			}
			string[] files = Directory.GetFiles(path, "*.dll");
			foreach (string assemblyFile in files)
			{
				try
				{
					Assembly.LoadFrom(assemblyFile).TryGetTypes();
				}
				catch
				{
				}
			}
		}

		internal static void CacheTypes(Assembly asm)
		{
			Type[] array = asm.TryGetTypes();
			foreach (Type type in array)
			{
				try
				{
					string text = type.Namespace;
					if (!string.IsNullOrEmpty(text) && uniqueNamespaces.Add(text))
					{
						int num = 0;
						foreach (string allNamespace in AllNamespaces)
						{
							if (text.CompareTo(allNamespace) >= 0)
							{
								num++;
								continue;
							}
							break;
						}
						AllNamespaces.Insert(num, text);
					}
				}
				catch (Exception arg)
				{
					Universe.LogWarning($"THIS WARNING IS NOT BUG!!!! DON'T REPORT THIS!!!!!\n Can't cache type named {type.Name} Error: {arg}");
				}
				AllTypes[type.FullName] = type;
				ReflectionUtility.OnTypeLoaded?.Invoke(type);
			}
		}

		public static Type GetTypeByName(string fullName)
		{
			return Instance.Internal_GetTypeByName(fullName);
		}

		internal virtual Type Internal_GetTypeByName(string fullName)
		{
			if (shorthandToType.TryGetValue(fullName, out var value))
			{
				return value;
			}
			AllTypes.TryGetValue(fullName, out var value2);
			if ((object)value2 == null)
			{
				return Type.GetType(fullName);
			}
			return value2;
		}

		internal virtual Type Internal_GetActualType(object obj)
		{
			return obj?.GetType();
		}

		internal virtual object Internal_TryCast(object obj, Type castTo)
		{
			return obj;
		}

		public static string ProcessTypeInString(Type type, string theString)
		{
			return Instance.Internal_ProcessTypeInString(theString, type);
		}

		internal virtual string Internal_ProcessTypeInString(string theString, Type type)
		{
			return theString;
		}

		public static void FindSingleton(string[] possibleNames, Type type, BindingFlags flags, List<object> instances)
		{
			Instance.Internal_FindSingleton(possibleNames, type, flags, instances);
		}

		internal virtual void Internal_FindSingleton(string[] possibleNames, Type type, BindingFlags flags, List<object> instances)
		{
			foreach (string name in possibleNames)
			{
				FieldInfo field = type.GetField(name, flags);
				if ((object)field != null)
				{
					object value = field.GetValue(null);
					if (value != null)
					{
						instances.Add(value);
						break;
					}
				}
			}
		}

		public static Type[] TryExtractTypesFromException(ReflectionTypeLoadException e)
		{
			try
			{
				return e.Types.Where((Type it) => (object)it != null).ToArray();
			}
			catch
			{
				return ArgumentUtility.EmptyTypes;
			}
		}

		public static Type[] GetAllBaseTypes(object obj)
		{
			return GetAllBaseTypes(obj?.GetActualType());
		}

		public static Type[] GetAllBaseTypes(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			string assemblyQualifiedName = type.AssemblyQualifiedName;
			if (baseTypes.TryGetValue(assemblyQualifiedName, out var value))
			{
				return value;
			}
			List<Type> list = new List<Type>();
			while ((object)type != null)
			{
				list.Add(type);
				type = type.BaseType;
			}
			value = list.ToArray();
			baseTypes.Add(assemblyQualifiedName, value);
			return value;
		}

		public static void GetImplementationsOf(Type baseType, Action<HashSet<Type>> onResultsFetched, bool allowAbstract, bool allowGeneric, bool allowEnum)
		{
			RuntimeHelper.StartCoroutine(DoGetImplementations(onResultsFetched, baseType, allowAbstract, allowGeneric, allowEnum));
		}

		private static IEnumerator DoGetImplementations(Action<HashSet<Type>> onResultsFetched, Type baseType, bool allowAbstract, bool allowGeneric, bool allowEnum)
		{
			List<Type> resolvedTypes = new List<Type>();
			OnTypeLoaded += ourListener;
			HashSet<Type> set = new HashSet<Type>();
			IEnumerator coro = GetImplementationsAsync(baseType, set, allowAbstract, allowGeneric, allowEnum, DefaultTypesEnumerator());
			while (coro.MoveNext())
			{
				yield return null;
			}
			OnTypeLoaded -= ourListener;
			if (resolvedTypes.Count > 0)
			{
				coro = GetImplementationsAsync(baseType, set, allowAbstract, allowGeneric, allowEnum, resolvedTypes.GetEnumerator());
				while (coro.MoveNext())
				{
					yield return null;
				}
			}
			onResultsFetched(set);
			void ourListener(Type t)
			{
				resolvedTypes.Add(t);
			}
		}

		private static IEnumerator<Type> DefaultTypesEnumerator()
		{
			string[] names = GetTypeNameArray();
			foreach (string key in names)
			{
				yield return AllTypes[key];
			}
		}

		private static IEnumerator GetImplementationsAsync(Type baseType, HashSet<Type> set, bool allowAbstract, bool allowGeneric, bool allowEnum, IEnumerator<Type> enumerator)
		{
			Stopwatch sw = new Stopwatch();
			sw.Start();
			bool isGenericParam = baseType?.IsGenericParameter ?? false;
			while (enumerator.MoveNext())
			{
				if (sw.ElapsedMilliseconds > 10)
				{
					yield return null;
					sw.Reset();
					sw.Start();
				}
				try
				{
					Type type = enumerator.Current;
					if (set.Contains(type) || (!allowAbstract && type.IsAbstract) || (!allowGeneric && type.IsGenericType) || (!allowEnum && type.IsEnum) || type.FullName.Contains("PrivateImplementationDetails") || type.FullName.Contains("DisplayClass") || Enumerable.Contains(type.FullName, '<'))
					{
						continue;
					}
					if (!isGenericParam)
					{
						if ((object)baseType == null || baseType.IsAssignableFrom(type))
						{
							goto IL_01e2;
						}
					}
					else if ((!type.IsClass || !MiscUtility.HasFlag(baseType.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint)) && (!type.IsValueType || !MiscUtility.HasFlag(baseType.GenericParameterAttributes, GenericParameterAttributes.ReferenceTypeConstraint)) && !baseType.GetGenericParameterConstraints().Any((Type it) => !it.IsAssignableFrom(type)))
					{
						goto IL_01e2;
					}
					goto end_IL_008c;
					IL_01e2:
					set.Add(type);
					end_IL_008c:;
				}
				catch
				{
				}
			}
		}

		public static bool IsEnumerable(Type type)
		{
			return Instance.Internal_IsEnumerable(type);
		}

		protected virtual bool Internal_IsEnumerable(Type type)
		{
			return typeof(IEnumerable).IsAssignableFrom(type);
		}

		public static bool TryGetEnumerator(object ienumerable, out IEnumerator enumerator)
		{
			return Instance.Internal_TryGetEnumerator(ienumerable, out enumerator);
		}

		protected virtual bool Internal_TryGetEnumerator(object list, out IEnumerator enumerator)
		{
			enumerator = (list as IEnumerable).GetEnumerator();
			return true;
		}

		public static bool TryGetEntryType(Type enumerableType, out Type type)
		{
			return Instance.Internal_TryGetEntryType(enumerableType, out type);
		}

		protected virtual bool Internal_TryGetEntryType(Type enumerableType, out Type type)
		{
			if (enumerableType.IsArray)
			{
				type = enumerableType.GetElementType();
				return true;
			}
			Type[] interfaces = enumerableType.GetInterfaces();
			foreach (Type type2 in interfaces)
			{
				if (type2.IsGenericType)
				{
					Type genericTypeDefinition = type2.GetGenericTypeDefinition();
					if ((object)genericTypeDefinition == typeof(IEnumerable<>) || (object)genericTypeDefinition == typeof(IList<>) || (object)genericTypeDefinition == typeof(ICollection<>))
					{
						type = type2.GetGenericArguments()[0];
						return true;
					}
				}
			}
			type = typeof(object);
			return false;
		}

		public static bool IsDictionary(Type type)
		{
			return Instance.Internal_IsDictionary(type);
		}

		protected virtual bool Internal_IsDictionary(Type type)
		{
			return typeof(IDictionary).IsAssignableFrom(type);
		}

		public static bool TryGetDictEnumerator(object dictionary, out IEnumerator<DictionaryEntry> dictEnumerator)
		{
			return Instance.Internal_TryGetDictEnumerator(dictionary, out dictEnumerator);
		}

		protected virtual bool Internal_TryGetDictEnumerator(object dictionary, out IEnumerator<DictionaryEntry> dictEnumerator)
		{
			dictEnumerator = EnumerateDictionary((IDictionary)dictionary);
			return true;
		}

		private IEnumerator<DictionaryEntry> EnumerateDictionary(IDictionary dict)
		{
			IDictionaryEnumerator enumerator = dict.GetEnumerator();
			while (enumerator.MoveNext())
			{
				yield return new DictionaryEntry(enumerator.Key, enumerator.Value);
			}
		}

		public static bool TryGetEntryTypes(Type dictionaryType, out Type keys, out Type values)
		{
			return Instance.Internal_TryGetEntryTypes(dictionaryType, out keys, out values);
		}

		protected virtual bool Internal_TryGetEntryTypes(Type dictionaryType, out Type keys, out Type values)
		{
			Type[] interfaces = dictionaryType.GetInterfaces();
			foreach (Type type in interfaces)
			{
				if (type.IsGenericType && (object)type.GetGenericTypeDefinition() == typeof(IDictionary<, >))
				{
					Type[] genericArguments = type.GetGenericArguments();
					keys = genericArguments[0];
					values = genericArguments[1];
					return true;
				}
			}
			keys = typeof(object);
			values = typeof(object);
			return false;
		}
	}
	public abstract class RuntimeHelper
	{
		internal static RuntimeHelper Instance { get; private set; }

		internal static void Init()
		{
			Instance = new MonoProvider();
			Instance.OnInitialize();
		}

		protected internal abstract void OnInitialize();

		public static Coroutine StartCoroutine(IEnumerator routine)
		{
			return Instance.Internal_StartCoroutine(routine);
		}

		protected internal abstract Coroutine Internal_StartCoroutine(IEnumerator routine);

		public static void StopCoroutine(Coroutine coroutine)
		{
			Instance.Internal_StopCoroutine(coroutine);
		}

		protected internal abstract void Internal_StopCoroutine(Coroutine coroutine);

		public static T AddComponent<T>(GameObject obj, Type type) where T : Component
		{
			return Instance.Internal_AddComponent<T>(obj, type);
		}

		protected internal abstract T Internal_AddComponent<T>(GameObject obj, Type type) where T : Component;

		public static ScriptableObject CreateScriptable(Type type)
		{
			return Instance.Internal_CreateScriptable(type);
		}

		protected internal abstract ScriptableObject Internal_CreateScriptable(Type type);

		public static string LayerToName(int layer)
		{
			return Instance.Internal_LayerToName(layer);
		}

		protected internal abstract string Internal_LayerToName(int layer);

		public static T[] FindObjectsOfTypeAll<T>() where T : Object
		{
			return Instance.Internal_FindObjectsOfTypeAll<T>();
		}

		public static Object[] FindObjectsOfTypeAll(Type type)
		{
			return Instance.Internal_FindObjectsOfTypeAll(type);
		}

		protected internal abstract T[] Internal_FindObjectsOfTypeAll<T>() where T : Object;

		protected internal abstract Object[] Internal_FindObjectsOfTypeAll(Type type);

		public static void GraphicRaycast(GraphicRaycaster raycaster, PointerEventData data, List<RaycastResult> list)
		{
			Instance.Internal_GraphicRaycast(raycaster, data, list);
		}

		protected internal abstract void Internal_GraphicRaycast(GraphicRaycaster raycaster, PointerEventData data, List<RaycastResult> list);

		public static GameObject[] GetRootGameObjects(Scene scene)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return Instance.Internal_GetRootGameObjects(scene);
		}

		protected internal abstract GameObject[] Internal_GetRootGameObjects(Scene scene);

		public static int GetRootCount(Scene scene)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return Instance.Internal_GetRootCount(scene);
		}

		protected internal abstract int Internal_GetRootCount(Scene scene);

		public static void SetColorBlockAuto(Selectable selectable, Color baseColor)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			Instance.Internal_SetColorBlock(selectable, baseColor, baseColor * 1.2f, baseColor * 0.8f);
		}

		public static void SetColorBlock(Selectable selectable, ColorBlock colors)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Instance.Internal_SetColorBlock(selectable, colors);
		}

		protected internal abstract void Internal_SetColorBlock(Selectable selectable, ColorBlock colors);

		public static void SetColorBlock(Selectable selectable, Color? normal = null, Color? highlighted = null, Color? pressed = null, Color? disabled = null)
		{
			Instance.Internal_SetColorBlock(selectable, normal, highlighted, pressed, disabled);
		}

		protected internal abstract void Internal_SetColorBlock(Selectable selectable, Color? normal = null, Color? highlighted = null, Color? pressed = null, Color? disabled = null);
	}
	internal class UniversalBehaviour : MonoBehaviour
	{
		internal static UniversalBehaviour Instance { get; private set; }

		internal static void Setup()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("UniverseLibBehaviour");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)(((Object)val).hideFlags | 0x3D);
			Instance = val.AddComponent<UniversalBehaviour>();
		}

		internal void Update()
		{
			Universe.Update();
		}
	}
	public static class Universe
	{
		public enum GlobalState
		{
			WaitingToSetup,
			SettingUp,
			SetupCompleted
		}

		public const string NAME = "UniverseLib";

		public const string VERSION = "1.5.11";

		public const string AUTHOR = "Sinai, yukieiji";

		public const string GUID = "com.sinai.universelib";

		private static float startupDelay;

		private static Action<string, LogType> logHandler;

		public static RuntimeContext Context { get; } = RuntimeContext.Mono;

		public static GlobalState CurrentGlobalState { get; private set; }

		internal static Harmony Harmony { get; } = new Harmony("com.sinai.universelib");

		private static event Action OnInitialized;

		public static void Init(Action onInitialized = null, Action<string, LogType> logHandler = null)
		{
			Init(1f, onInitialized, logHandler, default(UniverseLibConfig));
		}

		public static void Init(float startupDelay, Action onInitialized, Action<string, LogType> logHandler, UniverseLibConfig config)
		{
			if (CurrentGlobalState == GlobalState.SetupCompleted)
			{
				InvokeOnInitialized(onInitialized);
				return;
			}
			if (startupDelay > Universe.startupDelay)
			{
				Universe.startupDelay = startupDelay;
			}
			ConfigManager.LoadConfig(config);
			OnInitialized += onInitialized;
			if (logHandler != null && Universe.logHandler == null)
			{
				Universe.logHandler = logHandler;
			}
			if (CurrentGlobalState == GlobalState.WaitingToSetup)
			{
				CurrentGlobalState = GlobalState.SettingUp;
				Log("UniverseLib 1.5.11 initializing...");
				UniversalBehaviour.Setup();
				ReflectionUtility.Init();
				RuntimeHelper.Init();
				RuntimeHelper.Instance.Internal_StartCoroutine(SetupCoroutine());
				Log("Finished UniverseLib initial setup.");
			}
		}

		internal static void Update()
		{
			UniversalUI.Update();
		}

		private static IEnumerator SetupCoroutine()
		{
			yield return null;
			Stopwatch sw = new Stopwatch();
			sw.Start();
			while (ReflectionUtility.Initializing || (float)sw.ElapsedMilliseconds * 0.001f < startupDelay)
			{
				yield return null;
			}
			InputManager.Init();
			UniversalUI.Init();
			Log("UniverseLib 1.5.11 initialized.");
			CurrentGlobalState = GlobalState.SetupCompleted;
			InvokeOnInitialized(Universe.OnInitialized);
		}

		private static void InvokeOnInitialized(Action onInitialized)
		{
			if (onInitialized == null)
			{
				return;
			}
			Delegate[] invocationList = onInitialized.GetInvocationList();
			foreach (Delegate obj in invocationList)
			{
				try
				{
					obj.DynamicInvoke();
				}
				catch (Exception arg)
				{
					LogWarning($"Exception invoking onInitialized callback! {arg}");
				}
			}
		}

		internal static void Log(object message)
		{
			Log(message, (LogType)3);
		}

		internal static void LogWarning(object message)
		{
			Log(message, (LogType)2);
		}

		internal static void LogError(object message)
		{
			Log(message, (LogType)0);
		}

		private static void Log(object message, LogType logType)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (logHandler != null)
			{
				logHandler("[UniverseLib] " + (message?.ToString() ?? string.Empty), logType);
			}
		}

		internal static bool Patch(Type type, string methodName, MethodType methodType, Type[] arguments = null, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			try
			{
				string text = (((int)methodType == 1) ? "get_" : (((int)methodType != 2) ? string.Empty : "set_"));
				string text2 = text;
				MethodInfo methodInfo = ((arguments == null) ? type.GetMethod(text2 + methodName, AccessTools.all) : type.GetMethod(text2 + methodName, AccessTools.all, null, arguments, null));
				if ((object)methodInfo == null)
				{
					return false;
				}
				PatchProcessor val = Harmony.CreateProcessor((MethodBase)methodInfo);
				if ((object)prefix != null)
				{
					val.AddPrefix(new HarmonyMethod(prefix));
				}
				if ((object)postfix != null)
				{
					val.AddPostfix(new HarmonyMethod(postfix));
				}
				if ((object)finalizer != null)
				{
					val.AddFinalizer(new HarmonyMethod(finalizer));
				}
				val.Patch();
				return true;
			}
			catch (Exception arg)
			{
				LogWarning($"\t Exception patching {type.FullName}.{methodName}: {arg}");
				return false;
			}
		}

		internal static bool Patch(Type type, string[] possibleNames, MethodType methodType, Type[] arguments = null, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			foreach (string methodName in possibleNames)
			{
				if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool Patch(Type type, string[] possibleNames, MethodType methodType, Type[][] possibleArguments, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			foreach (string methodName in possibleNames)
			{
				foreach (Type[] arguments in possibleArguments)
				{
					if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer))
					{
						return true;
					}
				}
			}
			return false;
		}

		internal static bool Patch(Type type, string methodName, MethodType methodType, Type[][] possibleArguments, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			foreach (Type[] arguments in possibleArguments)
			{
				if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer))
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace UniverseLib.Utility
{
	public static class ArgumentUtility
	{
		public static readonly Type[] EmptyTypes = new Type[0];

		public static readonly object[] EmptyArgs = new object[0];

		public static readonly Type[] ParseArgs = new Type[1] { typeof(string) };
	}
	public static class IOUtility
	{
		private static readonly char[] invalidDirectoryCharacters = Path.GetInvalidPathChars();

		private static readonly char[] invalidFilenameCharacters = Path.GetInvalidFileNameChars();

		public static string EnsureValidFilePath(string fullPathWithFile)
		{
			fullPathWithFile = string.Concat(fullPathWithFile.Split(invalidDirectoryCharacters));
			Directory.CreateDirectory(Path.GetDirectoryName(fullPathWithFile));
			return fullPathWithFile;
		}

		public static string EnsureValidFilename(string filename)
		{
			return string.Concat(filename.Split(invalidFilenameCharacters));
		}
	}
	public static class MiscUtility
	{
		public static bool ContainsIgnoreCase(this string _this, string s)
		{
			return CultureInfo.CurrentCulture.CompareInfo.IndexOf(_this, s, CompareOptions.IgnoreCase) >= 0;
		}

		public static bool HasFlag(this Enum flags, Enum value)
		{
			try
			{
				ulong num = Convert.ToUInt64(value);
				return (Convert.ToUInt64(flags) & num) == num;
			}
			catch
			{
				long num2 = Convert.ToInt64(value);
				return (Convert.ToInt64(flags) & num2) == num2;
			}
		}

		public static bool EndsWith(this StringBuilder sb, string _string)
		{
			int length = _string.Length;
			if (sb.Length < length)
			{
				return false;
			}
			int num = 0;
			int num2 = sb.Length - length;
			while (num2 < sb.Length)
			{
				if (sb[num2] != _string[num])
				{
					return false;
				}
				num2++;
				num++;
			}
			return true;
		}
	}
	public static class ParseUtility
	{
		internal delegate object ParseMethod(string input);

		internal delegate string ToStringMethod(object obj);

		public static readonly string NumberFormatString = "0.####";

		private static readonly Dictionary<int, string> numSequenceStrings = new Dictionary<int, string>();

		private static readonly HashSet<Type> nonPrimitiveTypes = new HashSet<Type>
		{
			typeof(string),
			typeof(decimal),
			typeof(DateTime)
		};

		private static readonly HashSet<Type> formattedTypes = new HashSet<Type>
		{
			typeof(float),
			typeof(double),
			typeof(decimal)
		};

		private static readonly Dictionary<string, string> typeInputExamples = new Dictionary<string, string>();

		private static readonly Dictionary<string, ParseMethod> customTypes = new Dictionary<string, ParseMethod>
		{
			{
				typeof(Vector2).FullName,
				TryParseVector2
			},
			{
				typeof(Vector3).FullName,
				TryParseVector3
			},
			{
				typeof(Vector4).FullName,
				TryParseVector4
			},
			{
				typeof(Quaternion).FullName,
				TryParseQuaternion
			},
			{
				typeof(Rect).FullName,
				TryParseRect
			},
			{
				typeof(Color).FullName,
				TryParseColor
			},
			{
				typeof(Color32).FullName,
				TryParseColor32
			},
			{
				typeof(LayerMask).FullName,
				TryParseLayerMask
			}
		};

		private static readonly Dictionary<string, ToStringMethod> customTypesToString = new Dictionary<string, ToStringMethod>
		{
			{
				typeof(Vector2).FullName,
				Vector2ToString
			},
			{
				typeof(Vector3).FullName,
				Vector3ToString
			},
			{
				typeof(Vector4).FullName,
				Vector4ToString
			},
			{
				typeof(Quaternion).FullName,
				QuaternionToString
			},
			{
				typeof(Rect).FullName,
				RectToString
			},
			{
				typeof(Color).FullName,
				ColorToString
			},
			{
				typeof(Color32).FullName,
				Color32ToString
			},
			{
				typeof(LayerMask).FullName,
				LayerMaskToString
			}
		};

		public static string FormatDecimalSequence(params object[] numbers)
		{
			if (numbers.Length == 0)
			{
				return null;
			}
			return string.Format(CultureInfo.CurrentCulture, GetSequenceFormatString(numbers.Length), numbers);
		}

		internal static string GetSequenceFormatString(int count)
		{
			if (count <= 0)
			{
				return null;
			}
			if (numSequenceStrings.ContainsKey(count))
			{
				return numSequenceStrings[count];
			}
			string[] array = new string[count];
			for (int i = 0; i < count; i++)
			{
				array[i] = $"{{{i}:{NumberFormatString}}}";
			}
			string text = string.Join(" ", array);
			numSequenceStrings.Add(count, text);
			return text;
		}

		public static bool CanParse(Type type)
		{
			if (!string.IsNullOrEmpty(type?.FullName))
			{
				if (!type.IsPrimitive && !type.IsEnum && !nonPrimitiveTypes.Contains(type))
				{
					return customTypes.ContainsKey(type.FullName);
				}
				return true;
			}
			return false;
		}

		public static bool CanParse<T>()
		{
			return CanParse(typeof(T));
		}

		public static bool TryParse<T>(string input, out T obj, out Exception parseException)
		{
			object obj2;
			bool result = TryParse(input, typeof(T), out obj2, out parseException);
			if (obj2 != null)
			{
				obj = (T)obj2;
				return result;
			}
			obj = default(T);
			return result;
		}

		public static bool TryParse(string input, Type type, out object obj, out Exception parseException)
		{
			obj = null;
			parseException = null;
			if ((object)type == null)
			{
				return false;
			}
			if ((object)type == typeof(string))
			{
				obj = input;
				return true;
			}
			if (type.IsEnum)
			{
				try
				{
					obj = Enum.Parse(type, input);
					return true;
				}
				catch (Exception e)
				{
					parseException = e.GetInnerMostException();
					return false;
				}
			}
			try
			{
				if (customTypes.ContainsKey(type.FullName))
				{
					obj = customTypes[type.FullName](input);
				}
				else
				{
					obj = AccessTools.Method(type, "Parse", ArgumentUtility.ParseArgs, (Type[])null).Invoke(null, new object[1] { input });
				}
				return true;
			}
			catch (Exception e2)
			{
				Exception innerMostException = e2.GetInnerMostException();
				parseException = innerMostException;
			}
			return false;
		}

		public static string ToStringForInput<T>(object obj)
		{
			return ToStringForInput(obj, typeof(T));
		}

		public static string ToStringForInput(object obj, Type type)
		{
			if ((object)type == null || obj == null)
			{
				return null;
			}
			if ((object)type == typeof(string))
			{
				return obj as string;
			}
			if (type.IsEnum)
			{
				if (!Enum.IsDefined(type, obj))
				{
					return obj.ToString();
				}
				return Enum.GetName(type, obj);
			}
			try
			{
				if (customTypes.ContainsKey(type.FullName))
				{
					return customTypesToString[type.FullName](obj);
				}
				if (formattedTypes.Contains(type))
				{
					return AccessTools.Method(type, "ToString", new Type[2]
					{
						typeof(string),
						typeof(IFormatProvider)
					}, (Type[])null).Invoke(obj, new object[2]
					{
						NumberFormatString,
						CultureInfo.CurrentCulture
					}) as string;
				}
				return obj.ToString();
			}
			catch (Exception arg)
			{
				Universe.LogWarning($"Exception formatting object for input: {arg}");
				return null;
			}
		}

		public static string GetExampleInput<T>()
		{
			return GetExampleInput(typeof(T));
		}

		public static string GetExampleInput(Type type)
		{
			if (!typeInputExamples.ContainsKey(type.AssemblyQualifiedName))
			{
				try
				{
					if (type.IsEnum)
					{
						typeInputExamples.Add(type.AssemblyQualifiedName, Enum.GetNames(type).First());
					}
					else
					{
						object obj = Activator.CreateInstance(type);
						typeInputExamples.Add(type.AssemblyQualifiedName, ToStringForInput(obj, type));
					}
				}
				catch (Exception message)
				{
					Universe.LogWarning("Exception generating default instance for example input for '" + type.FullName + "'");
					Universe.Log(message);
					return "";
				}
			}
			return typeInputExamples[type.AssemblyQualifiedName];
		}

		internal static object TryParseVector2(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = default(Vector2);
			string[] array = input.Split(new char[1] { ' ' });
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

		internal static string Vector2ToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Vector2 val))
			{
				return null;
			}
			return FormatDecimalSequence(val.x, val.y);
		}

		internal static object TryParseVector3(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			string[] array = input.Split(new char[1] { ' ' });
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

		internal static string Vector3ToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Vector3 val))
			{
				return null;
			}
			return FormatDecimalSequence(val.x, val.y, val.z);
		}

		internal static object TryParseVector4(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			Vector4 val = default(Vector4);
			string[] array = input.Split(new char[1] { ' ' });
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			val.w = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

		internal static string Vector4ToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Vector4 val))
			{
				return null;
			}
			return FormatDecimalSequence(val.x, val.y, val.z, val.w);
		}

		internal static object TryParseQuaternion(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			string[] array = input.Split(new char[1] { ' ' });
			if (array.Length == 4)
			{
				return (object)new Quaternion
				{
					x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture),
					y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture),
					z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture),
					w = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture)
				};
			}
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			return Quaternion.Euler(val);
		}

		internal static string QuaternionToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Quaternion val))
			{
				return null;
			}
			Vector3 eulerAngles = ((Quaternion)(ref val)).eulerAngles;
			return FormatDecimalSequence(eulerAngles.x, eulerAngles.y, eulerAngles.z);
		}

		internal static object TryParseRect(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			Rect val = default(Rect);
			string[] array = input.Split(new char[1] { ' ' });
			((Rect)(ref val)).x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			((Rect)(ref val)).y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			((Rect)(ref val)).width = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			((Rect)(ref val)).height = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

		internal static string RectToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Rect val))
			{
				return null;
			}
			return FormatDecimalSequence(((Rect)(ref val)).x, ((Rect)(ref val)).y, ((Rect)(ref val)).width, ((Rect)(ref val)).height);
		}

		internal static object TryParseColor(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			Color val = default(Color);
			string[] array = input.Split(new char[1] { ' ' });
			val.r = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.g = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.b = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			if (array.Length > 3)
			{
				val.a = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			}
			else
			{
				val.a = 1f;
			}
			return val;
		}

		internal static string ColorToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Color val))
			{
				return null;
			}
			return FormatDecimalSequence(val.r, val.g, val.b, val.a);
		}

		internal static object TryParseColor32(string input)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			Color32 val = default(Color32);
			string[] array = input.Split(new char[1] { ' ' });
			val.r = byte.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.g = byte.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.b = byte.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			if (array.Length > 3)
			{
				val.a = byte.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			}
			else
			{
				val.a = byte.MaxValue;
			}
			return val;
		}

		internal static string Color32ToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Color32 val))
			{
				return null;
			}
			return $"{val.r} {val.g} {val.b} {val.a}";
		}

		internal static object TryParseLayerMask(string input)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return LayerMask.op_Implicit(int.Parse(input));
		}

		internal static string LayerMaskToString(object obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is LayerMask val))
			{
				return null;
			}
			return ((LayerMask)(ref val)).value.ToString();
		}
	}
	public static class SignatureHighlighter
	{
		public const string NAMESPACE = "#a8a8a8";

		public const string CONST = "#92c470";

		public const string CLASS_STATIC = "#3a8d71";

		public const string CLASS_INSTANCE = "#2df7b2";

		public const string STRUCT = "#0fba3a";

		public const string INTERFACE = "#9b9b82";

		public const string FIELD_STATIC = "#8d8dc6";

		public const string FIELD_INSTANCE = "#c266ff";

		public const string METHOD_STATIC = "#b55b02";

		public const string METHOD_INSTANCE = "#ff8000";

		public const string PROP_STATIC = "#588075";

		public const string PROP_INSTANCE = "#55a38e";

		public const string LOCAL_ARG = "#a6e9e9";

		public const string OPEN_COLOR = "<color=";

		public const string CLOSE_COLOR = "</color>";

		public const string OPEN_ITALIC = "<i>";

		public const string CLOSE_ITALIC = "</i>";

		public static readonly Regex ArrayTokenRegex = new Regex("\\[,*?\\]");

		private static readonly Regex colorTagRegex = new Regex("<color=#?[\\d|\\w]*>");

		public static readonly Color StringOrange = new Color(0.83f, 0.61f, 0.52f);

		public static readonly Color EnumGreen = new Color(0.57f, 0.76f, 0.43f);

		public static readonly Color KeywordBlue = new Color(0.3f, 0.61f, 0.83f);

		public static readonly string keywordBlueHex = KeywordBlue.ToHex();

		public static readonly Color NumberGreen = new Color(0.71f, 0.8f, 0.65f);

		private static readonly Dictionary<string, string> typeToRichType = new Dictionary<string, string>();

		private static readonly Dictionary<string, string> highlightedMethods = new Dictionary<string, string>();

		private static readonly Dictionary<Type, string> builtInTypesToShorthand = new Dictionary<Type, string>
		{
			{
				typeof(object),
				"object"
			},
			{
				typeof(string),
				"string"
			},
			{
				typeof(bool),
				"bool"
			},
			{
				typeof(byte),
				"byte"
			},
			{
				typeof(sbyte),
				"sbyte"
			},
			{
				typeof(char),
				"char"
			},
			{
				typeof(decimal),
				"decimal"
			},
			{
				typeof(double),
				"double"
			},
			{
				typeof(float),
				"float"
			},
			{
				typeof(int),
				"int"
			},
			{
				typeof(uint),
				"uint"
			},
			{
				typeof(long),
				"long"
			},
			{
				typeof(ulong),
				"ulong"
			},
			{
				typeof(short),
				"short"
			},
			{
				typeof(ushort),
				"ushort"
			},
			{
				typeof(void),
				"void"
			}
		};

		public static string Parse(Type type, bool includeNamespace, MemberInfo memberInfo = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (memberInfo is MethodInfo method)
			{
				return ParseMethod(method);
			}
			if (memberInfo is ConstructorInfo ctor)
			{
				return ParseConstructor(ctor);
			}
			StringBuilder stringBuilder = new StringBuilder();
			if (type.IsByRef)
			{
				AppendOpenColor(stringBuilder, "#" + keywordBlueHex).Append("ref ").Append("</color>");
			}
			Type type2 = type;
			while (type2.HasElementType)
			{
				type2 = type2.GetElementType();
			}
			includeNamespace &= !builtInTypesToShorthand.ContainsKey(type2);
			if (!type.IsGenericParameter && (!type.HasElementType || !type.GetElementType().IsGenericParameter) && includeNamespace && TryGetNamespace(type, out var ns))
			{
				AppendOpenColor(stringBuilder, "#a8a8a8").Append(ns).Append("</color>").Append('.');
			}
			stringBuilder.Append(ProcessType(type));
			if ((object)memberInfo != null)
			{
				stringBuilder.Append('.');
				int index = stringBuilder.Length - 1;
				AppendOpenColor(stringBuilder, GetMemberInfoColor(memberInfo, out var isStatic)).Append(memberInfo.Name).Append("</color>");
				if (isStatic)
				{
					stringBuilder.Insert(index, "<i>");
					stringBuilder.Append("</i>");
				}
			}
			return stringBuilder.ToString();
		}

		private static string ProcessType(Type type)
		{
			string key = type.ToString();
			if (typeToRichType.ContainsKey(key))
			{
				return typeToRichType[key];
			}
			StringBuilder stringBuilder = new StringBuilder();
			if (!type.IsGenericParameter)
			{
				int length = stringBuilder.Length;
				Type declaringType = type.DeclaringType;
				while ((object)declaringType != null)
				{
					stringBuilder.Insert(length, HighlightType(declaringType) + ".");
					declaringType = declaringType.DeclaringType;
				}
				stringBuilder.Append(HighlightType(type));
				if (type.IsGenericType)
				{
					ProcessGenericArguments(type, stringBuilder);
				}
			}
			else
			{
				stringBuilder.Append("<color=").Append("#92c470").Append('>')
					.Append(type.Name)
					.Append("</color>");
			}
			string text = stringBuilder.ToString();
			typeToRichType.Add(key, text);
			return text;
		}

		internal static string GetClassColor(Type type)
		{
			if (type.IsAbstract && type.IsSealed)
			{
				return "#3a8d71";
			}
			if (type.IsEnum || type.IsGenericParameter)
			{
				return "#92c470";
			}
			if (type.IsValueType)
			{
				return "#0fba3a";
			}
			if (type.IsInterface)
			{
				return "#9b9b82";
			}
			return "#2df7b2";
		}

		private static bool TryGetNamespace(Type type, out string ns)
		{
			return !string.IsNullOrEmpty(ns = type.Namespace?.Trim());
		}

		private static StringBuilder AppendOpenColor(StringBuilder sb, string color)
		{
			return sb.Append("<color=").Append(color).Append('>');
		}

		private static string HighlightType(Type type)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (type.IsByRef)
			{
				type = type.GetElementType();
			}
			int num = 0;
			Match match = ArrayTokenRegex.Match(type.Name);
			if (match != null && match.Success)
			{
				num = 1 + match.Value.Count((char c) => c == ',');
				type = type.GetElementType();
			}
			if (builtInTypesToShorthand.TryGetValue(type, out var value))
			{
				AppendOpenColor(stringBuilder, "#" + keywordBlueHex).Append(value).Append("</color>");
			}
			else
			{
				stringBuilder.Append("<color=" + GetClassColor(type) + ">").Append(type.Name).Append("</color>");
			}
			if (num > 0)
			{
				stringBuilder.Append('[').Append(new string(',', num - 1)).Append(']');
			}
			return stringBuilder.ToString();
		}

		private static void ProcessGenericArguments(Type type, StringBuilder sb)
		{
			List<Type> list = type.GetGenericArguments().ToList();
			for (int i = 0; i < sb.Length; i++)
			{
				if (!list.Any())
				{
					break;
				}
				if (sb[i] != '`')
				{
					continue;
				}
				int num = i;
				i++;
				StringBuilder stringBuilder = new StringBuilder();
				for (; char.IsDigit(sb[i]); i++)
				{
					stringBuilder.Append(sb[i]);
				}
				string text = stringBuilder.ToString();
				int num2 = int.Parse(text);
				sb.Remove(num, text.Length + 1);
				int num3 = 1;
				num++;
				while (num3 < "</color>".Length && sb[num] == "</color>"[num3])
				{
					num3++;
					num++;
				}
				sb.Insert(num, '<');
				num++;
				int length = sb.Length;
				while (num2 > 0 && list.Any())
				{
					num2--;
					Type type2 = list.First();
					list.RemoveAt(0);
					sb.Insert(num, ProcessType(type2));
					if (num2 > 0)
					{
						num += sb.Length - length;
						sb.Insert(num, ", ");
						num += 2;
						length = sb.Length;
					}
				}
				sb.Insert(num + sb.Length - length, '>');
			}
		}

		public static string RemoveHighlighting(string _string)
		{
			if (_string == null)
			{
				throw new ArgumentNullException("_string");
			}
			_string = _string.Replace("<i>", string.Empty);
			_string = _string.Replace("</i>", string.Empty);
			_string = colorTagRegex.Replace(_string, string.Empty);
			_string = _string.Replace("</color>", string.Empty);
			return _string;
		}

		[Obsolete("Use 'ParseMethod(MethodInfo)' instead (rename).")]
		public static string HighlightMethod(MethodInfo method)
		{
			return ParseMethod(method);
		}

		public static string ParseMethod(MethodInfo method)
		{
			string key = GeneralExtensions.FullDescription((MethodBase)method);
			if (highlightedMethods.ContainsKey(key))
			{
				return highlightedMethods[key];
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(Parse(method.DeclaringType, includeNamespace: false));
			stringBuilder.Append('.');
			string text = ((!method.IsStatic) ? "#ff8000" : "#b55b02");
			stringBuilder.Append("<color=" + text + ">" + method.Name + "</color>");
			if (method.IsGenericMethod)
			{
				stringBuilder.Append("<");
				Type[] genericArguments = method.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					Type type = genericArguments[i];
					if (type.IsGenericParameter)
					{
						stringBuilder.Append("<color=#92c470>" + genericArguments[i].Name + "</color>");
					}
					else
					{
						stringBuilder.Append(Parse(type, includeNamespace: false));
					}
					if (i < genericArguments.Length - 1)
					{
						stringBuilder.Append(", ");
					}
				}
				stringBuilder.Append(">");
			}
			stringBuilder.Append('(');
			ParameterInfo[] parameters = method.GetParameters();
			for (int j = 0; j < parameters.Length; j++)
			{
				ParameterInfo parameterInfo = parameters[j];
				stringBuilder.Append(Parse(parameterInfo.ParameterType, includeNamespace: false));
				if (j < parameters.Length - 1)
				{
					stringBuilder.Append(", ");
				}
			}
			stringBuilder.Append(')');
			string text2 = stringBuilder.ToString();
			highlightedMethods.Add(key, text2);
			return text2;
		}

		[Obsolete("Use 'ParseConstructor(ConstructorInfo)' instead (rename).")]
		public static string HighlightConstructor(ConstructorInfo ctor)
		{
			return ParseConstructor(ctor);
		}

		public static string ParseConstructor(ConstructorInfo ctor)
		{
			string key = GeneralExtensions.FullDescription((MethodBase)ctor);
			if (highlightedMethods.ContainsKey(key))
			{
				return highlightedMethods[key];
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(Parse(ctor.DeclaringType, includeNamespace: false));
			string value = stringBuilder.ToString();
			stringBuilder.Append('.');
			stringBuilder.Append(value);
			stringBuilder.Append('(');
			ParameterInfo[] parameters = ctor.GetParameters();
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				stringBuilder.Append(Parse(parameterInfo.ParameterType, includeNamespace: false));
				if (i < parameters.Length - 1)
				{
					stringBuilder.Append(", ");
				}
			}
			stringBuilder.Append(')');
			string text = stringBuilder.ToString();
			highlightedMethods.Add(key, text);
			return text;
		}

		public static string GetMemberInfoColor(MemberInfo memberInfo, out bool isStatic)
		{
			isStatic = false;
			if (memberInfo is FieldInfo fieldInfo)
			{
				if (fieldInfo.IsStatic)
				{
					isStatic = true;
					return "#8d8dc6";
				}
				return "#c266ff";
			}
			if (memberInfo is MethodInfo methodInfo)
			{
				if (methodInfo.IsStatic)
				{
					isStatic = true;
					return "#b55b02";
				}
				return "#ff8000";
			}
			if (memberInfo is PropertyInfo propertyInfo)
			{
				if (propertyInfo.GetAccessors(nonPublic: true)[0].IsStatic)
				{
					isStatic = true;
					return "#588075";
				}
				return "#55a38e";
			}
			if (memberInfo is ConstructorInfo)
			{
				isStatic = true;
				return "#2df7b2";
			}
			throw new NotImplementedException(memberInfo.GetType().Name + " is not supported");
		}
	}
	public static class ToStringUtility
	{
		internal static Dictionary<string, MethodInfo> toStringMethods = new Dictionary<string, MethodInfo>();

		private const string nullString = "<color=grey>null</color>";

		private const string nullUnknown = "<color=grey>null</color> (?)";

		private const string destroyedString = "<color=red>Destroyed</color>";

		private const string untitledString = "<i><color=grey>untitled</color></i>";

		private const string eventSystemNamespace = "UnityEngine.EventSystem";

		public static string PruneString(string s, int chars = 200, int lines = 5)
		{
			if (string.IsNullOrEmpty(s))
			{
				return s;
			}
			StringBuilder stringBuilder = new StringBuilder(Math.Max(chars, s.Length));
			int num = 0;
			for (int i = 0; i < s.Length; i++)
			{
				if (num >= lines || i >= chars)
				{
					stringBuilder.Append("...");
					break;
				}
				char c = s[i];
				if (c == '\r' || c == '\n')
				{
					num++;
				}
				stringBuilder.Append(c);
			}
			return stringBuilder.ToString();
		}

		public static string ToStringWithType(object value, Type fallbackType, bool includeNamespace = true)
		{
			if (value.IsNullOrDestroyed() && (object)fallbackType == null)
			{
				return "<color=grey>null</color> (?)";
			}
			Type type = value?.GetActualType() ?? fallbackType;
			string text = SignatureHighlighter.Parse(type, includeNamespace);
			StringBuilder stringBuilder = new StringBuilder();
			if (value.IsNullOrDestroyed())
			{
				if (value == null)
				{
					stringBuilder.Append("<color=grey>null</color>");
					AppendRichType(stringBuilder, text);
					return stringBuilder.ToString();
				}
				stringBuilder.Append("<color=red>Destroyed</color>");
				AppendRichType(stringBuilder, text);
				return stringBuilder.ToString();
			}
			Object val = (Object)((value is Object) ? value : null);
			if (val != null)
			{
				if (string.IsNullOrEmpty(val.name))
				{
					stringBuilder.Append("<i><color=grey>untitled</color></i>");
				}
				else
				{
					stringBuilder.Append('"');
					stringBuilder.Append(PruneString(val.name, 50, 1));
					stringBuilder.Append('"');
				}
				AppendRichType(stringBuilder, text);
			}
			else if (type.FullName.StartsWith("UnityEngine.EventSystem"))
			{
				stringBuilder.Append(text);
			}
			else
			{
				string text2 = ToString(value);
				if (type.IsGenericType || text2 == type.FullName || text2 == type.FullName + " " + type.FullName || text2 == "Il2Cpp" + type.FullName || type.FullName == "Il2Cpp" + text2)
				{
					stringBuilder.Append(text);
				}
				else
				{
					stringBuilder.Append(PruneString(text2));
					AppendRichType(stringBuilder, text);
				}
			}
			return stringBuilder.ToString();
		}

		private static void AppendRichType(StringBuilder sb, string richType)
		{
			sb.Append(' ');
			sb.Append('(');
			sb.Append(richType);
			sb.Append(')');
		}

		private static string ToString(object value)
		{
			if (value.IsNullOrDestroyed())
			{
				if (value == null)
				{
					return "<color=grey>null</color>";
				}
				return "<color=red>Destroyed</color>";
			}
			Type actualType = value.GetActualType();
			if (!toStringMethods.ContainsKey(actualType.AssemblyQualifiedName))
			{
				MethodInfo method = actualType.GetMethod("ToString", ArgumentUtility.EmptyTypes);
				toStringMethods.Add(actualType.AssemblyQualifiedName, method);
			}
			value = value.TryCast(actualType);
			string theString;
			try
			{
				theString = (string)toStringMethods[actualType.AssemblyQualifiedName].Invoke(value, ArgumentUtility.EmptyArgs);
			}
			catch (Exception e)
			{
				theString = e.ReflectionExToString();
			}
			return ReflectionUtility.ProcessTypeInString(actualType, theString);
		}
	}
	public static class UnityHelpers
	{
		private static PropertyInfo onEndEdit;

		public static bool OccuredEarlierThanDefault(this float time)
		{
			return Time.realtimeSinceStartup - 0.01f >= time;
		}

		public static bool OccuredEarlierThan(this float time, float secondsAgo)
		{
			return Time.realtimeSinceStartup - secondsAgo >= time;
		}

		public static bool IsNullOrDestroyed(this object obj, bool suppressWarning = true)
		{
			try
			{
				if (obj == null)
				{
					if (!suppressWarning)
					{
						Universe.LogWarning("The target instance is null!");
					}
					return true;
				}
				Object val = (Object)((obj is Object) ? obj : null);
				if (val != null && !Object.op_Implicit(val))
				{
					if (!suppressWarning)
					{
						Universe.LogWarning("The target UnityEngine.Object was destroyed!");
					}
					return true;
				}
				return false;
			}
			catch
			{
				return true;
			}
		}

		public static string GetTransformPath(this Transform transform, bool includeSelf = false)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (includeSelf)
			{
				stringBuilder.Append(((Object)transform).name);
			}
			while (Object.op_Implicit((Object)(object)transform.parent))
			{
				transform = transform.parent;
				stringBuilder.Insert(0, '/');
				stringBuilder.Insert(0, ((Object)transform).name);
			}
			return stringBuilder.ToString();
		}

		public static string ToHex(this Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			byte b = (byte)Mathf.Clamp(Mathf.RoundToInt(color.r * 255f), 0, 255);
			byte b2 = (byte)Mathf.Clamp(Mathf.RoundToInt(color.g * 255f), 0, 255);
			byte b3 = (byte)Mathf.Clamp(Mathf.RoundToInt(color.b * 255f), 0, 255);
			return $"{b:X2}{b2:X2}{b3:X2}";
		}

		public static Color ToColor(this string _string)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			_string = _string.Replace("#", "");
			if (_string.Length != 6)
			{
				return Color.magenta;
			}
			byte b = byte.Parse(_string.Substring(0, 2), NumberStyles.HexNumber);
			byte b2 = byte.Parse(_string.Substring(2, 2), NumberStyles.HexNumber);
			byte b3 = byte.Parse(_string.Substring(4, 2), NumberStyles.HexNumber);
			return new Color
			{
				r = (float)((decimal)b / 255m),
				g = (float)((decimal)b2 / 255m),
				b = (float)((decimal)b3 / 255m),
				a = 1f
			};
		}

		public static UnityEvent<string> GetOnEndEdit(this InputField _this)
		{
			if ((object)onEndEdit == null)
			{
				onEndEdit = AccessTools.Property(typeof(InputField), "onEndEdit") ?? throw new Exception("Could not get InputField.onEndEdit property!");
			}
			return onEndEdit.GetValue(_this, null).TryCast<UnityEvent<string>>();
		}
	}
}
namespace UniverseLib.UI
{
	public class UIBase
	{
		internal static readonly int TOP_SORTORDER = 30000;

		public string ID { get; }

		public GameObject RootObject { get; }

		public RectTransform RootRect { get; }

		public Canvas Canvas { get; }

		public Action UpdateMethod { get; }

		public PanelManager Panels { get; }

		public bool Enabled
		{
			get
			{
				if (Object.op_Implicit((Object)(object)RootObject))
				{
					return RootObject.activeSelf;
				}
				return false;
			}
			set
			{
				UniversalUI.SetUIActive(ID, value);
			}
		}

		public UIBase(string id, Action updateMethod)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("Cannot register a UI with a null or empty id!");
			}
			if (UniversalUI.registeredUIs.ContainsKey(id))
			{
				throw new ArgumentException("A UI with the id '" + id + "' is already registered!");
			}
			ID = id;
			UpdateMethod = updateMethod;
			RootObject = UIFactory.CreateUIObject(id + "_Root", UniversalUI.CanvasRoot);
			RootObject.SetActive(false);
			RootRect = RootObject.GetComponent<RectTransform>();
			Canvas = RootObject.AddComponent<Canvas>();
			Canvas.renderMode = (RenderMode)1;
			Canvas.referencePixelsPerUnit = 100f;
			Canvas.sortingOrder = TOP_SORTORDER;
			Canvas.overrideSorting = true;
			CanvasScaler obj = RootObject.AddComponent<CanvasScaler>();
			obj.referenceResolution = new Vector2(1920f, 1080f);
			obj.screenMatchMode = (ScreenMatchMode)1;
			RootObject.AddComponent<GraphicRaycaster>();
			RectTransform component = RootObject.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.pivot = new Vector2(0.5f, 0.5f);
			Panels = CreatePanelManager();
			RootObject.SetActive(true);
			UniversalUI.registeredUIs.Add(id, this);
			UniversalUI.uiBases.Add(this);
		}

		protected virtual PanelManager CreatePanelManager()
		{
			return new PanelManager(this);
		}

		public void SetOnTop()
		{
			RootObject.transform.SetAsLastSibling();
			foreach (UIBase uiBasis in UniversalUI.uiBases)
			{
				int num = UniversalUI.CanvasRoot.transform.childCount - ((Transform)uiBasis.RootRect).GetSiblingIndex();
				uiBasis.Canvas.sortingOrder = TOP_SORTORDER - num;
			}
			UniversalUI.uiBases.Sort((UIBase a, UIBase b) => b.RootObject.transform.GetSiblingIndex().CompareTo(a.RootObject.transform.GetSiblingIndex()));
		}

		internal void Update()
		{
			try
			{
				Panels.Update();
				UpdateMethod?.Invoke();
			}
			catch (Exception arg)
			{
				Universe.LogWarning($"Exception invoking update method for {ID}: {arg}");
			}
		}
	}
	public static class UIFactory
	{
		internal static Vector2 largeElementSize = new Vector2(100f, 30f);

		internal static Vector2 smallElementSize = new Vector2(25f, 25f);

		internal static Color defaultTextColor = Color.white;

		public static GameObject CreateUIObject(string name, GameObject parent, Vector2 sizeDelta = default(Vector2))
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name)
			{
				layer = 5,
				hideFlags = (HideFlags)61
			};
			if (Object.op_Implicit((Object)(object)parent))
			{
				val.transform.SetParent(parent.transform, false);
			}
			val.AddComponent<RectTransform>().sizeDelta = sizeDelta;
			return val;
		}

		internal static void SetDefaultTextValues(Text text)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			((Graphic)text).color = defaultTextColor;
			text.font = UniversalUI.DefaultFont;
			text.fontSize = 14;
		}

		internal static void SetDefaultSelectableValues(Selectable selectable)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			Navigation navigation = selectable.navigation;
			((Navigation)(ref navigation)).mode = (Mode)4;
			selectable.navigation = navigation;
			RuntimeHelper.Instance.Internal_SetColorBlock(selectable, (Color?)new Color(0.2f, 0.2f, 0.2f), (Color?)new Color(0.3f, 0.3f, 0.3f), (Color?)new Color(0.15f, 0.15f, 0.15f), (Color?)null);
		}

		public static LayoutElement SetLayoutElement(GameObject gameObject, int? minWidth = null, int? minHeight = null, int? flexibleWidth = null, int? flexibleHeight = null, int? preferredWidth = null, int? preferredHeight = null, bool? ignoreLayout = null)
		{
			LayoutElement val = gameObject.GetComponent<LayoutElement>();
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = gameObject.AddComponent<LayoutElement>();
			}
			if (minWidth.HasValue)
			{
				val.minWidth = minWidth.Value;
			}
			if (minHeight.HasValue)
			{
				val.minHeight = minHeight.Value;
			}
			if (flexibleWidth.HasValue)
			{
				val.flexibleWidth = flexibleWidth.Value;
			}
			if (flexibleHeight.HasValue)
			{
				val.flexibleHeight = flexibleHeight.Value;
			}
			if (preferredWidth.HasValue)
			{
				val.preferredWidth = preferredWidth.Value;
			}
			if (preferredHeight.HasValue)
			{
				val.preferredHeight = preferredHeight.Value;
			}
			if (ignoreLayout.HasValue)
			{
				val.ignoreLayout = ignoreLayout.Value;
			}
			return val;
		}

		public static T SetLayoutGroup<T>(GameObject gameObject, bool? forceWidth = null, bool? forceHeight = null, bool? childControlWidth = null, bool? childControlHeight = null, int? spacing = null, int? padTop = null, int? padBottom = null, int? padLeft = null, int? padRight = null, TextAnchor? childAlignment = null) where T : HorizontalOrVerticalLayoutGroup
		{
			T val = gameObject.GetComponent<T>();
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = gameObject.AddComponent<T>();
			}
			return SetLayoutGroup(val, forceWidth, forceHeight, childControlWidth, childControlHeight, spacing, padTop, padBottom, padLeft, padRight, childAlignment);
		}

		public static T SetLayoutGroup<T>(T group, bool? forceWidth = null, bool? forceHeight = null, bool? childControlWidth = null, bool? childControlHeight = null, int? spacing = null, int? padTop = null, int? padBottom = null, int? padLeft = null, int? padRight = null, TextAnchor? childAlignment = null) where T : HorizontalOrVerticalLayoutGroup
		{
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if (forceWidth.HasValue)
			{
				((HorizontalOrVerticalLayoutGroup)group).childForceExpandWidth = forceWidth.Value;
			}
			if (forceHeight.HasValue)
			{
				((HorizontalOrVerticalLayoutGroup)group).childForceExpandHeight = forceHeight.Value;
			}
			if (childControlWidth.HasValue)
			{
				((HorizontalOrVerticalLayoutGroup)(object)group).SetChildControlWidth(childControlWidth.Value);
			}
			if (childControlHeight.HasValue)
			{
				((HorizontalOrVerticalLayoutGroup)(object)group).SetChildControlHeight(childControlHeight.Value);
			}
			if (spacing.HasValue)
			{
				((HorizontalOrVerticalLayoutGroup)group).spacing = spacing.Value;
			}
			if (padTop.HasValue)
			{
				((LayoutGroup)(object)group).padding.top = padTop.Value;
			}
			if (padBottom.HasValue)
			{
				((LayoutGroup)(object)group).padding.bottom = padBottom.Value;
			}
			if (padLeft.HasValue)
			{
				((LayoutGroup)(object)group).padding.left = padLeft.Value;
			}
			if (padRight.HasValue)
			{
				((LayoutGroup)(object)group).padding.right = padRight.Value;
			}
			if (childAlignment.HasValue)
			{
				((LayoutGroup)(object)group).childAlignment = childAlignment.Value;
			}
			return group;
		}

		public static GameObject CreatePanel(string name, GameObject parent, out GameObject contentHolder, Color? bgColor = null)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent);
			UIFactory.SetLayoutGroup<VerticalLayoutGroup>(val, (bool?)true, (bool?)true, (bool?)true, (bool?)true, (int?)0, (int?)1, (int?)1, (int?)1, (int?)1, (TextAnchor?)null);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.anchoredPosition = Vector2.zero;
			component.sizeDelta = Vector2.zero;
			((Graphic)val.AddComponent<Image>()).color = Color.black;
			val.AddComponent<RectMask2D>();
			contentHolder = CreateUIObject("Content", val);
			Image obj = contentHolder.AddComponent<Image>();
			obj.type = (Type)3;
			((Graphic)obj).color = (Color)((!bgColor.HasValue) ? new Color(0.07f, 0.07f, 0.07f) : bgColor.Value);
			UIFactory.SetLayoutGroup<VerticalLayoutGroup>(contentHolder, (bool?)true, (bool?)true, (bool?)true, (bool?)true, (int?)3, (int?)3, (int?)3, (int?)3, (int?)3, (TextAnchor?)null);
			return val;
		}

		public static GameObject CreateVerticalGroup(GameObject parent, string name, bool forceWidth, bool forceHeight, bool childControlWidth, bool childControlHeight, int spacing = 0, Vector4 padding = default(Vector4), Color bgColor = default(Color), TextAnchor? childAlignment = null)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = CreateUIObject(name, parent);
			UIFactory.SetLayoutGroup<VerticalLayoutGroup>(obj, (bool?)forceWidth, (bool?)forceHeight, (bool?)childControlWidth, (bool?)childControlHeight, (int?)spacing, (int?)(int)padding.x, (int?)(int)padding.y, (int?)(int)padding.z, (int?)(int)padding.w, childAlignment);
			((Graphic)obj.AddComponent<Image>()).color = (Color)((bgColor == default(Color)) ? new Color(0.17f, 0.17f, 0.17f) : bgColor);
			return obj;
		}

		public static GameObject CreateHorizontalGroup(GameObject parent, string name, bool forceExpandWidth, bool forceExpandHeight, bool childControlWidth, bool childControlHeight, int spacing = 0, Vector4 padding = default(Vector4), Color bgColor = default(Color), TextAnchor? childAlignment = null)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = CreateUIObject(name, parent);
			UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(obj, (bool?)forceExpandWidth, (bool?)forceExpandHeight, (bool?)childControlWidth, (bool?)childControlHeight, (int?)spacing, (int?)(int)padding.x, (int?)(int)padding.y, (int?)(int)padding.z, (int?)(int)padding.w, childAlignment);
			((Graphic)obj.AddComponent<Image>()).color = (Color)((bgColor == default(Color)) ? new Color(0.17f, 0.17f, 0.17f) : bgColor);
			return obj;
		}

		public static GameObject CreateGridGroup(GameObject parent, string name, Vector2 cellSize, Vector2 spacing, Color bgColor = default(Color))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = CreateUIObject(name, parent);
			GridLayoutGroup obj2 = obj.AddComponent<GridLayoutGroup>();
			((LayoutGroup)obj2).childAlignment = (TextAnchor)0;
			obj2.cellSize = cellSize;
			obj2.spacing = spacing;
			((Graphic)obj.AddComponent<Image>()).color = (Color)((bgColor == default(Color)) ? new Color(0.17f, 0.17f, 0.17f) : bgColor);
			return obj;
		}

		public static Text CreateLabel(GameObject parent, string name, string defaultText, TextAnchor alignment = (TextAnchor)3, Color color = default(Color), bool supportRichText = true, int fontSize = 14)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Text obj = CreateUIObject(name, parent).AddComponent<Text>();
			SetDefaultTextValues(obj);
			obj.text = defaultText;
			((Graphic)obj).color = ((color == default(Color)) ? defaultTextColor : color);
			obj.supportRichText = supportRichText;
			obj.alignment = alignment;
			obj.fontSize = fontSize;
			return obj;
		}

		public static ButtonRef CreateButton(GameObject parent, string name, string text, Color? normalColor = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			Color valueOrDefault = normalColor.GetValueOrDefault();
			if (!normalColor.HasValue)
			{
				((Color)(ref valueOrDefault))..ctor(0.25f, 0.25f, 0.25f);
				normalColor = valueOrDefault;
			}
			ButtonRef buttonRef = CreateButton(parent, name, text, default(ColorBlock));
			RuntimeHelper instance = RuntimeHelper.Instance;
			Button component = buttonRef.Component;
			Color? normal = normalColor;
			Color? val = normalColor;
			float num = 1.2f;
			Color? highlighted = (val.HasValue ? new Color?(val.GetValueOrDefault() * num) : ((Color?)null));
			val = normalColor;
			num = 0.7f;
			instance.Internal_SetColorBlock((Selectable)(object)component, normal, highlighted, val.HasValue ? new Color?(val.GetValueOrDefault() * num) : ((Color?)null));
			return buttonRef;
		}

		public static ButtonRef CreateButton(GameObject parent, string name, string text, ColorBlock colors)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent, smallElementSize);
			GameObject obj = CreateUIObject("Text", val);
			Image obj2 = val.AddComponent<Image>();
			obj2.type = (Type)1;
			((Graphic)obj2).color = new Color(1f, 1f, 1f, 1f);
			Button val2 = val.AddComponent<Button>();
			SetDefaultSelectableValues((Selectable)(object)val2);
			((ColorBlock)(ref colors)).colorMultiplier = 1f;
			RuntimeHelper.Instance.Internal_SetColorBlock((Selectable)(object)val2, colors);
			Text obj3 = obj.AddComponent<Text>();
			obj3.text = text;
			SetDefaultTextValues(obj3);
			obj3.alignment = (TextAnchor)4;
			RectTransform component = obj.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.sizeDelta = Vector2.zero;
			SetButtonDeselectListener(val2);
			return new ButtonRef(val2);
		}

		internal static void SetButtonDeselectListener(Button button)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			((UnityEvent)button.onClick).AddListener((UnityAction)delegate
			{
				((Selectable)button).OnDeselect((BaseEventData)null);
			});
		}

		public static GameObject CreateSlider(GameObject parent, string name, out Slider slider)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent, smallElementSize);
			GameObject obj = CreateUIObject("Background", val);
			GameObject val2 = CreateUIObject("Fill Area", val);
			GameObject val3 = CreateUIObject("Fill", val2);
			GameObject val4 = CreateUIObject("Handle Slide Area", val);
			GameObject val5 = CreateUIObject("Handle", val4);
			Image obj2 = obj.AddComponent<Image>();
			obj2.type = (Type)1;
			((Graphic)obj2).color = new Color(0.15f, 0.15f, 0.15f, 1f);
			RectTransform component = obj.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 0.25f);
			component.anchorMax = new Vector2(1f, 0.75f);
			component.sizeDelta = new Vector2(0f, 0f);
			RectTransform component2 = val2.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0f, 0.25f);
			component2.anchorMax = new Vector2(1f, 0.75f);
			component2.anchoredPosition = new Vector2(-5f, 0f);
			component2.sizeDelta = new Vector2(-20f, 0f);
			Image obj3 = val3.AddComponent<Image>();
			obj3.type = (Type)1;
			((Graphic)obj3).color = new Color(0.3f, 0.3f, 0.3f, 1f);
			val3.GetComponent<RectTransform>().sizeDelta = new Vector2(10f, 0f);
			RectTransform component3 = val4.GetComponent<RectTransform>();
			component3.sizeDelta = new Vector2(-20f, 0f);
			component3.anchorMin = new Vector2(0f, 0f);
			component3.anchorMax = new Vector2(1f, 1f);
			Image val6 = val5.AddComponent<Image>();
			((Graphic)val6).color = new Color(0.5f, 0.5f, 0.5f, 1f);
			val5.GetComponent<RectTransform>().sizeDelta = new Vector2(20f, 0f);
			slider = val.AddComponent<Slider>();
			slider.fillRect = val3.GetComponent<RectTransform>();
			slider.handleRect = val5.GetComponent<RectTransform>();
			((Selectable)slider).targetGraphic = (Graphic)(object)val6;
			slider.direction = (Direction)0;
			RuntimeHelper.Instance.Internal_SetColorBlock((Selectable)(object)slider, (Color?)new Color(0.4f, 0.4f, 0.4f), (Color?)new Color(0.55f, 0.55f, 0.55f), (Color?)new Color(0.3f, 0.3f, 0.3f), (Color?)null);
			return val;
		}

		public static GameObject CreateScrollbar(GameObject parent, string name, out Scrollbar scrollbar)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent, smallElementSize);
			GameObject val2 = CreateUIObject("Sliding Area", val);
			GameObject obj = CreateUIObject("Handle", val2);
			Image obj2 = val.AddComponent<Image>();
			obj2.type = (Type)1;
			((Graphic)obj2).color = new Color(0.1f, 0.1f, 0.1f);
			Image val3 = obj.AddComponent<Image>();
			val3.type = (Type)1;
			((Graphic)val3).color = new Color(0.4f, 0.4f, 0.4f);
			RectTransform component = val2.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(-20f, -20f);
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			RectTransform component2 = obj.GetComponent<RectTransform>();
			component2.sizeDelta = new Vector2(20f, 20f);
			scrollbar = val.AddComponent<Scrollbar>();
			scrollbar.handleRect = component2;
			((Selectable)scrollbar).targetGraphic = (Graphic)(object)val3;
			SetDefaultSelectableValues((Selectable)(object)scrollbar);
			return val;
		}

		public static GameObject CreateToggle(GameObject parent, string name, out Toggle toggle, out Text text, Color bgColor = default(Color), int checkWidth = 20, int checkHeight = 20)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent, smallElementSize);
			UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(val, (bool?)false, (bool?)false, (bool?)true, (bool?)true, (int?)5, (int?)0, (int?)0, (int?)0, (int?)0, (TextAnchor?)(TextAnchor)3);
			toggle = val.AddComponent<Toggle>();
			toggle.isOn = true;
			SetDefaultSelectableValues((Selectable)(object)toggle);
			Toggle t2 = toggle;
			((UnityEvent<bool>)(object)toggle.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				((Selectable)t2).OnDeselect((BaseEventData)null);
			});
			GameObject val2 = CreateUIObject("Background", val);
			Image val3 = val2.AddComponent<Image>();
			((Graphic)val3).color = (Color)((bgColor == default(Color)) ? new Color(0.04f, 0.04f, 0.04f, 0.75f) : bgColor);
			UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(val2, (bool?)true, (bool?)true, (bool?)true, (bool?)true, (int?)0, (int?)2, (int?)2, (int?)2, (int?)2, (TextAnchor?)null);
			SetLayoutElement(val2, checkWidth, flexibleWidth: 0, minHeight: checkHeight, flexibleHeight: 0);
			Image val4 = CreateUIObject("Checkmark", val2).AddComponent<Image>();
			((Graphic)val4).color = new Color(0.8f, 1f, 0.8f, 0.3f);
			GameObject val5 = CreateUIObject("Label", val);
			text = val5.AddComponent<Text>();
			text.text = "";
			text.alignment = (TextAnchor)3;
			SetDefaultTextValues(text);
			SetLayoutElement(val5, 0, flexibleWidth: 0, minHeight: checkHeight, flexibleHeight: 0);
			toggle.graphic = (Graphic)(object)val4;
			((Selectable)toggle).targetGraphic = (Graphic)(object)val3;
			return val;
		}

		public static InputFieldRef CreateInputField(GameObject parent, string name, string placeHolderText)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent);
			Image val2 = val.AddComponent<Image>();
			val2.type = (Type)1;
			((Graphic)val2).color = new Color(0f, 0f, 0f, 0.5f);
			InputField val3 = val.AddComponent<InputField>();
			Navigation navigation = ((Selectable)val3).navigation;
			((Navigation)(ref navigation)).mode = (Mode)0;
			((Selectable)val3).navigation = navigation;
			val3.lineType = (LineType)0;
			((Selectable)val3).interactable = true;
			((Selectable)val3).transition = (Transition)1;
			((Selectable)val3).targetGraphic = (Graphic)(object)val2;
			RuntimeHelper.Instance.Internal_SetColorBlock((Selectable)(object)val3, (Color?)new Color(1f, 1f, 1f, 1f), (Color?)new Color(0.95f, 0.95f, 0.95f, 1f), (Color?)new Color(0.78f, 0.78f, 0.78f, 1f), (Color?)null);
			GameObject val4 = CreateUIObject("TextArea", val);
			val4.AddComponent<RectMask2D>();
			RectTransform component = val4.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			GameObject obj = CreateUIObject("Placeholder", val4);
			Text val5 = obj.AddComponent<Text>();
			SetDefaultTextValues(val5);
			val5.text = placeHolderText ?? "...";
			((Graphic)val5).color = new Color(0.5f, 0.5f, 0.5f, 1f);
			val5.horizontalOverflow = (HorizontalWrapMode)0;
			val5.alignment = (TextAnchor)3;
			val5.fontSize = 14;
			RectTransform component2 = obj.GetComponent<RectTransform>();
			component2.anchorMin = Vector2.zero;
			component2.anchorMax = Vector2.one;
			component2.offsetMin = Vector2.zero;
			component2.offsetMax = Vector2.zero;
			val3.placeholder = (Graphic)(object)val5;
			GameObject obj2 = CreateUIObject("Text", val4);
			Text val6 = obj2.AddComponent<Text>();
			SetDefaultTextValues(val6);
			val6.text = "";
			((Graphic)val6).color = new Color(1f, 1f, 1f, 1f);
			val6.horizontalOverflow = (HorizontalWrapMode)0;
			val6.alignment = (TextAnchor)3;
			val6.fontSize = 14;
			RectTransform component3 = obj2.GetComponent<RectTransform>();
			component3.anchorMin = Vector2.zero;
			component3.anchorMax = Vector2.one;
			component3.offsetMin = Vector2.zero;
			component3.offsetMax = Vector2.zero;
			val3.textComponent = val6;
			val3.characterLimit = 16000;
			return new InputFieldRef(val3);
		}

		public static GameObject CreateDropdown(GameObject parent, string name, out Dropdown dropdown, string defaultItemText, int itemFontSize, Action<int> onValueChanged, string[] defaultOptions = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing reference