Decompiled source of FaceSync v1.0.4

BepInEx/plugins/FaceSync/FaceSync.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using OpenCvSharp.Dnn;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("EmotionalResonance")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP")]
[assembly: AssemblyProduct("EmotionalResonance")]
[assembly: AssemblyCopyright("Copyright © HP 2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("96a2423f-4deb-40bd-9b0a-7c0a85c5f472")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace FaceSync
{
	public class NotificationManager : MonoBehaviour
	{
		private class Notification
		{
			public string message;

			public NotificationType type;

			public float lifetime;

			public float createdTime;

			public float alpha = 0f;

			public float slideOffset = 100f;

			public bool IsExpired => Time.time - createdTime > lifetime;

			public float Age => Time.time - createdTime;
		}

		public enum NotificationType
		{
			Info,
			Success,
			Warning,
			Error
		}

		private static NotificationManager instance;

		private List<Notification> activeNotifications = new List<Notification>();

		private const float NOTIFICATION_WIDTH = 320f;

		private const float NOTIFICATION_HEIGHT = 70f;

		private const float NOTIFICATION_MARGIN = 15f;

		private const float NOTIFICATION_PADDING = 12f;

		private const float FADE_IN_DURATION = 0.3f;

		private const float FADE_OUT_DURATION = 0.5f;

		private const float SLIDE_DURATION = 0.4f;

		private const float DEFAULT_LIFETIME = 3f;

		private const int MAX_NOTIFICATIONS = 5;

		private GUIStyle notificationStyle;

		private GUIStyle messageStyle;

		private GUIStyle iconStyle;

		private bool stylesInitialized = false;

		private Texture2D backgroundTexture;

		private static readonly Color InfoColor = new Color(0.2f, 0.6f, 1f, 1f);

		private static readonly Color SuccessColor = new Color(0.3f, 0.8f, 0.3f, 1f);

		private static readonly Color WarningColor = new Color(1f, 0.7f, 0.2f, 1f);

		private static readonly Color ErrorColor = new Color(1f, 0.3f, 0.3f, 1f);

		private void Awake()
		{
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}

		public static void Show(string message, NotificationType type = NotificationType.Info, float lifetime = 3f)
		{
			if ((Object)(object)instance != (Object)null)
			{
				instance.AddNotification(message, type, lifetime);
			}
		}

		private void AddNotification(string message, NotificationType type, float lifetime)
		{
			if (activeNotifications.Count >= 5)
			{
				activeNotifications.RemoveAt(0);
			}
			Notification item = new Notification
			{
				message = message,
				type = type,
				lifetime = lifetime,
				createdTime = Time.time
			};
			activeNotifications.Add(item);
		}

		private void Update()
		{
			activeNotifications.RemoveAll((Notification n) => n.IsExpired);
		}

		private void OnGUI()
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			if (!stylesInitialized)
			{
				InitializeStyles();
			}
			float num = Screen.width;
			float num2 = Screen.height;
			float num3 = num - 320f - 15f;
			float num4 = num2 - 15f;
			for (int num5 = activeNotifications.Count - 1; num5 >= 0; num5--)
			{
				Notification notification = activeNotifications[num5];
				float age = notification.Age;
				float num6 = Mathf.Clamp01(age / 0.3f);
				float num7 = 0f;
				if (age > notification.lifetime - 0.5f)
				{
					num7 = (age - (notification.lifetime - 0.5f)) / 0.5f;
				}
				notification.alpha = Mathf.Lerp(0f, 1f, num6) * (1f - num7);
				float t = Mathf.Clamp01(age / 0.4f);
				float num8 = EaseOutCubic(t);
				notification.slideOffset = Mathf.Lerp(100f, 0f, num8);
				float num9 = num3 + notification.slideOffset;
				float num10 = num4 - 70f;
				DrawNotification(notification, new Rect(num9, num10, 320f, 70f));
				num4 -= 85f;
			}
		}

		private void DrawNotification(Notification notification, Rect rect)
		{
			//IL_0008: 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_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_001b: 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_0021: 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_003f: 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)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: 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_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			Color backgroundColor = GetBackgroundColor(notification.type);
			Color accentColor = GetAccentColor(notification.type);
			Color color = GUI.color;
			GUI.color = new Color(backgroundColor.r, backgroundColor.g, backgroundColor.b, notification.alpha * 0.95f);
			GUI.DrawTexture(rect, (Texture)(object)Texture2D.whiteTexture);
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, 5f, ((Rect)(ref rect)).height);
			GUI.color = new Color(accentColor.r, accentColor.g, accentColor.b, notification.alpha);
			GUI.DrawTexture(val, (Texture)(object)Texture2D.whiteTexture);
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(((Rect)(ref rect)).x + 15f, ((Rect)(ref rect)).y + 12f, 32f, 32f);
			GUI.color = new Color(accentColor.r, accentColor.g, accentColor.b, notification.alpha);
			string icon = GetIcon(notification.type);
			iconStyle.normal.textColor = new Color(1f, 1f, 1f, notification.alpha);
			GUI.Label(val2, icon, iconStyle);
			Rect val3 = default(Rect);
			((Rect)(ref val3))..ctor(((Rect)(ref rect)).x + 55f, ((Rect)(ref rect)).y + 12f, ((Rect)(ref rect)).width - 65f, ((Rect)(ref rect)).height - 24f);
			messageStyle.fontSize = 17;
			messageStyle.normal.textColor = new Color(1f, 1f, 1f, notification.alpha);
			GUI.Label(val3, notification.message, messageStyle);
			Rect val4 = default(Rect);
			((Rect)(ref val4))..ctor(((Rect)(ref rect)).x + 2f, ((Rect)(ref rect)).y + 2f, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height);
			GUI.color = new Color(0f, 0f, 0f, notification.alpha * 0.3f);
			GUI.DrawTexture(val4, (Texture)(object)Texture2D.whiteTexture);
			GUI.color = color;
		}

		private void InitializeStyles()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_002e: 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_0068: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_00b1: 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)
			//IL_00d1: Expected O, but got Unknown
			notificationStyle = new GUIStyle(GUI.skin.box);
			backgroundTexture = MakeTexture(2, 2, new Color(0.1f, 0.1f, 0.1f, 0.95f));
			notificationStyle.normal.background = backgroundTexture;
			notificationStyle.border = new RectOffset(8, 8, 8, 8);
			messageStyle = new GUIStyle(GUI.skin.label);
			messageStyle.fontSize = 14;
			messageStyle.wordWrap = true;
			messageStyle.alignment = (TextAnchor)3;
			messageStyle.normal.textColor = Color.white;
			iconStyle = new GUIStyle(GUI.skin.label);
			iconStyle.fontSize = 28;
			iconStyle.alignment = (TextAnchor)4;
			iconStyle.fontStyle = (FontStyle)1;
			stylesInitialized = true;
		}

		private Color GetBackgroundColor(NotificationType type)
		{
			//IL_002f: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			return (Color)(type switch
			{
				NotificationType.Success => new Color(0.15f, 0.25f, 0.15f, 1f), 
				NotificationType.Warning => new Color(0.3f, 0.25f, 0.1f, 1f), 
				NotificationType.Error => new Color(0.3f, 0.15f, 0.15f, 1f), 
				_ => new Color(0.1f, 0.15f, 0.25f, 1f), 
			});
		}

		private Color GetAccentColor(NotificationType type)
		{
			//IL_001b: 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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			return (Color)(type switch
			{
				NotificationType.Success => SuccessColor, 
				NotificationType.Warning => WarningColor, 
				NotificationType.Error => ErrorColor, 
				_ => InfoColor, 
			});
		}

		private string GetIcon(NotificationType type)
		{
			return type switch
			{
				NotificationType.Success => "✓", 
				NotificationType.Warning => "⚠", 
				NotificationType.Error => "✖", 
				_ => "ℹ", 
			};
		}

		private float EaseOutCubic(float t)
		{
			return 1f - Mathf.Pow(1f - t, 3f);
		}

		private Texture2D MakeTexture(int width, int height, Color col)
		{
			//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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			Color[] array = (Color[])(object)new Color[width * height];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = col;
			}
			Texture2D val = new Texture2D(width, height);
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private void OnDestroy()
		{
			if ((Object)(object)instance == (Object)(object)this)
			{
				instance = null;
			}
			if ((Object)(object)backgroundTexture != (Object)null)
			{
				Object.Destroy((Object)(object)backgroundTexture);
				backgroundTexture = null;
			}
		}
	}
	public class FaceSyncMenu : MonoBehaviour
	{
		private ManualLogSource logger;

		private ThreadSafeEmotionState emotionState;

		private EmotionRecognition recognition;

		private bool showUI = true;

		private Rect windowRect = new Rect(100f, 100f, 1000f, 1050f);

		private bool showCameraPreview = false;

		private Texture2D previewTexture = null;

		private int selectedCameraIndex = 0;

		private int cameraCount = 0;

		private string[] cameraNames;

		private List<int> availableCameras = new List<int>();

		private float previewUpdateTimer = 0f;

		private const float PREVIEW_UPDATE_INTERVAL = 0.1f;

		private GUIStyle windowStyle;

		private GUIStyle labelStyle;

		private GUIStyle emotionLabelStyle;

		private GUIStyle headerStyle;

		private GUIStyle sliderStyle;

		private GUIStyle sliderThumbStyle;

		private bool stylesInitialized = false;

		private bool showGraph = true;

		private Vector2 lastMousePos;

		private bool isResizing = false;

		private Vector2 resizeStart;

		private Rect resizeStartRect;

		private const float RESIZE_HANDLE_SIZE = 20f;

		private const float MIN_WINDOW_WIDTH = 300f;

		private const float MIN_WINDOW_HEIGHT = 250f;

		private Texture2D whiteTexture;

		private readonly string[] emotionLabels = new string[8] { "Neutral", "Happiness", "Surprise", "Sadness", "Anger", "Disgust", "Fear", "Contempt" };

		private readonly Color[] emotionColors = (Color[])(object)new Color[8]
		{
			new Color(0.7f, 0.7f, 0.7f),
			new Color(1f, 0.9f, 0.2f),
			new Color(1f, 0.6f, 0f),
			new Color(0.3f, 0.5f, 1f),
			new Color(1f, 0.2f, 0.2f),
			new Color(0.6f, 0.2f, 0.6f),
			new Color(0.5f, 0.2f, 0.8f),
			new Color(0.8f, 0.6f, 0.3f)
		};

		public void Initialize(ThreadSafeEmotionState state, ManualLogSource logger, EmotionRecognition recognition)
		{
			emotionState = state;
			this.logger = logger;
			this.recognition = recognition;
			Thread thread = new Thread((ThreadStart)delegate
			{
				availableCameras = CameraUtils.GetAvailableCameras();
				cameraNames = new string[availableCameras.Count];
				for (int i = 0; i < availableCameras.Count; i++)
				{
					cameraNames[i] = $"Camera {availableCameras[i]}";
				}
				selectedCameraIndex = availableCameras.IndexOf(FSConfig.CameraIndex);
				if (selectedCameraIndex < 0)
				{
					selectedCameraIndex = 0;
				}
				logger.LogInfo((object)$"✓ Detected {availableCameras.Count} camera(s)");
			});
			thread.IsBackground = true;
			thread.Start();
		}

		private void Update()
		{
			if (Input.GetKeyDown((KeyCode)288))
			{
				showUI = !showUI;
			}
			if (showUI && showCameraPreview && recognition != null)
			{
				previewUpdateTimer += Time.deltaTime;
				if (previewUpdateTimer >= 0.1f)
				{
					previewUpdateTimer = 0f;
					UpdateCameraPreview();
				}
			}
		}

		private void UpdateCameraPreview()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			int width;
			int height;
			byte[] latestFrame = recognition.GetLatestFrame(out width, out height);
			if (latestFrame == null || latestFrame.Length == 0)
			{
				return;
			}
			try
			{
				if ((Object)(object)previewTexture == (Object)null || ((Texture)previewTexture).width != width || ((Texture)previewTexture).height != height)
				{
					if ((Object)(object)previewTexture != (Object)null)
					{
						Object.Destroy((Object)(object)previewTexture);
					}
					previewTexture = new Texture2D(width, height, (TextureFormat)3, false);
					((Texture)previewTexture).filterMode = (FilterMode)1;
				}
				previewTexture.LoadRawTextureData(latestFrame);
				previewTexture.Apply();
			}
			catch (Exception ex)
			{
				ManualLogSource obj = logger;
				if (obj != null)
				{
					obj.LogError((object)("Preview update failed: " + ex.Message));
				}
			}
		}

		private void OnGUI()
		{
			//IL_0029: 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_004a: Expected O, but got Unknown
			//IL_0045: 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 (showUI && emotionState != null)
			{
				InitializeStyles();
				windowRect = GUI.Window(12345, windowRect, new WindowFunction(DrawEmotionWindow), "Face Sync", windowStyle);
			}
		}

		private void InitializeStyles()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0047: 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)
			//IL_006f: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0085: 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_00b1: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Expected O, but got Unknown
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Expected O, but got Unknown
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Expected O, but got Unknown
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			if (!stylesInitialized)
			{
				windowStyle = new GUIStyle(GUI.skin.window);
				windowStyle.normal.background = MakeTexture(2, 2, new Color(0f, 0f, 0f, 1f));
				windowStyle.padding = new RectOffset(10, 10, 20, 10);
				whiteTexture = new Texture2D(2, 2);
				whiteTexture.SetPixel(0, 0, Color.white);
				whiteTexture.Apply();
				labelStyle = new GUIStyle(GUI.skin.label);
				labelStyle.fontSize = 19;
				labelStyle.normal.textColor = Color.white;
				labelStyle.wordWrap = false;
				emotionLabelStyle = new GUIStyle(GUI.skin.label);
				emotionLabelStyle.fontSize = 16;
				emotionLabelStyle.fontStyle = (FontStyle)1;
				emotionLabelStyle.normal.textColor = Color.white;
				emotionLabelStyle.alignment = (TextAnchor)4;
				headerStyle = new GUIStyle(GUI.skin.label);
				headerStyle.fontSize = 17;
				headerStyle.fontStyle = (FontStyle)1;
				headerStyle.normal.textColor = new Color(0.8f, 0.9f, 1f);
				sliderStyle = new GUIStyle(GUI.skin.horizontalSlider);
				sliderStyle.fixedHeight = 20f;
				sliderThumbStyle = new GUIStyle(GUI.skin.horizontalSliderThumb);
				sliderThumbStyle.fixedWidth = 20f;
				sliderThumbStyle.fixedHeight = 20f;
				sliderThumbStyle.normal.background = MakeTexture(2, 2, new Color(0.8f, 0.8f, 0.8f));
				sliderThumbStyle.hover.background = MakeTexture(2, 2, new Color(1f, 1f, 1f));
				sliderThumbStyle.active.background = MakeTexture(2, 2, new Color(0.6f, 0.8f, 1f));
				stylesInitialized = true;
			}
		}

		private void DrawEmotionWindow(int windowID)
		{
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: 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_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_041e: Unknown result type (might be due to invalid IL or missing references)
			//IL_048d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_055e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0874: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0924: Unknown result type (might be due to invalid IL or missing references)
			//IL_0938: Unknown result type (might be due to invalid IL or missing references)
			//IL_0956: Unknown result type (might be due to invalid IL or missing references)
			//IL_095b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0973: Unknown result type (might be due to invalid IL or missing references)
			//IL_0979: Invalid comparison between Unknown and I4
			//IL_0987: Unknown result type (might be due to invalid IL or missing references)
			//IL_098c: Unknown result type (might be due to invalid IL or missing references)
			//IL_098e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0991: Unknown result type (might be due to invalid IL or missing references)
			//IL_0996: Unknown result type (might be due to invalid IL or missing references)
			//IL_099b: Unknown result type (might be due to invalid IL or missing references)
			//IL_09b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_09dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a0a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a10: Invalid comparison between Unknown and I4
			//IL_0a36: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a86: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			if (cameraNames != null && cameraNames.Length != 0)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label("Camera:", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) });
				int num = GUILayout.SelectionGrid(selectedCameraIndex, cameraNames, Mathf.Min(cameraNames.Length, 4), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(25f) });
				if (num != selectedCameraIndex)
				{
					selectedCameraIndex = num;
					int num2 = availableCameras[selectedCameraIndex];
					recognition?.SwitchCamera(num2);
					Plugin.cameraIndex.Value = num2;
				}
				GUILayout.EndHorizontal();
				GUILayout.Space(5f);
			}
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Preview:", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) });
			bool flag = GUILayout.Toggle(showCameraPreview, showCameraPreview ? "Hide \ud83d\udcf7" : "Show \ud83d\udcf7", GUI.skin.button, Array.Empty<GUILayoutOption>());
			if (flag != showCameraPreview)
			{
				showCameraPreview = flag;
				recognition?.SetPreviewEnabled(showCameraPreview);
			}
			GUILayout.EndHorizontal();
			if (showCameraPreview && (Object)(object)previewTexture != (Object)null)
			{
				GUILayout.Space(5f);
				float num3 = ((Rect)(ref windowRect)).width - 20f;
				float num4 = 180f;
				float num5 = (float)((Texture)previewTexture).width / (float)((Texture)previewTexture).height;
				float num6 = num3;
				float num7 = num6 / num5;
				if (num7 > num4)
				{
					num7 = num4;
					num6 = num7 * num5;
				}
				Rect rect = GUILayoutUtility.GetRect(num6, num7);
				GUI.Box(rect, "");
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(0f, 1f, 1f, -1f);
				GUI.DrawTextureWithTexCoords(rect, (Texture)(object)previewTexture, val);
				GUILayout.Space(5f);
			}
			GUILayout.Space(10f);
			EmotionSnapshot snapshot = emotionState.GetSnapshot();
			if (!string.IsNullOrEmpty(snapshot.error))
			{
				GUI.color = new Color(1f, 0.3f, 0.3f);
				GUILayout.Label("Error: " + snapshot.error, labelStyle, Array.Empty<GUILayoutOption>());
				GUI.color = Color.white;
				GUILayout.EndVertical();
				GUI.DragWindow();
				return;
			}
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Status:", labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) });
			if (snapshot.active)
			{
				GUI.color = new Color(0.3f, 1f, 0.3f);
				GUILayout.Label("● Active", labelStyle, Array.Empty<GUILayoutOption>());
			}
			else
			{
				GUI.color = new Color(0.7f, 0.7f, 0.7f);
				GUILayout.Label("○ Inactive (Initializing...)", labelStyle, Array.Empty<GUILayoutOption>());
			}
			GUI.color = Color.white;
			GUILayout.EndHorizontal();
			if (snapshot.active)
			{
				float timeSinceUpdate = snapshot.TimeSinceUpdate;
				GUILayout.Label($"Last Update: {timeSinceUpdate:F1}s ago", labelStyle, Array.Empty<GUILayoutOption>());
			}
			GUILayout.Space(10f);
			if (snapshot.active && snapshot.emotion != "No Face")
			{
				GUI.color = GetEmotionColor(snapshot.emotion);
				GUILayout.Label("★ " + snapshot.emotion, emotionLabelStyle, Array.Empty<GUILayoutOption>());
				GUI.color = Color.white;
				if (snapshot.confidence > 0f)
				{
					GUILayout.Label($"Confidence: {snapshot.confidence:P0}", labelStyle, Array.Empty<GUILayoutOption>());
				}
			}
			else if (snapshot.emotion == "No Face")
			{
				GUI.color = new Color(0.7f, 0.7f, 0.7f);
				GUILayout.Label("No Face Detected", emotionLabelStyle, Array.Empty<GUILayoutOption>());
				GUI.color = Color.white;
			}
			GUILayout.Space(10f);
			GUILayout.Label("Emotion Probabilities:", headerStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Space(5f);
			bool flag2 = GUILayout.Toggle(showGraph, showGraph ? "Hide Graph" : "Show Graph", GUI.skin.button, Array.Empty<GUILayoutOption>());
			if (flag2 != showGraph)
			{
				showGraph = flag2;
			}
			if (showGraph)
			{
				for (int i = 0; i < Math.Min(snapshot.probs.Length, emotionLabels.Length); i++)
				{
					DrawEmotionBar(emotionLabels[i], snapshot.probs[i], emotionColors[i]);
				}
			}
			GUILayout.Space(20f);
			GUILayout.Label("Recoginzer Type", headerStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("CASCADE: Lightweight, but lighting and camera should be at the front (like a laptop) ", labelStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("DNN: Slightly heavier, but the camera does not need to be positioned at the front", labelStyle, Array.Empty<GUILayoutOption>());
			string[] names = Enum.GetNames(typeof(RecognizerType));
			int num8 = Array.IndexOf(names, FSConfig.RecognizerType.ToString());
			int num9 = GUILayout.SelectionGrid(num8, names, 1, Array.Empty<GUILayoutOption>());
			if (num9 != num8)
			{
				RecognizerType recognizerType2 = (FSConfig.RecognizerType = (RecognizerType)Enum.Parse(typeof(RecognizerType), names[num9]));
				Notification.Info($"Recognizer Type set to: {recognizerType2}");
			}
			GUILayout.Label("Recognition Update Interval", headerStyle, Array.Empty<GUILayoutOption>());
			float num10 = DrawCustomSlider("", (float)FSConfig.UpdateIntervalMs / 1000f, 0.1f, 1f, "s");
			if (Math.Abs(num10 - (float)FSConfig.UpdateIntervalMs / 1000f) > 0.01f)
			{
				FSConfig.UpdateIntervalMs = (int)(num10 * 1000f);
			}
			GUILayout.Space(10f);
			GUILayout.Label("Expression Sync", headerStyle, Array.Empty<GUILayoutOption>());
			bool flag3 = GUILayout.Toggle(FSConfig.EnableExpressionSync, FSConfig.EnableExpressionSync ? "ON" : "OFF", GUI.skin.button, Array.Empty<GUILayoutOption>());
			if (flag3 != FSConfig.EnableExpressionSync)
			{
				FSConfig.EnableExpressionSync = flag3;
				NotificationManager.Show("Expression Sync: " + (FSConfig.EnableExpressionSync ? "ON" : "OFF"), FSConfig.EnableExpressionSync ? NotificationManager.NotificationType.Success : NotificationManager.NotificationType.Warning);
			}
			GUILayout.Space(5f);
			GUILayout.Label("Hide Player Expression Popup", headerStyle, Array.Empty<GUILayoutOption>());
			bool flag4 = GUILayout.Toggle(FSConfig.AlwaysHidePlayerExpressionPopup, FSConfig.AlwaysHidePlayerExpressionPopup ? "ON" : "OFF", GUI.skin.button, Array.Empty<GUILayoutOption>());
			if (flag4 != FSConfig.AlwaysHidePlayerExpressionPopup)
			{
				FSConfig.AlwaysHidePlayerExpressionPopup = flag4;
				NotificationManager.Show("Always Hide Player Expression Popup: " + (FSConfig.AlwaysHidePlayerExpressionPopup ? "ON" : "OFF"), FSConfig.AlwaysHidePlayerExpressionPopup ? NotificationManager.NotificationType.Success : NotificationManager.NotificationType.Warning);
			}
			GUILayout.Space(10f);
			GUILayout.Label($"GPU Acceleration: {FSConfig.GpuAcceleration}", headerStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("This feature can accelerate emotional inference. \nIf any issues arise, please disable it in the Mod Manager Config", labelStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Space(10f);
			GUI.color = new Color(0.8f, 0.8f, 0.8f);
			GUILayout.Label("Controls:", headerStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("F7: Toggle Menu", labelStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("F8: Toggle Expression Sync", labelStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("F9: Toggle Player Expression Popup Invisible", labelStyle, Array.Empty<GUILayoutOption>());
			GUI.color = Color.white;
			GUILayout.EndVertical();
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(((Rect)(ref windowRect)).width - 20f, ((Rect)(ref windowRect)).height - 20f, 20f, 20f);
			Event current = Event.current;
			if ((int)current.type == 0 && current.button == 0 && ((Rect)(ref val2)).Contains(current.mousePosition))
			{
				isResizing = true;
				lastMousePos = current.mousePosition;
				current.Use();
			}
			if (isResizing && (int)current.type == 3)
			{
				Vector2 mousePosition = current.mousePosition;
				Vector2 val3 = mousePosition - lastMousePos;
				((Rect)(ref windowRect)).width = Mathf.Max(300f, ((Rect)(ref windowRect)).width + val3.x);
				((Rect)(ref windowRect)).height = Mathf.Max(250f, ((Rect)(ref windowRect)).height + val3.y);
				lastMousePos = mousePosition;
				current.Use();
			}
			if (isResizing && (int)current.type == 1 && current.button == 0)
			{
				isResizing = false;
				current.Use();
			}
			GUI.Box(val2, "⇲");
			if (!isResizing)
			{
				Rect val4 = default(Rect);
				((Rect)(ref val4))..ctor(0f, 0f, ((Rect)(ref windowRect)).width - 20f, ((Rect)(ref windowRect)).height - 20f);
				GUI.DragWindow(val4);
			}
		}

		private void DrawEmotionBar(string label, float value, Color color)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_0041: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(label, labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) });
			Rect rect = GUILayoutUtility.GetRect(180f, 18f);
			Color color2 = GUI.color;
			GUI.color = new Color(0.2f, 0.2f, 0.2f, 1f);
			GUI.DrawTexture(rect, (Texture)(object)whiteTexture);
			if (value > 0f)
			{
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * Mathf.Clamp01(value), ((Rect)(ref rect)).height);
				GUI.color = color;
				GUI.DrawTexture(val, (Texture)(object)whiteTexture);
			}
			GUI.color = color2;
			GUILayout.Label($"{value:P0}", labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) });
			GUILayout.EndHorizontal();
		}

		private float DrawCustomSlider(string label, float value, float min, float max, string unit = "", float labelWidth = 120f)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(label, labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(labelWidth) });
			Rect rect = GUILayoutUtility.GetRect(200f, 30f);
			Color color = GUI.color;
			GUI.color = new Color(0.2f, 0.2f, 0.2f);
			GUI.DrawTexture(rect, (Texture)(object)whiteTexture);
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref rect)).x + 10f, ((Rect)(ref rect)).y + 12f, ((Rect)(ref rect)).width - 20f, 6f);
			GUI.color = new Color(0.4f, 0.4f, 0.4f);
			GUI.DrawTexture(val, (Texture)(object)whiteTexture);
			float num = (value - min) / (max - min);
			float num2 = ((Rect)(ref val)).x + ((Rect)(ref val)).width * num;
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(num2 - 10f, ((Rect)(ref rect)).y + 5f, 20f, 20f);
			Color color2 = (((Rect)(ref val2)).Contains(Event.current.mousePosition) ? new Color(1f, 1f, 1f) : new Color(0.8f, 0.8f, 0.8f));
			GUI.color = color2;
			GUI.DrawTexture(val2, (Texture)(object)whiteTexture);
			GUI.color = color;
			if ((int)Event.current.type == 0 && ((Rect)(ref rect)).Contains(Event.current.mousePosition))
			{
				float x = Event.current.mousePosition.x;
				float num3 = Mathf.Clamp01((x - ((Rect)(ref val)).x) / ((Rect)(ref val)).width);
				value = min + (max - min) * num3;
				Event.current.Use();
			}
			GUILayout.Label($"{value:F1}{unit}", labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) });
			GUILayout.EndHorizontal();
			return value;
		}

		private Color GetEmotionColor(string emotion)
		{
			//IL_0034: 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_002c: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			int num = Array.IndexOf(emotionLabels, emotion);
			if (num >= 0 && num < emotionColors.Length)
			{
				return emotionColors[num];
			}
			return Color.white;
		}

		private Texture2D MakeTexture(int width, int height, Color col)
		{
			//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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			Color[] array = (Color[])(object)new Color[width * height];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = col;
			}
			Texture2D val = new Texture2D(width, height);
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		public void SetVisible(bool visible)
		{
			showUI = visible;
		}

		public void ResetWindowPosition()
		{
			//IL_0016: 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)
			windowRect = new Rect(20f, 20f, 400f, 350f);
		}

		private void OnDestroy()
		{
			if ((Object)(object)previewTexture != (Object)null)
			{
				Object.Destroy((Object)(object)previewTexture);
				previewTexture = null;
			}
			if ((Object)(object)whiteTexture != (Object)null)
			{
				Object.Destroy((Object)(object)whiteTexture);
				whiteTexture = null;
			}
		}
	}
	public static class CalcUtils
	{
		public static Rect Grow(Rect r, double ratio, int w, int h)
		{
			//IL_0001: 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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0036: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00a4: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			int num = r.X + r.Width / 2;
			int num2 = r.Y + r.Height / 2;
			int num3 = (int)((double)r.Width * (1.0 + ratio));
			int num4 = (int)((double)r.Height * (1.0 + ratio));
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(num - num3 / 2, num2 - num4 / 2, num3, num4);
			val.X = Math.Max(0, val.X);
			val.Y = Math.Max(0, val.Y);
			val.Width = Math.Min(val.Width, w - val.X);
			val.Height = Math.Min(val.Height, h - val.Y);
			return val;
		}

		public static bool IsProb(float[] v)
		{
			if (v.Length == 0)
			{
				return false;
			}
			float num = 0f;
			foreach (float num2 in v)
			{
				if ((double)num2 < -1E-06 || (double)num2 > 1.000001)
				{
					return false;
				}
				num += num2;
			}
			return Math.Abs(num - 1f) < 0.02f;
		}

		public static float[] ReweightFerPlus(float[] p)
		{
			float[] array = new float[8] { 0.7f, 1.2f, 1.2f, 1.15f, 1.15f, 1.1f, 1.1f, 1f };
			float[] array2 = new float[p.Length];
			float num = 0f;
			for (int i = 0; i < p.Length; i++)
			{
				array2[i] = p[i] * ((i < array.Length) ? array[i] : 1f);
				num += array2[i];
			}
			if (num <= 0f)
			{
				return p;
			}
			for (int j = 0; j < array2.Length; j++)
			{
				array2[j] /= num;
			}
			return array2;
		}

		public static float[] Softmax(float[] x)
		{
			float max = x.Max();
			float[] array = x.Select((float v) => (float)Math.Exp(v - max)).ToArray();
			float num = array.Sum();
			for (int i = 0; i < array.Length; i++)
			{
				array[i] /= num;
			}
			return array;
		}

		public static float[] Average(IEnumerable<float[]> arrs)
		{
			List<float[]> list = arrs.ToList();
			float[] array = new float[list[0].Length];
			foreach (float[] item in list)
			{
				for (int i = 0; i < array.Length; i++)
				{
					array[i] += item[i];
				}
			}
			for (int j = 0; j < array.Length; j++)
			{
				array[j] /= list.Count;
			}
			return array;
		}

		public static int ArgMax(float[] a)
		{
			int num = 0;
			for (int i = 1; i < a.Length; i++)
			{
				if (a[i] > a[num])
				{
					num = i;
				}
			}
			return num;
		}
	}
	public class EmotionRecognition
	{
		private readonly ManualLogSource _logger;

		private RecognizerType _recognizerType;

		private Dictionary<RecognizerType, EmotionRecognizer> _recognizers = new Dictionary<RecognizerType, EmotionRecognizer>();

		private VideoCapture _videoCapture = null;

		private EmotionRecognizer _recognizer;

		private int _currentCameraIndex = 0;

		protected volatile bool _isRunning = false;

		protected readonly object _captureLock = new object();

		protected readonly object _frameLock = new object();

		protected readonly object _recognizerLock = new object();

		private bool _previewEnabled = false;

		protected byte[] _latestFrameData = null;

		protected int _frameWidth = 0;

		protected int _frameHeight = 0;

		private Thread _workerThread = null;

		protected readonly ThreadSafeEmotionState _emotionState = new ThreadSafeEmotionState();

		public ThreadSafeEmotionState EmotionState => _emotionState;

		public EmotionRecognition(ManualLogSource logger, int cameraIndex)
		{
			_logger = logger;
			_currentCameraIndex = cameraIndex;
		}

		private void InitializeCapture(int cameraIndex)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			_videoCapture = new VideoCapture(cameraIndex, (VideoCaptureAPIs)0);
			if (!_videoCapture.IsOpened())
			{
				throw new Exception("Cannot open camera with index " + cameraIndex);
			}
			_videoCapture.Set((VideoCaptureProperties)3, 640.0);
			_videoCapture.Set((VideoCaptureProperties)4, 480.0);
		}

		public bool Start()
		{
			RecognizerType recognizerType = FSConfig.RecognizerType;
			if (!_recognizers.TryGetValue(recognizerType, out var value))
			{
				return false;
			}
			_recognizer = value;
			_recognizerType = recognizerType;
			_isRunning = true;
			_workerThread = new Thread(RecognizeLoop)
			{
				IsBackground = true,
				Priority = ThreadPriority.BelowNormal,
				Name = "EmotionRecognitionThread"
			};
			_workerThread.Start();
			return true;
		}

		public bool Stop()
		{
			if (!_isRunning)
			{
				return true;
			}
			_isRunning = false;
			if (_workerThread == null)
			{
				return true;
			}
			try
			{
				bool flag = _workerThread.Join(3000);
				if (!flag)
				{
					_logger.LogWarning((object)"[-] Emotion recognition thread did not terminate in time.");
				}
				return flag;
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("[-] Error while stopping emotion recognition thread: " + ex.Message));
				return false;
			}
		}

		private void RecognizeLoop()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				InitializeCapture(_currentCameraIndex);
			}
			catch (Exception ex)
			{
				_logger.LogError((object)("Failed to initialize camera: " + ex.Message));
				throw new Exception("Camera initialization failed", ex);
			}
			Mat val = new Mat();
			try
			{
				while (_isRunning)
				{
					bool flag = false;
					lock (_captureLock)
					{
						if (_videoCapture != null && _videoCapture.IsOpened())
						{
							flag = _videoCapture.Read(val) && !val.Empty();
						}
					}
					if (!flag)
					{
						Thread.Sleep(10);
						_emotionState.Update("Waiting for camera ...", 0f, null);
						continue;
					}
					if (_previewEnabled)
					{
						lock (_frameLock)
						{
							Mat val2 = new Mat();
							try
							{
								Cv2.CvtColor(InputArray.op_Implicit(val), OutputArray.op_Implicit(val2), (ColorConversionCodes)4, 0);
								int num = 320;
								int num2 = (int)((float)val.Height * ((float)num / (float)val.Width));
								Mat val3 = new Mat();
								try
								{
									Cv2.Resize(InputArray.op_Implicit(val2), OutputArray.op_Implicit(val3), new Size(num, num2), 0.0, 0.0, (InterpolationFlags)1);
									_frameWidth = num;
									_frameHeight = num2;
									int num3 = val3.Width * val3.Height * 3;
									if (_latestFrameData == null || _latestFrameData.Length != num3)
									{
										_latestFrameData = new byte[num3];
									}
									Marshal.Copy(val3.Data, _latestFrameData, 0, num3);
								}
								finally
								{
									((IDisposable)val3)?.Dispose();
								}
							}
							finally
							{
								((IDisposable)val2)?.Dispose();
							}
						}
					}
					if (!IsInGame())
					{
						_emotionState.Update("Waiting for starting game ...", 0f, null);
						Thread.Sleep(100);
						continue;
					}
					if (_recognizerType != FSConfig.RecognizerType)
					{
						lock (_recognizerLock)
						{
							_recognizerType = FSConfig.RecognizerType;
							_recognizer = _recognizers[_recognizerType];
						}
					}
					if (_recognizer.InferEmotion(val, out var emotion, out var confidence, out var probabilities))
					{
						_emotionState.Update(emotion, confidence, probabilities);
					}
					else
					{
						_emotionState.Update("No Face", 0f, new float[8]);
					}
					Thread.Sleep(FSConfig.UpdateIntervalMs);
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public byte[] GetLatestFrame(out int width, out int height)
		{
			lock (_frameLock)
			{
				width = _frameWidth;
				height = _frameHeight;
				if (_latestFrameData == null)
				{
					return null;
				}
				byte[] array = new byte[_latestFrameData.Length];
				Array.Copy(_latestFrameData, array, _latestFrameData.Length);
				return array;
			}
		}

		public void RegisterRecognizer(RecognizerType recognizerType, EmotionRecognizer recognizer)
		{
			_recognizers[recognizerType] = recognizer;
		}

		public void SwitchCamera(int newCameraIndex)
		{
			try
			{
				lock (_captureLock)
				{
					if (_videoCapture != null)
					{
						_videoCapture.Release();
						((DisposableObject)_videoCapture).Dispose();
						_videoCapture = null;
					}
					Thread.Sleep(100);
					_videoCapture = VideoCapture.FromCamera(newCameraIndex, (VideoCaptureAPIs)0);
					if (_videoCapture == null || !_videoCapture.IsOpened())
					{
						_logger.LogError((object)$"Failed to open camera {newCameraIndex}");
						_videoCapture = VideoCapture.FromCamera(_currentCameraIndex, (VideoCaptureAPIs)0);
					}
					else
					{
						_currentCameraIndex = newCameraIndex;
						NotificationManager.Show($"Camera switched to: {newCameraIndex}", NotificationManager.NotificationType.Success);
					}
				}
			}
			catch (Exception ex)
			{
				NotificationManager.Show("Camera switch failed", NotificationManager.NotificationType.Error);
				_logger.LogError((object)("Camera switch error: " + ex.Message));
			}
		}

		public void SetPreviewEnabled(bool enabled)
		{
			_previewEnabled = enabled;
		}

		public void Dispose()
		{
			if (Stop())
			{
				lock (_captureLock)
				{
					if (_videoCapture != null)
					{
						_videoCapture.Release();
						((DisposableObject)_videoCapture).Dispose();
						_videoCapture = null;
					}
				}
			}
			foreach (EmotionRecognizer value in _recognizers.Values)
			{
				value.Dispose();
			}
			_recognizers.Clear();
		}

		private static bool IsInGame()
		{
			return !SemiFunc.IsCurrentLevel(RunManager.instance.levelCurrent, RunManager.instance.levelLobbyMenu) && !SemiFunc.IsCurrentLevel(RunManager.instance.levelCurrent, RunManager.instance.levelMainMenu) && !SemiFunc.IsCurrentLevel(RunManager.instance.levelCurrent, RunManager.instance.levelSplashScreen) && !SemiFunc.IsCurrentLevel(RunManager.instance.levelCurrent, RunManager.instance.levelTutorial);
		}
	}
	public enum RecognizerType
	{
		CASCADE,
		DNN
	}
	public class CameraUtils
	{
		public static List<int> GetAvailableCameras()
		{
			List<int> list = new List<int>();
			for (int i = 0; i < 10; i++)
			{
				try
				{
					VideoCapture val = VideoCapture.FromCamera(i, (VideoCaptureAPIs)0);
					try
					{
						if (val != null && val.IsOpened())
						{
							list.Add(i);
							val.Release();
						}
						else if (list.Count > 0)
						{
							break;
						}
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
				}
				catch
				{
					if (list.Count > 0)
					{
						break;
					}
				}
			}
			if (list.Count == 0)
			{
				list.Add(0);
			}
			return list;
		}
	}
	public class FSConfig
	{
		public static int CameraIndex
		{
			get
			{
				return Plugin.cameraIndex.Value;
			}
			set
			{
				Plugin.cameraIndex.Value = value;
			}
		}

		public static int UpdateIntervalMs
		{
			get
			{
				return Plugin.updateIntervalMs.Value;
			}
			set
			{
				Plugin.updateIntervalMs.Value = value;
			}
		}

		public static bool GpuAcceleration
		{
			get
			{
				return Plugin.gpuAcceleration.Value;
			}
			set
			{
				Plugin.gpuAcceleration.Value = value;
			}
		}

		public static bool EnableExpressionSync
		{
			get
			{
				return Plugin.enableExpressionSync.Value;
			}
			set
			{
				Plugin.enableExpressionSync.Value = value;
			}
		}

		public static bool AlwaysHidePlayerExpressionPopup
		{
			get
			{
				return Plugin.alwaysHidePlayerExpressionPopup.Value;
			}
			set
			{
				Plugin.alwaysHidePlayerExpressionPopup.Value = value;
			}
		}

		public static RecognizerType RecognizerType
		{
			get
			{
				return Plugin.recognizerType.Value;
			}
			set
			{
				Plugin.recognizerType.Value = value;
			}
		}
	}
	public class DnnEmotionRecognizer : EmotionRecognizer
	{
		private const float CONFIDENCE_THRESHOLD = 0.6f;

		private Net faceNet;

		public DnnEmotionRecognizer(ManualLogSource logger, string modelPath, string faceProtoPath, string faceCaffeModelPath)
			: base(logger, modelPath)
		{
			faceNet = CvDnn.ReadNetFromCaffe(faceProtoPath, faceCaffeModelPath);
		}

		public override bool InferEmotion(Mat frame, out string emotion, out float confidence, out float[] probabilities)
		{
			//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_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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_0049: 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_008d: 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_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			Rect val = DetectFaceWithDNN(frame);
			if (val.Width > 0 && val.Height > 0)
			{
				flag = true;
			}
			else if (lastDetectedFace.HasValue)
			{
				val = lastDetectedFace.Value;
				flag = true;
			}
			if (!flag)
			{
				emotion = "No Face";
				confidence = 0f;
				probabilities = new float[8];
				return false;
			}
			Rect val2 = CalcUtils.Grow(val, 0.2, frame.Width, frame.Height);
			float[] array = new float[4096];
			Mat val3 = new Mat();
			try
			{
				Mat val4 = new Mat();
				try
				{
					Cv2.CvtColor(InputArray.op_Implicit(frame), OutputArray.op_Implicit(val3), (ColorConversionCodes)6, 0);
					Mat val5 = val3.SubMat(val2);
					try
					{
						Mat val6 = val5.Clone();
						try
						{
							Cv2.Resize(InputArray.op_Implicit(val6), OutputArray.op_Implicit(val4), new Size(64, 64), 0.0, 0.0, (InterpolationFlags)1);
						}
						finally
						{
							((IDisposable)val6)?.Dispose();
						}
					}
					finally
					{
						((IDisposable)val5)?.Dispose();
					}
					for (int i = 0; i < 64; i++)
					{
						for (int j = 0; j < 64; j++)
						{
							byte b = val4.At<byte>(i, j);
							array[i * 64 + j] = (int)b;
						}
					}
				}
				finally
				{
					((IDisposable)val4)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val3)?.Dispose();
			}
			Memory<float> memory = array;
			object obj = global::<PrivateImplementationDetails>.D4F9C16444BBD6A5FB4F10E9D647D15787CF536E9A2324E584122A50678AA55D_A6;
			if (obj == null)
			{
				obj = new int[4] { 1, 1, 64, 64 };
				global::<PrivateImplementationDetails>.D4F9C16444BBD6A5FB4F10E9D647D15787CF536E9A2324E584122A50678AA55D_A6 = (int[])obj;
			}
			DenseTensor<float> val7 = new DenseTensor<float>(memory, new ReadOnlySpan<int>((int[]?)obj), false);
			List<NamedOnnxValue> list = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor<float>("Input3", (Tensor<float>)(object)val7) };
			IDisposableReadOnlyCollection<DisposableNamedOnnxValue> val8 = session.Run((IReadOnlyCollection<NamedOnnxValue>)list);
			float[] item;
			try
			{
				Tensor<float> source = ((NamedOnnxValue)((IEnumerable<DisposableNamedOnnxValue>)val8).First((DisposableNamedOnnxValue r) => ((NamedOnnxValue)r).Name == "Plus692_Output_0")).AsTensor<float>();
				float[] array2 = ((IEnumerable<float>)source).ToArray();
				item = (CalcUtils.IsProb(array2) ? CalcUtils.ReweightFerPlus(array2) : CalcUtils.ReweightFerPlus(CalcUtils.Softmax(array2)));
			}
			finally
			{
				((IDisposable)val8)?.Dispose();
			}
			scoreHist.Enqueue(item);
			if (scoreHist.Count > smoothN)
			{
				scoreHist.Dequeue();
			}
			float[] array3 = CalcUtils.Average(scoreHist);
			int num = CalcUtils.ArgMax(array3);
			float num2 = array3[num];
			emotion = EmotionRecognizer.Labels[num];
			confidence = num2;
			probabilities = array3;
			return true;
		}

		private Rect DetectFaceWithDNN(Mat frame)
		{
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int rows = frame.Rows;
				int cols = frame.Cols;
				Mat val = CvDnn.BlobFromImage(frame, 1.0, new Size(300, 300), new Scalar(104.0, 117.0, 123.0), false, false);
				try
				{
					faceNet.SetInput(val, "data");
					Mat val2 = faceNet.Forward("detection_out");
					try
					{
						int num = val2.Size(2);
						Mat val3 = val2.Reshape(1, num);
						try
						{
							float num2 = 0f;
							Rect result = default(Rect);
							for (int i = 0; i < val3.Rows; i++)
							{
								float num3 = val3.At<float>(i, 2);
								if (num3 > 0.6f && num3 > num2)
								{
									int val4 = (int)(val3.At<float>(i, 3) * (float)cols);
									int val5 = (int)(val3.At<float>(i, 4) * (float)rows);
									int val6 = (int)(val3.At<float>(i, 5) * (float)cols);
									int val7 = (int)(val3.At<float>(i, 6) * (float)rows);
									val4 = Math.Max(0, Math.Min(val4, cols - 1));
									val5 = Math.Max(0, Math.Min(val5, rows - 1));
									val6 = Math.Max(0, Math.Min(val6, cols - 1));
									val7 = Math.Max(0, Math.Min(val7, rows - 1));
									int num4 = val6 - val4;
									int num5 = val7 - val5;
									if (num4 >= 30 && num5 >= 30)
									{
										num2 = num3;
										((Rect)(ref result))..ctor(val4, val5, num4, num5);
									}
								}
							}
							return result;
						}
						finally
						{
							((IDisposable)val3)?.Dispose();
						}
					}
					finally
					{
						((IDisposable)val2)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val)?.Dispose();
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("DNN detection error: " + ex.Message));
				return default(Rect);
			}
		}

		protected override string PickOutputName(InferenceSession session)
		{
			foreach (KeyValuePair<string, NodeMetadata> outputMetadatum in session.OutputMetadata)
			{
				int[] dimensions = outputMetadatum.Value.Dimensions;
				int num = 1;
				int[] array = dimensions;
				foreach (int num2 in array)
				{
					if (num2 > 0)
					{
						num *= num2;
					}
				}
				if (dimensions.Length <= 2 && num >= 7 && num <= 10)
				{
					return outputMetadatum.Key;
				}
			}
			string[] array2 = new string[5] { "Prob", "prob", "Plus692_Output_0", "output", "softmaxout" };
			foreach (string text in array2)
			{
				if (session.OutputMetadata.ContainsKey(text))
				{
					return text;
				}
			}
			return session.OutputMetadata.Keys.First();
		}

		public override void Dispose()
		{
			if (isDisposed)
			{
				return;
			}
			try
			{
				isRunning = false;
				Net obj = faceNet;
				if (obj != null)
				{
					((DisposableObject)obj).Dispose();
				}
				faceNet = null;
				InferenceSession obj2 = session;
				if (obj2 != null)
				{
					obj2.Dispose();
				}
				session = null;
				isDisposed = true;
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Error during disposal: " + ex.Message));
			}
		}
	}
	public abstract class EmotionRecognizer
	{
		protected static readonly string[] Labels = new string[8] { "Neutral", "Happiness", "Surprise", "Sadness", "Anger", "Disgust", "Fear", "Contempt" };

		protected readonly ManualLogSource logger;

		protected readonly ThreadSafeEmotionState emotionState;

		protected volatile bool isRunning = false;

		protected InferenceSession session;

		protected string inputName;

		protected string outputName;

		protected int frameCount = 0;

		protected bool isDisposed = false;

		protected int smoothN = 1;

		protected Rect? lastDetectedFace = null;

		protected int framesWithoutDetection = 0;

		protected const int MAX_FRAMES_WITHOUT_DETECTION = 30;

		protected int detectFrameCounter = 0;

		protected int detectEveryNFrames = 9;

		protected Queue<float[]> scoreHist = new Queue<float[]>();

		public ThreadSafeEmotionState EmotionState => emotionState;

		protected EmotionRecognizer(ManualLogSource logger, string modelPath)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			this.logger = logger;
			try
			{
				SessionOptions val = new SessionOptions
				{
					GraphOptimizationLevel = (GraphOptimizationLevel)99
				};
				if (FSConfig.GpuAcceleration)
				{
					val.AppendExecutionProvider_DML(0);
				}
				val.AppendExecutionProvider_CPU(1);
				session = new InferenceSession(modelPath, val);
				inputName = session.InputMetadata.Keys.First();
				outputName = PickOutputName(session);
			}
			catch (Exception ex)
			{
				logger.LogError((object)("[-] Failed to initialize emotion recognizer: " + ex.Message));
				throw;
			}
		}

		public abstract void Dispose();

		protected abstract string PickOutputName(InferenceSession session);

		public abstract bool InferEmotion(Mat frame, out string emotion, out float confidence, out float[] probabilities);
	}
	public class CascadeEmotionRecognizer : EmotionRecognizer
	{
		private CascadeClassifier faceCascade;

		public CascadeEmotionRecognizer(ManualLogSource logger, string modelPath, string cascadePath)
			: base(logger, modelPath)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			faceCascade = new CascadeClassifier(cascadePath);
			detectEveryNFrames = 1;
			smoothN = 3;
		}

		public override bool InferEmotion(Mat frame, out string emotion, out float confidence, out float[] probabilities)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Expected O, but got Unknown
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			Mat val = new Mat();
			try
			{
				Mat val2 = new Mat();
				try
				{
					Cv2.CvtColor(InputArray.op_Implicit(frame), OutputArray.op_Implicit(val), (ColorConversionCodes)6, 0);
					Rect? val3 = null;
					detectFrameCounter++;
					if (detectFrameCounter >= detectEveryNFrames || !lastDetectedFace.HasValue)
					{
						detectFrameCounter = 0;
						Cv2.Resize(InputArray.op_Implicit(val), OutputArray.op_Implicit(val2), new Size(0, 0), 0.5, 0.5, (InterpolationFlags)1);
						Rect[] array = faceCascade.DetectMultiScale(val2, 1.2, 3, (HaarDetectionTypes)0, (Size?)new Size(20, 20), (Size?)new Size(0, 0));
						if (array.Length != 0)
						{
							Rect val4 = array.OrderByDescending((Rect f) => f.Width * f.Height).First();
							val3 = (lastDetectedFace = new Rect(val4.X * 2, val4.Y * 2, val4.Width * 2, val4.Height * 2));
							framesWithoutDetection = 0;
						}
						else
						{
							framesWithoutDetection++;
						}
					}
					else
					{
						val3 = lastDetectedFace;
					}
					if (!val3.HasValue || framesWithoutDetection > 30)
					{
						emotion = "No Face";
						confidence = 0f;
						probabilities = new float[8];
						lastDetectedFace = null;
						return false;
					}
					Rect val5 = CalcUtils.Grow(val3.Value, 0.1, frame.Width, frame.Height);
					Mat val6 = new Mat(frame, val5);
					try
					{
						Mat val7 = new Mat();
						try
						{
							Cv2.CvtColor(InputArray.op_Implicit(val6), OutputArray.op_Implicit(val7), (ColorConversionCodes)6, 0);
							CLAHE val8 = Cv2.CreateCLAHE(2.0, (Size?)new Size(8, 8));
							try
							{
								val8.Apply(InputArray.op_Implicit(val7), OutputArray.op_Implicit(val7));
							}
							finally
							{
								((IDisposable)val8)?.Dispose();
							}
							Cv2.Resize(InputArray.op_Implicit(val7), OutputArray.op_Implicit(val7), new Size(64, 64), 0.0, 0.0, (InterpolationFlags)1);
							val7.ConvertTo(OutputArray.op_Implicit(val7), MatType.CV_32FC1, 1.0, 0.0);
							object obj = global::<PrivateImplementationDetails>.D4F9C16444BBD6A5FB4F10E9D647D15787CF536E9A2324E584122A50678AA55D_A6;
							if (obj == null)
							{
								obj = new int[4] { 1, 1, 64, 64 };
								global::<PrivateImplementationDetails>.D4F9C16444BBD6A5FB4F10E9D647D15787CF536E9A2324E584122A50678AA55D_A6 = (int[])obj;
							}
							DenseTensor<float> val9 = new DenseTensor<float>(new ReadOnlySpan<int>((int[]?)obj), false);
							Indexer<float> genericIndexer = val7.GetGenericIndexer<float>();
							int num = 0;
							for (int i = 0; i < 64; i++)
							{
								for (int j = 0; j < 64; j++)
								{
									val9.Buffer.Span[num++] = ((MatIndexer<float>)(object)genericIndexer)[i, j];
								}
							}
							List<NamedOnnxValue> list = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor<float>(inputName, (Tensor<float>)(object)val9) };
							IDisposableReadOnlyCollection<DisposableNamedOnnxValue> val10 = session.Run((IReadOnlyCollection<NamedOnnxValue>)list);
							try
							{
								float[] array2 = ((NamedOnnxValue)((IEnumerable<DisposableNamedOnnxValue>)val10).First((DisposableNamedOnnxValue r) => ((NamedOnnxValue)r).Name == outputName)).AsEnumerable<float>().ToArray();
								float[] p = (CalcUtils.IsProb(array2) ? array2 : CalcUtils.Softmax(array2));
								p = CalcUtils.ReweightFerPlus(p);
								scoreHist.Enqueue(p);
								if (scoreHist.Count > smoothN)
								{
									scoreHist.Dequeue();
								}
								float[] array3 = CalcUtils.Average(scoreHist);
								int num2 = CalcUtils.ArgMax(array3);
								string text = EmotionRecognizer.Labels[Math.Min(num2, EmotionRecognizer.Labels.Length - 1)];
								float num3 = array3[num2];
								emotion = text;
								confidence = num3;
								probabilities = array3;
								return true;
							}
							finally
							{
								((IDisposable)val10)?.Dispose();
							}
						}
						finally
						{
							((IDisposable)val7)?.Dispose();
						}
					}
					finally
					{
						((IDisposable)val6)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val2)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		protected override string PickOutputName(InferenceSession session)
		{
			foreach (KeyValuePair<string, NodeMetadata> outputMetadatum in session.OutputMetadata)
			{
				int[] dimensions = outputMetadatum.Value.Dimensions;
				int num = 1;
				int[] array = dimensions;
				foreach (int num2 in array)
				{
					if (num2 > 0)
					{
						num *= num2;
					}
				}
				if (dimensions.Length <= 2 && num >= 7 && num <= 10)
				{
					return outputMetadatum.Key;
				}
			}
			string[] array2 = new string[5] { "Prob", "prob", "Plus692_Output_0", "output", "softmaxout" };
			foreach (string text in array2)
			{
				if (session.OutputMetadata.ContainsKey(text))
				{
					return text;
				}
			}
			return session.OutputMetadata.Keys.First();
		}

		public override void Dispose()
		{
			if (isDisposed)
			{
				return;
			}
			try
			{
				CascadeClassifier obj = faceCascade;
				if (obj != null)
				{
					((DisposableObject)obj).Dispose();
				}
				faceCascade = null;
				InferenceSession obj2 = session;
				if (obj2 != null)
				{
					obj2.Dispose();
				}
				session = null;
				isDisposed = true;
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Error during disposal: " + ex.Message));
			}
		}
	}
	public static class Notification
	{
		public static void Info(string message)
		{
			NotificationManager.Show(message);
		}

		public static void Error(string message)
		{
			NotificationManager.Show(message, NotificationManager.NotificationType.Error);
		}

		public static void Warning(string message)
		{
			NotificationManager.Show(message, NotificationManager.NotificationType.Warning);
		}

		public static void Success(string message)
		{
			NotificationManager.Show(message, NotificationManager.NotificationType.Success);
		}
	}
	public class ExpressionIntegration : MonoBehaviour
	{
		private class EmotionMapping
		{
			public string Emotion;

			public int ExpressionIndex;

			public string ExpressionName;
		}

		private ManualLogSource logger;

		private ThreadSafeEmotionState emotionState;

		private float updateInterval = 0.3f;

		private float confidenceThreshold = 0.35f;

		private bool enableIntegration = true;

		private float updateTimer = 0f;

		private string lastAppliedEmotion = "";

		private float lastEmotionChangeTime = 0f;

		private const float MIN_EMOTION_CHANGE_INTERVAL = 0.7f;

		private string pendingEmotion = "";

		private float pendingEmotionConfidence = 0f;

		private int pendingEmotionCount = 0;

		private const int REQUIRED_STABLE_COUNT = 2;

		private Func<object> getPlayerAvatarInstance;

		private Func<object, object> getPlayerExpression;

		private Func<object, object> getInputToggleList;

		private Func<object, int> getItemIndex;

		private Action<object, bool> setItemActive;

		private bool listItemAccessorsInitialized = false;

		private Type playerAvatarType;

		private Type playerExpressionsUIType;

		private FieldInfo playerExpressionsUIInstanceField;

		private MethodInfo shrinkResetMethod;

		private bool reflectionCacheInitialized = false;

		private static readonly EmotionMapping[] EmotionMappings = new EmotionMapping[8]
		{
			new EmotionMapping
			{
				Emotion = "Neutral",
				ExpressionIndex = 0,
				ExpressionName = "SUSPICIOUS"
			},
			new EmotionMapping
			{
				Emotion = "Happiness",
				ExpressionIndex = 6,
				ExpressionName = "HAPPY"
			},
			new EmotionMapping
			{
				Emotion = "Surprise",
				ExpressionIndex = 5,
				ExpressionName = "EYES CLOSED"
			},
			new EmotionMapping
			{
				Emotion = "Sadness",
				ExpressionIndex = 2,
				ExpressionName = "SAD"
			},
			new EmotionMapping
			{
				Emotion = "Anger",
				ExpressionIndex = 1,
				ExpressionName = "ANGRY"
			},
			new EmotionMapping
			{
				Emotion = "Disgust",
				ExpressionIndex = 3,
				ExpressionName = "CRAZY"
			},
			new EmotionMapping
			{
				Emotion = "Fear",
				ExpressionIndex = 2,
				ExpressionName = "SAD"
			},
			new EmotionMapping
			{
				Emotion = "Contempt",
				ExpressionIndex = 3,
				ExpressionName = "ANGRY"
			}
		};

		public void Initialize(float updateInterval, float confidenceThreshold, float expressionDuration, bool enable)
		{
			this.updateInterval = 0.3f;
			this.confidenceThreshold = Mathf.Max(0.35f, confidenceThreshold - 0.05f);
			enableIntegration = enable;
			InitializeReflectionCache();
		}

		private void InitializeReflectionCache()
		{
			try
			{
				playerAvatarType = Type.GetType("PlayerAvatar, Assembly-CSharp");
				if (playerAvatarType != null)
				{
					FieldInfo field = playerAvatarType.GetField("instance", BindingFlags.Static | BindingFlags.Public);
					if (field != null)
					{
						getPlayerAvatarInstance = CreateStaticGetter(field);
					}
					FieldInfo field2 = playerAvatarType.GetField("playerExpression", BindingFlags.Instance | BindingFlags.Public);
					if (field2 != null)
					{
						getPlayerExpression = CreateFieldGetter(field2);
						Type fieldType = field2.FieldType;
						FieldInfo field3 = fieldType.GetField("inputToggleList", BindingFlags.Instance | BindingFlags.NonPublic);
						if (field3 != null)
						{
							getInputToggleList = CreateFieldGetter(field3);
						}
					}
				}
				playerExpressionsUIType = Type.GetType("PlayerExpressionsUI, Assembly-CSharp");
				if (playerExpressionsUIType != null)
				{
					playerExpressionsUIInstanceField = playerExpressionsUIType.GetField("instance", BindingFlags.Static | BindingFlags.Public);
					shrinkResetMethod = playerExpressionsUIType.GetMethod("ShrinkReset", BindingFlags.Instance | BindingFlags.Public);
				}
				reflectionCacheInitialized = getPlayerAvatarInstance != null && getPlayerExpression != null && getInputToggleList != null && playerExpressionsUIType != null && playerExpressionsUIInstanceField != null && shrinkResetMethod != null;
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Failed to initialize reflection cache: " + ex.Message));
				reflectionCacheInitialized = false;
			}
		}

		private Func<object> CreateStaticGetter(FieldInfo field)
		{
			MemberExpression expression = Expression.Field(null, field);
			UnaryExpression body = Expression.Convert(expression, typeof(object));
			return Expression.Lambda<Func<object>>(body, Array.Empty<ParameterExpression>()).Compile();
		}

		private Func<object, object> CreateFieldGetter(FieldInfo field)
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "target");
			UnaryExpression expression = Expression.Convert(parameterExpression, field.DeclaringType);
			MemberExpression expression2 = Expression.Field(expression, field);
			UnaryExpression body = Expression.Convert(expression2, typeof(object));
			return Expression.Lambda<Func<object, object>>(body, new ParameterExpression[1] { parameterExpression }).Compile();
		}

		private Func<object, int> CreateIntFieldGetter(FieldInfo field)
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "target");
			UnaryExpression expression = Expression.Convert(parameterExpression, field.DeclaringType);
			MemberExpression body = Expression.Field(expression, field);
			return Expression.Lambda<Func<object, int>>(body, new ParameterExpression[1] { parameterExpression }).Compile();
		}

		private Action<object, bool> CreateBoolFieldSetter(FieldInfo field)
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "target");
			ParameterExpression parameterExpression2 = Expression.Parameter(typeof(bool), "value");
			UnaryExpression expression = Expression.Convert(parameterExpression, field.DeclaringType);
			MemberExpression left = Expression.Field(expression, field);
			BinaryExpression body = Expression.Assign(left, parameterExpression2);
			return Expression.Lambda<Action<object, bool>>(body, new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile();
		}

		private void Update()
		{
			if (FSConfig.EnableExpressionSync && emotionState != null && reflectionCacheInitialized)
			{
				updateTimer += Time.deltaTime;
				if (updateTimer >= updateInterval)
				{
					updateTimer = 0f;
					UpdatePlayerExpression();
				}
			}
		}

		private void UpdatePlayerExpression()
		{
			try
			{
				object obj = getPlayerAvatarInstance();
				if (obj == null)
				{
					return;
				}
				object obj2 = getPlayerExpression(obj);
				if (obj2 == null)
				{
					return;
				}
				EmotionSnapshot snapshot = emotionState.GetSnapshot();
				if (!snapshot.active || snapshot.emotion == "No Face")
				{
					ResetPendingEmotion();
				}
				else
				{
					if (snapshot.confidence < confidenceThreshold)
					{
						return;
					}
					if (snapshot.emotion == pendingEmotion)
					{
						pendingEmotionCount++;
						pendingEmotionConfidence = Mathf.Max(pendingEmotionConfidence, snapshot.confidence);
					}
					else
					{
						pendingEmotion = snapshot.emotion;
						pendingEmotionConfidence = snapshot.confidence;
						pendingEmotionCount = 1;
					}
					if (pendingEmotion == lastAppliedEmotion || pendingEmotionCount < 2)
					{
						return;
					}
					float num = Time.time - lastEmotionChangeTime;
					if (!(num < 0.7f) || !(lastAppliedEmotion != ""))
					{
						EmotionMapping emotionMapping = GetEmotionMapping(pendingEmotion);
						if (emotionMapping != null)
						{
							SetPlayerExpression(obj2, emotionMapping.ExpressionIndex);
							lastAppliedEmotion = pendingEmotion;
							lastEmotionChangeTime = Time.time;
							ResetPendingEmotion();
						}
					}
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Failed to update expression: " + ex.Message));
			}
		}

		private void ResetPendingEmotion()
		{
			pendingEmotion = "";
			pendingEmotionConfidence = 0f;
			pendingEmotionCount = 0;
		}

		private void SetPlayerExpression(object playerExpression, int expressionIndex)
		{
			try
			{
				if (!(getInputToggleList(playerExpression) is IList list) || list.Count == 0)
				{
					return;
				}
				if (!listItemAccessorsInitialized)
				{
					object obj = list[0];
					Type type = obj.GetType();
					FieldInfo field = type.GetField("index", BindingFlags.Instance | BindingFlags.Public);
					FieldInfo field2 = type.GetField("active", BindingFlags.Instance | BindingFlags.Public);
					if (!(field != null) || !(field2 != null))
					{
						logger.LogError((object)"Failed to find 'index' or 'active' fields on list item");
						return;
					}
					getItemIndex = CreateIntFieldGetter(field);
					setItemActive = CreateBoolFieldSetter(field2);
					listItemAccessorsInitialized = true;
				}
				foreach (object item in list)
				{
					int num = getItemIndex(item);
					bool arg = num == expressionIndex;
					setItemActive(item, arg);
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Failed to set expression: " + ex.Message));
				listItemAccessorsInitialized = false;
			}
		}

		private void ShowPlayerExpressionsUI()
		{
			try
			{
				object value = playerExpressionsUIInstanceField.GetValue(null);
				if (value != null)
				{
					shrinkResetMethod?.Invoke(value, null);
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Failed to show UI: " + ex.Message));
			}
		}

		private EmotionMapping GetEmotionMapping(string emotionName)
		{
			EmotionMapping[] emotionMappings = EmotionMappings;
			foreach (EmotionMapping emotionMapping in emotionMappings)
			{
				if (emotionMapping.Emotion == emotionName)
				{
					return emotionMapping;
				}
			}
			return null;
		}

		public void SetEnabled(bool enabled)
		{
			enableIntegration = enabled;
			if (enabled)
			{
				lastAppliedEmotion = "";
				lastEmotionChangeTime = 0f;
				ResetPendingEmotion();
			}
		}

		public void TestExpression(int expressionIndex)
		{
		}
	}
	public class FaceSyncClient : MonoBehaviour
	{
		[CompilerGenerated]
		private sealed class <DelayedInitialization>d__10 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public FaceSyncClient <>4__this;

			private float <delay>5__1;

			private string <pluginDir>5__2;

			private string <modelPath>5__3;

			private string <cascadePath>5__4;

			private CascadeEmotionRecognizer <cascadeRecognizer>5__5;

			private string <deployProto>5__6;

			private string <caffemodel>5__7;

			private DnnEmotionRecognizer <dnnRecognizer>5__8;

			private FieldInfo <loggerField>5__9;

			private FieldInfo <emotionStateField>5__10;

			private Exception <ex>5__11;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DelayedInitialization>d__10(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<pluginDir>5__2 = null;
				<modelPath>5__3 = null;
				<cascadePath>5__4 = null;
				<cascadeRecognizer>5__5 = null;
				<deployProto>5__6 = null;
				<caffemodel>5__7 = null;
				<dnnRecognizer>5__8 = null;
				<loggerField>5__9 = null;
				<emotionStateField>5__10 = null;
				<ex>5__11 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<delay>5__1 = Plugin.startDelaySeconds.Value;
					<>2__current = (object)new WaitForSeconds(<delay>5__1);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					try
					{
						<pluginDir>5__2 = Path.GetDirectoryName(<>4__this.pluginInfo.Location);
						<modelPath>5__3 = Path.Combine(<pluginDir>5__2, "emotion-ferplus-8.onnx");
						<cascadePath>5__4 = Path.Combine(<pluginDir>5__2, "haarcascade_frontalface_default.xml");
						<cascadeRecognizer>5__5 = new CascadeEmotionRecognizer(<>4__this.logger, <modelPath>5__3, <cascadePath>5__4);
						<deployProto>5__6 = Path.Combine(<pluginDir>5__2, "deploy.prototxt");
						<caffemodel>5__7 = Path.Combine(<pluginDir>5__2, "res10_300x300_ssd_iter_140000.caffemodel");
						<dnnRecognizer>5__8 = new DnnEmotionRecognizer(<>4__this.logger, <modelPath>5__3, <deployProto>5__6, <caffemodel>5__7);
						<>4__this.recognition = new EmotionRecognition(<>4__this.logger, FSConfig.CameraIndex);
						<>4__this.recognition.RegisterRecognizer(RecognizerType.CASCADE, <cascadeRecognizer>5__5);
						<>4__this.recognition.RegisterRecognizer(RecognizerType.DNN, <dnnRecognizer>5__8);
						<>4__this.recognition.Start();
						<>4__this.displayUI = ((Component)<>4__this).gameObject.AddComponent<FaceSyncMenu>();
						<>4__this.displayUI.Initialize(<>4__this.recognition.EmotionState, <>4__this.logger, <>4__this.recognition);
						<>4__this.expressionIntegration = ((Component)<>4__this).gameObject.AddComponent<ExpressionIntegration>();
						<loggerField>5__9 = typeof(ExpressionIntegration).GetField("logger", BindingFlags.Instance | BindingFlags.NonPublic);
						<emotionStateField>5__10 = typeof(ExpressionIntegration).GetField("emotionState", BindingFlags.Instance | BindingFlags.NonPublic);
						<>4__this.notificationManager = ((Component)<>4__this).gameObject.AddComponent<NotificationManager>();
						if (<loggerField>5__9 != null)
						{
							<loggerField>5__9.SetValue(<>4__this.expressionIntegration, <>4__this.logger);
						}
						if (<emotionStateField>5__10 != null)
						{
							<emotionStateField>5__10.SetValue(<>4__this.expressionIntegration, <>4__this.recognition.EmotionState);
						}
						<>4__this.expressionIntegration.Initialize(Plugin.expressionUpdateInterval.Value, Plugin.expressionConfidenceThreshold.Value, Plugin.expressionDuration.Value, Plugin.enableExpressionSync.Value);
						<>4__this.isInitialized = true;
						NotificationManager.Show("Face Sync Started", NotificationManager.NotificationType.Success);
						<pluginDir>5__2 = null;
						<modelPath>5__3 = null;
						<cascadePath>5__4 = null;
						<cascadeRecognizer>5__5 = null;
						<deployProto>5__6 = null;
						<caffemodel>5__7 = null;
						<dnnRecognizer>5__8 = null;
						<loggerField>5__9 = null;
						<emotionStateField>5__10 = null;
					}
					catch (Exception ex)
					{
						<ex>5__11 = ex;
						<>4__this.logger.LogError((object)"===========================================");
						<>4__this.logger.LogError((object)"=== Initialization Failed ===");
						<>4__this.logger.LogError((object)"===========================================");
						<>4__this.logger.LogError((object)("Error: " + <ex>5__11.Message));
						<>4__this.logger.LogError((object)("Stack Trace:\n" + <ex>5__11.StackTrace));
						<>4__this.logger.LogError((object)"===========================================");
						NotificationManager.Show("Initialization Failed", NotificationManager.NotificationType.Error);
						<>4__this.CleanUp();
					}
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private ManualLogSource logger;

		private ConfigFile config;

		private PluginInfo pluginInfo;

		private EmotionRecognition recognition;

		private FaceSyncMenu displayUI;

		private ExpressionIntegration expressionIntegration;

		private NotificationManager notificationManager;

		private bool isInitialized = false;

		public void Initialize(ManualLogSource logger, ConfigFile config, PluginInfo pluginInfo)
		{
			this.logger = logger;
			this.config = config;
			this.pluginInfo = pluginInfo;
		}

		private void Start()
		{
			string directoryName = Path.GetDirectoryName(pluginInfo.Location);
			string text = Path.Combine(directoryName, "emotion-ferplus-8.onnx");
			string text2 = Path.Combine(directoryName, "haarcascade_frontalface_default.xml");
			if (!File.Exists(text))
			{
				Notification.Error("Model file not found: " + text);
			}
			else if (!File.Exists(text2))
			{
				Notification.Error("Cascade file not found: " + text2);
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(DelayedInitialization());
			}
		}

		[IteratorStateMachine(typeof(<DelayedInitialization>d__10))]
		private IEnumerator DelayedInitialization()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DelayedInitialization>d__10(0)
			{
				<>4__this = this
			};
		}

		private void Update()
		{
			if (isInitialized && recognition != null && !((Object)(object)expressionIntegration == (Object)null))
			{
				if (Input.GetKeyDown((KeyCode)289))
				{
					FSConfig.EnableExpressionSync = !FSConfig.EnableExpressionSync;
					NotificationManager.Show("Expression Sync: " + (FSConfig.EnableExpressionSync ? "ON" : "OFF"), FSConfig.EnableExpressionSync ? NotificationManager.NotificationType.Success : NotificationManager.NotificationType.Warning);
				}
				if (Input.GetKeyDown((KeyCode)290))
				{
					FSConfig.AlwaysHidePlayerExpressionPopup = !FSConfig.AlwaysHidePlayerExpressionPopup;
					NotificationManager.Show("Always Hide Player Expression Popup: " + (FSConfig.AlwaysHidePlayerExpressionPopup ? "ON" : "OFF"), FSConfig.AlwaysHidePlayerExpressionPopup ? NotificationManager.NotificationType.Success : NotificationManager.NotificationType.Warning);
				}
			}
		}

		private void OnDestroy()
		{
			ManualLogSource obj = logger;
			if (obj != null)
			{
				obj.LogInfo((object)"FaceSync- Shutting down...");
			}
			CleanUp();
		}

		private void CleanUp()
		{
			try
			{
				if (recognition != null)
				{
					recognition.Dispose();
					recognition = null;
				}
			}
			catch (Exception)
			{
			}
			isInitialized = false;
		}
	}
	public static class PlayerExpressionUIHelper
	{
		private static Type playerExpressionsUIType;

		private static FieldInfo instanceField;

		private static MethodInfo shrinkResetMethod;

		private static FieldInfo shrinkTimerField;

		private static bool cacheInitialized;

		private static bool initializationAttempted;

		private static void InitializeCache()
		{
			if (initializationAttempted)
			{
				return;
			}
			initializationAttempted = true;
			try
			{
				playerExpressionsUIType = Type.GetType("PlayerExpressionsUI, Assembly-CSharp");
				if (!(playerExpressionsUIType == null))
				{
					instanceField = playerExpressionsUIType.GetField("instance", BindingFlags.Static | BindingFlags.Public);
					shrinkResetMethod = playerExpressionsUIType.GetMethod("ShrinkReset", BindingFlags.Instance | BindingFlags.Public);
					shrinkTimerField = playerExpressionsUIType.GetField("shrinkTimer", BindingFlags.Instance | BindingFlags.NonPublic);
					cacheInitialized = playerExpressionsUIType != null && instanceField != null && shrinkResetMethod != null && shrinkTimerField != null;
				}
			}
			catch
			{
				cacheInitialized = false;
			}
		}

		public static object GetPlayerExpressionsUIInstance()
		{
			if (!cacheInitialized)
			{
				InitializeCache();
			}
			try
			{
				return instanceField?.GetValue(null);
			}
			catch
			{
				return null;
			}
		}

		public static bool ShowPlayerExpressionUI(ManualLogSource logger = null)
		{
			if (!cacheInitialized)
			{
				InitializeCache();
			}
			if (!cacheInitialized)
			{
				if (logger != null)
				{
					logger.LogWarning((object)"Reflection cache not initialized");
				}
				return false;
			}
			try
			{
				object value = instanceField.GetValue(null);
				if (value == null)
				{
					if (logger != null)
					{
						logger.LogDebug((object)"PlayerExpressionsUI.instance is null");
					}
					return false;
				}
				shrinkResetMethod.Invoke(value, null);
				if (logger != null)
				{
					logger.LogDebug((object)"PlayerExpressionsUI.ShrinkReset() called");
				}
				return true;
			}
			catch (Exception ex)
			{
				if (logger != null)
				{
					logger.LogError((object)("Failed to show PlayerExpressionsUI: " + ex.Message));
				}
				return false;
			}
		}

		public static bool KeepPlayerExpressionUIVisible(ManualLogSource logger = null)
		{
			if (!cacheInitialized)
			{
				InitializeCache();
			}
			if (!cacheInitialized)
			{
				return false;
			}
			try
			{
				object value = instanceField.GetValue(null);
				if (value == null)
				{
					return false;
				}
				shrinkTimerField.SetValue(value, 999999f);
				return true;
			}
			catch (Exception ex)
			{
				if (logger != null)
				{
					logger.LogError((object)("Failed to keep PlayerExpressionsUI visible: " + ex.Message));
				}
				return false;
			}
		}

		public static bool IsPlayerExpressionsUIAvailable()
		{
			return GetPlayerExpressionsUIInstance() != null;
		}

		public static void ResetCache()
		{
			cacheInitialized = false;
			initializationAttempted = false;
			playerExpressionsUIType = null;
			instanceField = null;
			shrinkResetMethod = null;
			shrinkTimerField = null;
		}
	}
	[BepInPlugin("rec.enuwbt.facesync", "Face Sync", "1.0.3")]
	public class Plugin : BaseUnityPlugin
	{
		public static ConfigEntry<bool> enableMod;

		public static ConfigEntry<bool> gpuAcceleration;

		public static ConfigEntry<bool> showUI;

		public static ConfigEntry<int> cameraIndex;

		public static ConfigEntry<int> updateIntervalMs;

		public static ConfigEntry<float> startDelaySeconds;

		public static ConfigEntry<bool> enableExpressionSync;

		public static ConfigEntry<float> expressionUpdateInterval;

		public static ConfigEntry<float> expressionConfidenceThreshold;

		public static ConfigEntry<float> expressionDuration;

		public static ConfigEntry<bool> alwaysHidePlayerExpressionPopup;

		public static ConfigEntry<RecognizerType> recognizerType;

		private void Awake()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"=== Face Sync v1.0.3 ===");
			InitializeConfig();
			if (!enableMod.Value)
			{
				Notification.Warning("Face Sync mod is disabled in config");
				return;
			}
			GameObject val = new GameObject("FaceSyncMod");
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val);
			Harmony val2 = new Harmony("rec.enuwbt.facesync");
			val2.PatchAll();
			FaceSyncClient faceSyncClient = val.AddComponent<FaceSyncClient>();
			faceSyncClient.Initialize(((BaseUnityPlugin)this).Logger, ((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Info);
		}

		private void InitializeConfig()
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			enableMod = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableMod", true, "Enable the mod");
			showUI = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ShowUI", true, "Show UI on startup");
			gpuAcceleration = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "GPUAcceleration", false, "Enable GPU acceleration for emotion recognition (requires compatible GPU)");
			cameraIndex = ((BaseUnityPlugin)this).Config.Bind<int>("Camera", "CameraIndex", 0, new ConfigDescription("Camera index (0=default)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			cameraIndex.SettingChanged += delegate
			{
				((BaseUnityPlugin)this).Config.Save();
			};
			updateIntervalMs = ((BaseUnityPlugin)this).Config.Bind<int>("Performance", "UpdateIntervalMs", 500, new ConfigDescription("Emotion recognition update interval (milliseconds)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(100, 5000), Array.Empty<object>()));
			startDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Performance", "StartDelaySeconds", 5f, new ConfigDescription("Delay before starting MOD after game launch (seconds)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
			enableExpressionSync = ((BaseUnityPlugin)this).Config.Bind<bool>("Expression", "EnableExpressionSync", true, "Automatically change player expression based on detected emotion");
			expressionUpdateInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Expression", "UpdateInterval", 0.1f, new ConfigDescription("Expression update check interval (seconds)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f), Array.Empty<object>()));
			expressionConfidenceThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("Expression", "ConfidenceThreshold", 0.4f, new ConfigDescription("Minimum confidence for expression change (0.0-1.0)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 0.9f), Array.Empty<object>()));
			expressionDuration = ((BaseUnityPlugin)this).Config.Bind<float>("Expression", "ExpressionDuration", 100f, new ConfigDescription("Expression intensity (%)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f), Array.Empty<object>()));
			alwaysHidePlayerExpressionPopup = ((BaseUnityPlugin)this).Config.Bind<bool>("Expression", "AlwaysHidePlayerExpressionUI", true, "Keep in-game expression UI always invisible");
			alwaysHidePlayerExpressionPopup.SettingChanged += delegate
			{
				((BaseUnityPlugin)this).Config.Save();
			};
			recognizerType = ((BaseUnityPlugin)this).Config.Bind<RecognizerType>("Recognizer", "RecognizerType", RecognizerType.CASCADE, new ConfigDescription("Recognizer Selection\n- CASCADE: Lightweight, fast (camera in front)\n- DNN: Heavier, camera angle-agnostic", (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	public class ThreadSafeEmotionState
	{
		private readonly object lockObject = new object();

		private string currentEmotion = "Unknown";

		private float confidence = 0f;

		private float[] probabilities = new float[8];

		private DateTime lastUpdate = DateTime.MinValue;

		private bool isActive = false;

		private string errorMessage = null;

		public string CurrentEmotion
		{
			get
			{
				lock (lockObject)
				{
					return currentEmotion;
				}
			}
		}

		public float Confidence
		{
			get
			{
				lock (lockObject)
				{
					return confidence;
				}
			}
		}

		public bool IsActive
		{
			get
			{
				lock (lockObject)
				{
					return isActive;
				}
			}
		}

		public void Update(string emotion, float confidence, float[] probs)
		{
			lock (lockObject)
			{
				currentEmotion = emotion;
				this.confidence = confidence;
				if (probs != null && probs.Length >= 8)
				{
					Array.Copy(probs, probabilities, Math.Min(probs.Length, 8));
				}
				lastUpdate = DateTime.Now;
				isActive = true;
				errorMessage = null;
			}
		}

		public void SetError(string error)
		{
			lock (lockObject)
			{
				errorMessage = error;
				isActive = false;
			}
		}

		public EmotionSnapshot GetSnapshot()
		{
			lock (lockObject)
			{
				EmotionSnapshot result = default(EmotionSnapshot);
				result.emotion = currentEmotion;
				result.confidence = confidence;
				result.probs = (float[])probabilities.Clone();
				result.time = lastUpdate;
				result.active = isActive;
				result.error = errorMessage;
				return result;
			}
		}

		public void Reset()
		{
			lock (lockObject)
			{
				currentEmotion = "Unknown";
				confidence = 0f;
				Array.Clear(probabilities, 0, probabilities.Length);
				lastUpdate = DateTime.MinValue;
				isActive = false;
				errorMessage = null;
			}
		}
	}
	public struct EmotionSnapshot
	{
		public string emotion;

		public float confidence;

		public float[] probs;

		public DateTime time;

		public bool active;

		public string error;

		public bool IsValid => active && string.IsNullOrEmpty(error) && emotion != "No Face";

		public float TimeSinceUpdate => (float)(DateTime.Now - time).TotalSeconds;
	}
}
namespace FaceSync.patch
{
	public class PlayerExpressionsUIPatch
	{
		[HarmonyPatch(typeof(PlayerExpressionsUI))]
		public static class Update
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(typeof(PlayerExpressionsUI), "Update", (Type[])null, (Type[])null);
			}

			private static void Prefix(PlayerExpressionsUI __instance)
			{
				if (FSConfig.AlwaysHidePlayerExpressionPopup)
				{
					((SemiUI)__instance).isHidden = true;
				}
			}
		}
	}
}

BepInEx/plugins/FaceSync/Microsoft.ML.OnnxRuntime.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.ML.OnnxRuntime.CompileApi;
using Microsoft.ML.OnnxRuntime.Tensors;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.ML.OnnxRuntime.Tests.Common, PublicKey=002400000480000094000000060200000024000052534131000400000100010059013e94e4bc70136ca4c35f33acd6b62974536b698f9c7a21cee18d805c7ad860ad9eebfdc47a96ba2f8d03f4cf1c36b9d30787e276c7b9833b5bf2a6eba7e919e6b90083078a352262aed1d842e5f70a3085cbcf4c56ae851b161137920961c23fcc246598d61d258ccc615c927b2441359eea666a99ce1c3c07dca18fb0e1")]
[assembly: InternalsVisibleTo("Microsoft.ML.OnnxRuntime.Tests.NetCoreApp, PublicKey=002400000480000094000000060200000024000052534131000400000100010059013e94e4bc70136ca4c35f33acd6b62974536b698f9c7a21cee18d805c7ad860ad9eebfdc47a96ba2f8d03f4cf1c36b9d30787e276c7b9833b5bf2a6eba7e919e6b90083078a352262aed1d842e5f70a3085cbcf4c56ae851b161137920961c23fcc246598d61d258ccc615c927b2441359eea666a99ce1c3c07dca18fb0e1")]
[assembly: InternalsVisibleTo("Microsoft.ML.OnnxRuntime.Tests.MAUI, PublicKey=002400000480000094000000060200000024000052534131000400000100010059013e94e4bc70136ca4c35f33acd6b62974536b698f9c7a21cee18d805c7ad860ad9eebfdc47a96ba2f8d03f4cf1c36b9d30787e276c7b9833b5bf2a6eba7e919e6b90083078a352262aed1d842e5f70a3085cbcf4c56ae851b161137920961c23fcc246598d61d258ccc615c927b2441359eea666a99ce1c3c07dca18fb0e1")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyConfiguration("RelWithDebInfo")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("This package contains ONNX Runtime for .Net platforms")]
[assembly: AssemblyFileVersion("1.23.2.0")]
[assembly: AssemblyInformationalVersion("1.23.2+a83fc4d58cb48eb68890dd689f94f28288cf2278")]
[assembly: AssemblyProduct("Microsoft.ML.OnnxRuntime")]
[assembly: AssemblyTitle("Microsoft.ML.OnnxRuntime C# Bindings")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/microsoft/onnxruntime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.23.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 Microsoft.ML.OnnxRuntime
{
	[Flags]
	public enum OrtCompileApiFlags : uint
	{
		NONE = 0u,
		ERROR_IF_NO_NODES_COMPILED = 1u,
		ERROR_IF_OUTPUT_FILE_EXISTS = 2u
	}
	public class OrtModelCompilationOptions : IDisposable
	{
		public delegate void WriteBufferToDestinationDelegate(ReadOnlySpan<byte> buffer);

		public delegate OrtExternalInitializerInfo GetInitializerLocationDelegate(string initializerName, IReadOnlyOrtValue initializerValue, IReadOnlyExternalInitializerInfo originalInitializerLocation);

		private class WriteBufferToDestinationConnector
		{
			private readonly WriteBufferToDestinationDelegate _userDelegate;

			internal WriteBufferToDestinationConnector(WriteBufferToDestinationDelegate writeBufferDelegate)
			{
				_userDelegate = writeBufferDelegate;
			}

			public unsafe static IntPtr WriteBufferToDestinationDelegateWrapper(IntPtr state, IntPtr buffer, UIntPtr bufferNumBytes)
			{
				try
				{
					WriteBufferToDestinationConnector obj = (WriteBufferToDestinationConnector)GCHandle.FromIntPtr(state).Target;
					ReadOnlySpan<byte> buffer2 = new ReadOnlySpan<byte>(buffer.ToPointer(), checked((int)(uint)bufferNumBytes));
					obj._userDelegate(buffer2);
				}
				catch (Exception ex)
				{
					string s = "The C# WriteBufferToDestination delegate threw an exception: " + ex.Message;
					return NativeMethods.OrtCreateStatus(1u, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(s));
				}
				return IntPtr.Zero;
			}
		}

		private class GetInitializerLocationConnector
		{
			private readonly GetInitializerLocationDelegate _userDelegate;

			internal GetInitializerLocationConnector(GetInitializerLocationDelegate getInitializerLocationDelegate)
			{
				_userDelegate = getInitializerLocationDelegate;
			}

			public static IntPtr GetInitializerLocationDelegateWrapper(IntPtr state, IntPtr initializerName, IntPtr initializerValue, IntPtr originalInitializerLocation, out IntPtr newInitializerLocationOutput)
			{
				newInitializerLocationOutput = IntPtr.Zero;
				try
				{
					GetInitializerLocationConnector obj = (GetInitializerLocationConnector)GCHandle.FromIntPtr(state).Target;
					string initializerName2 = NativeOnnxValueHelper.StringFromNativeUtf8(initializerName);
					IReadOnlyOrtValue initializerValue2 = new OrtValue(initializerValue, owned: false);
					IReadOnlyExternalInitializerInfo originalInitializerLocation2 = null;
					if (originalInitializerLocation != IntPtr.Zero)
					{
						originalInitializerLocation2 = new OrtExternalInitializerInfo(originalInitializerLocation);
					}
					OrtExternalInitializerInfo ortExternalInitializerInfo = obj._userDelegate(initializerName2, initializerValue2, originalInitializerLocation2);
					if (ortExternalInitializerInfo != null)
					{
						byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(ortExternalInitializerInfo.GetFilePath());
						IntPtr intPtr = NativeMethods.OrtCreateExternalInitializerInfo(platformSerializedString, ortExternalInitializerInfo.GetFileOffset(), (UIntPtr)(ulong)ortExternalInitializerInfo.GetByteSize(), out newInitializerLocationOutput);
						if (intPtr != IntPtr.Zero)
						{
							return intPtr;
						}
					}
					else
					{
						newInitializerLocationOutput = IntPtr.Zero;
					}
				}
				catch (Exception ex)
				{
					string s = "The C# GetInitializerLocation delegate threw an exception: " + ex.Message;
					return NativeMethods.OrtCreateStatus(1u, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(s));
				}
				return IntPtr.Zero;
			}
		}

		private class DelegateResources<Connector, Delegate> : IDisposable where Connector : class where Delegate : class
		{
			private Connector _connector;

			private Delegate _delegate;

			private GCHandle _connectorHandle;

			private GCHandle _delegateHandle;

			private bool _disposed;

			public DelegateResources(Connector connector, Delegate @delegate)
			{
				_connector = connector;
				_delegate = @delegate;
				_connectorHandle = GCHandle.Alloc(_connector);
				_delegateHandle = GCHandle.Alloc(_delegate);
			}

			internal IntPtr GetFunctionPointerForDelegate()
			{
				return Marshal.GetFunctionPointerForDelegate(_delegate);
			}

			internal IntPtr GetConnectorHandleAsPointer()
			{
				return GCHandle.ToIntPtr(_connectorHandle);
			}

			public void Dispose()
			{
				Dispose(disposing: true);
				GC.SuppressFinalize(this);
			}

			protected virtual void Dispose(bool disposing)
			{
				if (!_disposed)
				{
					if (_connectorHandle.IsAllocated)
					{
						_connectorHandle.Free();
						_connector = null;
					}
					if (_delegateHandle.IsAllocated)
					{
						_delegateHandle.Free();
						_delegate = null;
					}
					_disposed = true;
				}
			}

			~DelegateResources()
			{
				Dispose(disposing: false);
			}
		}

		private IntPtr _handle;

		private bool _disposed;

		private DelegateResources<WriteBufferToDestinationConnector, NativeMethods.DOrtWriteBufferToDestinationDelegate> _writeBufferToDestinationDelegateState;

		private DelegateResources<GetInitializerLocationConnector, NativeMethods.DOrtGetInitializerLocationDelegate> _getInitializerLocationDelegateState;

		public OrtModelCompilationOptions(SessionOptions sessionOptions)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtCreateModelCompilationOptionsFromSessionOptions(OrtEnv.Instance().Handle, sessionOptions.Handle, out _handle));
		}

		public void CompileModel()
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtCompileModel(OrtEnv.Instance().Handle, _handle));
		}

		public void SetInputModelPath(string path)
		{
			byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(path);
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelPath(_handle, platformSerializedString));
		}

		public void SetInputModelFromBuffer(byte[] buffer)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelFromBuffer(_handle, buffer, (UIntPtr)(ulong)buffer.Length));
		}

		public void SetOutputModelPath(string path)
		{
			byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(path);
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelPath(_handle, platformSerializedString));
		}

		public void SetOutputModelExternalInitializersFile(string filePath, ulong threshold)
		{
			byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(filePath);
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelExternalInitializersFile(_handle, platformSerializedString, new UIntPtr(threshold)));
		}

		internal void SetOutputModelBuffer(OrtAllocator allocator, ref IntPtr outputModelBufferPtr, ref UIntPtr outputModelBufferSizePtr)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelBuffer(_handle, allocator.Pointer, ref outputModelBufferPtr, ref outputModelBufferSizePtr));
		}

		public void SetEpContextEmbedMode(bool embed)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextEmbedMode(_handle, embed));
		}

		public void SetFlags(OrtCompileApiFlags flags)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetFlags(_handle, (uint)flags));
		}

		public void SetEpContextBinaryInformation(string outputDirectory, string modelName)
		{
			byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(outputDirectory);
			byte[] platformSerializedString2 = NativeOnnxValueHelper.GetPlatformSerializedString(modelName);
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextBinaryInformation(_handle, platformSerializedString, platformSerializedString2));
		}

		public void SetGraphOptimizationLevel(GraphOptimizationLevel graphOptimizationLevel)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetGraphOptimizationLevel(_handle, graphOptimizationLevel));
		}

		public void SetOutputModelWriteDelegate(WriteBufferToDestinationDelegate writeBufferDelegate)
		{
			_writeBufferToDestinationDelegateState?.Dispose();
			_writeBufferToDestinationDelegateState = new DelegateResources<WriteBufferToDestinationConnector, NativeMethods.DOrtWriteBufferToDestinationDelegate>(new WriteBufferToDestinationConnector(writeBufferDelegate), WriteBufferToDestinationConnector.WriteBufferToDestinationDelegateWrapper);
			IntPtr functionPointerForDelegate = _writeBufferToDestinationDelegateState.GetFunctionPointerForDelegate();
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelWriteFunc(_handle, functionPointerForDelegate, _writeBufferToDestinationDelegateState.GetConnectorHandleAsPointer()));
		}

		public void SetOutputModelGetInitializerLocationDelegate(GetInitializerLocationDelegate getInitializerLocationDelegate)
		{
			_getInitializerLocationDelegateState?.Dispose();
			_getInitializerLocationDelegateState = new DelegateResources<GetInitializerLocationConnector, NativeMethods.DOrtGetInitializerLocationDelegate>(new GetInitializerLocationConnector(getInitializerLocationDelegate), GetInitializerLocationConnector.GetInitializerLocationDelegateWrapper);
			IntPtr functionPointerForDelegate = _getInitializerLocationDelegateState.GetFunctionPointerForDelegate();
			NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelGetInitializerLocationFunc(_handle, functionPointerForDelegate, _getInitializerLocationDelegateState.GetConnectorHandleAsPointer()));
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing)
				{
					_writeBufferToDestinationDelegateState?.Dispose();
					_getInitializerLocationDelegateState?.Dispose();
				}
				NativeMethods.CompileApi.OrtReleaseModelCompilationOptions(_handle);
				_handle = IntPtr.Zero;
				_disposed = true;
			}
		}

		~OrtModelCompilationOptions()
		{
			Dispose(disposing: false);
		}
	}
	public interface IDisposableReadOnlyCollection<T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IDisposable
	{
	}
	internal class DisposableList<T> : List<T>, IDisposableReadOnlyCollection<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IDisposable where T : IDisposable
	{
		private bool _disposed;

		public DisposableList()
		{
		}

		public DisposableList(int count)
			: base(count)
		{
		}

		public DisposableList(IEnumerable<T> collection)
			: base(collection)
		{
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_disposed || !disposing)
			{
				return;
			}
			for (int num = base.Count - 1; num >= 0; num--)
			{
				T val = base[num];
				if (val != null)
				{
					val.Dispose();
				}
			}
			Clear();
			_disposed = true;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public class DisposableNamedOnnxValue : NamedOnnxValue, IDisposable
	{
		private IOrtValueOwner _ortValueHolder;

		private bool _disposed;

		public TensorElementType ElementType { get; }

		private DisposableNamedOnnxValue(string name, object value, TensorElementType elementType, IOrtValueOwner ortValueHolder)
			: base(name, value, OnnxValueType.ONNX_TYPE_TENSOR)
		{
			_ortValueHolder = ortValueHolder;
			ElementType = elementType;
		}

		private DisposableNamedOnnxValue(string name, object value, OnnxValueType onnxValueType, IOrtValueOwner ortValueHolder)
			: base(name, value, onnxValueType)
		{
			_ortValueHolder = ortValueHolder;
			ElementType = TensorElementType.DataTypeMax;
		}

		private DisposableNamedOnnxValue(string name, object value, MapHelper mapHelper, IOrtValueOwner ortValueHolder)
			: base(name, value, mapHelper)
		{
			_ortValueHolder = ortValueHolder;
			ElementType = TensorElementType.DataTypeMax;
		}

		internal override IntPtr InputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryHolder)
		{
			if (_ortValueHolder == null)
			{
				throw new InvalidOperationException("The instance of this class does not own an OrtValue");
			}
			memoryHolder = null;
			return _ortValueHolder.Value.Handle;
		}

		internal override IntPtr OutputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryOwner)
		{
			return InputToOrtValueHandle(metadata, out memoryOwner);
		}

		internal static DisposableNamedOnnxValue CreateFromOrtValue(string name, ref OrtValue ortValue)
		{
			return CreateFromOrtValue(name, ref ortValue, OrtAllocator.DefaultInstance);
		}

		internal static DisposableNamedOnnxValue CreateFromOrtValue(string name, ref OrtValue ortValue, OrtAllocator allocator)
		{
			OnnxValueType onnxType = ortValue.OnnxType;
			return onnxType switch
			{
				OnnxValueType.ONNX_TYPE_TENSOR => FromNativeTensor(name, ref ortValue), 
				OnnxValueType.ONNX_TYPE_SEQUENCE => FromNativeSequence(name, ref ortValue, allocator), 
				OnnxValueType.ONNX_TYPE_MAP => FromNativeMap(name, ref ortValue, allocator), 
				_ => throw new NotSupportedException($"OnnxValueType : {onnxType} is not supported"), 
			};
		}

		private static DisposableNamedOnnxValue FromNativeTensor(string name, ref OrtValue ortValue)
		{
			OrtTensorTypeAndShapeInfo tensorTypeAndShape = ortValue.GetTensorTypeAndShape();
			switch (tensorTypeAndShape.ElementDataType)
			{
			case TensorElementType.Float:
				return FromNativeTensor<float>(name, ref ortValue);
			case TensorElementType.Double:
				return FromNativeTensor<double>(name, ref ortValue);
			case TensorElementType.Int16:
				return FromNativeTensor<short>(name, ref ortValue);
			case TensorElementType.UInt16:
				return FromNativeTensor<ushort>(name, ref ortValue);
			case TensorElementType.Int32:
				return FromNativeTensor<int>(name, ref ortValue);
			case TensorElementType.UInt32:
				return FromNativeTensor<uint>(name, ref ortValue);
			case TensorElementType.Int64:
				return FromNativeTensor<long>(name, ref ortValue);
			case TensorElementType.UInt64:
				return FromNativeTensor<ulong>(name, ref ortValue);
			case TensorElementType.UInt8:
				return FromNativeTensor<byte>(name, ref ortValue);
			case TensorElementType.Int8:
				return FromNativeTensor<sbyte>(name, ref ortValue);
			case TensorElementType.String:
			{
				int[] shape = Array.ConvertAll(tensorTypeAndShape.Shape, Convert.ToInt32);
				return FromNativeStringTensor(name, shape, ref ortValue);
			}
			case TensorElementType.Bool:
				return FromNativeTensor<bool>(name, ref ortValue);
			case TensorElementType.Float16:
				return FromNativeTensor<Float16>(name, ref ortValue);
			case TensorElementType.BFloat16:
				return FromNativeTensor<BFloat16>(name, ref ortValue);
			default:
				throw new NotSupportedException($"Tensor of element type: {tensorTypeAndShape.ElementDataType} is not supported");
			}
		}

		private static DisposableNamedOnnxValue FromNativeStringTensor(string name, int[] shape, ref OrtValue ortValue)
		{
			DenseTensor<string> value = new DenseTensor<string>(ortValue.GetStringTensorAsArray(), shape);
			DisposableNamedOnnxValue result = new DisposableNamedOnnxValue(name, value, TensorElementType.String, ortValue);
			ortValue = null;
			return result;
		}

		private static DisposableNamedOnnxValue FromNativeTensor<T>(string name, ref OrtValue ortValue)
		{
			OrtValueTensor<T> ortValueTensor = new OrtValueTensor<T>(ref ortValue);
			try
			{
				DenseTensor<T> value = new DenseTensor<T>(ortValueTensor.Memory, ortValueTensor.Dimensions);
				return new DisposableNamedOnnxValue(name, value, ortValueTensor.ElementType, ortValueTensor);
			}
			catch (Exception)
			{
				ortValueTensor.Dispose();
				throw;
			}
		}

		private static DisposableNamedOnnxValue FromNativeSequence(string name, ref OrtValue ortValueSequence, OrtAllocator allocator)
		{
			int valueCount = ortValueSequence.GetValueCount();
			DisposableList<DisposableNamedOnnxValue> disposableList = new DisposableList<DisposableNamedOnnxValue>(valueCount);
			try
			{
				for (int i = 0; i < valueCount; i++)
				{
					OrtValue ortValue = ortValueSequence.GetValue(i, allocator);
					try
					{
						disposableList.Add(CreateFromOrtValue(string.Empty, ref ortValue, allocator));
					}
					finally
					{
						ortValue?.Dispose();
					}
				}
				NativeOrtValueCollectionOwner ortValueHolder = new NativeOrtValueCollectionOwner(ref ortValueSequence, disposableList);
				return new DisposableNamedOnnxValue(name, disposableList, OnnxValueType.ONNX_TYPE_SEQUENCE, ortValueHolder);
			}
			catch (Exception)
			{
				disposableList.Dispose();
				throw;
			}
		}

		private static DisposableNamedOnnxValue FromNativeMap(string name, ref OrtValue ortValueMap, OrtAllocator allocator)
		{
			DisposableNamedOnnxValue result = null;
			Span<OrtValue> disposables = new OrtValue[2];
			DisposableArray<OrtValue> disposableArray = new DisposableArray<OrtValue>(disposables);
			try
			{
				disposables[0] = ortValueMap.GetValue(0, allocator);
				disposables[1] = ortValueMap.GetValue(1, allocator);
				OrtTensorTypeAndShapeInfo tensorTypeAndShape = disposables[0].GetTensorTypeAndShape();
				OrtTensorTypeAndShapeInfo tensorTypeAndShape2 = disposables[1].GetTensorTypeAndShape();
				int[] keysShape = Array.ConvertAll(tensorTypeAndShape.Shape, Convert.ToInt32);
				int[] valsShape = Array.ConvertAll(tensorTypeAndShape2.Shape, Convert.ToInt32);
				result = tensorTypeAndShape.ElementDataType switch
				{
					TensorElementType.Int64 => tensorTypeAndShape2.ElementDataType switch
					{
						TensorElementType.Float => FromNativeMapElements<long, float>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						TensorElementType.Double => FromNativeMapElements<long, double>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						TensorElementType.Int64 => FromNativeMapElements<long, long>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						TensorElementType.String => FromNativeMapElements<long, string>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						_ => throw new NotSupportedException($"Map value type: {tensorTypeAndShape2.ElementDataType} is not supported"), 
					}, 
					TensorElementType.String => tensorTypeAndShape2.ElementDataType switch
					{
						TensorElementType.Float => FromNativeMapElements<string, float>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						TensorElementType.Double => FromNativeMapElements<string, double>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						TensorElementType.Int64 => FromNativeMapElements<string, long>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						TensorElementType.String => FromNativeMapElements<string, string>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), 
						_ => throw new NotSupportedException($"Map value type: {tensorTypeAndShape2.ElementDataType} is not supported"), 
					}, 
					_ => throw new NotSupportedException($"Map key type: {tensorTypeAndShape.ElementDataType} is not supported"), 
				};
			}
			finally
			{
				disposableArray.Dispose();
			}
			return result;
		}

		private static DisposableNamedOnnxValue FromNativeMapElements<K, V>(string name, ref OrtValue ortValueMap, int[] keysShape, ref OrtValue ortValueTensorKeys, int[] valsShape, ref OrtValue ortValueTensorValues)
		{
			if (typeof(K) == typeof(string))
			{
				DenseTensor<string> denseTensorKeys = new DenseTensor<string>(ortValueTensorKeys.GetStringTensorAsArray(), keysShape);
				if (typeof(V) == typeof(string))
				{
					DenseTensor<string> denseTensorValues = new DenseTensor<string>(ortValueTensorValues.GetStringTensorAsArray(), valsShape);
					Dictionary<string, string> value = Enumerable.Range(0, (int)denseTensorKeys.Length).ToDictionary((int i) => denseTensorKeys[new int[1] { i }], (int i) => denseTensorValues[new int[1] { i }]);
					MapHelper mapHelper = new MapHelper(denseTensorKeys, denseTensorValues);
					DisposableNamedOnnxValue result = new DisposableNamedOnnxValue(name, value, mapHelper, ortValueMap);
					ortValueMap = null;
					return result;
				}
				OrtValueTensor<V> ortValueTensor = new OrtValueTensor<V>(ref ortValueTensorValues);
				try
				{
					DenseTensor<V> values = new DenseTensor<V>(ortValueTensor.Memory, ortValueTensor.Dimensions);
					return FromMapDenseTensors(name, ref ortValueMap, denseTensorKeys, values, ortValueTensor);
				}
				catch (Exception)
				{
					ortValueTensor.Dispose();
					throw;
				}
			}
			DisposableList<IDisposable> disposableList = new DisposableList<IDisposable>(2);
			try
			{
				OrtValueTensor<K> ortValueTensor2 = new OrtValueTensor<K>(ref ortValueTensorKeys);
				disposableList.Add(ortValueTensor2);
				DenseTensor<K> keys = new DenseTensor<K>(ortValueTensor2.Memory, ortValueTensor2.Dimensions);
				if (typeof(V) == typeof(string))
				{
					DenseTensor<string> values2 = new DenseTensor<string>(ortValueTensorValues.GetStringTensorAsArray(), valsShape);
					return FromMapDenseTensors(name, ref ortValueMap, keys, values2, disposableList);
				}
				OrtValueTensor<V> ortValueTensor3 = new OrtValueTensor<V>(ref ortValueTensorValues);
				disposableList.Add(ortValueTensor3);
				DenseTensor<V> values3 = new DenseTensor<V>(ortValueTensor3.Memory, ortValueTensor3.Dimensions);
				return FromMapDenseTensors(name, ref ortValueMap, keys, values3, disposableList);
			}
			catch (Exception)
			{
				disposableList.Dispose();
				throw;
			}
		}

		private static DisposableNamedOnnxValue FromMapDenseTensors<K, V>(string name, ref OrtValue ortValueMap, DenseTensor<K> keys, DenseTensor<V> values, IDisposable disposables)
		{
			Dictionary<K, V> value = Enumerable.Range(0, (int)keys.Length).ToDictionary((int i) => keys[new int[1] { i }], (int i) => values[new int[1] { i }]);
			MapHelper mapHelper = new MapHelper(keys, values);
			NativeOrtValueCollectionOwner ortValueHolder = new NativeOrtValueCollectionOwner(ref ortValueMap, disposables);
			return new DisposableNamedOnnxValue(name, value, mapHelper, ortValueHolder);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing && _ortValueHolder != null)
				{
					_ortValueHolder.Dispose();
					_ortValueHolder = null;
				}
				_disposed = true;
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}
	}
	internal enum ErrorCode
	{
		Ok,
		Fail,
		InvalidArgument,
		NoSuchFile,
		NoModel,
		EngineError,
		RuntimeException,
		InvalidProtobuf,
		ModelLoaded,
		NotImplemented,
		InvalidGraph,
		ShapeInferenceNotRegistered,
		RequirementNotRegistered
	}
	public class OnnxRuntimeException : Exception
	{
		private static Dictionary<ErrorCode, string> errorCodeToString = new Dictionary<ErrorCode, string>
		{
			{
				ErrorCode.Ok,
				"Ok"
			},
			{
				ErrorCode.Fail,
				"Fail"
			},
			{
				ErrorCode.InvalidArgument,
				"InvalidArgument"
			},
			{
				ErrorCode.NoSuchFile,
				"NoSuchFile"
			},
			{
				ErrorCode.NoModel,
				"NoModel"
			},
			{
				ErrorCode.EngineError,
				"EngineError"
			},
			{
				ErrorCode.RuntimeException,
				"RuntimeException"
			},
			{
				ErrorCode.InvalidProtobuf,
				"InvalidProtobuf"
			},
			{
				ErrorCode.ModelLoaded,
				"ModelLoaded"
			},
			{
				ErrorCode.NotImplemented,
				"NotImplemented"
			},
			{
				ErrorCode.InvalidGraph,
				"InvalidGraph"
			},
			{
				ErrorCode.ShapeInferenceNotRegistered,
				"ShapeInferenceNotRegistered"
			},
			{
				ErrorCode.RequirementNotRegistered,
				"RequirementNotRegistered"
			}
		};

		internal OnnxRuntimeException(ErrorCode errorCode, string message)
			: base("[ErrorCode:" + errorCodeToString[errorCode] + "] " + message)
		{
		}
	}
	public class FixedBufferOnnxValue : IDisposable
	{
		private bool _disposed;

		internal OrtValue Value { get; private set; }

		internal OnnxValueType OnnxValueType { get; private set; }

		internal TensorElementType ElementType { get; private set; }

		private FixedBufferOnnxValue(ref OrtValue ortValue, OnnxValueType onnxValueType, TensorElementType elementType)
		{
			Value = ortValue;
			ortValue = null;
			OnnxValueType = onnxValueType;
			ElementType = elementType;
		}

		public static FixedBufferOnnxValue CreateFromTensor<T>(Tensor<T> value)
		{
			TensorElementType elementType;
			OrtValue ortValue = OrtValue.CreateFromTensorObject(value, out elementType);
			return new FixedBufferOnnxValue(ref ortValue, OnnxValueType.ONNX_TYPE_TENSOR, elementType);
		}

		public static FixedBufferOnnxValue CreateFromMemory<T>(OrtMemoryInfo memoryInfo, Memory<T> memory, TensorElementType elementType, long[] shape, long bytesSize) where T : unmanaged
		{
			if (elementType == TensorElementType.String)
			{
				throw new ArgumentException("String data type is not supported");
			}
			OrtValue ortValue = OrtValue.CreateTensorValueFromMemory(memoryInfo, memory, shape);
			try
			{
				return new FixedBufferOnnxValue(ref ortValue, OnnxValueType.ONNX_TYPE_TENSOR, elementType);
			}
			catch (Exception)
			{
				ortValue?.Dispose();
				throw;
			}
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing)
				{
					Value.Dispose();
				}
				_disposed = true;
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public class InferenceSession : IDisposable
	{
		private delegate string NameExtractor<in TInput>(TInput input);

		private delegate IntPtr OrtValueHandleExtractor(NamedOnnxValue value, NodeMetadata metadata, out IDisposable memOwner);

		private delegate NodeMetadata MetadataLookup(string nodeName);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate void OrtCallbackDelegate(IntPtr userData, IntPtr[] outputs, uint numOutputs, IntPtr status);

		private delegate void UserCallbackDelegate(IReadOnlyCollection<OrtValue> outputs, IntPtr status);

		private class CallbackHost
		{
			public IReadOnlyCollection<string> inputNames { get; }

			public IReadOnlyCollection<OrtValue> inputValues { get; }

			public IReadOnlyCollection<string> outputNames { get; }

			public IReadOnlyCollection<OrtValue> outputValues { get; }

			public UserCallbackDelegate callback { get; }

			public IntPtr[] rawInputNames { get; }

			public IntPtr[] rawInputValues { get; }

			public IntPtr[] rawOutputNames { get; }

			public IntPtr[] rawOutputValues { get; }

			public CallbackHost(InferenceSession session, IReadOnlyCollection<string> cbInputNames, IReadOnlyCollection<OrtValue> cbinputValues, IReadOnlyCollection<string> cbOutputNames, IReadOnlyCollection<OrtValue> cbOutputValues, UserCallbackDelegate userCallback)
			{
				inputNames = cbInputNames;
				inputValues = cbinputValues;
				outputNames = cbOutputNames;
				outputValues = cbOutputValues;
				callback = userCallback;
				rawInputNames = LookupUtf8Names(inputNames, (string n) => n, session.LookupInputMetadata);
				rawInputValues = inputValues.Select((OrtValue v) => v.Handle).ToArray();
				rawOutputNames = LookupUtf8Names(outputNames, (string n) => n, session.LookupOutputMetadata);
				rawOutputValues = outputValues.Select((OrtValue v) => v.Handle).ToArray();
			}
		}

		private IntPtr _nativeHandle;

		private Dictionary<string, NodeMetadata> _inputMetadata;

		private List<string> _inputNames;

		private Dictionary<string, NodeMetadata> _outputMetadata;

		private List<string> _outputNames;

		private Dictionary<string, NodeMetadata> _overridableInitializerMetadata;

		private List<IntPtr> _namesMemoryPtrs;

		private SessionOptions _builtInSessionOptions;

		private RunOptions _builtInRunOptions;

		private ModelMetadata _modelMetadata;

		private bool _disposed;

		private ulong _profilingStartTimeNs;

		private static OrtCallbackDelegate ortCallback = OrtCallback;

		public IReadOnlyDictionary<string, NodeMetadata> InputMetadata => _inputMetadata;

		public IReadOnlyList<string> InputNames => _inputNames;

		public IReadOnlyDictionary<string, NodeMetadata> OutputMetadata => _outputMetadata;

		public IReadOnlyList<string> OutputNames => _outputNames;

		public IReadOnlyDictionary<string, NodeMetadata> OverridableInitializerMetadata => _overridableInitializerMetadata;

		public ModelMetadata ModelMetadata
		{
			get
			{
				if (_modelMetadata != null)
				{
					return _modelMetadata;
				}
				_modelMetadata = new ModelMetadata(this);
				return _modelMetadata;
			}
		}

		public ulong ProfilingStartTimeNs => _profilingStartTimeNs;

		internal IntPtr Handle => _nativeHandle;

		public InferenceSession(string modelPath)
		{
			_builtInSessionOptions = new SessionOptions();
			Init(modelPath, _builtInSessionOptions);
		}

		public InferenceSession(string modelPath, PrePackedWeightsContainer prepackedWeightsContainer)
		{
			_builtInSessionOptions = new SessionOptions();
			Init(modelPath, _builtInSessionOptions, prepackedWeightsContainer);
		}

		public InferenceSession(string modelPath, SessionOptions options)
		{
			Init(modelPath, options);
		}

		public InferenceSession(string modelPath, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer)
		{
			Init(modelPath, options, prepackedWeightsContainer);
		}

		public InferenceSession(byte[] model)
		{
			_builtInSessionOptions = new SessionOptions();
			Init(model, _builtInSessionOptions);
		}

		public InferenceSession(byte[] model, PrePackedWeightsContainer prepackedWeightsContainer)
		{
			_builtInSessionOptions = new SessionOptions();
			Init(model, _builtInSessionOptions, prepackedWeightsContainer);
		}

		public InferenceSession(byte[] model, SessionOptions options)
		{
			Init(model, options);
		}

		public InferenceSession(byte[] model, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer)
		{
			Init(model, options, prepackedWeightsContainer);
		}

		public IDisposableReadOnlyCollection<OrtMemoryInfo> GetMemoryInfosForInputs()
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputCount(_nativeHandle, out var count));
			if (count == UIntPtr.Zero)
			{
				return new DisposableList<OrtMemoryInfo>();
			}
			IntPtr[] array = new IntPtr[(ulong)count];
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetMemoryInfoForInputs(_nativeHandle, array, count));
			return new DisposableList<OrtMemoryInfo>(array.Select((IntPtr ptr) => new OrtMemoryInfo(ptr, owned: false)));
		}

		public IDisposableReadOnlyCollection<OrtMemoryInfo> GetMemoryInfosForOutputs()
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputCount(_nativeHandle, out var count));
			if (count == UIntPtr.Zero)
			{
				return new DisposableList<OrtMemoryInfo>();
			}
			IntPtr[] array = new IntPtr[(ulong)count];
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetMemoryInfoForOutputs(_nativeHandle, array, count));
			return new DisposableList<OrtMemoryInfo>(array.Select((IntPtr ptr) => new OrtMemoryInfo(ptr, owned: false)));
		}

		public IReadOnlyList<OrtEpDevice> GetEpDeviceForInputs()
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputCount(_nativeHandle, out var count));
			if (count == UIntPtr.Zero)
			{
				return Array.Empty<OrtEpDevice>();
			}
			IntPtr[] array = new IntPtr[(ulong)count];
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetEpDeviceForInputs(_nativeHandle, array, count));
			return array.Select((IntPtr ptr) => (!(ptr == IntPtr.Zero)) ? new OrtEpDevice(ptr) : null).ToList().AsReadOnly();
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs)
		{
			return Run(inputs, _outputNames);
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames)
		{
			return Run(inputs, outputNames, _builtInRunOptions);
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames, RunOptions options)
		{
			IntPtr[] inputNames = LookupUtf8Names(inputs, (NamedOnnxValue v) => v.Name, LookupInputMetadata);
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			DisposableArray<IDisposable> disposer;
			IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput, out disposer);
			try
			{
				using DisposableOrtValueHandleArray disposableOrtValueHandleArray = RunImpl(options, inputNames, ortValuesHandles, outputNames2);
				return CreateDisposableResult(disposableOrtValueHandleArray.Span, outputNames);
			}
			finally
			{
				disposer.Dispose();
			}
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues)
		{
			return Run(inputNames, inputValues, _outputNames, _builtInRunOptions);
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames)
		{
			return Run(inputNames, inputValues, outputNames, _builtInRunOptions);
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames, RunOptions options)
		{
			if (inputNames.Count != inputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count));
			}
			IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata);
			IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputValues, input: true);
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			using DisposableOrtValueHandleArray disposableOrtValueHandleArray = RunImpl(options, inputNames2, ortValuesHandles, outputNames2);
			return CreateDisposableResult(disposableOrtValueHandleArray.Span, outputNames);
		}

		public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues)
		{
			Run(inputNames, inputValues, outputNames, outputValues, _builtInRunOptions);
		}

		public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues, RunOptions options)
		{
			if (inputNames.Count != inputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count));
			}
			if (outputNames.Count != outputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count));
			}
			IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata);
			IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputValues, input: true);
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(outputValues, input: false);
			NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames2, ortValuesHandles, (UIntPtr)(ulong)inputNames.Count, outputNames2, (UIntPtr)(ulong)outputNames.Count, ortValuesHandles2));
		}

		public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<NamedOnnxValue> outputs)
		{
			Run(inputs, outputs, _builtInRunOptions);
		}

		public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<NamedOnnxValue> outputs, RunOptions options)
		{
			IntPtr[] inputNames = LookupUtf8Names(inputs, (NamedOnnxValue i) => i.Name, LookupInputMetadata);
			IntPtr[] outputNames = LookupUtf8Names(outputs, (NamedOnnxValue o) => o.Name, LookupOutputMetadata);
			DisposableArray<IDisposable> disposer;
			IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput, out disposer);
			try
			{
				DisposableArray<IDisposable> disposer2;
				IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(outputs, LookupOutputMetadata, ExtractOrtValueHandleForOutput, out disposer2);
				try
				{
					NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames, ortValuesHandles, (UIntPtr)(ulong)inputs.Count, outputNames, (UIntPtr)(ulong)outputs.Count, ortValuesHandles2));
				}
				finally
				{
					disposer2.Dispose();
				}
			}
			finally
			{
				disposer.Dispose();
			}
		}

		public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues)
		{
			Run(inputs, outputNames, outputValues, _builtInRunOptions);
		}

		public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues, RunOptions options)
		{
			if (outputNames.Count != outputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count));
			}
			IntPtr[] inputNames = LookupUtf8Names(inputs, (NamedOnnxValue i) => i.Name, LookupInputMetadata);
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			IntPtr[] ortValuesHandles = GetOrtValuesHandles(outputValues, input: false);
			DisposableArray<IDisposable> disposer;
			IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput, out disposer);
			try
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames, ortValuesHandles2, (UIntPtr)(ulong)inputs.Count, outputNames2, (UIntPtr)(ulong)outputNames.Count, ortValuesHandles));
			}
			finally
			{
				disposer.Dispose();
			}
		}

		public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<NamedOnnxValue> outputs)
		{
			Run(inputNames, inputValues, outputs, _builtInRunOptions);
		}

		public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<NamedOnnxValue> outputs, RunOptions options)
		{
			if (inputNames.Count != inputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count));
			}
			IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata);
			IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputValues, input: true);
			IntPtr[] outputNames = LookupUtf8Names(outputs, (NamedOnnxValue o) => o.Name, LookupOutputMetadata);
			DisposableArray<IDisposable> disposer;
			IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(outputs, LookupOutputMetadata, ExtractOrtValueHandleForOutput, out disposer);
			try
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames2, ortValuesHandles, (UIntPtr)(ulong)inputNames.Count, outputNames, (UIntPtr)(ulong)outputs.Count, ortValuesHandles2));
			}
			finally
			{
				disposer.Dispose();
			}
		}

		public IDisposableReadOnlyCollection<OrtValue> Run(RunOptions runOptions, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames)
		{
			if (inputNames.Count != inputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count));
			}
			IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata);
			IntPtr[] inputValues2 = inputValues.Select((OrtValue v) => v.Handle).ToArray();
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			using DisposableOrtValueHandleArray disposableHandles = RunImpl(runOptions, inputNames2, inputValues2, outputNames2);
			return CreateDisposableResult(disposableHandles);
		}

		public IDisposableReadOnlyCollection<OrtValue> Run(RunOptions runOptions, IReadOnlyDictionary<string, OrtValue> inputs, IReadOnlyCollection<string> outputNames)
		{
			IntPtr[] array = new IntPtr[inputs.Count];
			IntPtr[] array2 = new IntPtr[inputs.Count];
			int num = 0;
			foreach (KeyValuePair<string, OrtValue> input in inputs)
			{
				array[num] = LookupInputMetadata(input.Key).ZeroTerminatedName;
				array2[num] = input.Value.Handle;
				num++;
			}
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			using DisposableOrtValueHandleArray disposableHandles = RunImpl(runOptions, array, array2, outputNames2);
			return CreateDisposableResult(disposableHandles);
		}

		private static IDisposableReadOnlyCollection<OrtValue> CreateDisposableResult(DisposableOrtValueHandleArray disposableHandles)
		{
			DisposableList<OrtValue> disposableList = new DisposableList<OrtValue>(disposableHandles.Span.Length);
			try
			{
				for (int i = 0; i < disposableHandles.Span.Length; i++)
				{
					disposableList.Add(new OrtValue(disposableHandles.Span[i]));
					disposableHandles.Span[i] = IntPtr.Zero;
				}
				return disposableList;
			}
			catch (Exception)
			{
				disposableList.Dispose();
				throw;
			}
		}

		public void Run(RunOptions runOptions, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues)
		{
			if (inputNames.Count != inputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count));
			}
			if (outputNames.Count != outputValues.Count)
			{
				throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count));
			}
			if (runOptions == null)
			{
				runOptions = _builtInRunOptions;
			}
			IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata);
			IntPtr[] inputValues2 = inputValues.Select((OrtValue v) => v.Handle).ToArray();
			IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata);
			IntPtr[] outputValues2 = outputValues.Select((OrtValue v) => v.Handle).ToArray();
			NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, runOptions.Handle, inputNames2, inputValues2, (UIntPtr)(ulong)inputNames.Count, outputNames2, (UIntPtr)(ulong)outputNames.Count, outputValues2));
		}

		public OrtIoBinding CreateIoBinding()
		{
			return new OrtIoBinding(this);
		}

		public void RunWithBinding(RunOptions runOptions, OrtIoBinding ioBinding)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle));
		}

		public IDisposableReadOnlyCollection<OrtValue> RunWithBoundResults(RunOptions runOptions, OrtIoBinding ioBinding)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle));
			return ioBinding.GetOutputValues();
		}

		public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> RunWithBindingAndNames(RunOptions runOptions, OrtIoBinding ioBinding, string[] names = null)
		{
			string[] array = names;
			if (array == null || names.Length == 0)
			{
				array = ioBinding.GetOutputNames();
			}
			NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle));
			OrtValue[] outputOrtValues = ioBinding.GetOutputOrtValues();
			DisposableArray<OrtValue> disposableArray = new DisposableArray<OrtValue>(outputOrtValues);
			try
			{
				DisposableList<DisposableNamedOnnxValue> disposableList = new DisposableList<DisposableNamedOnnxValue>(outputOrtValues.Length);
				try
				{
					for (int i = 0; i < array.Length; i++)
					{
						disposableList.Add(DisposableNamedOnnxValue.CreateFromOrtValue(array[i], ref outputOrtValues[i]));
					}
					return disposableList;
				}
				catch (Exception)
				{
					disposableList.Dispose();
					throw;
				}
			}
			finally
			{
				disposableArray.Dispose();
			}
		}

		public string EndProfiling()
		{
			OrtAllocator defaultInstance = OrtAllocator.DefaultInstance;
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionEndProfiling(_nativeHandle, defaultInstance.Pointer, out var profile_file));
			return NativeOnnxValueHelper.StringFromNativeUtf8(profile_file, defaultInstance);
		}

		private NodeMetadata LookupInputMetadata(string nodeName)
		{
			if (!_inputMetadata.TryGetValue(nodeName, out var value) && !_overridableInitializerMetadata.TryGetValue(nodeName, out value))
			{
				throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Input name: '" + nodeName + "' is not in the metadata");
			}
			return value;
		}

		private NodeMetadata LookupOutputMetadata(string nodeName)
		{
			if (!_outputMetadata.TryGetValue(nodeName, out var value))
			{
				throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Output name: '" + nodeName + "' is not in the metadata");
			}
			return value;
		}

		private static IntPtr ExtractOrtValueHandleForInput(NamedOnnxValue input, NodeMetadata metadata, out IDisposable memOwner)
		{
			return input.InputToOrtValueHandle(metadata, out memOwner);
		}

		private static IntPtr ExtractOrtValueHandleForOutput(NamedOnnxValue output, NodeMetadata metadata, out IDisposable memOwner)
		{
			return output.OutputToOrtValueHandle(metadata, out memOwner);
		}

		private static IntPtr[] LookupUtf8Names<T>(IReadOnlyCollection<T> values, NameExtractor<T> nameExtractor, MetadataLookup metaLookup)
		{
			IntPtr[] array = new IntPtr[values.Count];
			for (int i = 0; i < values.Count; i++)
			{
				string nodeName = nameExtractor(values.ElementAt(i));
				NodeMetadata nodeMetadata = metaLookup(nodeName);
				array[i] = nodeMetadata.ZeroTerminatedName;
			}
			return array;
		}

		private static IntPtr[] GetOrtValuesHandles(IReadOnlyCollection<NamedOnnxValue> values, MetadataLookup metaLookup, OrtValueHandleExtractor ortValueExtractor, out DisposableArray<IDisposable> disposer)
		{
			IDisposable[] array = new IDisposable[values.Count];
			DisposableArray<IDisposable> disposableArray = new DisposableArray<IDisposable>(array);
			try
			{
				IntPtr[] array2 = new IntPtr[values.Count];
				for (int i = 0; i < values.Count; i++)
				{
					NamedOnnxValue namedOnnxValue = values.ElementAt(i);
					NodeMetadata metadata = metaLookup(namedOnnxValue.Name);
					array2[i] = ortValueExtractor(namedOnnxValue, metadata, out var memOwner);
					if (memOwner != null)
					{
						array[i] = memOwner;
					}
				}
				disposer = disposableArray;
				return array2;
			}
			catch (Exception)
			{
				disposableArray.Dispose();
				throw;
			}
		}

		private static IntPtr[] GetOrtValuesHandles(IReadOnlyCollection<FixedBufferOnnxValue> values, bool input)
		{
			IntPtr[] array = new IntPtr[values.Count];
			for (int i = 0; i < values.Count; i++)
			{
				FixedBufferOnnxValue fixedBufferOnnxValue = values.ElementAt(i);
				if (!input && fixedBufferOnnxValue.ElementType == TensorElementType.String)
				{
					throw new NotSupportedException("Using string type FixedBufferOnnxValue in outputs is not supported.");
				}
				array[i] = fixedBufferOnnxValue.Value.Handle;
			}
			return array;
		}

		private DisposableOrtValueHandleArray RunImpl(RunOptions options, IntPtr[] inputNames, IntPtr[] inputValues, IntPtr[] outputNames)
		{
			IntPtr[] array = new IntPtr[outputNames.Length];
			NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames, inputValues, (UIntPtr)(ulong)inputNames.Length, outputNames, (UIntPtr)(ulong)outputNames.Length, array));
			return new DisposableOrtValueHandleArray(array);
		}

		private static IDisposableReadOnlyCollection<DisposableNamedOnnxValue> CreateDisposableResult(Span<IntPtr> valueHandles, IReadOnlyCollection<string> outputNames)
		{
			DisposableList<DisposableNamedOnnxValue> disposableList = new DisposableList<DisposableNamedOnnxValue>(valueHandles.Length);
			try
			{
				for (int i = 0; i < valueHandles.Length; i++)
				{
					OrtValue ortValue = new OrtValue(valueHandles[i]);
					disposableList.Add(DisposableNamedOnnxValue.CreateFromOrtValue(outputNames.ElementAt(i), ref ortValue));
					valueHandles[i] = IntPtr.Zero;
				}
				return disposableList;
			}
			catch (OnnxRuntimeException)
			{
				disposableList.Dispose();
				throw;
			}
		}

		private static void OrtCallback(IntPtr userData, IntPtr[] outputs, uint numOutputs, IntPtr status)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(userData);
			CallbackHost callbackHost = (CallbackHost)gCHandle.Target;
			try
			{
				callbackHost.callback(callbackHost.outputValues, status);
			}
			finally
			{
				gCHandle.Free();
			}
		}

		private unsafe void RunAsyncInternal(RunOptions options, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues, UserCallbackDelegate callback)
		{
			CallbackHost callbackHost = new CallbackHost(this, inputNames, inputValues, outputNames, outputValues, callback);
			GCHandle value = GCHandle.Alloc(callbackHost, GCHandleType.Normal);
			try
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtRunAsync(_nativeHandle, options?.Handle ?? ((IntPtr)(void*)null), callbackHost.rawInputNames, callbackHost.rawInputValues, (UIntPtr)(ulong)callbackHost.rawInputNames.Length, callbackHost.rawOutputNames, (UIntPtr)(ulong)callbackHost.rawOutputNames.Length, callbackHost.rawOutputValues, Marshal.GetFunctionPointerForDelegate(ortCallback), GCHandle.ToIntPtr(value)));
			}
			catch (OnnxRuntimeException)
			{
				value.Free();
				throw;
			}
		}

		public async Task<IReadOnlyCollection<OrtValue>> RunAsync(RunOptions options, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues)
		{
			TaskCompletionSource<IReadOnlyCollection<OrtValue>> promise = new TaskCompletionSource<IReadOnlyCollection<OrtValue>>();
			RunAsyncInternal(options, inputNames, inputValues, outputNames, outputValues, delegate(IReadOnlyCollection<OrtValue> outputs, IntPtr status)
			{
				try
				{
					NativeApiStatus.VerifySuccess(status);
					promise.SetResult(outputs);
				}
				catch (Exception exception)
				{
					promise.SetException(exception);
				}
			});
			return await promise.Task;
		}

		private void Init(string modelPath, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer = null)
		{
			IntPtr handle = OrtEnv.Instance().Handle;
			IntPtr session;
			if (prepackedWeightsContainer == null)
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSession(handle, NativeOnnxValueHelper.GetPlatformSerializedString(modelPath), options.Handle, out session));
			}
			else
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionWithPrepackedWeightsContainer(handle, NativeOnnxValueHelper.GetPlatformSerializedString(modelPath), options.Handle, prepackedWeightsContainer.Pointer, out session));
			}
			InitWithSessionHandle(session);
		}

		private void Init(byte[] modelData, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer = null)
		{
			IntPtr handle = OrtEnv.Instance().Handle;
			IntPtr session;
			if (prepackedWeightsContainer == null)
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionFromArray(handle, modelData, (UIntPtr)(ulong)modelData.Length, options.Handle, out session));
			}
			else
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionFromArrayWithPrepackedWeightsContainer(handle, modelData, (UIntPtr)(ulong)modelData.Length, options.Handle, prepackedWeightsContainer.Pointer, out session));
			}
			InitWithSessionHandle(session);
		}

		private void InitWithSessionHandle(IntPtr session)
		{
			_nativeHandle = session;
			try
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputCount(_nativeHandle, out var count));
				NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputCount(_nativeHandle, out var count2));
				NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOverridableInitializerCount(_nativeHandle, out var count3));
				int capacity = (int)((uint)count + (uint)count2 + (uint)count3);
				_namesMemoryPtrs = new List<IntPtr>(capacity);
				_inputMetadata = new Dictionary<string, NodeMetadata>((int)(uint)count);
				_inputNames = new List<string>((int)(uint)count);
				for (ulong num = 0uL; num < (ulong)count; num++)
				{
					NodeMetadata inputMetadata = GetInputMetadata(num);
					IntPtr utf;
					string inputName = GetInputName(num, out utf);
					_namesMemoryPtrs.Add(utf);
					inputMetadata.ZeroTerminatedName = utf;
					_inputNames.Add(inputName);
					_inputMetadata[inputName] = inputMetadata;
				}
				_outputMetadata = new Dictionary<string, NodeMetadata>((int)(uint)count2);
				_outputNames = new List<string>((int)(uint)count2);
				for (ulong num2 = 0uL; num2 < (ulong)count2; num2++)
				{
					NodeMetadata outputMetadata = GetOutputMetadata(num2);
					IntPtr utf2;
					string outputName = GetOutputName(num2, out utf2);
					_namesMemoryPtrs.Add(utf2);
					outputMetadata.ZeroTerminatedName = utf2;
					_outputNames.Add(outputName);
					_outputMetadata[outputName] = outputMetadata;
				}
				_overridableInitializerMetadata = new Dictionary<string, NodeMetadata>((int)(uint)count3);
				for (ulong num3 = 0uL; num3 < (ulong)count3; num3++)
				{
					NodeMetadata overridableInitializerMetadata = GetOverridableInitializerMetadata(num3);
					IntPtr utf3;
					string overridableInitializerName = GetOverridableInitializerName(num3, out utf3);
					_namesMemoryPtrs.Add(utf3);
					overridableInitializerMetadata.ZeroTerminatedName = utf3;
					_overridableInitializerMetadata[overridableInitializerName] = overridableInitializerMetadata;
				}
				NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetProfilingStartTimeNs(_nativeHandle, out var startTime));
				_profilingStartTimeNs = (ulong)startTime;
			}
			catch (Exception)
			{
				DisposeImpl(disposing: true);
				throw;
			}
			_builtInRunOptions = new RunOptions();
		}

		private string GetOutputName(ulong index, out IntPtr utf8)
		{
			OrtAllocator defaultInstance = OrtAllocator.DefaultInstance;
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputName(_nativeHandle, (UIntPtr)index, defaultInstance.Pointer, out var name));
			NativeOnnxValueHelper.StringAndUtf8FromNative(defaultInstance, name, out var str, out utf8);
			return str;
		}

		private string GetInputName(ulong index, out IntPtr utf8)
		{
			OrtAllocator defaultInstance = OrtAllocator.DefaultInstance;
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputName(_nativeHandle, (UIntPtr)index, defaultInstance.Pointer, out var name));
			NativeOnnxValueHelper.StringAndUtf8FromNative(defaultInstance, name, out var str, out utf8);
			return str;
		}

		private string GetOverridableInitializerName(ulong index, out IntPtr utf8)
		{
			OrtAllocator defaultInstance = OrtAllocator.DefaultInstance;
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOverridableInitializerName(_nativeHandle, (UIntPtr)index, defaultInstance.Pointer, out var name));
			NativeOnnxValueHelper.StringAndUtf8FromNative(defaultInstance, name, out var str, out utf8);
			return str;
		}

		private NodeMetadata GetInputMetadata(ulong index)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputTypeInfo(_nativeHandle, (UIntPtr)index, out var typeInfo));
			try
			{
				return GetMetadataFromTypeInfo(typeInfo);
			}
			finally
			{
				NativeMethods.OrtReleaseTypeInfo(typeInfo);
			}
		}

		private NodeMetadata GetOutputMetadata(ulong index)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputTypeInfo(_nativeHandle, (UIntPtr)index, out var typeInfo));
			try
			{
				return GetMetadataFromTypeInfo(typeInfo);
			}
			finally
			{
				NativeMethods.OrtReleaseTypeInfo(typeInfo);
			}
		}

		private NodeMetadata GetOverridableInitializerMetadata(ulong index)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOverridableInitializerTypeInfo(_nativeHandle, (UIntPtr)index, out var typeInfo));
			try
			{
				return GetMetadataFromTypeInfo(typeInfo);
			}
			finally
			{
				NativeMethods.OrtReleaseTypeInfo(typeInfo);
			}
		}

		internal static NodeMetadata GetMetadataFromTypeInfo(IntPtr typeInfo)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetOnnxTypeFromTypeInfo(typeInfo, out var onnxtype));
			OnnxValueType onnxValueType = (OnnxValueType)(int)onnxtype;
			switch (onnxValueType)
			{
			case OnnxValueType.ONNX_TYPE_TENSOR:
			case OnnxValueType.ONNX_TYPE_SPARSETENSOR:
				return GetTensorNodeMetadata(onnxValueType, typeInfo);
			case OnnxValueType.ONNX_TYPE_SEQUENCE:
				return GetSequenceMetadataFromTypeInfo(typeInfo);
			case OnnxValueType.ONNX_TYPE_MAP:
				return GetMapMetadataFromTypeInfo(typeInfo);
			case OnnxValueType.ONNX_TYPE_OPTIONAL:
				return GetOptionalMetadataFromTypeInfo(typeInfo);
			default:
				throw new OnnxRuntimeException(ErrorCode.NotImplemented, $"Value type: '{onnxValueType}' not supported in this code");
			}
		}

		internal static NodeMetadata GetSequenceMetadataFromTypeInfo(IntPtr typeInfo)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToSequenceTypeInfo(typeInfo, out var sequenceTypeInfo));
			if (sequenceTypeInfo == IntPtr.Zero)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to SequenceTypeInfo failed. The object does not represent a sequence");
			}
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetSequenceElementType(sequenceTypeInfo, out var elementTypeInfo));
			try
			{
				return new NodeMetadata(new SequenceMetadata(GetMetadataFromTypeInfo(elementTypeInfo)));
			}
			finally
			{
				NativeMethods.OrtReleaseTypeInfo(elementTypeInfo);
			}
		}

		internal static NodeMetadata GetMapMetadataFromTypeInfo(IntPtr typeInfo)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToMapTypeInfo(typeInfo, out var mapTypeInfo));
			if (mapTypeInfo == IntPtr.Zero)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to MapTypeInfo failed. The object does not represent a map");
			}
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetMapKeyType(mapTypeInfo, out var tensorElementType));
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetMapValueType(mapTypeInfo, out var type_info));
			try
			{
				NodeMetadata metadataFromTypeInfo = GetMetadataFromTypeInfo(type_info);
				return new NodeMetadata(new MapMetadata((TensorElementType)(int)tensorElementType, metadataFromTypeInfo));
			}
			finally
			{
				NativeMethods.OrtReleaseTypeInfo(type_info);
			}
		}

		internal static NodeMetadata GetOptionalMetadataFromTypeInfo(IntPtr typeInfo)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToOptionalTypeInfo(typeInfo, out var optionalTypeInfo));
			if (optionalTypeInfo == IntPtr.Zero)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to OptionalTypeInfo failed. The object does not represent a optional value");
			}
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetOptionalContainedTypeInfo(optionalTypeInfo, out var containedTypeInfo));
			try
			{
				return new NodeMetadata(new OptionalMetadata(GetMetadataFromTypeInfo(containedTypeInfo)));
			}
			finally
			{
				NativeMethods.OrtReleaseTypeInfo(containedTypeInfo);
			}
		}

		internal static NodeMetadata GetTensorNodeMetadata(OnnxValueType valueType, IntPtr typeInfo)
		{
			NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToTensorInfo(typeInfo, out var typeAndShapeInfo));
			if (typeAndShapeInfo == IntPtr.Zero)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to TensorTypeInfo failed. The object does not represent a tensor");
			}
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTensorElementType(typeAndShapeInfo, out var output));
			TensorElementType elementType = (TensorElementType)(int)output;
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetDimensionsCount(typeAndShapeInfo, out var output2));
			long[] array = new long[(uint)output2];
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetDimensions(typeAndShapeInfo, array, output2));
			int[] array2 = new int[(uint)output2];
			for (int i = 0; (long)i < (long)(ulong)output2; i++)
			{
				array2[i] = (int)array[i];
			}
			IntPtr[] array3 = new IntPtr[(uint)output2];
			NativeApiStatus.VerifySuccess(NativeMethods.OrtGetSymbolicDimensions(typeAndShapeInfo, array3, output2));
			string[] array4 = new string[(uint)output2];
			for (int j = 0; j < (int)(uint)output2; j++)
			{
				array4[j] = NativeOnnxValueHelper.StringFromNativeUtf8(array3[j]);
			}
			TensorTypeAndShape typeAndShape = new TensorTypeAndShape(elementType, array2, array4);
			return new NodeMetadata(valueType, typeAndShape);
		}

		~InferenceSession()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				DisposeImpl(disposing);
			}
		}

		private void DisposeImpl(bool disposing)
		{
			if (disposing)
			{
				if (_namesMemoryPtrs != null)
				{
					foreach (IntPtr namesMemoryPtr in _namesMemoryPtrs)
					{
						Marshal.FreeHGlobal(namesMemoryPtr);
					}
					_namesMemoryPtrs = null;
				}
				if (_builtInSessionOptions != null)
				{
					_builtInSessionOptions.Dispose();
					_builtInSessionOptions = null;
				}
				if (_builtInRunOptions != null)
				{
					_builtInRunOptions.Dispose();
					_builtInRunOptions = null;
				}
			}
			if (_nativeHandle != IntPtr.Zero)
			{
				NativeMethods.OrtReleaseSession(_nativeHandle);
				_nativeHandle = IntPtr.Zero;
			}
			_disposed = true;
		}
	}
	public class TensorTypeAndShape
	{
		public TensorElementType ElementDataType { get; }

		public int[] Dimensions { get; }

		public string[] SymbolicDimensions { get; }

		public TensorElementTypeInfo ElementTypeInfo { get; }

		internal TensorTypeAndShape(TensorElementType elementType, int[] dimensions, string[] symbolicDimensions)
		{
			ElementTypeInfo = TensorBase.GetElementTypeInfo(elementType);
			if (ElementTypeInfo == null)
			{
				throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Unregistered TensorElementType value of: " + elementType);
			}
			ElementDataType = elementType;
			Dimensions = dimensions;
			SymbolicDimensions = symbolicDimensions;
		}
	}
	public class SequenceMetadata
	{
		public NodeMetadata ElementMeta { get; }

		internal SequenceMetadata(NodeMetadata elementData)
		{
			ElementMeta = elementData;
		}
	}
	public class OptionalMetadata
	{
		public NodeMetadata ElementMeta { get; }

		internal OptionalMetadata(NodeMetadata elementData)
		{
			ElementMeta = elementData;
		}
	}
	public class MapMetadata
	{
		public TensorElementType KeyDataType { get; }

		public NodeMetadata ValueMetadata { get; }

		internal MapMetadata(TensorElementType keyDataType, NodeMetadata valueMetadata)
		{
			KeyDataType = keyDataType;
			ValueMetadata = valueMetadata;
		}
	}
	public class NodeMetadata
	{
		private readonly object _metadata;

		public OnnxValueType OnnxValueType { get; }

		internal IntPtr ZeroTerminatedName { get; set; }

		public int[] Dimensions
		{
			get
			{
				CheckTensor();
				return (_metadata as TensorTypeAndShape).Dimensions;
			}
		}

		public string[] SymbolicDimensions
		{
			get
			{
				CheckTensor();
				return (_metadata as TensorTypeAndShape).SymbolicDimensions;
			}
		}

		public Type ElementType
		{
			get
			{
				CheckTensor();
				return (_metadata as TensorTypeAndShape).ElementTypeInfo.TensorType;
			}
		}

		public TensorElementType ElementDataType
		{
			get
			{
				CheckTensor();
				return (_metadata as TensorTypeAndShape).ElementDataType;
			}
		}

		public bool IsString
		{
			get
			{
				CheckTensor();
				return (_metadata as TensorTypeAndShape).ElementTypeInfo.IsString;
			}
		}

		public bool IsTensor
		{
			get
			{
				if (OnnxValueType != OnnxValueType.ONNX_TYPE_TENSOR)
				{
					return OnnxValueType == OnnxValueType.ONNX_TYPE_SPARSETENSOR;
				}
				return true;
			}
		}

		internal NodeMetadata(OnnxValueType onnxValueType, TensorTypeAndShape typeAndShape)
		{
			OnnxValueType = onnxValueType;
			CheckTensor();
			_metadata = typeAndShape;
		}

		internal NodeMetadata(MapMetadata mapMetadata)
		{
			OnnxValueType = OnnxValueType.ONNX_TYPE_MAP;
			_metadata = mapMetadata;
		}

		internal NodeMetadata(SequenceMetadata sequenceMetadata)
		{
			OnnxValueType = OnnxValueType.ONNX_TYPE_SEQUENCE;
			_metadata = sequenceMetadata;
		}

		internal NodeMetadata(OptionalMetadata optMetadata)
		{
			OnnxValueType = OnnxValueType.ONNX_TYPE_OPTIONAL;
			_metadata = optMetadata;
		}

		private void CheckTensor()
		{
			if (!IsTensor)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "OnnxValueType must either be a tensor or sparse tensor");
			}
		}

		public MapMetadata AsMapMetadata()
		{
			if (OnnxValueType != OnnxValueType.ONNX_TYPE_MAP)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "Instance does not contain Map metadata");
			}
			return _metadata as MapMetadata;
		}

		public SequenceMetadata AsSequenceMetadata()
		{
			if (OnnxValueType != OnnxValueType.ONNX_TYPE_SEQUENCE)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "Instance does not contain Sequence metadata");
			}
			return _metadata as SequenceMetadata;
		}

		public OptionalMetadata AsOptionalMetadata()
		{
			if (OnnxValueType != OnnxValueType.ONNX_TYPE_OPTIONAL)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "Instance does not contain Optional metadata");
			}
			return _metadata as OptionalMetadata;
		}
	}
	public class ModelMetadata
	{
		private string _producerName;

		private string _graphName;

		private string _domain;

		private string _description;

		private string _graphDescription;

		private long _version;

		private Dictionary<string, string> _customMetadataMap = new Dictionary<string, string>();

		public string ProducerName => _producerName;

		public string GraphName => _graphName;

		public string Domain => _domain;

		public string Description => _description;

		public string GraphDescription => _graphDescription;

		public long Version => _version;

		public Dictionary<string, string> CustomMetadataMap => _customMetadataMap;

		internal unsafe ModelMetadata(InferenceSession session)
		{
			OrtAllocator defaultInstance = OrtAllocator.DefaultInstance;
			NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetModelMetadata(session.Handle, out var modelMetadata));
			try
			{
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetProducerName(modelMetadata, defaultInstance.Pointer, out var value));
				_producerName = NativeOnnxValueHelper.StringFromNativeUtf8(value, defaultInstance);
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetGraphName(modelMetadata, defaultInstance.Pointer, out var value2));
				_graphName = NativeOnnxValueHelper.StringFromNativeUtf8(value2, defaultInstance);
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetDomain(modelMetadata, defaultInstance.Pointer, out var value3));
				_domain = NativeOnnxValueHelper.StringFromNativeUtf8(value3, defaultInstance);
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetDescription(modelMetadata, defaultInstance.Pointer, out var value4));
				_description = NativeOnnxValueHelper.StringFromNativeUtf8(value4, defaultInstance);
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetGraphDescription(modelMetadata, defaultInstance.Pointer, out var value5));
				_graphDescription = NativeOnnxValueHelper.StringFromNativeUtf8(value5, defaultInstance);
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetVersion(modelMetadata, out _version));
				NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetCustomMetadataMapKeys(modelMetadata, defaultInstance.Pointer, out var keys, out var numKeys));
				try
				{
					Span<IntPtr> span = new Span<IntPtr>(keys.ToPointer(), (int)numKeys);
					using DisposableList<OrtMemoryAllocation> disposableList = new DisposableList<OrtMemoryAllocation>((int)numKeys);
					Span<IntPtr> span2 = span;
					for (int i = 0; i < span2.Length; i++)
					{
						IntPtr pointer = span2[i];
						disposableList.Add(new OrtMemoryAllocation(defaultInstance, pointer, 0u));
					}
					span2 = span;
					for (int i = 0; i < span2.Length; i++)
					{
						IntPtr intPtr = span2[i];
						NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataLookupCustomMetadataMap(modelMetadata, defaultInstance.Pointer, intPtr, out var value6));
						string value7 = NativeOnnxValueHelper.StringFromNativeUtf8(value6, defaultInstance);
						string key = NativeOnnxValueHelper.StringFromNativeUtf8(intPtr);
						_customMetadataMap[key] = value7;
					}
				}
				finally
				{
					defaultInstance.FreeMemory(keys);
				}
			}
			finally
			{
				NativeMethods.OrtReleaseModelMetadata(modelMetadata);
			}
		}
	}
	internal class ManagedTypeProjection
	{
		internal static OrtValue CreateProjection(NamedOnnxValue namedOnnxValue, NodeMetadata metadata)
		{
			NodeMetadata nodeMetadata = metadata;
			if (metadata.OnnxValueType == OnnxValueType.ONNX_TYPE_OPTIONAL)
			{
				nodeMetadata = metadata.AsOptionalMetadata().ElementMeta;
			}
			if (namedOnnxValue.ValueType != nodeMetadata.OnnxValueType)
			{
				throw new OnnxRuntimeException(ErrorCode.RuntimeException, $"NamedOnnxValue: {namedOnnxValue.Name} has value type: {namedOnnxValue.ValueType}" + $" expected: {nodeMetadata.OnnxValueType} after optional type adjustment");
			}
			return namedOnnxValue.ValueType switch
			{
				OnnxValueType.ONNX_TYPE_TENSOR => CreateTensorProjection(namedOnnxValue, nodeMetadata), 
				OnnxValueType.ONNX_TYPE_SEQUENCE => CreateSequenceProjection(namedOnnxValue, nodeMetadata), 
				OnnxValueType.ONNX_TYPE_MAP => CreateMapProjection(namedOnnxValue, nodeMetadata), 
				_ => throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "ManagedTypeProjection can only project tensors, sequences, maps and optional types"), 
			};
		}

		private static OrtValue CreateSequenceProjection(NamedOnnxValue namedOnnxValue, NodeMetadata metadata)
		{
			NodeMetadata elementMeta = metadata.AsSequenceMetadata().ElementMeta;
			OnnxValueType onnxValueType = elementMeta.OnnxValueType;
			IEnumerable<NamedOnnxValue> enumerable = namedOnnxValue.AsEnumerable<NamedOnnxValue>() ?? throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "NamedOnnxValue: " + namedOnnxValue.Name + " sequence does not contain NamedOnnxValue elements");
			int count = 0;
			if (enumerable is ICollection<NamedOnnxValue> collection)
			{
				count = collection.Count;
			}
			DisposableList<OrtValue> compositeMembers = new DisposableList<OrtValue>(count);
			try
			{
				foreach (NamedOnnxValue item in enumerable)
				{
					if (onnxValueType != item.ValueType)
					{
						throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"NamedOnnxValue: {namedOnnxValue.Name} sequence element expected to be {onnxValueType}, received {item.ValueType}");
					}
					compositeMembers.Add(CreateProjection(item, elementMeta));
				}
				return OrtValue.CreateSequence(ref compositeMembers);
			}
			catch (Exception)
			{
				compositeMembers?.Dispose();
				throw;
			}
		}

		private static OrtValue CreateMapProjection(NamedOnnxValue node, NodeMetadata elementMeta)
		{
			MapMetadata mapMetadata = elementMeta.AsMapMetadata();
			NodeMetadata valueMetadata = mapMetadata.ValueMetadata;
			if (valueMetadata.OnnxValueType != OnnxValueType.ONNX_TYPE_TENSOR)
			{
				throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Node: " + node.Name + " onnxruntime only supports maps with primitive types values");
			}
			Span<OrtValue> disposables = new OrtValue[2];
			DisposableArray<OrtValue> disposableArray = new DisposableArray<OrtValue>(disposables);
			try
			{
				TensorBase dictionaryKeys = node.GetDictionaryKeys();
				disposables[0] = OrtValue.CreateFromTensorObject(dictionaryKeys, out var elementType);
				if (elementType != mapMetadata.KeyDataType)
				{
					throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Map key data type supplied: {elementType} metadata expected: {mapMetadata.KeyDataType}");
				}
				TensorBase dictionaryValues = node.GetDictionaryValues();
				disposables[1] = OrtValue.CreateFromTensorObject(dictionaryValues, out var elementType2);
				if (elementType2 != valueMetadata.ElementDataType)
				{
					throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Map value data type supplied: {elementType2} metadata expected: {valueMetadata.ElementDataType}");
				}
				return OrtValue.CreateMap(ref disposables[0], ref disposables[1]);
			}
			catch (Exception)
			{
				disposableArray.Dispose();
				throw;
			}
		}

		private static OrtValue CreateTensorProjection(NamedOnnxValue node, NodeMetadata elementMeta)
		{
			if (!(node.Value is TensorBase))
			{
				throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"NamedOnnxValue contains: {node.Value.GetType()}, expecting a Tensor<T>");
			}
			TensorElementType elementType;
			OrtValue ortValue = OrtValue.CreateFromTensorObject(node.Value as TensorBase, out elementType);
			try
			{
				if (elementType != elementMeta.ElementDataType)
				{
					throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Tensor element data type discovered: {elementType} metadata expected: {elementMeta.ElementDataType}");
				}
				return ortValue;
			}
			catch (Exception)
			{
				ortValue.Dispose();
				throw;
			}
		}
	}
	internal class MapHelper
	{
		internal TensorBase Keys { get; }

		internal TensorBase Values { get; }

		internal MapHelper(TensorBase keys, TensorBase values)
		{
			Keys = keys;
			Values = values;
		}
	}
	public class NamedOnnxValue
	{
		private object _value;

		private string _name;

		private MapHelper _mapHelper;

		public OnnxValueType ValueType { get; internal set; }

		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				_name = value;
			}
		}

		public object Value
		{
			get
			{
				return _value;
			}
			set
			{
				_value = value;
			}
		}

		[Obsolete("Use constructors with valueType or static factory methods")]
		protected NamedOnnxValue(string name, object value)
		{
			_name = name;
			_value = value;
			ValueType = OnnxValueType.ONNX_TYPE_UNKNOWN;
		}

		internal NamedOnnxValue(string name, object value, OnnxValueType valueType)
		{
			_name = name;
			_value = value;
			ValueType = valueType;
			if (valueType == OnnxValueType.ONNX_TYPE_MAP)
			{
				throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Use another __ctor for maps");
			}
		}

		internal NamedOnnxValue(string name, object value, MapHelper helper)
		{
			_name = name;
			_value = value;
			ValueType = OnnxValueType.ONNX_TYPE_MAP;
			_mapHelper = helper;
		}

		public static NamedOnnxValue CreateFromTensor<T>(string name, Tensor<T> value)
		{
			return new NamedOnnxValue(name, value, OnnxValueType.ONNX_TYPE_TENSOR);
		}

		public static NamedOnnxValue CreateFromSequence<T>(string name, IEnumerable<T> value)
		{
			return new NamedOnnxValue(name, value, OnnxValueType.ONNX_TYPE_SEQUENCE);
		}

		public static NamedOnnxValue CreateFromMap<K, V>(string name, IDictionary<K, V> value)
		{
			return CreateFromMap(name, value.Keys, value.Values);
		}

		internal static NamedOnnxValue CreateFromMap<K, V>(string name, ICollection<K> keys, ICollection<V> values)
		{
			DenseTensor<K> keys2 = new DenseTensor<K>(keys.ToArray(), new int[1] { keys.Count });
			DenseTensor<V> values2 = new DenseTensor<V>(values.ToArray(), new int[1] { values.Count });
			return new NamedOnnxValue(name, values, new MapHelper(keys2, values2));
		}

		public Tensor<T> AsTensor<T>()
		{
			return _value as Tensor<T>;
		}

		public IEnumerable<T> AsEnumerable<T>()
		{
			return _value as IEnumerable<T>;
		}

		public IDictionary<K, V> AsDictionary<K, V>()
		{
			return _value as IDictionary<K, V>;
		}

		internal virtual IntPtr InputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryOwner)
		{
			return ((OrtValue)(memoryOwner = ManagedTypeProjection.CreateProjection(this, metadata))).Handle;
		}

		internal virtual IntPtr OutputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryOwner)
		{
			if (metadata.OnnxValueType == OnnxValueType.ONNX_TYPE_TENSOR)
			{
				return ((OrtValue)(memoryOwner = ManagedTypeProjection.CreateProjection(this, metadata))).Handle;
			}
			if (metadata.OnnxValueType == OnnxValueType.ONNX_TYPE_OPTIONAL && metadata.AsOptionalMetadata().ElementMeta.OnnxValueType == OnnxValueType.ONNX_TYPE_TENSOR)
			{
				return ((OrtValue)(memoryOwner = ManagedTypeProjection.CreateProjection(this, metadata))).Handle;
			}
			throw new OnnxRuntimeException(ErrorCode.NotImplemented, $"Can not create output OrtValue for NamedOnnxValue '{metadata.OnnxValueType}' type." + " Only tensors can be pre-allocated for outputs  Use Run() overloads that return DisposableNamedOnnxValue to get access to all Onnx value types that may be returned as output.");
		}

		internal TensorBase GetDictionaryKeys()
		{
			if (ValueType != OnnxValueType.ONNX_TYPE_MAP)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "This NamedOnnxValue instance does not contain a dictionary");
			}
			return _mapHelper.Keys;
		}

		internal TensorBase GetDictionaryValues()
		{
			if (ValueType != OnnxValueType.ONNX_TYPE_MAP)
			{
				throw new OnnxRuntimeException(ErrorCode.Fail, "This NamedOnnxValue instance does not contain a dictionary");
			}
			return _mapHelper.Values;
		}
	}
	internal class NativeApiStatus
	{
		private static string GetErrorMessage(IntPtr status)
		{
			return NativeOnnxValueHelper.StringFromNativeUtf8(NativeMethods.OrtGetErrorMessage(status));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void VerifySuccess(IntPtr nativeStatus)
		{
			if (nativeStatus != IntPtr.Zero)
			{
				try
				{
					ErrorCode errorCode = NativeMethods.OrtGetErrorCode(nativeStatus);
					string errorMessage = GetErrorMessage(nativeStatus);
					throw new OnnxRuntimeException(errorCode, errorMessage);
				}
				finally
				{
					NativeMethods.OrtReleaseStatus(nativeStatus);
				}
			}
		}
	}
	[StructLayout(LayoutKind.Sequential)]
	public class OrtApiBase
	{
		public IntPtr GetApi;

		public IntPtr GetVersionString;
	}
	[StructLayout(LayoutKind.Sequential)]
	public class OrtApi
	{
		public IntPtr CreateStatus;

		public IntPtr GetErrorCode;

		public IntPtr GetErrorMessage;

		public IntPtr CreateEnv;

		public IntPtr CreateEnvWithCustomLogger;

		public IntPtr EnableTelemetryEvents;

		public IntPtr DisableTelemetryEvents;

		public IntPtr CreateSession;

		public IntPtr CreateSessionFromArray;

		public IntPtr Run;

		public IntPtr CreateSessionOptions;

		public IntPtr SetOptimizedModelFilePath;

		public IntPtr CloneSessionOptions;

		public IntPtr SetSessionExecutionMode;

		public IntPtr EnableProfiling;

		public IntPtr DisableProfiling;

		public IntPtr EnableMemPattern;

		public IntPtr DisableMemPattern;

		public IntPtr EnableCpuMemArena;

		public IntPtr DisableCpuMemArena;

		public IntPtr SetSessionLogId;

		public IntPtr SetSessionLogVerbosityLevel;

		public IntPtr SetSessionLogSeverityLevel;

		public IntPtr SetSessionGraphOptimizationLevel;

		public IntPtr SetIntraOpNumThreads;

		public IntPtr SetInterOpNumThreads;

		public IntPtr CreateCustomOpDomain;

		public IntPtr CustomOpDomain_Add;

		public IntPtr AddCustomOpDomain;

		public IntPtr RegisterCustomOpsLibrary;

		public IntPtr SessionGetInputCount;

		public IntPtr SessionGetOutputCount;

		public IntPtr SessionGetOverridableInitializerCount;

		public IntPtr SessionGetInputTypeInfo;

		public IntPtr SessionGetOutputTypeInfo;

		public IntPtr SessionGetOverridableInitializerTypeInfo;

		public IntPtr SessionGetInputName;

		public IntPtr SessionGetOutputName;

		public IntPtr SessionGetOverridableInitializerName;

		public IntPtr CreateRunOptions;

		public IntPtr RunOptionsSetRunLogVerbosityLevel;

		public IntPtr RunOptionsSetRunLogSeverityLevel;

		public IntPtr RunOptionsSetRunTag;

		public IntPtr RunOptionsGetRunLogVerbosityLevel;

		public IntPtr RunOptionsGetRunLogSeverityLevel;

		public IntPtr RunOptionsGetRunTag;

		public IntPtr RunOptionsSetTerminate;

		public IntPtr RunOptionsUnsetTerminate;

		public IntPtr CreateTensorAsOrtValue;

		public IntPtr CreateTensorWithDataAsOrtValue;

		public IntPtr IsTensor;

		public IntPtr GetTensorMutableData;

		public IntPtr FillStringTensor;

		public IntPtr GetStringTensorDataLength;

		public IntPtr GetStringTensorContent;

		public IntPtr CastTypeInfoToTensorInfo;

		public IntPtr GetOnnxTypeFromTypeInfo;

		public IntPtr CreateTensorTypeAndShapeInfo;

		public IntPtr SetTensorElementType;

		public IntPtr SetDimensions;

		public IntPtr GetTensorElementType;

		public IntPtr GetDimensionsCount;

		public IntPtr GetDimensions;

		public IntPtr GetSymbolicDimensions;

		public IntPtr GetTensorShapeElementCount;

		public IntPtr GetTensorTypeAndShape;

		public IntPtr GetTypeInfo;

		public IntPtr GetValueType;

		public IntPtr CreateMemoryInfo;

		public IntPtr CreateCpuMemoryInfo;

		public IntPtr CompareMemoryInfo;

		public IntPtr MemoryInfoGetName;

		public IntPtr MemoryInfoGetId;

		public IntPtr MemoryInfoGetMemType;

		public IntPtr MemoryInfoGetType;

		public IntPtr AllocatorAlloc;

		public IntPtr AllocatorFree;

		public IntPtr AllocatorGetInfo;

		public IntPtr GetAllocatorWithDefaultOptions;

		public IntPtr AddFreeDimensionOverride;

		public IntPtr GetValue;

		public IntPtr GetValueCount;

		public IntPtr CreateValue;

		public IntPtr CreateOpaqueValue;

		public IntPtr GetOpaqueValue;

		public IntPtr KernelInfoGetAttribute_float;

		public IntPtr KernelInfoGetAttribute_int64;

		public IntPtr KernelInfoGetAttribute_string;

		public IntPtr KernelContext_GetInputCount;

		public IntPtr KernelContext_GetOutputCount;

		public IntPtr KernelContext_GetInput;

		public IntPtr KernelContext_GetOutput;

		public IntPtr ReleaseEnv;

		public IntPtr ReleaseStatus;

		public IntPtr ReleaseMemoryInfo;

		public IntPtr ReleaseSession;

		public IntPtr ReleaseValue;

		public IntPtr ReleaseRunOptions;

		public IntPtr ReleaseTypeInfo;

		public IntPtr ReleaseTensorTypeAndShapeInfo;

		public IntPtr ReleaseSessionOptions;

		public IntPtr ReleaseCustomOpDomain;

		public IntPtr GetDenotationFromTypeInfo;

		public IntPtr CastTypeInfoToMapTypeInfo;

		public IntPtr CastTypeInfoToSequenceTypeInfo;

		public IntPtr GetMapKeyType;

		public IntPtr GetMapValueType;

		public IntPtr GetSequenceElementType;

		public IntPtr ReleaseMapTypeInfo;

		public IntPtr ReleaseSequenceTypeInfo;

		public IntPtr SessionEndProfiling;

		public IntPtr SessionGetModelMetadata;

		public IntPtr ModelMetadataGetProducerName;

		public IntPtr ModelMetadataGetGraphName;

		public IntPtr ModelMetadataGetDomain;

		public IntPtr ModelMetadataGetDescription;

		public IntPtr ModelMetadataLookupCustomMetadataMap;

		public IntPtr ModelMetadataGetVersion;

		public IntPtr ReleaseModelMetadata;

		public IntPtr CreateEnvWithGlobalThreadPools;

		public IntPtr DisablePerSessionThreads;

		public IntPtr CreateThreadingOptions;

		public IntPtr ReleaseThreadingOptions;

		public IntPtr ModelMetadataGetCustomMetadataMapKeys;

		public IntPtr AddFreeDimensionOverrideByName;

		public IntPtr GetAvailableProviders;

		public IntPtr ReleaseAvailableProviders;

		public IntPtr GetStringTensorElementLength;

		public IntPtr GetStringTensorElement;

		public IntPtr FillStringTensorElement;

		public IntPtr AddSessionConfigEntry;

		public IntPtr CreateAllocator;

		public IntPtr ReleaseAllocator;

		public IntPtr RunWithBinding;

		public IntPtr CreateIoBinding;

		public IntPtr ReleaseIoBinding;

		public IntPtr BindInput;

		public IntPtr BindOutput;

		public IntPtr BindOutputToDevice;

		public IntPtr GetBoundOutputNames;

		public IntPtr GetBoundOutputValues;

		public IntPtr ClearBoundInputs;

		public IntPtr ClearBoundOutputs;

		public IntPtr TensorAt;

		public IntPtr CreateAndRegisterAllocator;

		public IntPtr SetLanguageProjection;

		public IntPtr SessionGetProfilingStartTimeNs;

		public IntPtr SetGlobalIntraOpNumThreads;

		public IntPtr SetGlobalInterOpNumThreads;

		public IntPtr SetGlobalSpinControl;

		public IntPtr AddInitializer;

		public IntPtr CreateEnvWithCustomLoggerAndGlobalThreadPools;

		public IntPtr SessionOptionsAppendExecutionProvider_CUDA;

		public IntPtr SessionOptionsAppendExecutionProvider_ROCM;

		public IntPtr SessionOptionsAppendExecutionProvider_OpenVINO;

		public IntPtr SetGlobalDenormalAsZero;

		public IntPtr CreateArenaCfg;

		public IntPtr ReleaseArenaCfg;

		public IntPtr ModelMetadataGetGraphDescription;

		public IntPtr SessionOptionsAppendExecutionProvider_TensorRT;

		public IntPtr SetCurrentGpuDeviceId;

		public IntPtr GetCurrentGpuDeviceId;

		public IntPtr KernelInfoGetAttributeArray_float;

		public IntPtr KernelInfoGetAttributeArray_int64;

		public IntPtr CreateArenaCfgV2;

		public IntPtr AddRunConfigEntry;

		public IntPtr CreatePrepackedWeightsContainer;

		public IntPtr ReleasePrepackedWeightsContainer;

		public IntPtr CreateSessionWithPrepackedWeightsContainer;

		public IntPtr CreateSessionFromArrayWithPrepackedWeightsContainer;

		public IntPtr SessionOptionsAppendExecutionProvider_TensorRT_V2;

		public IntPtr CreateTensorRTProviderOptions;

		public IntPtr UpdateTensorRTProviderOptions;

		public IntPtr GetTensorRTProviderOptionsAsString;

		public IntPtr ReleaseTensorRTProviderOptions;

		public IntPtr EnableOrtCustomOps;

		public IntPtr RegisterAllocator;

		public IntPtr UnregisterAllocator;

		public IntPtr IsSparseTensor;

		public IntPtr CreateSparseTensorAsOrtValue;

		public IntPtr FillSparseTensorCoo;

		public IntPtr FillSparseTensorCsr;

		public IntPtr FillSparseTensorBlockSparse;

		public IntPtr CreateSparseTensorWithValuesAsOrtValue;

		public IntPtr UseCooIndices;

		public IntPtr UseCsrIndices;

		public IntPtr UseBlockSparseIndices;

		public IntPtr GetSparseTensorFormat;

		public IntPtr GetSparseTensorValuesTypeAndShape;

		public IntPtr GetSparseTensorValues;

		public IntPtr GetSparseTensorIndicesTypeShape;

		public IntPtr GetSparseTensorIndices;

		public IntPtr HasValue;

		public IntPtr KernelContext_GetGPUComputeStream;

		public IntPtr GetTensorMemoryInfo;

		public IntPtr GetExecutionProviderApi;

		public IntPtr SessionOptionsSetCustomCreateThreadFn;

		public IntPtr SessionOptionsSetCustomThreadCreationOptions;

		public IntPtr SessionOptionsSetCustomJoinThreadFn;

		public IntPtr SetGlobalCustomCreateThreadFn;

		public IntPtr SetGlobalCustomThreadCreationOptions;

		public IntPtr SetGlobalCustomJoinThreadFn;

		public IntPtr SynchronizeBoundInputs;

		public IntPtr SynchronizeBoundOutputs;

		public IntPtr SessionOptionsAppendExecutionProvider_CUDA_V2;

		public IntPtr CreateCUDAProviderOptions;

		public IntPtr UpdateCUDAProviderOptions;

		public IntPtr GetCUDAProviderOptionsAsString;

		public IntPtr ReleaseCUDAProviderOptions;

		public IntPtr SessionOptionsAppendExecutionProvider_MIGraphX;

		public IntPtr AddExternalInitializers;

		public IntPtr CreateOpAttr;

		public IntPtr ReleaseOpAttr;

		public IntPtr CreateOp;

		public IntPtr InvokeOp;

		public IntPtr ReleaseOp;

		public IntPtr SessionOptionsAppendExecutionProvider;

		public IntPtr CopyKernelInfo;

		public IntPtr ReleaseKernelInfo;

		public IntPtr GetTrainingApi;

		public IntPtr SessionOptionsAppendExecutionProvider_CANN;

		public IntPtr CreateCANNProviderOptions;

		public IntPtr UpdateCANNProviderOptions;

		public IntPtr GetCANNProviderOptionsAsString;

		public IntPtr ReleaseCANNProviderOptions;

		public IntPtr MemoryInfoGetDeviceType;

		public IntPtr UpdateEnvWithCustomLogLevel;

		public IntPtr SetGlobalIntraOpThreadAffinity;

		public IntPtr RegisterCustomOpsLibrary_V2;

		public IntPtr RegisterCustomOpsUsingFunction;

		public IntPtr KernelInfo_GetInputCount;

		public IntPtr KernelInfo_GetOutputCount;

		public IntPtr KernelInfo_GetInputName;

		public IntPtr KernelInfo_GetOutputName;

		public IntPtr KernelInfo_GetInputTypeInfo;

		public IntPtr KernelInfo_GetOutputTypeInfo;

		public IntPtr KernelInfoGetAttribute_tensor;

		public IntPtr HasSessionConfigEntry;

		public IntPtr GetSessionConfigEntry;

		public IntPtr SessionOptionsAppendExecutionProvider_Dnnl;

		public IntPtr CreateDnnlProviderOptions;

		public IntPtr UpdateDnnlProviderOptions;

		public IntPtr GetDnnlProviderOptionsAsString;

		public IntPtr ReleaseDnnlProviderOptions;

		public IntPtr KernelInfo_GetNodeName;

		public IntPtr KernelInfo_GetLogger;

		public IntPtr KernelContext_GetLogger;

		public IntPtr Logger_LogMessage;

		public IntPtr Logger_GetLoggingSeverityLevel;

		public IntPtr KernelInfoGetConstantInput_tensor;

		public IntPtr CastTypeInfoToOptionalTypeInfo;

		public IntPtr GetOptionalContainedTypeInfo;

		public IntPtr GetResizedStringTensorElementBuffer;

		public IntPtr KernelContext_GetAllocator;

		public IntPtr GetBuildInfoString;

		public IntPtr CreateROCMProviderOptions;

		public IntPtr UpdateROCMProviderOptions;

		public IntPtr GetROCMProviderOptionsAsString;

		public IntPtr ReleaseROCMProviderOptions;

		public IntPtr CreateAndRegisterAllocatorV2;

		public IntPtr RunAsync;

		public IntPtr UpdateTensorRTProviderOptionsWithValue;

		public IntPtr GetTensorRTProviderOptionsByName;

		public IntPtr UpdateCUDAProviderOptionsWithValue;

		public IntPtr GetCUDAProviderOptionsByName;

		public IntPtr KernelContext_GetResource;

		public IntPtr SetUserLoggingFunction;

		public IntPtr ShapeInferContext_GetInputCount;

		public IntPtr ShapeInferContext_GetInputTypeShape;

		public IntPtr ShapeInferContext_GetAttribute;

		public IntPtr ShapeInferContext_SetOutputTypeShape;

		public IntPtr SetSymbolicDimensions;

		public IntPtr ReadOpAttr;

		public IntPtr SetDeterministicCompute;

		public IntPtr KernelContext_ParallelFor;

		public IntPtr SessionOptionsAppendExecutionProvider_OpenVINO_V2;

		public IntPtr SessionOptionsAppendExecutionProvider_VitisAI;

		public IntPtr KernelContext_GetScratchBuffer;

		public IntPtr KernelInfoGetAllocator;

		public IntPtr AddExternalInitializersFromFilesInMemory;

		public IntPtr CreateLoraAdapter;

		public IntPtr CreateLoraAdapterFromArray;

		public IntPtr ReleaseLoraAdapter;

		public IntPtr RunOptionsAddActiveLoraAdapter;

		public IntPtr SetEpDynamicOptions;

		public IntPtr ReleaseValueInfo;

		public IntPtr ReleaseNode;

		public IntPtr ReleaseGraph;

		public IntPtr ReleaseModel;

		public IntPtr GetValueInfoName;

		public IntPtr GetValueInfoTypeInfo;

		public IntPtr GetModelEditorApi;

		public IntPtr CreateTensorWithDataAndDeleterAsOrtValue;

		public IntPtr SessionOptionsSetLoadCancellationFlag;

		public IntPtr GetCompileApi;

		public IntPtr CreateKeyValuePairs;

		public IntPtr AddKeyValuePair;

		public IntPtr GetKeyValue;

		public IntPtr GetKeyValuePairs;

		public IntPtr RemoveKeyValuePair;

		public IntPtr ReleaseKeyValuePairs;

		public IntPtr RegisterExecutionProviderLibrary;

		public IntPtr UnregisterExecutionProviderLibrary;

		public IntPtr GetEpDevices;

		public IntPtr SessionOptionsAppendExecutionProvider_V2;

		public IntPtr SessionOptionsSetEpSelectionPolicy;

		public IntPtr SessionOptionsSetEpSelectionPolicyDelegate;

		public IntPtr HardwareDevice_Type;

		public IntPtr HardwareDevice_VendorId;

		public IntPtr HardwareDevice_Vendor;

		public IntPtr HardwareDevice_DeviceId;

		public IntPtr HardwareDevice_Metadata;

		public IntPtr EpDevice_EpName;

		public IntPtr EpDevice_EpVendor;

		public IntPtr EpDevice_EpMetadata;

		public IntPtr EpDevice_EpOptions;

		public IntPtr EpDevice_Device;

		public IntPtr GetEpApi;

		public IntPtr GetTensorSizeInBytes;

		public IntPtr AllocatorGetStats;

		public IntPtr CreateMemoryInfo_V2;

		public IntPtr MemoryInfoGetDeviceMemType;

		public IntPtr MemoryInfoGetVendorId;

		public IntPtr ValueInfo_GetValueProducer;

		public IntPtr ValueInfo_GetValueNumConsumers;

		public IntPtr ValueInfo_GetValueConsumers;

		public IntPtr ValueInfo_GetInitializerValue;

		public IntPtr ValueInfo_GetExternalInitializerInfo;

		public IntPtr ValueInfo_IsRequiredGraphInput;

		public IntPtr ValueInfo_IsOptionalGraphInput;

		public IntPtr ValueInfo_IsGraphOutput;

		public IntPtr ValueInfo_IsConstantInitializer;

		public IntPtr ValueInfo_IsFromOuterScope;

		public IntPtr Graph_GetName;

		public IntPtr Graph_GetModelPath;

		public IntPtr Graph_GetOnnxIRVersion;

		public IntPtr Graph_GetNumOperatorSets;

		public IntPtr Graph_GetOperatorSets;

		public IntPtr Graph_GetNumInputs;

		public IntPtr Graph_GetInputs;

		public IntPtr Graph_GetNumOutputs;

		public IntPtr Graph_GetOutputs;

		public IntPtr Graph_GetNumInitializers;

		public IntPtr Graph_GetInitializers;

		public IntPtr Graph_GetNumNodes;

		public IntPtr Graph_GetNodes;

		public IntPtr Graph_GetParentNode;

		public IntPtr Graph_GetGraphView;

		public IntPtr Node_GetId;

		public IntPtr Node_GetName;

		public IntPtr Node_GetOperatorType;

		public IntPtr Node_GetDomain;

		public IntPtr Node_GetSinceVersion;

		public IntPtr Node_GetNumInputs;

		public IntPtr Node_GetInputs;

		public IntPtr Node_GetNumOutputs;

		public IntPtr Node_GetOutputs;

		public IntPtr Node_GetNumImplicitInputs;

		public IntPtr Node_GetImplicitInputs;

		public IntPtr Node_GetNumAttributes;

		public IntPtr Node_GetAttributes;

		public IntPtr Node_GetAttributeByName;

		public IntPtr Node_GetTensorAttributeAsOrtValue;

		public IntPtr OpAttr_GetType;

		public IntPtr OpAttr_GetName;

		public IntPtr Node_GetNumSubgraphs;

		public IntPtr Node_GetSubgraphs;

		public IntPtr Node_GetGraph;

		public IntPtr Node_GetEpName;

		public IntPtr ReleaseExternalInitializerInfo;

		public IntPtr ExternalInitializerInfo_GetFilePath;

		public IntPtr ExternalInitializerInfo_GetFileOffset;

		public IntPtr ExternalInitializerInfo_GetByteSize;

		public IntPtr GetRunConfigEntry;

		public IntPtr EpDevice_MemoryInfo;

		public IntPtr CreateSharedAllocator;

		public IntPtr GetSharedAllocator;

		public IntPtr ReleaseSharedAllocator;

		public IntPtr GetTensorData;

		public IntPtr GetSessionOptionsConfigEntries;

		public IntPtr SessionGetMemoryInfoForInputs;

		public IntPtr SessionGetMemoryInfoForOutputs;

		public IntPtr SessionGetEpDeviceForInputs;

		public IntPtr CreateSyncStreamForEpDevice;

		public IntPtr SyncStream_GetHandle;

		public IntPtr ReleaseSyncStream;

		public IntPtr CopyTensors;

		public IntPtr Graph_GetModelMetadata;

		public IntPtr GetModelCompatibilityForEpDevices;

		public IntPtr CreateExternalInitializerInfo;
	}
	internal static class NativeMethods
	{
		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtGetApi(uint version);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtGetVersionString();

		internal class NativeLib
		{
			internal const string DllName = "onnxruntime";
		}

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtCreateEnv(OrtLoggingLevel defaultLoggingLevel, byte[] logId, out IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtCreateEnvWithCustomLogger(IntPtr loggingFunction, IntPtr loggerParam, OrtLoggingLevel defaultLoggingLevel, byte[] logId, out IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtCreateEnvWithGlobalThreadPools(OrtLoggingLevel defaultWarningLevel, byte[] logId, IntPtr threadingOptions, out IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtCreateEnvWithCustomLoggerAndGlobalThreadPools(IntPtr loggingFunction, IntPtr loggerParam, OrtLoggingLevel logSeverityLevel, byte[] logId, IntPtr threadingOptions, out IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate void DOrtReleaseEnv(IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtEnableTelemetryEvents(IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtDisableTelemetryEvents(IntPtr env);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtUpdateEnvWithCustomLogLevel(IntPtr env, OrtLoggingLevel custom_log_level);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DCreateAndRegisterAllocatorV2(IntPtr environment, IntPtr provderType, IntPtr memInfo, IntPtr arenaCfg, IntPtr[] providerOptionsKeys, IntPtr[] providerOptionsValues, UIntPtr numKeys);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtCreateSharedAllocator(IntPtr ortEnv, IntPtr epDevice, OrtDeviceMemoryType deviceMemoryType, OrtAllocatorType allocatorType, IntPtr allocatorOptions, out IntPtr allocator);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtGetSharedAllocator(IntPtr env, IntPtr memInfo, out IntPtr allocator);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtReleaseSharedAllocator(IntPtr env, IntPtr epDevice, OrtDeviceMemoryType deviceMemoryType);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		public delegate IntPtr DOrtCopyTensors(IntPtr env, IntPtr[] srcTensors, IntPtr[] dstTensors, IntPtr stream, UIntPtr numTensors);

		[UnmanagedFunctio

BepInEx/plugins/FaceSync/OpenCvSharp.dll

Decompiled a month ago
using System;
using System.Buffers;
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.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using OpenCvSharp.Aruco;
using OpenCvSharp.Detail;
using OpenCvSharp.Dnn;
using OpenCvSharp.Flann;
using OpenCvSharp.Internal;
using OpenCvSharp.Internal.Util;
using OpenCvSharp.Internal.Vectors;
using OpenCvSharp.ML;
using OpenCvSharp.Tracking;
using OpenCvSharp.XImgProc.Segmentation;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.LegacyBehavior)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OpenCvSharp")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("eb310923-197f-4e20-b123-3a3e7f1d5069")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+7088049f6bee1baa244661ba2353c36bef151896")]
[assembly: AssemblyTitle("OpenCvSharp")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/shimat/opencvsharp.git")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 OpenCvSharp
{
	public static class Cv2
	{
		public static class FishEye
		{
			public static void ProjectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, InputArray k, InputArray d, double alpha = 0.0, OutputArray? jacobian = null)
			{
				if (objectPoints == null)
				{
					throw new ArgumentNullException("objectPoints");
				}
				if (imagePoints == null)
				{
					throw new ArgumentNullException("imagePoints");
				}
				if (rvec == null)
				{
					throw new ArgumentNullException("rvec");
				}
				if (tvec == null)
				{
					throw new ArgumentNullException("tvec");
				}
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				objectPoints.ThrowIfDisposed();
				rvec.ThrowIfDisposed();
				tvec.ThrowIfDisposed();
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				jacobian?.ThrowIfNotReady();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_projectPoints2(objectPoints.CvPtr, imagePoints.CvPtr, rvec.CvPtr, tvec.CvPtr, k.CvPtr, d.CvPtr, alpha, ToPtr(jacobian)));
				GC.KeepAlive(objectPoints);
				GC.KeepAlive(rvec);
				GC.KeepAlive(tvec);
				GC.KeepAlive(k);
				GC.KeepAlive(d);
				GC.KeepAlive(imagePoints);
				GC.KeepAlive(jacobian);
			}

			public static void DistortPoints(InputArray undistorted, OutputArray distorted, InputArray k, InputArray d, double alpha = 0.0)
			{
				if (undistorted == null)
				{
					throw new ArgumentNullException("undistorted");
				}
				if (distorted == null)
				{
					throw new ArgumentNullException("distorted");
				}
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				undistorted.ThrowIfDisposed();
				distorted.ThrowIfNotReady();
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_distortPoints(undistorted.CvPtr, distorted.CvPtr, k.CvPtr, d.CvPtr, alpha));
				GC.KeepAlive(undistorted);
				GC.KeepAlive(distorted);
				GC.KeepAlive(k);
				GC.KeepAlive(d);
			}

			public static void UndistortPoints(InputArray distorted, OutputArray undistorted, InputArray k, InputArray d, InputArray? r = null, InputArray? p = null)
			{
				if (distorted == null)
				{
					throw new ArgumentNullException("distorted");
				}
				if (undistorted == null)
				{
					throw new ArgumentNullException("undistorted");
				}
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				distorted.ThrowIfDisposed();
				undistorted.ThrowIfNotReady();
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				r?.ThrowIfDisposed();
				p?.ThrowIfDisposed();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_undistortPoints(distorted.CvPtr, undistorted.CvPtr, k.CvPtr, d.CvPtr, ToPtr(r), ToPtr(p)));
				GC.KeepAlive(distorted);
				GC.KeepAlive(undistorted);
				GC.KeepAlive(k);
				GC.KeepAlive(d);
				GC.KeepAlive(r);
				GC.KeepAlive(p);
			}

			public static void InitUndistortRectifyMap(InputArray k, InputArray d, InputArray r, InputArray p, Size size, int m1type, OutputArray map1, OutputArray map2)
			{
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				if (r == null)
				{
					throw new ArgumentNullException("r");
				}
				if (p == null)
				{
					throw new ArgumentNullException("p");
				}
				if (map1 == null)
				{
					throw new ArgumentNullException("map1");
				}
				if (map2 == null)
				{
					throw new ArgumentNullException("map2");
				}
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				r.ThrowIfDisposed();
				p.ThrowIfDisposed();
				map1.ThrowIfNotReady();
				map2.ThrowIfNotReady();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_initUndistortRectifyMap(k.CvPtr, d.CvPtr, r.CvPtr, p.CvPtr, size, m1type, map1.CvPtr, map2.CvPtr));
				GC.KeepAlive(k);
				GC.KeepAlive(d);
				GC.KeepAlive(r);
				GC.KeepAlive(p);
				GC.KeepAlive(map1);
				GC.KeepAlive(map2);
			}

			public static void UndistortImage(InputArray distorted, OutputArray undistorted, InputArray k, InputArray d, InputArray? knew = null, Size newSize = default(Size))
			{
				if (distorted == null)
				{
					throw new ArgumentNullException("distorted");
				}
				if (undistorted == null)
				{
					throw new ArgumentNullException("undistorted");
				}
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				distorted.ThrowIfDisposed();
				undistorted.ThrowIfNotReady();
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				knew?.ThrowIfDisposed();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_undistortImage(distorted.CvPtr, undistorted.CvPtr, k.CvPtr, d.CvPtr, ToPtr(knew), newSize));
				GC.KeepAlive(distorted);
				GC.KeepAlive(undistorted);
				GC.KeepAlive(k);
				GC.KeepAlive(d);
				GC.KeepAlive(knew);
			}

			public static void EstimateNewCameraMatrixForUndistortRectify(InputArray k, InputArray d, Size imageSize, InputArray r, OutputArray p, double balance = 0.0, Size newSize = default(Size), double fovScale = 1.0)
			{
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				if (r == null)
				{
					throw new ArgumentNullException("r");
				}
				if (p == null)
				{
					throw new ArgumentNullException("p");
				}
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				r.ThrowIfDisposed();
				p.ThrowIfNotReady();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_estimateNewCameraMatrixForUndistortRectify(k.CvPtr, d.CvPtr, imageSize, r.CvPtr, p.CvPtr, balance, newSize, fovScale));
				GC.KeepAlive(k);
				GC.KeepAlive(d);
				GC.KeepAlive(r);
				GC.KeepAlive(p);
			}

			public static double Calibrate(IEnumerable<Mat> objectPoints, IEnumerable<Mat> imagePoints, Size imageSize, InputOutputArray k, InputOutputArray d, out IEnumerable<Mat> rvecs, out IEnumerable<Mat> tvecs, FishEyeCalibrationFlags flags = FishEyeCalibrationFlags.None, TermCriteria? criteria = null)
			{
				if (objectPoints == null)
				{
					throw new ArgumentNullException("objectPoints");
				}
				if (imagePoints == null)
				{
					throw new ArgumentNullException("imagePoints");
				}
				if (k == null)
				{
					throw new ArgumentNullException("k");
				}
				if (d == null)
				{
					throw new ArgumentNullException("d");
				}
				k.ThrowIfDisposed();
				d.ThrowIfDisposed();
				TermCriteria valueOrDefault = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 100, double.Epsilon));
				using VectorOfMat vectorOfMat = new VectorOfMat(objectPoints);
				using VectorOfMat vectorOfMat2 = new VectorOfMat(imagePoints);
				using VectorOfMat vectorOfMat3 = new VectorOfMat();
				using VectorOfMat vectorOfMat4 = new VectorOfMat();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_calibrate(vectorOfMat.CvPtr, vectorOfMat2.CvPtr, imageSize, k.CvPtr, d.CvPtr, vectorOfMat3.CvPtr, vectorOfMat4.CvPtr, (int)flags, valueOrDefault, out var returnValue));
				rvecs = vectorOfMat3.ToArray();
				tvecs = vectorOfMat4.ToArray();
				GC.KeepAlive(objectPoints);
				GC.KeepAlive(imagePoints);
				GC.KeepAlive(k);
				GC.KeepAlive(d);
				return returnValue;
			}

			public static void StereoRectify(InputArray k1, InputArray d1, InputArray k2, InputArray d2, Size imageSize, InputArray r, InputArray tvec, OutputArray r1, OutputArray r2, OutputArray p1, OutputArray p2, OutputArray q, FishEyeCalibrationFlags flags, Size newImageSize = default(Size), double balance = 0.0, double fovScale = 1.0)
			{
				if (k1 == null)
				{
					throw new ArgumentNullException("k1");
				}
				if (d1 == null)
				{
					throw new ArgumentNullException("d1");
				}
				if (k2 == null)
				{
					throw new ArgumentNullException("k2");
				}
				if (d2 == null)
				{
					throw new ArgumentNullException("d2");
				}
				if (r == null)
				{
					throw new ArgumentNullException("r");
				}
				if (tvec == null)
				{
					throw new ArgumentNullException("tvec");
				}
				if (r1 == null)
				{
					throw new ArgumentNullException("r1");
				}
				if (r2 == null)
				{
					throw new ArgumentNullException("r2");
				}
				if (p1 == null)
				{
					throw new ArgumentNullException("p1");
				}
				if (p2 == null)
				{
					throw new ArgumentNullException("p2");
				}
				if (q == null)
				{
					throw new ArgumentNullException("q");
				}
				k1.ThrowIfDisposed();
				d1.ThrowIfDisposed();
				k2.ThrowIfDisposed();
				d2.ThrowIfDisposed();
				r.ThrowIfDisposed();
				tvec.ThrowIfDisposed();
				r1.ThrowIfNotReady();
				r2.ThrowIfNotReady();
				p1.ThrowIfNotReady();
				p2.ThrowIfNotReady();
				q.ThrowIfNotReady();
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_stereoRectify(k1.CvPtr, d1.CvPtr, k2.CvPtr, d2.CvPtr, imageSize, r.CvPtr, tvec.CvPtr, r1.CvPtr, r2.CvPtr, p1.CvPtr, p2.CvPtr, q.CvPtr, (int)flags, newImageSize, balance, fovScale));
				GC.KeepAlive(k1);
				GC.KeepAlive(d1);
				GC.KeepAlive(k2);
				GC.KeepAlive(d2);
				GC.KeepAlive(r);
				GC.KeepAlive(tvec);
				GC.KeepAlive(r1);
				GC.KeepAlive(r2);
				GC.KeepAlive(p1);
				GC.KeepAlive(p2);
				GC.KeepAlive(q);
			}

			public static double StereoCalibrate(IEnumerable<Mat> objectPoints, IEnumerable<Mat> imagePoints1, IEnumerable<Mat> imagePoints2, InputOutputArray k1, InputOutputArray d1, InputOutputArray k2, InputOutputArray d2, Size imageSize, OutputArray r, OutputArray t, FishEyeCalibrationFlags flags = FishEyeCalibrationFlags.FixIntrinsic, TermCriteria? criteria = null)
			{
				if (objectPoints == null)
				{
					throw new ArgumentNullException("objectPoints");
				}
				if (imagePoints1 == null)
				{
					throw new ArgumentNullException("imagePoints1");
				}
				if (imagePoints2 == null)
				{
					throw new ArgumentNullException("imagePoints2");
				}
				if (k1 == null)
				{
					throw new ArgumentNullException("k1");
				}
				if (d1 == null)
				{
					throw new ArgumentNullException("d1");
				}
				if (k2 == null)
				{
					throw new ArgumentNullException("k2");
				}
				if (d2 == null)
				{
					throw new ArgumentNullException("d2");
				}
				if (r == null)
				{
					throw new ArgumentNullException("r");
				}
				if (t == null)
				{
					throw new ArgumentNullException("t");
				}
				k1.ThrowIfNotReady();
				d1.ThrowIfNotReady();
				k2.ThrowIfNotReady();
				d2.ThrowIfNotReady();
				r.ThrowIfNotReady();
				t.ThrowIfNotReady();
				TermCriteria valueOrDefault = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 100, double.Epsilon));
				using VectorOfMat vectorOfMat = new VectorOfMat(objectPoints);
				using VectorOfMat vectorOfMat2 = new VectorOfMat(imagePoints1);
				using VectorOfMat vectorOfMat3 = new VectorOfMat(imagePoints2);
				NativeMethods.HandleException(NativeMethods.calib3d_fisheye_stereoCalibrate(vectorOfMat.CvPtr, vectorOfMat2.CvPtr, vectorOfMat3.CvPtr, k1.CvPtr, d1.CvPtr, k2.CvPtr, d2.CvPtr, imageSize, r.CvPtr, t.CvPtr, (int)flags, valueOrDefault, out var returnValue));
				GC.KeepAlive(objectPoints);
				GC.KeepAlive(imagePoints1);
				GC.KeepAlive(imagePoints2);
				GC.KeepAlive(k1);
				GC.KeepAlive(d1);
				GC.KeepAlive(k2);
				GC.KeepAlive(d2);
				GC.KeepAlive(r);
				GC.KeepAlive(t);
				return returnValue;
			}
		}

		public delegate bool PartitionPredicate<in T>(T t1, T t2);

		public const double PI = Math.PI;

		public const double LOG2 = 0.6931471805599453;

		public const int FILLED = -1;

		internal static IntPtr ToPtr(ICvPtrHolder? obj)
		{
			return obj?.CvPtr ?? IntPtr.Zero;
		}

		public static void Rodrigues(InputArray src, OutputArray dst, OutputArray? jacobian = null)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (dst == null)
			{
				throw new ArgumentNullException("dst");
			}
			src.ThrowIfDisposed();
			dst.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_Rodrigues(src.CvPtr, dst.CvPtr, ToPtr(jacobian)));
			GC.KeepAlive(src);
			GC.KeepAlive(dst);
			GC.KeepAlive(jacobian);
			dst.Fix();
			jacobian?.Fix();
		}

		public static void Rodrigues(double[] vector, out double[,] matrix, out double[,] jacobian)
		{
			if (vector == null)
			{
				throw new ArgumentNullException("vector");
			}
			if (vector.Length != 3)
			{
				throw new ArgumentException("Length != 3", "vector");
			}
			using Mat mat = Mat.FromPixelData(3, 1, MatType.CV_64FC1, vector, 0L);
			using Mat<double> mat2 = new Mat<double>();
			using Mat<double> mat3 = new Mat<double>();
			using InputArray src = InputArray.Create(mat);
			using OutputArray dst = OutputArray.Create(mat2);
			using OutputArray jacobian2 = OutputArray.Create(mat3);
			Rodrigues(src, dst, jacobian2);
			matrix = mat2.ToRectangularArray();
			jacobian = mat3.ToRectangularArray();
		}

		public static void Rodrigues(double[,] matrix, out double[] vector, out double[,] jacobian)
		{
			if (matrix == null)
			{
				throw new ArgumentNullException("matrix");
			}
			if (matrix.GetLength(0) != 3 || matrix.GetLength(1) != 3)
			{
				throw new ArgumentException("matrix must be double[3,3]");
			}
			using Mat mat = Mat.FromPixelData(3, 3, MatType.CV_64FC1, matrix, 0L);
			using Mat<double> mat2 = new Mat<double>();
			using Mat<double> mat3 = new Mat<double>();
			using InputArray src = InputArray.Create(mat);
			using OutputArray dst = OutputArray.Create(mat2);
			using OutputArray jacobian2 = OutputArray.Create(mat3);
			Rodrigues(src, dst, jacobian2);
			vector = mat2.ToArray();
			jacobian = mat3.ToRectangularArray();
		}

		public static Mat FindHomography(InputArray srcPoints, InputArray dstPoints, HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3.0, OutputArray? mask = null, int maxIters = 2000, double confidence = 0.995)
		{
			if (srcPoints == null)
			{
				throw new ArgumentNullException("srcPoints");
			}
			if (dstPoints == null)
			{
				throw new ArgumentNullException("dstPoints");
			}
			srcPoints.ThrowIfDisposed();
			dstPoints.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_findHomography_InputArray(srcPoints.CvPtr, dstPoints.CvPtr, (int)method, ransacReprojThreshold, ToPtr(mask), maxIters, confidence, out var returnValue));
			GC.KeepAlive(srcPoints);
			GC.KeepAlive(dstPoints);
			GC.KeepAlive(mask);
			mask?.Fix();
			return new Mat(returnValue);
		}

		public static Mat FindHomography(IEnumerable<Point2d> srcPoints, IEnumerable<Point2d> dstPoints, HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3.0, OutputArray? mask = null, int maxIters = 2000, double confidence = 0.995)
		{
			if (srcPoints == null)
			{
				throw new ArgumentNullException("srcPoints");
			}
			if (dstPoints == null)
			{
				throw new ArgumentNullException("dstPoints");
			}
			Point2d[] obj = (srcPoints as Point2d[]) ?? srcPoints.ToArray();
			Point2d[] array = (dstPoints as Point2d[]) ?? dstPoints.ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_findHomography_vector(obj, obj.Length, array, array.Length, (int)method, ransacReprojThreshold, ToPtr(mask), maxIters, confidence, out var returnValue));
			GC.KeepAlive(mask);
			mask?.Fix();
			return new Mat(returnValue);
		}

		public static Mat FindHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask, UsacParams? @params)
		{
			if (srcPoints == null)
			{
				throw new ArgumentNullException("srcPoints");
			}
			if (dstPoints == null)
			{
				throw new ArgumentNullException("dstPoints");
			}
			if (mask == null)
			{
				throw new ArgumentNullException("mask");
			}
			srcPoints.ThrowIfDisposed();
			dstPoints.ThrowIfDisposed();
			mask.ThrowIfNotReady();
			WUsacParams params2 = (@params ?? new UsacParams()).ToNativeStruct();
			NativeMethods.HandleException(NativeMethods.calib3d_findHomography_UsacParams(srcPoints.CvPtr, dstPoints.CvPtr, ToPtr(mask), ref params2, out var returnValue));
			GC.KeepAlive(srcPoints);
			GC.KeepAlive(dstPoints);
			GC.KeepAlive(mask);
			mask.Fix();
			return new Mat(returnValue);
		}

		public static Vec3d RQDecomp3x3(InputArray src, OutputArray mtxR, OutputArray mtxQ, OutputArray? qx = null, OutputArray? qy = null, OutputArray? qz = null)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (mtxR == null)
			{
				throw new ArgumentNullException("mtxR");
			}
			if (mtxQ == null)
			{
				throw new ArgumentNullException("mtxQ");
			}
			src.ThrowIfDisposed();
			mtxR.ThrowIfNotReady();
			mtxQ.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_RQDecomp3x3_InputArray(src.CvPtr, mtxR.CvPtr, mtxQ.CvPtr, ToPtr(qx), ToPtr(qy), ToPtr(qz), out var outVal));
			GC.KeepAlive(src);
			GC.KeepAlive(mtxR);
			GC.KeepAlive(mtxQ);
			qx?.Fix();
			qy?.Fix();
			qz?.Fix();
			return outVal;
		}

		public static Vec3d RQDecomp3x3(double[,] src, out double[,] mtxR, out double[,] mtxQ)
		{
			double[,] qx;
			double[,] qy;
			double[,] qz;
			return RQDecomp3x3(src, out mtxR, out mtxQ, out qx, out qy, out qz);
		}

		public static Vec3d RQDecomp3x3(double[,] src, out double[,] mtxR, out double[,] mtxQ, out double[,] qx, out double[,] qy, out double[,] qz)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (src.GetLength(0) != 3 || src.GetLength(1) != 3)
			{
				throw new ArgumentException("src must be double[3,3]");
			}
			using Mat mat = Mat.FromPixelData(3, 3, MatType.CV_64FC1, src, 0L);
			using Mat<double> mat2 = new Mat<double>();
			using Mat<double> mat3 = new Mat<double>();
			using Mat<double> mat4 = new Mat<double>();
			using Mat<double> mat5 = new Mat<double>();
			using Mat<double> mat6 = new Mat<double>();
			NativeMethods.HandleException(NativeMethods.calib3d_RQDecomp3x3_Mat(mat.CvPtr, mat2.CvPtr, mat3.CvPtr, mat4.CvPtr, mat5.CvPtr, mat6.CvPtr, out var outVal));
			mtxR = mat2.ToRectangularArray();
			mtxQ = mat3.ToRectangularArray();
			qx = mat4.ToRectangularArray();
			qy = mat5.ToRectangularArray();
			qz = mat6.ToRectangularArray();
			return outVal;
		}

		public static void DecomposeProjectionMatrix(InputArray projMatrix, OutputArray cameraMatrix, OutputArray rotMatrix, OutputArray transVect, OutputArray? rotMatrixX = null, OutputArray? rotMatrixY = null, OutputArray? rotMatrixZ = null, OutputArray? eulerAngles = null)
		{
			if (projMatrix == null)
			{
				throw new ArgumentNullException("projMatrix");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (rotMatrix == null)
			{
				throw new ArgumentNullException("rotMatrix");
			}
			if (transVect == null)
			{
				throw new ArgumentNullException("transVect");
			}
			projMatrix.ThrowIfDisposed();
			cameraMatrix.ThrowIfNotReady();
			rotMatrix.ThrowIfNotReady();
			transVect.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_decomposeProjectionMatrix_InputArray(projMatrix.CvPtr, cameraMatrix.CvPtr, rotMatrix.CvPtr, transVect.CvPtr, ToPtr(rotMatrixX), ToPtr(rotMatrixY), ToPtr(rotMatrixZ), ToPtr(eulerAngles)));
			GC.KeepAlive(projMatrix);
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(rotMatrix);
			GC.KeepAlive(transVect);
			GC.KeepAlive(rotMatrixX);
			GC.KeepAlive(rotMatrixY);
			GC.KeepAlive(rotMatrixZ);
			GC.KeepAlive(eulerAngles);
			cameraMatrix.Fix();
			rotMatrix.Fix();
			transVect.Fix();
			rotMatrixX?.Fix();
			rotMatrixY?.Fix();
			rotMatrixZ?.Fix();
			eulerAngles?.Fix();
		}

		public static void DecomposeProjectionMatrix(double[,] projMatrix, out double[,] cameraMatrix, out double[,] rotMatrix, out double[] transVect, out double[,] rotMatrixX, out double[,] rotMatrixY, out double[,] rotMatrixZ, out double[] eulerAngles)
		{
			if (projMatrix == null)
			{
				throw new ArgumentNullException("projMatrix");
			}
			int length = projMatrix.GetLength(0);
			int length2 = projMatrix.GetLength(1);
			if ((length != 3 || length2 != 4) && (length != 4 || length2 != 3))
			{
				throw new ArgumentException("projMatrix must be double[3,4] or double[4,3]");
			}
			using Mat mat = Mat.FromPixelData(3, 4, MatType.CV_64FC1, projMatrix, 0L);
			using Mat<double> mat2 = new Mat<double>();
			using Mat<double> mat3 = new Mat<double>();
			using Mat<double> mat4 = new Mat<double>();
			using Mat<double> mat5 = new Mat<double>();
			using Mat<double> mat6 = new Mat<double>();
			using Mat<double> mat7 = new Mat<double>();
			using Mat<double> mat8 = new Mat<double>();
			NativeMethods.HandleException(NativeMethods.calib3d_decomposeProjectionMatrix_Mat(mat.CvPtr, mat2.CvPtr, mat3.CvPtr, mat4.CvPtr, mat5.CvPtr, mat6.CvPtr, mat7.CvPtr, mat8.CvPtr));
			cameraMatrix = mat2.ToRectangularArray();
			rotMatrix = mat3.ToRectangularArray();
			transVect = mat4.ToArray();
			rotMatrixX = mat5.ToRectangularArray();
			rotMatrixY = mat6.ToRectangularArray();
			rotMatrixZ = mat7.ToRectangularArray();
			eulerAngles = mat8.ToArray();
		}

		public static void DecomposeProjectionMatrix(double[,] projMatrix, out double[,] cameraMatrix, out double[,] rotMatrix, out double[] transVect)
		{
			DecomposeProjectionMatrix(projMatrix, out cameraMatrix, out rotMatrix, out transVect, out double[,] _, out double[,] _, out double[,] _, out double[] _);
		}

		public static void MatMulDeriv(InputArray a, InputArray b, OutputArray dABdA, OutputArray dABdB)
		{
			if (a == null)
			{
				throw new ArgumentNullException("a");
			}
			if (b == null)
			{
				throw new ArgumentNullException("b");
			}
			if (dABdA == null)
			{
				throw new ArgumentNullException("dABdA");
			}
			if (dABdB == null)
			{
				throw new ArgumentNullException("dABdB");
			}
			a.ThrowIfDisposed();
			b.ThrowIfDisposed();
			dABdA.ThrowIfNotReady();
			dABdB.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_matMulDeriv(a.CvPtr, b.CvPtr, dABdA.CvPtr, dABdB.CvPtr));
			GC.KeepAlive(a);
			GC.KeepAlive(b);
			dABdA.Fix();
			dABdB.Fix();
		}

		public static void ComposeRT(InputArray rvec1, InputArray tvec1, InputArray rvec2, InputArray tvec2, OutputArray rvec3, OutputArray tvec3, OutputArray? dr3dr1 = null, OutputArray? dr3dt1 = null, OutputArray? dr3dr2 = null, OutputArray? dr3dt2 = null, OutputArray? dt3dr1 = null, OutputArray? dt3dt1 = null, OutputArray? dt3dr2 = null, OutputArray? dt3dt2 = null)
		{
			if (rvec1 == null)
			{
				throw new ArgumentNullException("rvec1");
			}
			if (tvec1 == null)
			{
				throw new ArgumentNullException("tvec1");
			}
			if (rvec2 == null)
			{
				throw new ArgumentNullException("rvec2");
			}
			if (tvec2 == null)
			{
				throw new ArgumentNullException("tvec2");
			}
			if (rvec3 == null)
			{
				throw new ArgumentNullException("rvec3");
			}
			if (tvec3 == null)
			{
				throw new ArgumentNullException("tvec3");
			}
			rvec1.ThrowIfDisposed();
			tvec1.ThrowIfDisposed();
			rvec2.ThrowIfDisposed();
			tvec2.ThrowIfDisposed();
			rvec3.ThrowIfNotReady();
			tvec3.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_composeRT_InputArray(rvec1.CvPtr, tvec1.CvPtr, rvec2.CvPtr, tvec2.CvPtr, rvec3.CvPtr, tvec3.CvPtr, ToPtr(dr3dr1), ToPtr(dr3dt1), ToPtr(dr3dr2), ToPtr(dr3dt2), ToPtr(dt3dr1), ToPtr(dt3dt1), ToPtr(dt3dr2), ToPtr(dt3dt2)));
			GC.KeepAlive(rvec1);
			GC.KeepAlive(tvec1);
			GC.KeepAlive(rvec2);
			GC.KeepAlive(tvec2);
			GC.KeepAlive(rvec3);
			GC.KeepAlive(tvec3);
			GC.KeepAlive(dr3dr1);
			GC.KeepAlive(dr3dt1);
			GC.KeepAlive(dr3dr2);
			GC.KeepAlive(dr3dt2);
			GC.KeepAlive(dt3dr1);
			GC.KeepAlive(dt3dt1);
			GC.KeepAlive(dt3dr2);
			GC.KeepAlive(dt3dt2);
		}

		public static void ComposeRT(double[] rvec1, double[] tvec1, double[] rvec2, double[] tvec2, out double[] rvec3, out double[] tvec3, out double[,] dr3dr1, out double[,] dr3dt1, out double[,] dr3dr2, out double[,] dr3dt2, out double[,] dt3dr1, out double[,] dt3dt1, out double[,] dt3dr2, out double[,] dt3dt2)
		{
			if (rvec1 == null)
			{
				throw new ArgumentNullException("rvec1");
			}
			if (tvec1 == null)
			{
				throw new ArgumentNullException("tvec1");
			}
			if (rvec2 == null)
			{
				throw new ArgumentNullException("rvec2");
			}
			if (tvec2 == null)
			{
				throw new ArgumentNullException("tvec2");
			}
			using Mat mat = Mat.FromPixelData(3, 1, MatType.CV_64FC1, rvec1, 0L);
			using Mat mat2 = Mat.FromPixelData(3, 1, MatType.CV_64FC1, tvec1, 0L);
			using Mat mat3 = Mat.FromPixelData(3, 1, MatType.CV_64FC1, rvec2, 0L);
			using Mat mat4 = Mat.FromPixelData(3, 1, MatType.CV_64FC1, tvec2, 0L);
			using Mat<double> mat5 = new Mat<double>();
			using Mat<double> mat6 = new Mat<double>();
			using Mat<double> mat7 = new Mat<double>();
			using Mat<double> mat8 = new Mat<double>();
			using Mat<double> mat9 = new Mat<double>();
			using Mat<double> mat10 = new Mat<double>();
			using Mat<double> mat11 = new Mat<double>();
			using Mat<double> mat12 = new Mat<double>();
			using Mat<double> mat13 = new Mat<double>();
			using Mat<double> mat14 = new Mat<double>();
			NativeMethods.HandleException(NativeMethods.calib3d_composeRT_Mat(mat.CvPtr, mat2.CvPtr, mat3.CvPtr, mat4.CvPtr, mat5.CvPtr, mat6.CvPtr, mat7.CvPtr, mat8.CvPtr, mat9.CvPtr, mat10.CvPtr, mat11.CvPtr, mat12.CvPtr, mat13.CvPtr, mat14.CvPtr));
			rvec3 = mat5.ToArray();
			tvec3 = mat6.ToArray();
			dr3dr1 = mat7.ToRectangularArray();
			dr3dt1 = mat8.ToRectangularArray();
			dr3dr2 = mat9.ToRectangularArray();
			dr3dt2 = mat10.ToRectangularArray();
			dt3dr1 = mat11.ToRectangularArray();
			dt3dt1 = mat12.ToRectangularArray();
			dt3dr2 = mat13.ToRectangularArray();
			dt3dt2 = mat14.ToRectangularArray();
		}

		public static void ComposeRT(double[] rvec1, double[] tvec1, double[] rvec2, double[] tvec2, out double[] rvec3, out double[] tvec3)
		{
			ComposeRT(rvec1, tvec1, rvec2, tvec2, out rvec3, out tvec3, out double[,] _, out double[,] _, out double[,] _, out double[,] _, out double[,] _, out double[,] _, out double[,] _, out double[,] _);
		}

		public static void ProjectPoints(InputArray objectPoints, InputArray rvec, InputArray tvec, InputArray cameraMatrix, InputArray distCoeffs, OutputArray imagePoints, OutputArray? jacobian = null, double aspectRatio = 0.0)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (rvec == null)
			{
				throw new ArgumentNullException("rvec");
			}
			if (tvec == null)
			{
				throw new ArgumentNullException("tvec");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			objectPoints.ThrowIfDisposed();
			rvec.ThrowIfDisposed();
			tvec.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			imagePoints.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_projectPoints_InputArray(objectPoints.CvPtr, rvec.CvPtr, tvec.CvPtr, cameraMatrix.CvPtr, ToPtr(distCoeffs), imagePoints.CvPtr, ToPtr(jacobian), aspectRatio));
			GC.KeepAlive(objectPoints);
			GC.KeepAlive(rvec);
			GC.KeepAlive(tvec);
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(distCoeffs);
			GC.KeepAlive(imagePoints);
			GC.KeepAlive(jacobian);
		}

		public static void ProjectPoints(IEnumerable<Point3f> objectPoints, double[] rvec, double[] tvec, double[,] cameraMatrix, double[] distCoeffs, out Point2f[] imagePoints, out double[,] jacobian, double aspectRatio = 0.0)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (rvec == null)
			{
				throw new ArgumentNullException("rvec");
			}
			if (rvec.Length != 3)
			{
				throw new ArgumentException("rvec.Length != 3");
			}
			if (tvec == null)
			{
				throw new ArgumentNullException("tvec");
			}
			if (tvec.Length != 3)
			{
				throw new ArgumentException("tvec.Length != 3");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3)
			{
				throw new ArgumentException("cameraMatrix must be double[3,3]");
			}
			Point3f[] array = (objectPoints as Point3f[]) ?? objectPoints.ToArray();
			using Mat mat = Mat.FromPixelData(array.Length, 1, MatType.CV_32FC3, array, 0L);
			using Mat mat2 = Mat.FromPixelData(3, 1, MatType.CV_64FC1, rvec, 0L);
			using Mat mat3 = Mat.FromPixelData(3, 1, MatType.CV_64FC1, tvec, 0L);
			using Mat mat4 = Mat.FromPixelData(3, 3, MatType.CV_64FC1, cameraMatrix, 0L);
			using Mat mat5 = ((distCoeffs == null) ? new Mat() : Mat.FromPixelData(distCoeffs.Length, 1, MatType.CV_64FC1, distCoeffs, 0L));
			using Mat<Point2f> mat6 = new Mat<Point2f>();
			using Mat<double> mat7 = new Mat<double>();
			NativeMethods.HandleException(NativeMethods.calib3d_projectPoints_Mat(mat.CvPtr, mat2.CvPtr, mat3.CvPtr, mat4.CvPtr, mat5.CvPtr, mat6.CvPtr, mat7.CvPtr, aspectRatio));
			imagePoints = mat6.ToArray();
			jacobian = mat7.ToRectangularArray();
		}

		public static void SolvePnP(InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, SolvePnPFlags flags = SolvePnPFlags.Iterative)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (distCoeffs == null)
			{
				throw new ArgumentNullException("distCoeffs");
			}
			if (rvec == null)
			{
				throw new ArgumentNullException("rvec");
			}
			if (tvec == null)
			{
				throw new ArgumentNullException("tvec");
			}
			objectPoints.ThrowIfDisposed();
			imagePoints.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			distCoeffs.ThrowIfDisposed();
			rvec.ThrowIfDisposed();
			tvec.ThrowIfDisposed();
			IntPtr distCoeffs2 = ToPtr(distCoeffs);
			NativeMethods.HandleException(NativeMethods.calib3d_solvePnP_InputArray(objectPoints.CvPtr, imagePoints.CvPtr, cameraMatrix.CvPtr, distCoeffs2, rvec.CvPtr, tvec.CvPtr, useExtrinsicGuess ? 1 : 0, (int)flags));
			rvec.Fix();
			tvec.Fix();
			GC.KeepAlive(objectPoints);
			GC.KeepAlive(imagePoints);
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(distCoeffs);
		}

		public unsafe static void SolvePnP(IEnumerable<Point3f> objectPoints, IEnumerable<Point2f> imagePoints, double[,] cameraMatrix, IEnumerable<double>? distCoeffs, ref double[] rvec, ref double[] tvec, bool useExtrinsicGuess = false, SolvePnPFlags flags = SolvePnPFlags.Iterative)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3)
			{
				throw new ArgumentException("");
			}
			Point3f[] obj = (objectPoints as Point3f[]) ?? objectPoints.ToArray();
			Point2f[] array = (imagePoints as Point2f[]) ?? imagePoints.ToArray();
			double[] array2 = (distCoeffs as double[]) ?? distCoeffs?.ToArray();
			if (!useExtrinsicGuess)
			{
				rvec = new double[3];
				tvec = new double[3];
			}
			fixed (double* cameraMatrix2 = cameraMatrix)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_solvePnP_vector(obj, obj.Length, array, array.Length, cameraMatrix2, array2, (array2 != null) ? array2.Length : 0, rvec, tvec, useExtrinsicGuess ? 1 : 0, (int)flags));
			}
		}

		public static void SolvePnPRansac(InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray? rvec, OutputArray? tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8f, double confidence = 0.99, OutputArray? inliers = null, SolvePnPFlags flags = SolvePnPFlags.Iterative)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (distCoeffs == null)
			{
				throw new ArgumentNullException("distCoeffs");
			}
			if (rvec == null)
			{
				throw new ArgumentNullException("rvec");
			}
			if (tvec == null)
			{
				throw new ArgumentNullException("tvec");
			}
			objectPoints.ThrowIfDisposed();
			imagePoints.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			distCoeffs.ThrowIfDisposed();
			rvec.ThrowIfDisposed();
			tvec.ThrowIfDisposed();
			IntPtr distCoeffs2 = ToPtr(distCoeffs);
			NativeMethods.HandleException(NativeMethods.calib3d_solvePnPRansac_InputArray(objectPoints.CvPtr, imagePoints.CvPtr, cameraMatrix.CvPtr, distCoeffs2, rvec.CvPtr, tvec.CvPtr, useExtrinsicGuess ? 1 : 0, iterationsCount, reprojectionError, confidence, ToPtr(inliers), (int)flags));
			GC.KeepAlive(objectPoints);
			GC.KeepAlive(imagePoints);
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(distCoeffs);
			rvec.Fix();
			tvec.Fix();
			inliers?.Fix();
		}

		public static void SolvePnPRansac(IEnumerable<Point3f> objectPoints, IEnumerable<Point2f> imagePoints, double[,] cameraMatrix, IEnumerable<double> distCoeffs, out double[] rvec, out double[] tvec)
		{
			SolvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs, out rvec, out tvec, out int[] _);
		}

		public unsafe static void SolvePnPRansac(IEnumerable<Point3f> objectPoints, IEnumerable<Point2f> imagePoints, double[,] cameraMatrix, IEnumerable<double>? distCoeffs, out double[] rvec, out double[] tvec, out int[] inliers, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8f, double confidence = 0.99, SolvePnPFlags flags = SolvePnPFlags.Iterative)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3)
			{
				throw new ArgumentException("Size of cameraMatrix must be 3x3");
			}
			Point3f[] array = (objectPoints as Point3f[]) ?? objectPoints.ToArray();
			Point2f[] array2 = (imagePoints as Point2f[]) ?? imagePoints.ToArray();
			double[] array3 = (distCoeffs as double[]) ?? distCoeffs?.ToArray();
			rvec = new double[3];
			tvec = new double[3];
			using VectorOfInt32 vectorOfInt = new VectorOfInt32();
			fixed (double* cameraMatrix2 = cameraMatrix)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_solvePnPRansac_vector(array, array.Length, array2, array2.Length, cameraMatrix2, array3, (array3 != null) ? array3.Length : 0, rvec, tvec, useExtrinsicGuess ? 1 : 0, iterationsCount, reprojectionError, confidence, vectorOfInt.CvPtr, (int)flags));
				inliers = vectorOfInt.ToArray();
			}
		}

		public static Mat InitCameraMatrix2D(IEnumerable<Mat> objectPoints, IEnumerable<Mat> imagePoints, Size imageSize, double aspectRatio = 1.0)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			IntPtr[] array = objectPoints.Select((Mat x) => x.CvPtr).ToArray();
			IntPtr[] array2 = imagePoints.Select((Mat x) => x.CvPtr).ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_initCameraMatrix2D_Mat(array, array.Length, array2, array2.Length, imageSize, aspectRatio, out var returnValue));
			return new Mat(returnValue);
		}

		public static Mat InitCameraMatrix2D(IEnumerable<IEnumerable<Point3f>> objectPoints, IEnumerable<IEnumerable<Point2f>> imagePoints, Size imageSize, double aspectRatio = 1.0)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			using ArrayAddress2<Point3f> arrayAddress = new ArrayAddress2<Point3f>(objectPoints);
			using ArrayAddress2<Point2f> arrayAddress2 = new ArrayAddress2<Point2f>(imagePoints);
			NativeMethods.HandleException(NativeMethods.calib3d_initCameraMatrix2D_array(arrayAddress.GetPointer(), arrayAddress.GetDim1Length(), arrayAddress.GetDim2Lengths(), arrayAddress2.GetPointer(), arrayAddress2.GetDim1Length(), arrayAddress2.GetDim2Lengths(), imageSize, aspectRatio, out var returnValue));
			return new Mat(returnValue);
		}

		public static bool FindChessboardCorners(InputArray image, Size patternSize, OutputArray corners, ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			if (corners == null)
			{
				throw new ArgumentNullException("corners");
			}
			image.ThrowIfDisposed();
			corners.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_findChessboardCorners_InputArray(image.CvPtr, patternSize, corners.CvPtr, (int)flags, out var returnValue));
			GC.KeepAlive(image);
			corners.Fix();
			return returnValue != 0;
		}

		public static bool FindChessboardCorners(InputArray image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			image.ThrowIfDisposed();
			using VectorOfPoint2f vectorOfPoint2f = new VectorOfPoint2f();
			NativeMethods.HandleException(NativeMethods.calib3d_findChessboardCorners_vector(image.CvPtr, patternSize, vectorOfPoint2f.CvPtr, (int)flags, out var returnValue));
			GC.KeepAlive(image);
			corners = vectorOfPoint2f.ToArray();
			return returnValue != 0;
		}

		public static bool CheckChessboard(InputArray img, Size size)
		{
			if (img == null)
			{
				throw new ArgumentNullException("img");
			}
			img.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_checkChessboard(img.CvPtr, size, out var returnValue));
			GC.KeepAlive(img);
			return returnValue != 0;
		}

		public static bool FindChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners, ChessboardFlags flags = ChessboardFlags.None)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			if (corners == null)
			{
				throw new ArgumentNullException("corners");
			}
			image.ThrowIfDisposed();
			corners.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_findChessboardCornersSB_OutputArray(image.CvPtr, patternSize, corners.CvPtr, (int)flags, out var returnValue));
			GC.KeepAlive(image);
			GC.KeepAlive(corners);
			return returnValue != 0;
		}

		public static bool FindChessboardCornersSB(InputArray image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = ChessboardFlags.None)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			image.ThrowIfDisposed();
			using VectorOfPoint2f vectorOfPoint2f = new VectorOfPoint2f();
			NativeMethods.HandleException(NativeMethods.calib3d_findChessboardCornersSB_vector(image.CvPtr, patternSize, vectorOfPoint2f.CvPtr, (int)flags, out var returnValue));
			corners = vectorOfPoint2f.ToArray();
			GC.KeepAlive(image);
			return returnValue != 0;
		}

		public static bool Find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size regionSize)
		{
			if (img == null)
			{
				throw new ArgumentNullException("img");
			}
			if (corners == null)
			{
				throw new ArgumentNullException("corners");
			}
			img.ThrowIfDisposed();
			corners.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_find4QuadCornerSubpix_InputArray(img.CvPtr, corners.CvPtr, regionSize, out var returnValue));
			GC.KeepAlive(img);
			corners.Fix();
			return returnValue != 0;
		}

		public static bool Find4QuadCornerSubpix(InputArray img, Point2f[] corners, Size regionSize)
		{
			if (img == null)
			{
				throw new ArgumentNullException("img");
			}
			if (corners == null)
			{
				throw new ArgumentNullException("corners");
			}
			img.ThrowIfDisposed();
			using VectorOfPoint2f vectorOfPoint2f = new VectorOfPoint2f(corners);
			NativeMethods.HandleException(NativeMethods.calib3d_find4QuadCornerSubpix_vector(img.CvPtr, vectorOfPoint2f.CvPtr, regionSize, out var returnValue));
			GC.KeepAlive(img);
			Point2f[] array = vectorOfPoint2f.ToArray();
			for (int i = 0; i < corners.Length; i++)
			{
				corners[i] = array[i];
			}
			return returnValue != 0;
		}

		public static void DrawChessboardCorners(InputOutputArray image, Size patternSize, InputArray corners, bool patternWasFound)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			if (corners == null)
			{
				throw new ArgumentNullException("corners");
			}
			image.ThrowIfNotReady();
			corners.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_drawChessboardCorners_InputArray(image.CvPtr, patternSize, corners.CvPtr, patternWasFound ? 1 : 0));
			GC.KeepAlive(corners);
			image.Fix();
		}

		public static void DrawChessboardCorners(InputOutputArray image, Size patternSize, IEnumerable<Point2f> corners, bool patternWasFound)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			if (corners == null)
			{
				throw new ArgumentNullException("corners");
			}
			image.ThrowIfNotReady();
			Point2f[] array = (corners as Point2f[]) ?? corners.ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_drawChessboardCorners_array(image.CvPtr, patternSize, array, array.Length, patternWasFound ? 1 : 0));
			image.Fix();
		}

		public static void DrawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, InputArray rvec, InputArray tvec, float length, int thickness = 3)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (distCoeffs == null)
			{
				throw new ArgumentNullException("distCoeffs");
			}
			if (rvec == null)
			{
				throw new ArgumentNullException("rvec");
			}
			if (tvec == null)
			{
				throw new ArgumentNullException("tvec");
			}
			image.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			distCoeffs.ThrowIfDisposed();
			rvec.ThrowIfDisposed();
			tvec.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_drawFrameAxes(image.CvPtr, cameraMatrix.CvPtr, distCoeffs.CvPtr, rvec.CvPtr, tvec.CvPtr, length, thickness));
			GC.KeepAlive(image);
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(distCoeffs);
			GC.KeepAlive(rvec);
			GC.KeepAlive(tvec);
		}

		public static bool FindCirclesGrid(InputArray image, Size patternSize, OutputArray centers, FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, Feature2D? blobDetector = null)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			if (centers == null)
			{
				throw new ArgumentNullException("centers");
			}
			image.ThrowIfDisposed();
			centers.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_findCirclesGrid_InputArray(image.CvPtr, patternSize, centers.CvPtr, (int)flags, ToPtr(blobDetector), out var returnValue));
			GC.KeepAlive(image);
			GC.KeepAlive(centers);
			GC.KeepAlive(blobDetector);
			centers.Fix();
			return returnValue != 0;
		}

		public static bool FindCirclesGrid(InputArray image, Size patternSize, out Point2f[] centers, FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, Feature2D? blobDetector = null)
		{
			if (image == null)
			{
				throw new ArgumentNullException("image");
			}
			image.ThrowIfDisposed();
			using VectorOfPoint2f vectorOfPoint2f = new VectorOfPoint2f();
			NativeMethods.HandleException(NativeMethods.calib3d_findCirclesGrid_vector(image.CvPtr, patternSize, vectorOfPoint2f.CvPtr, (int)flags, ToPtr(blobDetector), out var returnValue));
			GC.KeepAlive(image);
			GC.KeepAlive(blobDetector);
			centers = vectorOfPoint2f.ToArray();
			return returnValue != 0;
		}

		public static double CalibrateCamera(IEnumerable<Mat> objectPoints, IEnumerable<Mat> imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, out Mat[] rvecs, out Mat[] tvecs, CalibrationFlags flags = CalibrationFlags.None, TermCriteria? criteria = null)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (distCoeffs == null)
			{
				throw new ArgumentNullException("distCoeffs");
			}
			cameraMatrix.ThrowIfNotReady();
			distCoeffs.ThrowIfNotReady();
			TermCriteria valueOrDefault = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 30, double.Epsilon));
			IntPtr[] array = objectPoints.Select((Mat x) => x.CvPtr).ToArray();
			IntPtr[] imagePoints2 = imagePoints.Select((Mat x) => x.CvPtr).ToArray();
			using VectorOfMat vectorOfMat = new VectorOfMat();
			using VectorOfMat vectorOfMat2 = new VectorOfMat();
			NativeMethods.HandleException(NativeMethods.calib3d_calibrateCamera_InputArray(array, array.Length, imagePoints2, array.Length, imageSize, cameraMatrix.CvPtr, distCoeffs.CvPtr, vectorOfMat.CvPtr, vectorOfMat2.CvPtr, (int)flags, valueOrDefault, out var returnValue));
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(distCoeffs);
			GC.KeepAlive(objectPoints);
			GC.KeepAlive(imagePoints);
			rvecs = vectorOfMat.ToArray();
			tvecs = vectorOfMat2.ToArray();
			cameraMatrix.Fix();
			distCoeffs.Fix();
			return returnValue;
		}

		public unsafe static double CalibrateCamera(IEnumerable<IEnumerable<Point3f>> objectPoints, IEnumerable<IEnumerable<Point2f>> imagePoints, Size imageSize, double[,] cameraMatrix, double[] distCoeffs, out Vec3d[] rvecs, out Vec3d[] tvecs, CalibrationFlags flags = CalibrationFlags.None, TermCriteria? criteria = null)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints == null)
			{
				throw new ArgumentNullException("imagePoints");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (distCoeffs == null)
			{
				throw new ArgumentNullException("distCoeffs");
			}
			TermCriteria valueOrDefault = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 30, double.Epsilon));
			using ArrayAddress2<Point3f> arrayAddress = new ArrayAddress2<Point3f>(objectPoints);
			using ArrayAddress2<Point2f> arrayAddress2 = new ArrayAddress2<Point2f>(imagePoints);
			using VectorOfMat vectorOfMat = new VectorOfMat();
			using VectorOfMat vectorOfMat2 = new VectorOfMat();
			fixed (double* cameraMatrix2 = cameraMatrix)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_calibrateCamera_vector(arrayAddress.GetPointer(), arrayAddress.GetDim1Length(), arrayAddress.GetDim2Lengths(), arrayAddress2.GetPointer(), arrayAddress2.GetDim1Length(), arrayAddress2.GetDim2Lengths(), imageSize, cameraMatrix2, distCoeffs, distCoeffs.Length, vectorOfMat.CvPtr, vectorOfMat2.CvPtr, (int)flags, valueOrDefault, out var returnValue));
				Mat[] source = vectorOfMat.ToArray();
				Mat[] source2 = vectorOfMat2.ToArray();
				rvecs = source.Select((Mat m) => m.Get<Vec3d>(0)).ToArray();
				tvecs = source2.Select((Mat m) => m.Get<Vec3d>(0)).ToArray();
				return returnValue;
			}
		}

		public static void CalibrationMatrixValues(InputArray cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, out double fovx, out double fovy, out double focalLength, out Point2d principalPoint, out double aspectRatio)
		{
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			cameraMatrix.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_calibrationMatrixValues_InputArray(cameraMatrix.CvPtr, imageSize, apertureWidth, apertureHeight, out fovx, out fovy, out focalLength, out principalPoint, out aspectRatio));
			GC.KeepAlive(cameraMatrix);
		}

		public unsafe static void CalibrationMatrixValues(double[,] cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, out double fovx, out double fovy, out double focalLength, out Point2d principalPoint, out double aspectRatio)
		{
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3)
			{
				throw new ArgumentException("cameraMatrix must be 3x3");
			}
			fixed (double* cameraMatrix2 = cameraMatrix)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_calibrationMatrixValues_array(cameraMatrix2, imageSize, apertureWidth, apertureHeight, out fovx, out fovy, out focalLength, out principalPoint, out aspectRatio));
			}
		}

		public static double StereoCalibrate(IEnumerable<InputArray> objectPoints, IEnumerable<InputArray> imagePoints1, IEnumerable<InputArray> imagePoints2, InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, Size imageSize, OutputArray R, OutputArray T, OutputArray E, OutputArray F, CalibrationFlags flags = CalibrationFlags.FixIntrinsic, TermCriteria? criteria = null)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints1 == null)
			{
				throw new ArgumentNullException("imagePoints1");
			}
			if (imagePoints2 == null)
			{
				throw new ArgumentNullException("imagePoints2");
			}
			if (cameraMatrix1 == null)
			{
				throw new ArgumentNullException("cameraMatrix1");
			}
			if (distCoeffs1 == null)
			{
				throw new ArgumentNullException("distCoeffs1");
			}
			if (cameraMatrix2 == null)
			{
				throw new ArgumentNullException("cameraMatrix2");
			}
			if (distCoeffs2 == null)
			{
				throw new ArgumentNullException("distCoeffs2");
			}
			cameraMatrix1.ThrowIfDisposed();
			distCoeffs1.ThrowIfDisposed();
			cameraMatrix2.ThrowIfDisposed();
			distCoeffs2.ThrowIfDisposed();
			cameraMatrix1.ThrowIfNotReady();
			cameraMatrix2.ThrowIfNotReady();
			distCoeffs1.ThrowIfNotReady();
			distCoeffs2.ThrowIfNotReady();
			IntPtr[] array = objectPoints.Select((InputArray x) => x.CvPtr).ToArray();
			IntPtr[] array2 = imagePoints1.Select((InputArray x) => x.CvPtr).ToArray();
			IntPtr[] array3 = imagePoints2.Select((InputArray x) => x.CvPtr).ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_stereoCalibrate_InputArray(criteria: criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 30, 1E-06)), objectPoints: array, opSize: array.Length, imagePoints1: array2, ip1Size: array2.Length, imagePoints2: array3, ip2Size: array3.Length, cameraMatrix1: cameraMatrix1.CvPtr, distCoeffs1: distCoeffs1.CvPtr, cameraMatrix2: cameraMatrix2.CvPtr, distCoeffs2: distCoeffs2.CvPtr, imageSize: imageSize, R: ToPtr(R), T: ToPtr(T), E: ToPtr(E), F: ToPtr(F), flags: (int)flags, returnValue: out var returnValue));
			GC.KeepAlive(cameraMatrix1);
			GC.KeepAlive(distCoeffs1);
			GC.KeepAlive(cameraMatrix2);
			GC.KeepAlive(distCoeffs2);
			GC.KeepAlive(R);
			GC.KeepAlive(T);
			GC.KeepAlive(E);
			GC.KeepAlive(F);
			GC.KeepAlive(objectPoints);
			GC.KeepAlive(imagePoints1);
			GC.KeepAlive(imagePoints2);
			cameraMatrix1.Fix();
			distCoeffs1.Fix();
			cameraMatrix2.Fix();
			distCoeffs2.Fix();
			R.Fix();
			T.Fix();
			E.Fix();
			F.Fix();
			return returnValue;
		}

		public unsafe static double StereoCalibrate(IEnumerable<IEnumerable<Point3f>> objectPoints, IEnumerable<IEnumerable<Point2f>> imagePoints1, IEnumerable<IEnumerable<Point2f>> imagePoints2, double[,] cameraMatrix1, double[] distCoeffs1, double[,] cameraMatrix2, double[] distCoeffs2, Size imageSize, OutputArray R, OutputArray T, OutputArray E, OutputArray F, CalibrationFlags flags = CalibrationFlags.FixIntrinsic, TermCriteria? criteria = null)
		{
			if (objectPoints == null)
			{
				throw new ArgumentNullException("objectPoints");
			}
			if (imagePoints1 == null)
			{
				throw new ArgumentNullException("imagePoints1");
			}
			if (imagePoints2 == null)
			{
				throw new ArgumentNullException("imagePoints2");
			}
			if (cameraMatrix1 == null)
			{
				throw new ArgumentNullException("cameraMatrix1");
			}
			if (distCoeffs1 == null)
			{
				throw new ArgumentNullException("distCoeffs1");
			}
			if (cameraMatrix2 == null)
			{
				throw new ArgumentNullException("cameraMatrix2");
			}
			if (distCoeffs2 == null)
			{
				throw new ArgumentNullException("distCoeffs2");
			}
			TermCriteria valueOrDefault = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 30, 1E-06));
			using ArrayAddress2<Point3f> arrayAddress = new ArrayAddress2<Point3f>(objectPoints);
			using ArrayAddress2<Point2f> arrayAddress2 = new ArrayAddress2<Point2f>(imagePoints1);
			using ArrayAddress2<Point2f> arrayAddress3 = new ArrayAddress2<Point2f>(imagePoints2);
			fixed (double* cameraMatrix3 = cameraMatrix1)
			{
				fixed (double* cameraMatrix4 = cameraMatrix2)
				{
					NativeMethods.HandleException(NativeMethods.calib3d_stereoCalibrate_array(arrayAddress.GetPointer(), arrayAddress.GetDim1Length(), arrayAddress.GetDim2Lengths(), arrayAddress2.GetPointer(), arrayAddress2.GetDim1Length(), arrayAddress2.GetDim2Lengths(), arrayAddress3.GetPointer(), arrayAddress3.GetDim1Length(), arrayAddress3.GetDim2Lengths(), cameraMatrix3, distCoeffs1, distCoeffs1.Length, cameraMatrix4, distCoeffs2, distCoeffs2.Length, imageSize, ToPtr(R), ToPtr(T), ToPtr(E), ToPtr(F), (int)flags, valueOrDefault, out var returnValue));
					GC.KeepAlive(R);
					GC.KeepAlive(T);
					GC.KeepAlive(E);
					GC.KeepAlive(F);
					return returnValue;
				}
			}
		}

		public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, Size imageSize, InputArray R, InputArray T, OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, StereoRectificationFlags flags = StereoRectificationFlags.ZeroDisparity, double alpha = -1.0, Size? newImageSize = null)
		{
			Size valueOrDefault = newImageSize.GetValueOrDefault(new Size(0, 0));
			StereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q, flags, alpha, valueOrDefault, out var _, out var _);
		}

		public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, Size imageSize, InputArray R, InputArray T, OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, StereoRectificationFlags flags, double alpha, Size newImageSize, out Rect validPixROI1, out Rect validPixROI2)
		{
			if (cameraMatrix1 == null)
			{
				throw new ArgumentNullException("cameraMatrix1");
			}
			if (distCoeffs1 == null)
			{
				throw new ArgumentNullException("distCoeffs1");
			}
			if (cameraMatrix2 == null)
			{
				throw new ArgumentNullException("cameraMatrix2");
			}
			if (distCoeffs2 == null)
			{
				throw new ArgumentNullException("distCoeffs2");
			}
			if (R == null)
			{
				throw new ArgumentNullException("R");
			}
			if (T == null)
			{
				throw new ArgumentNullException("T");
			}
			if (R1 == null)
			{
				throw new ArgumentNullException("R1");
			}
			if (R2 == null)
			{
				throw new ArgumentNullException("R2");
			}
			if (P1 == null)
			{
				throw new ArgumentNullException("P1");
			}
			if (P2 == null)
			{
				throw new ArgumentNullException("P2");
			}
			if (Q == null)
			{
				throw new ArgumentNullException("Q");
			}
			cameraMatrix1.ThrowIfDisposed();
			distCoeffs1.ThrowIfDisposed();
			cameraMatrix2.ThrowIfDisposed();
			distCoeffs2.ThrowIfDisposed();
			R.ThrowIfDisposed();
			T.ThrowIfDisposed();
			R1.ThrowIfNotReady();
			R2.ThrowIfNotReady();
			P1.ThrowIfNotReady();
			P2.ThrowIfNotReady();
			Q.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_stereoRectify_InputArray(cameraMatrix1.CvPtr, distCoeffs1.CvPtr, cameraMatrix2.CvPtr, distCoeffs2.CvPtr, imageSize, R.CvPtr, T.CvPtr, R1.CvPtr, R2.CvPtr, P1.CvPtr, P2.CvPtr, Q.CvPtr, (int)flags, alpha, newImageSize, out validPixROI1, out validPixROI2));
			GC.KeepAlive(cameraMatrix1);
			GC.KeepAlive(distCoeffs1);
			GC.KeepAlive(cameraMatrix2);
			GC.KeepAlive(distCoeffs2);
			GC.KeepAlive(R);
			GC.KeepAlive(T);
			GC.KeepAlive(R1);
			GC.KeepAlive(R2);
			GC.KeepAlive(P1);
			GC.KeepAlive(P2);
			GC.KeepAlive(Q);
			R1.Fix();
			R2.Fix();
			P1.Fix();
			P2.Fix();
			Q.Fix();
		}

		public static void StereoRectify(double[,] cameraMatrix1, double[] distCoeffs1, double[,] cameraMatrix2, double[] distCoeffs2, Size imageSize, double[,] R, double[] T, out double[,] R1, out double[,] R2, out double[,] P1, out double[,] P2, out double[,] Q, StereoRectificationFlags flags = StereoRectificationFlags.ZeroDisparity, double alpha = -1.0, Size? newImageSize = null)
		{
			Size valueOrDefault = newImageSize.GetValueOrDefault(new Size(0, 0));
			StereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, out R1, out R2, out P1, out P2, out Q, flags, alpha, valueOrDefault, out var _, out var _);
		}

		public unsafe static void StereoRectify(double[,] cameraMatrix1, double[] distCoeffs1, double[,] cameraMatrix2, double[] distCoeffs2, Size imageSize, double[,] R, double[] T, out double[,] R1, out double[,] R2, out double[,] P1, out double[,] P2, out double[,] Q, StereoRectificationFlags flags, double alpha, Size newImageSize, out Rect validPixROI1, out Rect validPixROI2)
		{
			if (cameraMatrix1 == null)
			{
				throw new ArgumentNullException("cameraMatrix1");
			}
			if (distCoeffs1 == null)
			{
				throw new ArgumentNullException("distCoeffs1");
			}
			if (cameraMatrix2 == null)
			{
				throw new ArgumentNullException("cameraMatrix2");
			}
			if (distCoeffs2 == null)
			{
				throw new ArgumentNullException("distCoeffs2");
			}
			if (R == null)
			{
				throw new ArgumentNullException("R");
			}
			if (T == null)
			{
				throw new ArgumentNullException("T");
			}
			R1 = new double[3, 3];
			R2 = new double[3, 3];
			P1 = new double[3, 4];
			P2 = new double[3, 4];
			Q = new double[4, 4];
			fixed (double* cameraMatrix3 = cameraMatrix1)
			{
				fixed (double* cameraMatrix4 = cameraMatrix2)
				{
					fixed (double* r = R)
					{
						fixed (double* r2 = R1)
						{
							fixed (double* r3 = R2)
							{
								fixed (double* p = P1)
								{
									fixed (double* p2 = P2)
									{
										fixed (double* q = Q)
										{
											NativeMethods.HandleException(NativeMethods.calib3d_stereoRectify_array(cameraMatrix3, distCoeffs1, distCoeffs1.Length, cameraMatrix4, distCoeffs2, distCoeffs2.Length, imageSize, r, T, r2, r3, p, p2, q, (int)flags, alpha, newImageSize, out validPixROI1, out validPixROI2));
										}
									}
								}
							}
						}
					}
				}
			}
		}

		public static bool StereoRectifyUncalibrated(InputArray points1, InputArray points2, InputArray F, Size imgSize, OutputArray H1, OutputArray H2, double threshold = 5.0)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (H1 == null)
			{
				throw new ArgumentNullException("H1");
			}
			if (H2 == null)
			{
				throw new ArgumentNullException("H2");
			}
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			F.ThrowIfDisposed();
			H1.ThrowIfNotReady();
			H2.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_stereoRectifyUncalibrated_InputArray(points1.CvPtr, points2.CvPtr, F.CvPtr, imgSize, H1.CvPtr, H2.CvPtr, threshold, out var returnValue));
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			GC.KeepAlive(F);
			GC.KeepAlive(H1);
			GC.KeepAlive(H2);
			H1.Fix();
			H2.Fix();
			return returnValue != 0;
		}

		public unsafe static bool StereoRectifyUncalibrated(IEnumerable<Point2d> points1, IEnumerable<Point2d> points2, double[,] F, Size imgSize, out double[,] H1, out double[,] H2, double threshold = 5.0)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (F.GetLength(0) != 3 || F.GetLength(1) != 3)
			{
				throw new ArgumentException("F != double[3,3]");
			}
			Point2d[] obj = (points1 as Point2d[]) ?? points1.ToArray();
			Point2d[] array = (points2 as Point2d[]) ?? points2.ToArray();
			H1 = new double[3, 3];
			H2 = new double[3, 3];
			fixed (double* f = F)
			{
				fixed (double* h = H1)
				{
					fixed (double* h2 = H1)
					{
						NativeMethods.HandleException(NativeMethods.calib3d_stereoRectifyUncalibrated_array(obj, obj.Length, array, array.Length, f, imgSize, h, h2, threshold, out var returnValue));
						return returnValue != 0;
					}
				}
			}
		}

		public static float Rectify3Collinear(InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, InputArray cameraMatrix3, InputArray distCoeffs3, IEnumerable<InputArray> imgpt1, IEnumerable<InputArray> imgpt3, Size imageSize, InputArray R12, InputArray T12, InputArray R13, InputArray T13, OutputArray R1, OutputArray R2, OutputArray R3, OutputArray P1, OutputArray P2, OutputArray P3, OutputArray Q, double alpha, Size newImgSize, out Rect roi1, out Rect roi2, StereoRectificationFlags flags)
		{
			if (cameraMatrix1 == null)
			{
				throw new ArgumentNullException("cameraMatrix1");
			}
			if (distCoeffs1 == null)
			{
				throw new ArgumentNullException("distCoeffs1");
			}
			if (cameraMatrix2 == null)
			{
				throw new ArgumentNullException("cameraMatrix2");
			}
			if (distCoeffs2 == null)
			{
				throw new ArgumentNullException("distCoeffs2");
			}
			if (cameraMatrix3 == null)
			{
				throw new ArgumentNullException("cameraMatrix3");
			}
			if (distCoeffs3 == null)
			{
				throw new ArgumentNullException("distCoeffs3");
			}
			if (imgpt1 == null)
			{
				throw new ArgumentNullException("imgpt1");
			}
			if (imgpt3 == null)
			{
				throw new ArgumentNullException("imgpt3");
			}
			if (R12 == null)
			{
				throw new ArgumentNullException("R12");
			}
			if (T12 == null)
			{
				throw new ArgumentNullException("T12");
			}
			if (R13 == null)
			{
				throw new ArgumentNullException("R13");
			}
			if (T13 == null)
			{
				throw new ArgumentNullException("T13");
			}
			if (R1 == null)
			{
				throw new ArgumentNullException("R1");
			}
			if (R2 == null)
			{
				throw new ArgumentNullException("R2");
			}
			if (R3 == null)
			{
				throw new ArgumentNullException("R3");
			}
			if (P1 == null)
			{
				throw new ArgumentNullException("P1");
			}
			if (P2 == null)
			{
				throw new ArgumentNullException("P2");
			}
			if (P3 == null)
			{
				throw new ArgumentNullException("P3");
			}
			if (Q == null)
			{
				throw new ArgumentNullException("Q");
			}
			cameraMatrix1.ThrowIfDisposed();
			distCoeffs1.ThrowIfDisposed();
			cameraMatrix2.ThrowIfDisposed();
			distCoeffs2.ThrowIfDisposed();
			cameraMatrix3.ThrowIfDisposed();
			distCoeffs3.ThrowIfDisposed();
			R12.ThrowIfDisposed();
			T12.ThrowIfDisposed();
			R13.ThrowIfDisposed();
			T13.ThrowIfDisposed();
			R1.ThrowIfNotReady();
			R2.ThrowIfNotReady();
			R3.ThrowIfNotReady();
			P1.ThrowIfNotReady();
			P2.ThrowIfNotReady();
			P3.ThrowIfNotReady();
			Q.ThrowIfNotReady();
			IntPtr[] array = imgpt1.Select((InputArray x) => x.CvPtr).ToArray();
			IntPtr[] array2 = imgpt3.Select((InputArray x) => x.CvPtr).ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_rectify3Collinear_InputArray(cameraMatrix1.CvPtr, distCoeffs1.CvPtr, cameraMatrix2.CvPtr, distCoeffs2.CvPtr, cameraMatrix3.CvPtr, distCoeffs3.CvPtr, array, array.Length, array2, array2.Length, imageSize, R12.CvPtr, T12.CvPtr, R13.CvPtr, T13.CvPtr, R1.CvPtr, R2.CvPtr, R3.CvPtr, P1.CvPtr, P2.CvPtr, P3.CvPtr, Q.CvPtr, alpha, newImgSize, out roi1, out roi2, (int)flags, out var returnValue));
			GC.KeepAlive(cameraMatrix1);
			GC.KeepAlive(distCoeffs1);
			GC.KeepAlive(cameraMatrix2);
			GC.KeepAlive(distCoeffs2);
			GC.KeepAlive(cameraMatrix3);
			GC.KeepAlive(distCoeffs3);
			GC.KeepAlive(imgpt1);
			GC.KeepAlive(imgpt3);
			GC.KeepAlive(R12);
			GC.KeepAlive(T12);
			GC.KeepAlive(R13);
			GC.KeepAlive(T13);
			GC.KeepAlive(R1);
			GC.KeepAlive(R2);
			GC.KeepAlive(R3);
			GC.KeepAlive(P1);
			GC.KeepAlive(P2);
			GC.KeepAlive(P3);
			GC.KeepAlive(Q);
			R1.Fix();
			R2.Fix();
			R3.Fix();
			P1.Fix();
			P2.Fix();
			P3.Fix();
			Q.Fix();
			return returnValue;
		}

		public static Mat GetOptimalNewCameraMatrix(InputArray cameraMatrix, InputArray? distCoeffs, Size imageSize, double alpha, Size newImgSize, out Rect validPixROI, bool centerPrincipalPoint = false)
		{
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			cameraMatrix.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_getOptimalNewCameraMatrix_InputArray(cameraMatrix.CvPtr, ToPtr(distCoeffs), imageSize, alpha, newImgSize, out validPixROI, centerPrincipalPoint ? 1 : 0, out var returnValue));
			GC.KeepAlive(cameraMatrix);
			GC.KeepAlive(distCoeffs);
			return new Mat(returnValue);
		}

		public unsafe static double[,]? GetOptimalNewCameraMatrix(double[,] cameraMatrix, double[] distCoeffs, Size imageSize, double alpha, Size newImgSize, out Rect validPixROI, bool centerPrincipalPoint = false)
		{
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (distCoeffs == null)
			{
				throw new ArgumentNullException("distCoeffs");
			}
			IntPtr returnValue;
			fixed (double* cameraMatrix2 = cameraMatrix)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_getOptimalNewCameraMatrix_array(cameraMatrix2, distCoeffs, distCoeffs.Length, imageSize, alpha, newImgSize, out validPixROI, centerPrincipalPoint ? 1 : 0, out returnValue));
				if (returnValue == IntPtr.Zero)
				{
					return null;
				}
			}
			using Mat<double> mat = Mat<double>.FromNativePointer(returnValue);
			return mat.ToRectangularArray();
		}

		public static void CalibrateHandEye(IEnumerable<Mat> R_gripper2base, IEnumerable<Mat> t_gripper2base, IEnumerable<Mat> R_target2cam, IEnumerable<Mat> t_target2cam, OutputArray R_cam2gripper, OutputArray t_cam2gripper, HandEyeCalibrationMethod method = HandEyeCalibrationMethod.TSAI)
		{
			if (R_gripper2base == null)
			{
				throw new ArgumentNullException("R_gripper2base");
			}
			if (t_gripper2base == null)
			{
				throw new ArgumentNullException("t_gripper2base");
			}
			if (R_target2cam == null)
			{
				throw new ArgumentNullException("R_target2cam");
			}
			if (t_target2cam == null)
			{
				throw new ArgumentNullException("t_target2cam");
			}
			if (R_cam2gripper == null)
			{
				throw new ArgumentNullException("R_cam2gripper");
			}
			if (t_cam2gripper == null)
			{
				throw new ArgumentNullException("t_cam2gripper");
			}
			R_cam2gripper.ThrowIfNotReady();
			t_cam2gripper.ThrowIfNotReady();
			Mat[] obj = (R_gripper2base as Mat[]) ?? R_gripper2base.ToArray();
			Mat[] array = (t_gripper2base as Mat[]) ?? t_gripper2base.ToArray();
			Mat[] array2 = (R_target2cam as Mat[]) ?? R_target2cam.ToArray();
			Mat[] array3 = (t_target2cam as Mat[]) ?? t_target2cam.ToArray();
			if (obj.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "R_gripper2base");
			}
			if (array.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "t_gripper2base");
			}
			if (array2.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "R_target2cam");
			}
			if (array3.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "t_target2cam");
			}
			IntPtr[] array4 = obj.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array5 = array.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array6 = array2.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array7 = array3.Select((Mat m) => m.CvPtr).ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_calibrateHandEye(array4, array4.Length, array5, array5.Length, array6, array6.Length, array7, array7.Length, R_cam2gripper.CvPtr, t_cam2gripper.CvPtr, (int)method));
			GC.KeepAlive(R_gripper2base);
			GC.KeepAlive(t_gripper2base);
			GC.KeepAlive(R_target2cam);
			GC.KeepAlive(t_target2cam);
			R_cam2gripper.Fix();
			t_cam2gripper.Fix();
			Mat[] array8 = obj;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array2;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array3;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
		}

		public static void CalibrateRobotWorldHandEye(IEnumerable<Mat> R_world2cam, IEnumerable<Mat> t_world2cam, IEnumerable<Mat> R_base2gripper, IEnumerable<Mat> t_base2gripper, OutputArray R_base2world, OutputArray t_base2world, OutputArray R_gripper2cam, OutputArray t_gripper2cam, RobotWorldHandEyeCalibrationMethod method = RobotWorldHandEyeCalibrationMethod.SHAH)
		{
			if (R_world2cam == null)
			{
				throw new ArgumentNullException("R_world2cam");
			}
			if (t_world2cam == null)
			{
				throw new ArgumentNullException("t_world2cam");
			}
			if (R_base2gripper == null)
			{
				throw new ArgumentNullException("R_base2gripper");
			}
			if (t_base2gripper == null)
			{
				throw new ArgumentNullException("t_base2gripper");
			}
			if (R_base2world == null)
			{
				throw new ArgumentNullException("R_base2world");
			}
			if (t_base2world == null)
			{
				throw new ArgumentNullException("t_base2world");
			}
			if (R_gripper2cam == null)
			{
				throw new ArgumentNullException("R_gripper2cam");
			}
			if (t_gripper2cam == null)
			{
				throw new ArgumentNullException("t_gripper2cam");
			}
			R_base2world.ThrowIfNotReady();
			t_base2world.ThrowIfNotReady();
			R_gripper2cam.ThrowIfNotReady();
			t_gripper2cam.ThrowIfNotReady();
			Mat[] obj = (R_world2cam as Mat[]) ?? R_world2cam.ToArray();
			Mat[] array = (t_world2cam as Mat[]) ?? t_world2cam.ToArray();
			Mat[] array2 = (R_base2gripper as Mat[]) ?? R_base2gripper.ToArray();
			Mat[] array3 = (t_base2gripper as Mat[]) ?? t_base2gripper.ToArray();
			if (obj.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "R_world2cam");
			}
			if (array.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "t_world2cam");
			}
			if (array2.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "R_base2gripper");
			}
			if (array3.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "t_base2gripper");
			}
			IntPtr[] array4 = obj.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array5 = array.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array6 = array2.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array7 = array3.Select((Mat m) => m.CvPtr).ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_calibrateRobotWorldHandEye_OutputArray(array4, array4.Length, array5, array5.Length, array6, array6.Length, array7, array7.Length, R_base2world.CvPtr, t_base2world.CvPtr, R_gripper2cam.CvPtr, t_gripper2cam.CvPtr, (int)method));
			R_base2world.Fix();
			t_base2world.Fix();
			R_gripper2cam.Fix();
			t_gripper2cam.Fix();
			Mat[] array8 = obj;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array2;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array3;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
		}

		public static void CalibrateRobotWorldHandEye(IEnumerable<Mat> R_world2cam, IEnumerable<Mat> t_world2cam, IEnumerable<Mat> R_base2gripper, IEnumerable<Mat> t_base2gripper, out double[,] R_base2world, out double[] t_base2world, out double[,] R_gripper2cam, out double[] t_gripper2cam, RobotWorldHandEyeCalibrationMethod method = RobotWorldHandEyeCalibrationMethod.SHAH)
		{
			if (R_world2cam == null)
			{
				throw new ArgumentNullException("R_world2cam");
			}
			if (t_world2cam == null)
			{
				throw new ArgumentNullException("t_world2cam");
			}
			if (R_base2gripper == null)
			{
				throw new ArgumentNullException("R_base2gripper");
			}
			if (t_base2gripper == null)
			{
				throw new ArgumentNullException("t_base2gripper");
			}
			Mat[] obj = (R_world2cam as Mat[]) ?? R_world2cam.ToArray();
			Mat[] array = (t_world2cam as Mat[]) ?? t_world2cam.ToArray();
			Mat[] array2 = (R_base2gripper as Mat[]) ?? R_base2gripper.ToArray();
			Mat[] array3 = (t_base2gripper as Mat[]) ?? t_base2gripper.ToArray();
			if (obj.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "R_world2cam");
			}
			if (array.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "t_world2cam");
			}
			if (array2.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "R_base2gripper");
			}
			if (array3.Length == 0)
			{
				throw new ArgumentException("Empty sequence", "t_base2gripper");
			}
			IntPtr[] array4 = obj.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array5 = array.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array6 = array2.Select((Mat m) => m.CvPtr).ToArray();
			IntPtr[] array7 = array3.Select((Mat m) => m.CvPtr).ToArray();
			R_base2world = new double[3, 3];
			t_base2world = new double[3];
			R_gripper2cam = new double[3, 3];
			t_gripper2cam = new double[3];
			NativeMethods.HandleException(NativeMethods.calib3d_calibrateRobotWorldHandEye_Pointer(array4, array4.Length, array5, array5.Length, array6, array6.Length, array7, array7.Length, R_base2world, t_base2world, R_gripper2cam, t_gripper2cam, (int)method));
			Mat[] array8 = obj;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array2;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
			array8 = array3;
			for (int i = 0; i < array8.Length; i++)
			{
				GC.KeepAlive(array8[i]);
			}
		}

		public static void ConvertPointsToHomogeneous(InputArray src, OutputArray dst)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (dst == null)
			{
				throw new ArgumentNullException("dst");
			}
			src.ThrowIfDisposed();
			dst.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsToHomogeneous_InputArray(src.CvPtr, dst.CvPtr));
			GC.KeepAlive(src);
			GC.KeepAlive(dst);
			dst.Fix();
		}

		public static Vec3f[] ConvertPointsToHomogeneous(IEnumerable<Vec2f> src)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			Vec2f[] array = (src as Vec2f[]) ?? src.ToArray();
			Vec3f[] array2 = new Vec3f[array.Length];
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsToHomogeneous_array1(array, array2, array.Length));
			return array2;
		}

		public static Vec4f[] ConvertPointsToHomogeneous(IEnumerable<Vec3f> src)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			Vec3f[] array = (src as Vec3f[]) ?? src.ToArray();
			Vec4f[] array2 = new Vec4f[array.Length];
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsToHomogeneous_array2(array, array2, array.Length));
			return array2;
		}

		public static void ConvertPointsFromHomogeneous(InputArray src, OutputArray dst)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (dst == null)
			{
				throw new ArgumentNullException("dst");
			}
			src.ThrowIfDisposed();
			dst.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsFromHomogeneous_InputArray(src.CvPtr, dst.CvPtr));
			GC.KeepAlive(src);
			dst.Fix();
		}

		public static Vec2f[] ConvertPointsFromHomogeneous(IEnumerable<Vec3f> src)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			Vec3f[] array = (src as Vec3f[]) ?? src.ToArray();
			Vec2f[] array2 = new Vec2f[array.Length];
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsFromHomogeneous_array1(array, array2, array.Length));
			return array2;
		}

		public static Vec3f[] ConvertPointsFromHomogeneous(IEnumerable<Vec4f> src)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			Vec4f[] array = (src as Vec4f[]) ?? src.ToArray();
			Vec3f[] array2 = new Vec3f[array.Length];
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsFromHomogeneous_array2(array, array2, array.Length));
			return array2;
		}

		public static void ConvertPointsHomogeneous(InputArray src, OutputArray dst)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (dst == null)
			{
				throw new ArgumentNullException("dst");
			}
			src.ThrowIfDisposed();
			dst.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_convertPointsHomogeneous(src.CvPtr, dst.CvPtr));
			GC.KeepAlive(src);
			dst.Fix();
		}

		public static Mat FindFundamentalMat(InputArray points1, InputArray points2, FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, OutputArray? mask = null)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_findFundamentalMat_InputArray(points1.CvPtr, points2.CvPtr, (int)method, param1, param2, ToPtr(mask), out var returnValue));
			mask?.Fix();
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			return new Mat(returnValue);
		}

		public static Mat FindFundamentalMat(IEnumerable<Point2f> points1, IEnumerable<Point2f> points2, FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, OutputArray? mask = null)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			Point2f[] obj = (points1 as Point2f[]) ?? points1.ToArray();
			Point2f[] array = (points2 as Point2f[]) ?? points2.ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_findFundamentalMat_arrayF32(obj, obj.Length, array, array.Length, (int)method, param1, param2, ToPtr(mask), out var returnValue));
			mask?.Fix();
			return new Mat(returnValue);
		}

		public static Mat FindFundamentalMat(IEnumerable<Point2d> points1, IEnumerable<Point2d> points2, FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, OutputArray? mask = null)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			Point2d[] obj = (points1 as Point2d[]) ?? points1.ToArray();
			Point2d[] array = (points2 as Point2d[]) ?? points2.ToArray();
			NativeMethods.HandleException(NativeMethods.calib3d_findFundamentalMat_arrayF64(obj, obj.Length, array, array.Length, (int)method, param1, param2, ToPtr(mask), out var returnValue));
			mask?.Fix();
			return new Mat(returnValue);
		}

		public static void ComputeCorrespondEpilines(InputArray points, int whichImage, InputArray F, OutputArray lines)
		{
			if (points == null)
			{
				throw new ArgumentNullException("points");
			}
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (lines == null)
			{
				throw new ArgumentNullException("lines");
			}
			points.ThrowIfDisposed();
			F.ThrowIfDisposed();
			lines.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_computeCorrespondEpilines_InputArray(points.CvPtr, whichImage, F.CvPtr, lines.CvPtr));
			GC.KeepAlive(F);
			GC.KeepAlive(points);
			lines.Fix();
		}

		public unsafe static Point3f[] ComputeCorrespondEpilines(IEnumerable<Point2d> points, int whichImage, double[,] F)
		{
			if (points == null)
			{
				throw new ArgumentNullException("points");
			}
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (F.GetLength(0) != 3 && F.GetLength(1) != 3)
			{
				throw new ArgumentException("F != double[3,3]");
			}
			Point2d[] obj = (points as Point2d[]) ?? points.ToArray();
			Point3f[] array = new Point3f[obj.Length];
			fixed (double* f = F)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_computeCorrespondEpilines_array2d(obj, obj.Length, whichImage, f, array));
			}
			return array;
		}

		public unsafe static Point3f[] ComputeCorrespondEpilines(IEnumerable<Point3d> points, int whichImage, double[,] F)
		{
			if (points == null)
			{
				throw new ArgumentNullException("points");
			}
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (F.GetLength(0) != 3 && F.GetLength(1) != 3)
			{
				throw new ArgumentException("F != double[3,3]");
			}
			Point3d[] obj = (points as Point3d[]) ?? points.ToArray();
			Point3f[] array = new Point3f[obj.Length];
			fixed (double* f = F)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_computeCorrespondEpilines_array3d(obj, obj.Length, whichImage, f, array));
			}
			return array;
		}

		public static void TriangulatePoints(InputArray projMatr1, InputArray projMatr2, InputArray projPoints1, InputArray projPoints2, OutputArray points4D)
		{
			if (projMatr1 == null)
			{
				throw new ArgumentNullException("projMatr1");
			}
			if (projMatr2 == null)
			{
				throw new ArgumentNullException("projMatr2");
			}
			if (projPoints1 == null)
			{
				throw new ArgumentNullException("projPoints1");
			}
			if (projPoints2 == null)
			{
				throw new ArgumentNullException("projPoints2");
			}
			if (points4D == null)
			{
				throw new ArgumentNullException("points4D");
			}
			projMatr1.ThrowIfDisposed();
			projMatr2.ThrowIfDisposed();
			projPoints1.ThrowIfDisposed();
			projPoints2.ThrowIfDisposed();
			points4D.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_triangulatePoints_InputArray(projMatr1.CvPtr, projMatr2.CvPtr, projPoints1.CvPtr, projPoints2.CvPtr, points4D.CvPtr));
			GC.KeepAlive(projMatr1);
			GC.KeepAlive(projMatr2);
			GC.KeepAlive(projPoints1);
			GC.KeepAlive(projPoints2);
			points4D.Fix();
		}

		public unsafe static Vec4d[] TriangulatePoints(double[,] projMatr1, double[,] projMatr2, IEnumerable<Point2d> projPoints1, IEnumerable<Point2d> projPoints2)
		{
			if (projMatr1 == null)
			{
				throw new ArgumentNullException("projMatr1");
			}
			if (projMatr2 == null)
			{
				throw new ArgumentNullException("projMatr2");
			}
			if (projPoints1 == null)
			{
				throw new ArgumentNullException("projPoints1");
			}
			if (projPoints2 == null)
			{
				throw new ArgumentNullException("projPoints2");
			}
			if (projMatr1.GetLength(0) != 3 && projMatr1.GetLength(1) != 4)
			{
				throw new ArgumentException("projMatr1 != double[3,4]");
			}
			if (projMatr2.GetLength(0) != 3 && projMatr2.GetLength(1) != 4)
			{
				throw new ArgumentException("projMatr2 != double[3,4]");
			}
			Point2d[] array = (projPoints1 as Point2d[]) ?? projPoints1.ToArray();
			Point2d[] array2 = (projPoints2 as Point2d[]) ?? projPoints2.ToArray();
			Vec4d[] array3 = new Vec4d[array.Length];
			fixed (double* projMatr3 = projMatr1)
			{
				fixed (double* projMatr4 = projMatr2)
				{
					NativeMethods.HandleException(NativeMethods.calib3d_triangulatePoints_array(projMatr3, projMatr4, array, array.Length, array2, array2.Length, array3));
				}
			}
			return array3;
		}

		public static void CorrectMatches(InputArray F, InputArray points1, InputArray points2, OutputArray newPoints1, OutputArray newPoints2)
		{
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (newPoints1 == null)
			{
				throw new ArgumentNullException("newPoints1");
			}
			if (newPoints2 == null)
			{
				throw new ArgumentNullException("newPoints2");
			}
			F.ThrowIfDisposed();
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			newPoints1.ThrowIfNotReady();
			newPoints2.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_correctMatches_InputArray(F.CvPtr, points1.CvPtr, points2.CvPtr, newPoints1.CvPtr, newPoints2.CvPtr));
			GC.KeepAlive(F);
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			newPoints1.Fix();
			newPoints2.Fix();
		}

		public unsafe static void CorrectMatches(double[,] F, IEnumerable<Point2d> points1, IEnumerable<Point2d> points2, out Point2d[] newPoints1, out Point2d[] newPoints2)
		{
			if (F == null)
			{
				throw new ArgumentNullException("F");
			}
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			Point2d[] array = (points1 as Point2d[]) ?? points1.ToArray();
			Point2d[] array2 = (points2 as Point2d[]) ?? points2.ToArray();
			newPoints1 = new Point2d[array.Length];
			newPoints2 = new Point2d[array2.Length];
			fixed (double* f = F)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_correctMatches_array(f, array, array.Length, array2, array2.Length, newPoints1, newPoints2));
			}
		}

		public static int RecoverPose(InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, OutputArray R, OutputArray t, InputOutputArray? mask = null)
		{
			if (E == null)
			{
				throw new ArgumentNullException("E");
			}
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (R == null)
			{
				throw new ArgumentNullException("R");
			}
			if (t == null)
			{
				throw new ArgumentNullException("t");
			}
			E.ThrowIfDisposed();
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			R.ThrowIfNotReady();
			t.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_recoverPose_InputArray1(E.CvPtr, points1.CvPtr, points2.CvPtr, cameraMatrix.CvPtr, R.CvPtr, t.CvPtr, ToPtr(mask), out var returnValue));
			GC.KeepAlive(E);
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			GC.KeepAlive(cameraMatrix);
			R.Fix();
			t.Fix();
			mask?.Fix();
			return returnValue;
		}

		public static int RecoverPose(InputArray E, InputArray points1, InputArray points2, OutputArray R, OutputArray t, double focal, Point2d pp, InputOutputArray? mask = null)
		{
			if (E == null)
			{
				throw new ArgumentNullException("E");
			}
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (R == null)
			{
				throw new ArgumentNullException("R");
			}
			if (t == null)
			{
				throw new ArgumentNullException("t");
			}
			E.ThrowIfDisposed();
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			R.ThrowIfNotReady();
			t.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_recoverPose_InputArray2(E.CvPtr, points1.CvPtr, points2.CvPtr, R.CvPtr, t.CvPtr, focal, pp, ToPtr(mask), out var returnValue));
			GC.KeepAlive(E);
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			GC.KeepAlive(pp);
			R.Fix();
			t.Fix();
			mask?.Fix();
			return returnValue;
		}

		public static int RecoverPose(InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceTresh, InputOutputArray? mask = null, OutputArray? triangulatedPoints = null)
		{
			if (E == null)
			{
				throw new ArgumentNullException("E");
			}
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			if (R == null)
			{
				throw new ArgumentNullException("R");
			}
			if (t == null)
			{
				throw new ArgumentNullException("t");
			}
			E.ThrowIfDisposed();
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			R.ThrowIfNotReady();
			t.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_recoverPose_InputArray3(E.CvPtr, points1.CvPtr, points2.CvPtr, cameraMatrix.CvPtr, R.CvPtr, t.CvPtr, distanceTresh, ToPtr(mask), ToPtr(triangulatedPoints), out var returnValue));
			GC.KeepAlive(E);
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			GC.KeepAlive(cameraMatrix);
			R.Fix();
			t.Fix();
			mask?.Fix();
			triangulatedPoints?.Fix();
			return returnValue;
		}

		public static Mat FindEssentialMat(InputArray points1, InputArray points2, InputArray cameraMatrix, EssentialMatMethod method = EssentialMatMethod.Ransac, double prob = 0.999, double threshold = 1.0, OutputArray? mask = null)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			if (cameraMatrix == null)
			{
				throw new ArgumentNullException("cameraMatrix");
			}
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			cameraMatrix.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_findEssentialMat_InputArray1(points1.CvPtr, points2.CvPtr, cameraMatrix.CvPtr, (int)method, prob, threshold, ToPtr(mask), out var returnValue));
			mask?.Fix();
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			GC.KeepAlive(cameraMatrix);
			return new Mat(returnValue);
		}

		public static Mat FindEssentialMat(InputArray points1, InputArray points2, double focal, Point2d pp, EssentialMatMethod method = EssentialMatMethod.Ransac, double prob = 0.999, double threshold = 1.0, OutputArray? mask = null)
		{
			if (points1 == null)
			{
				throw new ArgumentNullException("points1");
			}
			if (points2 == null)
			{
				throw new ArgumentNullException("points2");
			}
			points1.ThrowIfDisposed();
			points2.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_findEssentialMat_InputArray2(points1.CvPtr, points2.CvPtr, focal, pp, (int)method, prob, threshold, ToPtr(mask), out var returnValue));
			mask?.Fix();
			GC.KeepAlive(points1);
			GC.KeepAlive(points2);
			return new Mat(returnValue);
		}

		public static void FilterSpeckles(InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff, InputOutputArray? buf = null)
		{
			if (img == null)
			{
				throw new ArgumentNullException("img");
			}
			img.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_filterSpeckles(img.CvPtr, newVal, maxSpeckleSize, maxDiff, ToPtr(buf)));
			GC.KeepAlive(img);
			GC.KeepAlive(buf);
			img.Fix();
		}

		public static Rect GetValidDisparityROI(Rect roi1, Rect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize)
		{
			NativeMethods.HandleException(NativeMethods.calib3d_getValidDisparityROI(roi1, roi2, minDisparity, numberOfDisparities, SADWindowSize, out var returnValue));
			return returnValue;
		}

		public static void ValidateDisparity(InputOutputArray disparity, InputArray cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1)
		{
			if (disparity == null)
			{
				throw new ArgumentNullException("disparity");
			}
			if (cost == null)
			{
				throw new ArgumentNullException("cost");
			}
			disparity.ThrowIfNotReady();
			cost.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_validateDisparity(disparity.CvPtr, cost.CvPtr, minDisparity, numberOfDisparities, disp12MaxDisp));
			disparity.Fix();
			GC.KeepAlive(disparity);
			GC.KeepAlive(cost);
		}

		public static void ReprojectImageTo3D(InputArray disparity, OutputArray _3dImage, InputArray Q, bool handleMissingValues = false, int ddepth = -1)
		{
			if (disparity == null)
			{
				throw new ArgumentNullException("disparity");
			}
			if (_3dImage == null)
			{
				throw new ArgumentNullException("_3dImage");
			}
			if (Q == null)
			{
				throw new ArgumentNullException("Q");
			}
			disparity.ThrowIfDisposed();
			_3dImage.ThrowIfNotReady();
			Q.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_reprojectImageTo3D(disparity.CvPtr, _3dImage.CvPtr, Q.CvPtr, handleMissingValues ? 1 : 0, ddepth));
			_3dImage.Fix();
			GC.KeepAlive(disparity);
			GC.KeepAlive(_3dImage);
			GC.KeepAlive(Q);
		}

		public static int EstimateAffine3D(InputArray src, InputArray dst, OutputArray outVal, OutputArray inliers, double ransacThreshold = 3.0, double confidence = 0.99)
		{
			if (src == null)
			{
				throw new ArgumentNullException("src");
			}
			if (dst == null)
			{
				throw new ArgumentNullException("dst");
			}
			if (outVal == null)
			{
				throw new ArgumentNullException("outVal");
			}
			if (inliers == null)
			{
				throw new ArgumentNullException("inliers");
			}
			src.ThrowIfDisposed();
			dst.ThrowIfDisposed();
			outVal.ThrowIfNotReady();
			inliers.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_estimateAffine3D(src.CvPtr, dst.CvPtr, outVal.CvPtr, inliers.CvPtr, ransacThreshold, confidence, out var returnValue));
			outVal.Fix();
			inliers.Fix();
			GC.KeepAlive(src);
			GC.KeepAlive(dst);
			return returnValue;
		}

		public static double SampsonDistance(InputArray pt1, InputArray pt2, InputArray f)
		{
			if (pt1 == null)
			{
				throw new ArgumentNullException("pt1");
			}
			if (pt2 == null)
			{
				throw new ArgumentNullException("pt2");
			}
			if (f == null)
			{
				throw new ArgumentNullException("f");
			}
			pt1.ThrowIfDisposed();
			pt2.ThrowIfDisposed();
			f.ThrowIfDisposed();
			NativeMethods.HandleException(NativeMethods.calib3d_sampsonDistance_InputArray(pt1.CvPtr, pt2.CvPtr, f.CvPtr, out var returnValue));
			GC.KeepAlive(pt1);
			GC.KeepAlive(pt2);
			return returnValue;
		}

		public unsafe static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f)
		{
			if (f == null)
			{
				throw new ArgumentNullException("f");
			}
			if (f.GetLength(0) != 3 || f.GetLength(1) != 3)
			{
				throw new ArgumentException("f should be 3x3 matrix", "f");
			}
			fixed (double* f2 = f)
			{
				NativeMethods.HandleException(NativeMethods.calib3d_sampsonDistance_Point3d(pt1, pt2, f2, out var returnValue));
				GC.KeepAlive(f);
				return returnValue;
			}
		}

		public static Mat? EstimateAffine2D(InputArray from, InputArray to, OutputArray? inliers = null, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3.0, ulong maxIters = 2000uL, double confidence = 0.99, ulong refineIters = 10uL)
		{
			if (from == null)
			{
				throw new ArgumentNullException("from");
			}
			if (to == null)
			{
				throw new ArgumentNullException("to");
			}
			from.ThrowIfDisposed();
			to.ThrowIfDisposed();
			inliers?.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_estimateAffine2D(from.CvPtr, to.CvPtr, ToPtr(inliers), (int)method, ransacReprojThreshold, maxIters, confidence, refineIters, out var returnValue));
			GC.KeepAlive(from);
			GC.KeepAlive(to);
			GC.KeepAlive(inliers);
			if (!(returnValue == IntPtr.Zero))
			{
				return new Mat(returnValue);
			}
			return null;
		}

		public static Mat? EstimateAffinePartial2D(InputArray from, InputArray to, OutputArray? inliers = null, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3.0, ulong maxIters = 2000uL, double confidence = 0.99, ulong refineIters = 10uL)
		{
			if (from == null)
			{
				throw new ArgumentNullException("from");
			}
			if (to == null)
			{
				throw new ArgumentNullException("to");
			}
			from.ThrowIfDisposed();
			to.ThrowIfDisposed();
			inliers?.ThrowIfNotReady();
			NativeMethods.HandleException(NativeMethods.calib3d_estimateAffinePartial2D(from.CvPtr, to.CvPtr, ToPtr(inliers), (int)method, ransacReprojThreshold, maxIters, confidence, refineIters, out var returnValue));
			GC.KeepAlive(from);
			GC.KeepAlive(to);
			GC.KeepAlive(inliers);
			if (!(returnValue == IntPtr.Zero))
			{
				return new Mat(returnValue);
			}
			return null;
		}

		public static int DecomposeHomographyMat(InputArray h, InputArray k, out Mat[] rotations, out Mat[] translations, out Mat[] normals)
		{
			if (h == null)
			{
				throw new ArgumentNullException("h");
			}
			if (k == null)
			{
				throw new ArgumentNullException("k");
			}
			h.ThrowIfDisposed();
			k.ThrowIfDisposed();
			using VectorOfMat vectorOfMat = new VectorOfMat();
			using VectorOfMat vectorOfMat2 = new VectorOfMat();
			using VectorOfMat vectorOfMat3 = new VectorOfMat();
			NativeMethods.HandleException(NativeMethods.calib3d_decomposeHomographyMat(h.CvPtr, k.CvPtr, vectorOfMat.CvPtr, vectorOfMat2.CvPtr, vectorOfMat3.CvPtr, out var returnValue));
			rotations = vectorOfMat.ToArray();
			translations = vectorOfMat2.ToArray();
			normals = vecto

BepInEx/plugins/FaceSync/System.Buffers.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using FxResources.System.Buffers;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDefaultAlias("System.Buffers")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.Buffers")]
[assembly: AssemblyFileVersion("4.600.125.16908")]
[assembly: AssemblyInformationalVersion("4.6.1+6b84308c9ad012f53240d72c1d716d7e42546483")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Buffers")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/maintenance-packages")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.5.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 FxResources.System.Buffers
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool");

		private static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		internal static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object? p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object? p1, object? p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object? p1, object? p2, object? p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Buffers
{
	public abstract class ArrayPool<T>
	{
		private static ArrayPool<T> s_sharedInstance;

		public static ArrayPool<T> Shared
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static ArrayPool<T> EnsureSharedCreated()
		{
			Interlocked.CompareExchange(ref s_sharedInstance, Create(), null);
			return s_sharedInstance;
		}

		public static ArrayPool<T> Create()
		{
			return new DefaultArrayPool<T>();
		}

		public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket)
		{
			return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket);
		}

		public abstract T[] Rent(int minimumLength);

		public abstract void Return(T[] array, bool clearArray = false);
	}
	[EventSource(Name = "System.Buffers.ArrayPoolEventSource")]
	internal sealed class ArrayPoolEventSource : EventSource
	{
		internal enum BufferAllocatedReason
		{
			Pooled,
			OverMaximumSize,
			PoolExhausted
		}

		internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource();

		[Event(1, Level = EventLevel.Verbose)]
		internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId)
		{
			EventData* ptr = stackalloc EventData[4];
			*ptr = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferId)
			};
			ptr[1] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferSize)
			};
			ptr[2] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&poolId)
			};
			ptr[3] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bucketId)
			};
			WriteEventCore(1, 4, ptr);
		}

		[Event(2, Level = EventLevel.Informational)]
		internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason)
		{
			EventData* ptr = stackalloc EventData[5];
			*ptr = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferId)
			};
			ptr[1] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bufferSize)
			};
			ptr[2] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&poolId)
			};
			ptr[3] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&bucketId)
			};
			ptr[4] = new EventData
			{
				Size = 4,
				DataPointer = (IntPtr)(&reason)
			};
			WriteEventCore(2, 5, ptr);
		}

		[Event(3, Level = EventLevel.Verbose)]
		internal void BufferReturned(int bufferId, int bufferSize, int poolId)
		{
			WriteEvent(3, bufferId, bufferSize, poolId);
		}
	}
	internal sealed class DefaultArrayPool<T> : ArrayPool<T>
	{
		private sealed class Bucket
		{
			internal readonly int _bufferLength;

			private readonly T[][] _buffers;

			private readonly int _poolId;

			private SpinLock _lock;

			private int _index;

			internal int Id => GetHashCode();

			internal Bucket(int bufferLength, int numberOfBuffers, int poolId)
			{
				_lock = new SpinLock(Debugger.IsAttached);
				_buffers = new T[numberOfBuffers][];
				_bufferLength = bufferLength;
				_poolId = poolId;
			}

			internal T[] Rent()
			{
				T[][] buffers = _buffers;
				T[] array = null;
				bool lockTaken = false;
				bool flag = false;
				try
				{
					_lock.Enter(ref lockTaken);
					if (_index < buffers.Length)
					{
						array = buffers[_index];
						buffers[_index++] = null;
						flag = array == null;
					}
				}
				finally
				{
					if (lockTaken)
					{
						_lock.Exit(useMemoryBarrier: false);
					}
				}
				if (flag)
				{
					array = new T[_bufferLength];
					System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
					if (log.IsEnabled())
					{
						log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled);
					}
				}
				return array;
			}

			internal void Return(T[] array)
			{
				if (array.Length != _bufferLength)
				{
					throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array");
				}
				bool lockTaken = false;
				try
				{
					_lock.Enter(ref lockTaken);
					if (_index != 0)
					{
						_buffers[--_index] = array;
					}
				}
				finally
				{
					if (lockTaken)
					{
						_lock.Exit(useMemoryBarrier: false);
					}
				}
			}
		}

		private const int DefaultMaxArrayLength = 1048576;

		private const int DefaultMaxNumberOfArraysPerBucket = 50;

		private static T[] s_emptyArray;

		private readonly Bucket[] _buckets;

		private int Id => GetHashCode();

		internal DefaultArrayPool()
			: this(1048576, 50)
		{
		}

		internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket)
		{
			if (maxArrayLength <= 0)
			{
				throw new ArgumentOutOfRangeException("maxArrayLength");
			}
			if (maxArraysPerBucket <= 0)
			{
				throw new ArgumentOutOfRangeException("maxArraysPerBucket");
			}
			if (maxArrayLength > 1073741824)
			{
				maxArrayLength = 1073741824;
			}
			else if (maxArrayLength < 16)
			{
				maxArrayLength = 16;
			}
			int id = Id;
			int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength);
			Bucket[] array = new Bucket[num + 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id);
			}
			_buckets = array;
		}

		public override T[] Rent(int minimumLength)
		{
			if (minimumLength < 0)
			{
				throw new ArgumentOutOfRangeException("minimumLength");
			}
			if (minimumLength == 0)
			{
				return s_emptyArray ?? (s_emptyArray = new T[0]);
			}
			System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
			T[] array = null;
			int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength);
			if (num < _buckets.Length)
			{
				int num2 = num;
				do
				{
					array = _buckets[num2].Rent();
					if (array != null)
					{
						if (log.IsEnabled())
						{
							log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id);
						}
						return array;
					}
				}
				while (++num2 < _buckets.Length && num2 != num + 2);
				array = new T[_buckets[num]._bufferLength];
			}
			else
			{
				array = new T[minimumLength];
			}
			if (log.IsEnabled())
			{
				int hashCode = array.GetHashCode();
				int bucketId = -1;
				log.BufferRented(hashCode, array.Length, Id, bucketId);
				log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted);
			}
			return array;
		}

		public override void Return(T[] array, bool clearArray = false)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Length == 0)
			{
				return;
			}
			int num = System.Buffers.Utilities.SelectBucketIndex(array.Length);
			if (num < _buckets.Length)
			{
				if (clearArray)
				{
					Array.Clear(array, 0, array.Length);
				}
				_buckets[num].Return(array);
			}
			System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log;
			if (log.IsEnabled())
			{
				log.BufferReturned(array.GetHashCode(), array.Length, Id);
			}
		}
	}
	internal static class Utilities
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int SelectBucketIndex(int bufferSize)
		{
			uint num = (uint)(bufferSize - 1) >> 4;
			int num2 = 0;
			if (num > 65535)
			{
				num >>= 16;
				num2 = 16;
			}
			if (num > 255)
			{
				num >>= 8;
				num2 += 8;
			}
			if (num > 15)
			{
				num >>= 4;
				num2 += 4;
			}
			if (num > 3)
			{
				num >>= 2;
				num2 += 2;
			}
			if (num > 1)
			{
				num >>= 1;
				num2++;
			}
			return num2 + (int)num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int GetMaxSizeForBucket(int binIndex)
		{
			return 16 << binIndex;
		}
	}
}

BepInEx/plugins/FaceSync/System.Memory.dll

Decompiled a month ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FxResources.System.Memory;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDefaultAlias("System.Memory")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.Memory")]
[assembly: AssemblyFileVersion("4.600.325.20307")]
[assembly: AssemblyInformationalVersion("4.6.3+f62ca0009b038cab4725a720f386623a969d73ad")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Memory")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/maintenance-packages")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.5.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 FxResources.System.Memory
{
	internal static class SR
	{
	}
}
namespace System
{
	[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly struct Memory<T>
	{
		private readonly object _object;

		private readonly int _index;

		private readonly int _length;

		private const int RemoveFlagsBitMask = int.MaxValue;

		public static Memory<T> Empty => default(Memory<T>);

		public int Length => _length & 0x7FFFFFFF;

		public bool IsEmpty => (_length & 0x7FFFFFFF) == 0;

		public Span<T> Span
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				Span<T> result;
				if (_index < 0)
				{
					result = ((MemoryManager<T>)_object).GetSpan();
					return result.Slice(_index & 0x7FFFFFFF, _length);
				}
				if (typeof(T) == typeof(char) && _object is string text)
				{
					result = new Span<T>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)text), MemoryExtensions.StringAdjustment, text.Length);
					return result.Slice(_index, _length);
				}
				if (_object != null)
				{
					return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF);
				}
				result = default(Span<T>);
				return result;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory(T[] array)
		{
			if (array == null)
			{
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			_object = array;
			_index = 0;
			_length = array.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(T[] array, int start)
		{
			if (array == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = array.Length - start;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(Memory<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(MemoryManager<T> manager, int length)
		{
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = manager;
			_index = int.MinValue;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(MemoryManager<T> manager, int start, int length)
		{
			if (length < 0 || start < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = manager;
			_index = start | int.MinValue;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Memory(object obj, int start, int length)
		{
			_object = obj;
			_index = start;
			_length = length;
		}

		public static implicit operator Memory<T>(T[] array)
		{
			return new Memory<T>(array);
		}

		public static implicit operator Memory<T>(ArraySegment<T> segment)
		{
			return new Memory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public static implicit operator ReadOnlyMemory<T>(Memory<T> memory)
		{
			return System.Runtime.CompilerServices.Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
		}

		public override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (!(_object is string text))
				{
					return Span.ToString();
				}
				return text.Substring(_index, _length & 0x7FFFFFFF);
			}
			return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory<T> Slice(int start)
		{
			int length = _length;
			int num = length & 0x7FFFFFFF;
			if ((uint)start > (uint)num)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Memory<T>(_object, _index + start, length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Memory<T> Slice(int start, int length)
		{
			int length2 = _length;
			int num = length2 & 0x7FFFFFFF;
			if ((uint)start > (uint)num || (uint)length > (uint)(num - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue));
		}

		public void CopyTo(Memory<T> destination)
		{
			Span.CopyTo(destination.Span);
		}

		public bool TryCopyTo(Memory<T> destination)
		{
			return Span.TryCopyTo(destination.Span);
		}

		public unsafe MemoryHandle Pin()
		{
			if (_index < 0)
			{
				return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF);
			}
			if (typeof(T) == typeof(char) && _object is string value)
			{
				GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
				void* pointer = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = System.Runtime.CompilerServices.Unsafe.Add<T>(System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer3, handle2);
			}
			return default(MemoryHandle);
		}

		public T[] ToArray()
		{
			return Span.ToArray();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is ReadOnlyMemory<T> readOnlyMemory)
			{
				return readOnlyMemory.Equals(this);
			}
			if (obj is Memory<T> other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(Memory<T> other)
		{
			if (_object == other._object && _index == other._index)
			{
				return _length == other._length;
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			if (_object == null)
			{
				return 0;
			}
			int hashCode = _object.GetHashCode();
			int index = _index;
			int hashCode2 = index.GetHashCode();
			index = _length;
			return CombineHashCodes(hashCode, hashCode2, index.GetHashCode());
		}

		private static int CombineHashCodes(int left, int right)
		{
			return ((left << 5) + left) ^ right;
		}

		private static int CombineHashCodes(int h1, int h2, int h3)
		{
			return CombineHashCodes(CombineHashCodes(h1, h2), h3);
		}
	}
	internal sealed class MemoryDebugView<T>
	{
		private readonly ReadOnlyMemory<T> _memory;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items => _memory.ToArray();

		public MemoryDebugView(Memory<T> memory)
		{
			_memory = memory;
		}

		public MemoryDebugView(ReadOnlyMemory<T> memory)
		{
			_memory = memory;
		}
	}
	public static class MemoryExtensions
	{
		internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment();

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span)
		{
			return span.TrimStart().TrimEnd();
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span)
		{
			int i;
			for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++)
			{
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span)
		{
			int num = span.Length - 1;
			while (num >= 0 && char.IsWhiteSpace(span[num]))
			{
				num--;
			}
			return span.Slice(0, num + 1);
		}

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar)
		{
			return span.TrimStart(trimChar).TrimEnd(trimChar);
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar)
		{
			int i;
			for (i = 0; i < span.Length && span[i] == trimChar; i++)
			{
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar)
		{
			int num = span.Length - 1;
			while (num >= 0 && span[num] == trimChar)
			{
				num--;
			}
			return span.Slice(0, num + 1);
		}

		public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			return span.TrimStart(trimChars).TrimEnd(trimChars);
		}

		public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			if (trimChars.IsEmpty)
			{
				return span.TrimStart();
			}
			int i;
			for (i = 0; i < span.Length; i++)
			{
				int num = 0;
				while (num < trimChars.Length)
				{
					if (span[i] != trimChars[num])
					{
						num++;
						continue;
					}
					goto IL_003c;
				}
				break;
				IL_003c:;
			}
			return span.Slice(i);
		}

		public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars)
		{
			if (trimChars.IsEmpty)
			{
				return span.TrimEnd();
			}
			int num;
			for (num = span.Length - 1; num >= 0; num--)
			{
				int num2 = 0;
				while (num2 < trimChars.Length)
				{
					if (span[num] != trimChars[num2])
					{
						num2++;
						continue;
					}
					goto IL_0044;
				}
				break;
				IL_0044:;
			}
			return span.Slice(0, num + 1);
		}

		public static bool IsWhiteSpace(this ReadOnlySpan<char> span)
		{
			for (int i = 0; i < span.Length; i++)
			{
				if (!char.IsWhiteSpace(span[i]))
				{
					return false;
				}
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T>
		{
			int length = span.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length == other.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size);
				}
				return false;
			}
			if (length == other.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length);
			}
			return false;
		}

		public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length);
			}
			return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length);
			}
			return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T>
		{
			int length = span.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length == other.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size);
				}
				return false;
			}
			if (length == other.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T>
		{
			if (typeof(T) == typeof(byte))
			{
				return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length <= span.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size);
				}
				return false;
			}
			if (length <= span.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length <= span.Length)
				{
					return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size);
				}
				return false;
			}
			if (length <= span.Length)
			{
				return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = span.Length;
			int length2 = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length2 <= length)
				{
					return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2);
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>
		{
			int length = span.Length;
			int length2 = value.Length;
			if (default(T) != null && IsTypeComparableAsBytes<T>(out var size))
			{
				if (length2 <= length)
				{
					return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2);
			}
			return false;
		}

		public static void Reverse<T>(this Span<T> span)
		{
			ref T reference = ref MemoryMarshal.GetReference(span);
			int num = 0;
			int num2 = span.Length - 1;
			while (num < num2)
			{
				T val = System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num);
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num) = System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num2);
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num2) = val;
				num++;
				num2--;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this T[] array)
		{
			return new Span<T>(array);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this T[] array, int start, int length)
		{
			return new Span<T>(array, start, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment)
		{
			return new Span<T>(segment.Array, segment.Offset, segment.Count);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			if ((uint)length > segment.Count - start)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length);
			}
			return new Span<T>(segment.Array, segment.Offset + start, length);
		}

		public static Memory<T> AsMemory<T>(this T[] array)
		{
			return new Memory<T>(array);
		}

		public static Memory<T> AsMemory<T>(this T[] array, int start)
		{
			return new Memory<T>(array, start);
		}

		public static Memory<T> AsMemory<T>(this T[] array, int start, int length)
		{
			return new Memory<T>(array, start, length);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment)
		{
			return new Memory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start);
		}

		public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length)
		{
			if ((uint)start > segment.Count)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			if ((uint)length > segment.Count - start)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length);
			}
			return new Memory<T>(segment.Array, segment.Offset + start, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void CopyTo<T>(this T[] source, Span<T> destination)
		{
			new ReadOnlySpan<T>(source).CopyTo(destination);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void CopyTo<T>(this T[] source, Memory<T> destination)
		{
			source.CopyTo(destination.Span);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other)
		{
			return ((ReadOnlySpan<T>)span).Overlaps(other);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset)
		{
			return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset);
		}

		public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other)
		{
			if (span.IsEmpty || other.IsEmpty)
			{
				return false;
			}
			IntPtr intPtr = System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (System.Runtime.CompilerServices.Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr >= (uint)(span.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()))
				{
					return (uint)(int)intPtr > (uint)(-(other.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()));
				}
				return true;
			}
			if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()))
			{
				return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()));
			}
			return true;
		}

		public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset)
		{
			if (span.IsEmpty || other.IsEmpty)
			{
				elementOffset = 0;
				return false;
			}
			IntPtr intPtr = System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (System.Runtime.CompilerServices.Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr < (uint)(span.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>())))
				{
					if ((int)intPtr % System.Runtime.CompilerServices.Unsafe.SizeOf<T>() != 0)
					{
						System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
					}
					elementOffset = (int)intPtr / System.Runtime.CompilerServices.Unsafe.SizeOf<T>();
					return true;
				}
				elementOffset = 0;
				return false;
			}
			if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>())))
			{
				if ((long)intPtr % System.Runtime.CompilerServices.Unsafe.SizeOf<T>() != 0L)
				{
					System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
				}
				elementOffset = (int)((long)intPtr / System.Runtime.CompilerServices.Unsafe.SizeOf<T>());
				return true;
			}
			elementOffset = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable)
		{
			return span.BinarySearch<T, IComparable<T>>(comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			return BinarySearch((ReadOnlySpan<T>)span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T>
		{
			return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable)
		{
			return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			return System.SpanHelpers.BinarySearch(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T>
		{
			if (comparer == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer);
			}
			System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer);
			return BinarySearch(span, comparable);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool IsTypeComparableAsBytes<T>(out NUInt size)
		{
			if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
			{
				size = (NUInt)1;
				return true;
			}
			if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort))
			{
				size = (NUInt)2;
				return true;
			}
			if (typeof(T) == typeof(int) || typeof(T) == typeof(uint))
			{
				size = (NUInt)4;
				return true;
			}
			if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong))
			{
				size = (NUInt)8;
				return true;
			}
			size = default(NUInt);
			return false;
		}

		public static Span<T> AsSpan<T>(this T[] array, int start)
		{
			return Span<T>.Create(array, start);
		}

		public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			return span.IndexOf(value, comparisonType) >= 0;
		}

		public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.SequenceEqual(other);
			case StringComparison.OrdinalIgnoreCase:
				if (span.Length != other.Length)
				{
					return false;
				}
				return EqualsOrdinalIgnoreCase(span, other);
			default:
				return span.ToString().Equals(other.ToString(), comparisonType);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other)
		{
			if (other.Length == 0)
			{
				return true;
			}
			return CompareToOrdinalIgnoreCase(span, other) == 0;
		}

		public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
		{
			return comparisonType switch
			{
				StringComparison.Ordinal => span.SequenceCompareTo(other), 
				StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), 
				_ => string.Compare(span.ToString(), other.ToString(), comparisonType), 
			};
		}

		private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
		{
			int num = Math.Min(strA.Length, strB.Length);
			int num2 = num;
			fixed (char* ptr = &MemoryMarshal.GetReference(strA))
			{
				fixed (char* ptr3 = &MemoryMarshal.GetReference(strB))
				{
					char* ptr2 = ptr;
					char* ptr4 = ptr3;
					while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f')
					{
						int num3 = *ptr2;
						int num4 = *ptr4;
						if (num3 == num4)
						{
							ptr2++;
							ptr4++;
							num--;
							continue;
						}
						if ((uint)(num3 - 97) <= 25u)
						{
							num3 -= 32;
						}
						if ((uint)(num4 - 97) <= 25u)
						{
							num4 -= 32;
						}
						if (num3 != num4)
						{
							return num3 - num4;
						}
						ptr2++;
						ptr4++;
						num--;
					}
					if (num == 0)
					{
						return strA.Length - strB.Length;
					}
					num2 -= num;
					return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase);
				}
			}
		}

		public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			if (comparisonType == StringComparison.Ordinal)
			{
				return span.IndexOf(value);
			}
			return span.ToString().IndexOf(value.ToString(), comparisonType);
		}

		public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			if (destination.Length < source.Length)
			{
				return -1;
			}
			string text = source.ToString();
			string text2 = text.ToLower(culture);
			AsSpan(text2).CopyTo(destination);
			return source.Length;
		}

		public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination)
		{
			return source.ToLower(destination, CultureInfo.InvariantCulture);
		}

		public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			if (destination.Length < source.Length)
			{
				return -1;
			}
			string text = source.ToString();
			string text2 = text.ToUpper(culture);
			AsSpan(text2).CopyTo(destination);
			return source.Length;
		}

		public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination)
		{
			return source.ToUpper(destination, CultureInfo.InvariantCulture);
		}

		public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.EndsWith(value);
			case StringComparison.OrdinalIgnoreCase:
				if (value.Length <= span.Length)
				{
					return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value);
				}
				return false;
			default:
			{
				string text = span.ToString();
				string value2 = value.ToString();
				return text.EndsWith(value2, comparisonType);
			}
			}
		}

		public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
		{
			switch (comparisonType)
			{
			case StringComparison.Ordinal:
				return span.StartsWith(value);
			case StringComparison.OrdinalIgnoreCase:
				if (value.Length <= span.Length)
				{
					return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value);
				}
				return false;
			default:
			{
				string text = span.ToString();
				string value2 = value.ToString();
				return text.StartsWith(value2, comparisonType);
			}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text)
		{
			if (text == null)
			{
				return default(ReadOnlySpan<char>);
			}
			return new ReadOnlySpan<char>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text), StringAdjustment, text.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text, int start)
		{
			if (text == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlySpan<char>);
			}
			if ((uint)start > (uint)text.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlySpan<char>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text), StringAdjustment + start * 2, text.Length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ReadOnlySpan<char> AsSpan(this string text, int start, int length)
		{
			if (text == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlySpan<char>);
			}
			if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlySpan<char>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text), StringAdjustment + start * 2, length);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text)
		{
			if (text == null)
			{
				return default(ReadOnlyMemory<char>);
			}
			return new ReadOnlyMemory<char>(text, 0, text.Length);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text, int start)
		{
			if (text == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlyMemory<char>);
			}
			if ((uint)start > (uint)text.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<char>(text, start, text.Length - start);
		}

		public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length)
		{
			if (text == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(ReadOnlyMemory<char>);
			}
			if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<char>(text, start, length);
		}

		private unsafe static IntPtr MeasureStringAdjustment()
		{
			string text = "a";
			fixed (char* ptr = text)
			{
				return System.Runtime.CompilerServices.Unsafe.ByteOffset<char>(ref System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text).Data, ref System.Runtime.CompilerServices.Unsafe.AsRef<char>((void*)ptr));
			}
		}
	}
	internal struct MutableDecimal
	{
		public uint Flags;

		public uint High;

		public uint Low;

		public uint Mid;

		private const uint SignMask = 2147483648u;

		private const uint ScaleMask = 16711680u;

		private const int ScaleShift = 16;

		public bool IsNegative
		{
			get
			{
				return (Flags & 0x80000000u) != 0;
			}
			set
			{
				Flags = (Flags & 0x7FFFFFFFu) | (value ? 2147483648u : 0u);
			}
		}

		public int Scale
		{
			get
			{
				return (byte)(Flags >> 16);
			}
			set
			{
				Flags = (Flags & 0xFF00FFFFu) | (uint)(value << 16);
			}
		}
	}
	internal struct NUInt
	{
		private unsafe readonly void* _value;

		private unsafe NUInt(uint value)
		{
			_value = (void*)value;
		}

		private unsafe NUInt(ulong value)
		{
			_value = (void*)value;
		}

		public static implicit operator NUInt(uint value)
		{
			return new NUInt(value);
		}

		public unsafe static implicit operator IntPtr(NUInt value)
		{
			return (IntPtr)value._value;
		}

		public static explicit operator NUInt(int value)
		{
			return new NUInt((uint)value);
		}

		public unsafe static explicit operator void*(NUInt value)
		{
			return value._value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static NUInt operator *(NUInt left, NUInt right)
		{
			if (sizeof(IntPtr) != 4)
			{
				return new NUInt((ulong)left._value * (ulong)right._value);
			}
			return new NUInt((uint)((int)left._value * (int)right._value));
		}
	}
	internal static class DecimalDecCalc
	{
		private static uint D32DivMod1E9(uint hi32, ref uint lo32)
		{
			ulong num = ((ulong)hi32 << 32) | lo32;
			lo32 = (uint)(num / 1000000000);
			return (uint)(num % 1000000000);
		}

		internal static uint DecDivMod1E9(ref MutableDecimal value)
		{
			return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low);
		}

		internal static void DecAddInt32(ref MutableDecimal value, uint i)
		{
			if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u))
			{
				D32AddCarry(ref value.High, 1u);
			}
		}

		private static bool D32AddCarry(ref uint value, uint i)
		{
			uint num = value;
			uint num2 = (value = num + i);
			if (num2 >= num)
			{
				return num2 < i;
			}
			return true;
		}

		internal static void DecMul10(ref MutableDecimal value)
		{
			MutableDecimal d = value;
			DecShiftLeft(ref value);
			DecShiftLeft(ref value);
			DecAdd(ref value, d);
			DecShiftLeft(ref value);
		}

		private static void DecShiftLeft(ref MutableDecimal value)
		{
			uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u);
			uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u);
			value.Low <<= 1;
			value.Mid = (value.Mid << 1) | num;
			value.High = (value.High << 1) | num2;
		}

		private static void DecAdd(ref MutableDecimal value, MutableDecimal d)
		{
			if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u))
			{
				D32AddCarry(ref value.High, 1u);
			}
			if (D32AddCarry(ref value.Mid, d.Mid))
			{
				D32AddCarry(ref value.High, 1u);
			}
			D32AddCarry(ref value.High, d.High);
		}
	}
	internal static class Number
	{
		private static class DoubleHelper
		{
			public unsafe static uint Exponent(double d)
			{
				return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu;
			}

			public unsafe static ulong Mantissa(double d)
			{
				return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32);
			}

			public unsafe static bool Sign(double d)
			{
				return *(uint*)((byte*)(&d) + 4) >> 31 != 0;
			}
		}

		internal const int DECIMAL_PRECISION = 29;

		private static readonly ulong[] s_rgval64Power10 = new ulong[30]
		{
			11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL,
			13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL,
			9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL
		};

		private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15]
		{
			4, 7, 10, 14, 17, 20, 24, 27, 30, 34,
			37, 40, 44, 47, 50
		};

		private static readonly ulong[] s_rgval64Power10By16 = new ulong[42]
		{
			10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL,
			14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL,
			10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL,
			12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL,
			18230774251475056952uL, 16420821625123739930uL
		};

		private static readonly short[] s_rgexp64Power10By16 = new short[21]
		{
			54, 107, 160, 213, 266, 319, 373, 426, 479, 532,
			585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064,
			1117
		};

		public static void RoundNumber(ref NumberBuffer number, int pos)
		{
			Span<byte> digits = number.Digits;
			int i;
			for (i = 0; i < pos && digits[i] != 0; i++)
			{
			}
			if (i == pos && digits[i] >= 53)
			{
				while (i > 0 && digits[i - 1] == 57)
				{
					i--;
				}
				if (i > 0)
				{
					digits[i - 1]++;
				}
				else
				{
					number.Scale++;
					digits[0] = 49;
					i = 1;
				}
			}
			else
			{
				while (i > 0 && digits[i - 1] == 48)
				{
					i--;
				}
			}
			if (i == 0)
			{
				number.Scale = 0;
				number.IsNegative = false;
			}
			digits[i] = 0;
		}

		internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value)
		{
			double num = NumberToDouble(ref number);
			uint num2 = DoubleHelper.Exponent(num);
			ulong num3 = DoubleHelper.Mantissa(num);
			switch (num2)
			{
			case 2047u:
				value = 0.0;
				return false;
			case 0u:
				if (num3 == 0L)
				{
					num = 0.0;
				}
				break;
			}
			value = num;
			return true;
		}

		public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value)
		{
			MutableDecimal value2 = default(MutableDecimal);
			byte* ptr = number.UnsafeDigits;
			int num = number.Scale;
			if (*ptr == 0)
			{
				if (num > 0)
				{
					num = 0;
				}
			}
			else
			{
				if (num > 29)
				{
					return false;
				}
				while ((num > 0 || (*ptr != 0 && num > -28)) && (value2.High < 429496729 || (value2.High == 429496729 && (value2.Mid < 2576980377u || (value2.Mid == 2576980377u && (value2.Low < 2576980377u || (value2.Low == 2576980377u && *ptr <= 53)))))))
				{
					DecimalDecCalc.DecMul10(ref value2);
					if (*ptr != 0)
					{
						DecimalDecCalc.DecAddInt32(ref value2, (uint)(*(ptr++) - 48));
					}
					num--;
				}
				if (*(ptr++) >= 53)
				{
					bool flag = true;
					if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0)
					{
						int num2 = 20;
						while (*ptr == 48 && num2 != 0)
						{
							ptr++;
							num2--;
						}
						if (*ptr == 0 || num2 == 0)
						{
							flag = false;
						}
					}
					if (flag)
					{
						DecimalDecCalc.DecAddInt32(ref value2, 1u);
						if ((value2.High | value2.Mid | value2.Low) == 0)
						{
							value2.High = 429496729u;
							value2.Mid = 2576980377u;
							value2.Low = 2576980378u;
							num++;
						}
					}
				}
			}
			if (num > 0)
			{
				return false;
			}
			if (num <= -29)
			{
				value2.High = 0u;
				value2.Low = 0u;
				value2.Mid = 0u;
				value2.Scale = 28;
			}
			else
			{
				value2.Scale = -num;
			}
			value2.IsNegative = number.IsNegative;
			value = System.Runtime.CompilerServices.Unsafe.As<MutableDecimal, decimal>(ref value2);
			return true;
		}

		public static void DecimalToNumber(decimal value, ref NumberBuffer number)
		{
			ref MutableDecimal reference = ref System.Runtime.CompilerServices.Unsafe.As<decimal, MutableDecimal>(ref value);
			Span<byte> digits = number.Digits;
			number.IsNegative = reference.IsNegative;
			int num = 29;
			while ((reference.Mid != 0) | (reference.High != 0))
			{
				uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference);
				for (int i = 0; i < 9; i++)
				{
					digits[--num] = (byte)(num2 % 10 + 48);
					num2 /= 10;
				}
			}
			for (uint num3 = reference.Low; num3 != 0; num3 /= 10)
			{
				digits[--num] = (byte)(num3 % 10 + 48);
			}
			int num4 = 29 - num;
			number.Scale = num4 - reference.Scale;
			Span<byte> digits2 = number.Digits;
			int index = 0;
			while (--num4 >= 0)
			{
				digits2[index++] = digits[num++];
			}
			digits2[index] = 0;
		}

		private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count)
		{
			uint value;
			int bytesConsumed;
			bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D');
			return value;
		}

		private static ulong Mul32x32To64(uint a, uint b)
		{
			return (ulong)a * (ulong)b;
		}

		private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp)
		{
			ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32);
			if ((num & 0x8000000000000000uL) == 0L)
			{
				num <<= 1;
				pexp--;
			}
			return num;
		}

		private static int abs(int value)
		{
			if (value < 0)
			{
				return -value;
			}
			return value;
		}

		private unsafe static double NumberToDouble(ref NumberBuffer number)
		{
			ReadOnlySpan<byte> digits = number.Digits;
			int i = 0;
			int numDigits = number.NumDigits;
			int num = numDigits;
			for (; digits[i] == 48; i++)
			{
				num--;
			}
			if (num == 0)
			{
				return 0.0;
			}
			int num2 = Math.Min(num, 9);
			num -= num2;
			ulong num3 = DigitsToInt(digits, num2);
			if (num > 0)
			{
				num2 = Math.Min(num, 9);
				num -= num2;
				uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]);
				num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2);
			}
			int num4 = number.Scale - (numDigits - num);
			int num5 = abs(num4);
			if (num5 >= 352)
			{
				ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0);
				if (number.IsNegative)
				{
					num6 |= 0x8000000000000000uL;
				}
				return *(double*)(&num6);
			}
			int pexp = 64;
			if ((num3 & 0xFFFFFFFF00000000uL) == 0L)
			{
				num3 <<= 32;
				pexp -= 32;
			}
			if ((num3 & 0xFFFF000000000000uL) == 0L)
			{
				num3 <<= 16;
				pexp -= 16;
			}
			if ((num3 & 0xFF00000000000000uL) == 0L)
			{
				num3 <<= 8;
				pexp -= 8;
			}
			if ((num3 & 0xF000000000000000uL) == 0L)
			{
				num3 <<= 4;
				pexp -= 4;
			}
			if ((num3 & 0xC000000000000000uL) == 0L)
			{
				num3 <<= 2;
				pexp -= 2;
			}
			if ((num3 & 0x8000000000000000uL) == 0L)
			{
				num3 <<= 1;
				pexp--;
			}
			int num7 = num5 & 0xF;
			if (num7 != 0)
			{
				int num8 = s_rgexp64Power10[num7 - 1];
				pexp += ((num4 < 0) ? (-num8 + 1) : num8);
				ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1];
				num3 = Mul64Lossy(num3, b2, ref pexp);
			}
			num7 = num5 >> 4;
			if (num7 != 0)
			{
				int num9 = s_rgexp64Power10By16[num7 - 1];
				pexp += ((num4 < 0) ? (-num9 + 1) : num9);
				ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1];
				num3 = Mul64Lossy(num3, b3, ref pexp);
			}
			if (((uint)(int)num3 & 0x400u) != 0)
			{
				ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1);
				if (num10 < num3)
				{
					num10 = (num10 >> 1) | 0x8000000000000000uL;
					pexp++;
				}
				num3 = num10;
			}
			pexp += 1022;
			num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL));
			if (number.IsNegative)
			{
				num3 |= 0x8000000000000000uL;
			}
			return *(double*)(&num3);
		}
	}
	internal ref struct NumberBuffer
	{
		public int Scale;

		public bool IsNegative;

		public const int BufferSize = 51;

		private byte _b0;

		private byte _b1;

		private byte _b2;

		private byte _b3;

		private byte _b4;

		private byte _b5;

		private byte _b6;

		private byte _b7;

		private byte _b8;

		private byte _b9;

		private byte _b10;

		private byte _b11;

		private byte _b12;

		private byte _b13;

		private byte _b14;

		private byte _b15;

		private byte _b16;

		private byte _b17;

		private byte _b18;

		private byte _b19;

		private byte _b20;

		private byte _b21;

		private byte _b22;

		private byte _b23;

		private byte _b24;

		private byte _b25;

		private byte _b26;

		private byte _b27;

		private byte _b28;

		private byte _b29;

		private byte _b30;

		private byte _b31;

		private byte _b32;

		private byte _b33;

		private byte _b34;

		private byte _b35;

		private byte _b36;

		private byte _b37;

		private byte _b38;

		private byte _b39;

		private byte _b40;

		private byte _b41;

		private byte _b42;

		private byte _b43;

		private byte _b44;

		private byte _b45;

		private byte _b46;

		private byte _b47;

		private byte _b48;

		private byte _b49;

		private byte _b50;

		public unsafe Span<byte> Digits => new Span<byte>(System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref _b0), 51);

		public unsafe byte* UnsafeDigits => (byte*)System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref _b0);

		public int NumDigits => Digits.IndexOf<byte>(0);

		[Conditional("DEBUG")]
		public void CheckConsistency()
		{
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append('[');
			stringBuilder.Append('"');
			Span<byte> digits = Digits;
			for (int i = 0; i < 51; i++)
			{
				byte b = digits[i];
				if (b == 0)
				{
					break;
				}
				stringBuilder.Append((char)b);
			}
			stringBuilder.Append('"');
			stringBuilder.Append(", Scale = " + Scale);
			stringBuilder.Append(", IsNegative   = " + IsNegative);
			stringBuilder.Append(']');
			return stringBuilder.ToString();
		}
	}
	[StructLayout(LayoutKind.Sequential)]
	internal sealed class Pinnable<T>
	{
		public T Data;
	}
	[DebuggerTypeProxy(typeof(System.MemoryDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly struct ReadOnlyMemory<T>
	{
		private readonly object _object;

		private readonly int _index;

		private readonly int _length;

		internal const int RemoveFlagsBitMask = int.MaxValue;

		public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>);

		public int Length => _length & 0x7FFFFFFF;

		public bool IsEmpty => (_length & 0x7FFFFFFF) == 0;

		public ReadOnlySpan<T> Span
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (_index < 0)
				{
					return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length);
				}
				ReadOnlySpan<T> result;
				if (typeof(T) == typeof(char) && _object is string text)
				{
					result = new ReadOnlySpan<T>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)text), MemoryExtensions.StringAdjustment, text.Length);
					return result.Slice(_index, _length);
				}
				if (_object != null)
				{
					return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF);
				}
				result = default(ReadOnlySpan<T>);
				return result;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory(T[] array)
		{
			if (array == null)
			{
				this = default(ReadOnlyMemory<T>);
				return;
			}
			_object = array;
			_index = 0;
			_length = array.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException();
				}
				this = default(ReadOnlyMemory<T>);
				return;
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException();
			}
			_object = array;
			_index = start;
			_length = length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ReadOnlyMemory(object obj, int start, int length)
		{
			_object = obj;
			_index = start;
			_length = length;
		}

		public static implicit operator ReadOnlyMemory<T>(T[] array)
		{
			return new ReadOnlyMemory<T>(array);
		}

		public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment)
		{
			return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
		}

		public override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (!(_object is string text))
				{
					return Span.ToString();
				}
				return text.Substring(_index, _length & 0x7FFFFFFF);
			}
			return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory<T> Slice(int start)
		{
			int length = _length;
			int num = length & 0x7FFFFFFF;
			if ((uint)start > (uint)num)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<T>(_object, _index + start, length - start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlyMemory<T> Slice(int start, int length)
		{
			int length2 = _length;
			int num = _length & 0x7FFFFFFF;
			if ((uint)start > (uint)num || (uint)length > (uint)(num - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue));
		}

		public void CopyTo(Memory<T> destination)
		{
			Span.CopyTo(destination.Span);
		}

		public bool TryCopyTo(Memory<T> destination)
		{
			return Span.TryCopyTo(destination.Span);
		}

		public unsafe MemoryHandle Pin()
		{
			if (_index < 0)
			{
				return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF);
			}
			if (typeof(T) == typeof(char) && _object is string value)
			{
				GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
				void* pointer = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = System.Runtime.CompilerServices.Unsafe.Add<T>(System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer3, handle2);
			}
			return default(MemoryHandle);
		}

		public T[] ToArray()
		{
			return Span.ToArray();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is ReadOnlyMemory<T> other)
			{
				return Equals(other);
			}
			if (obj is Memory<T> memory)
			{
				return Equals(memory);
			}
			return false;
		}

		public bool Equals(ReadOnlyMemory<T> other)
		{
			if (_object == other._object && _index == other._index)
			{
				return _length == other._length;
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			if (_object == null)
			{
				return 0;
			}
			int hashCode = _object.GetHashCode();
			int index = _index;
			int hashCode2 = index.GetHashCode();
			index = _length;
			return CombineHashCodes(hashCode, hashCode2, index.GetHashCode());
		}

		private static int CombineHashCodes(int left, int right)
		{
			return ((left << 5) + left) ^ right;
		}

		private static int CombineHashCodes(int h1, int h2, int h3)
		{
			return CombineHashCodes(CombineHashCodes(h1, h2), h3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal object GetObjectStartLength(out int start, out int length)
		{
			start = _index;
			length = _length;
			return _object;
		}
	}
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly ref struct ReadOnlySpan<T>
	{
		public ref struct Enumerator
		{
			private readonly ReadOnlySpan<T> _span;

			private int _index;

			public ref readonly T Current
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return ref _span[_index];
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal Enumerator(ReadOnlySpan<T> span)
			{
				_span = span;
				_index = -1;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public bool MoveNext()
			{
				int num = _index + 1;
				if (num < _span.Length)
				{
					_index = num;
					return true;
				}
				return false;
			}
		}

		private readonly Pinnable<T> _pinnable;

		private readonly IntPtr _byteOffset;

		private readonly int _length;

		public int Length => _length;

		public bool IsEmpty => _length == 0;

		public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);

		public unsafe ref readonly T this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if ((uint)index >= (uint)_length)
				{
					System.ThrowHelper.ThrowIndexOutOfRangeException();
				}
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
			}
		}

		internal Pinnable<T> Pinnable => _pinnable;

		internal IntPtr ByteOffset => _byteOffset;

		public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
		{
			return !(left == right);
		}

		[Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan);
		}

		[Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan);
		}

		public static implicit operator ReadOnlySpan<T>(T[] array)
		{
			return new ReadOnlySpan<T>(array);
		}

		public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment)
		{
			return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan(T[] array)
		{
			if (array == null)
			{
				this = default(ReadOnlySpan<T>);
				return;
			}
			_length = array.Length;
			_pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				this = default(ReadOnlySpan<T>);
				return;
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public unsafe ReadOnlySpan(void* pointer, int length)
		{
			if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
			}
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = null;
			_byteOffset = new IntPtr(pointer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length)
		{
			_length = length;
			_pinnable = pinnable;
			_byteOffset = byteOffset;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public unsafe ref readonly T GetPinnableReference()
		{
			if (_length != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
			}
			return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>((void*)null);
		}

		public void CopyTo(Span<T> destination)
		{
			if (!TryCopyTo(destination))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
		}

		public bool TryCopyTo(Span<T> destination)
		{
			int length = _length;
			int length2 = destination.Length;
			if (length == 0)
			{
				return true;
			}
			if ((uint)length > (uint)length2)
			{
				return false;
			}
			ref T src = ref DangerousGetPinnableReference();
			System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length);
			return true;
		}

		public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
		{
			if (left._length == right._length)
			{
				return System.Runtime.CompilerServices.Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (_byteOffset == MemoryExtensions.StringAdjustment)
				{
					object obj = System.Runtime.CompilerServices.Unsafe.As<object>((object)_pinnable);
					if (obj is string text && _length == text.Length)
					{
						return text;
					}
				}
				fixed (char* value = &System.Runtime.CompilerServices.Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
				{
					return new string(value, 0, _length);
				}
			}
			return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan<T> Slice(int start)
		{
			if ((uint)start > (uint)_length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			int length = _length - start;
			return new ReadOnlySpan<T>(_pinnable, byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ReadOnlySpan<T> Slice(int start, int length)
		{
			if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			return new ReadOnlySpan<T>(_pinnable, byteOffset, length);
		}

		public T[] ToArray()
		{
			if (_length == 0)
			{
				return System.SpanHelpers.PerTypeValues<T>.EmptyArray;
			}
			T[] array = new T[_length];
			CopyTo(array);
			return array;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal unsafe ref T DangerousGetPinnableReference()
		{
			if (_pinnable == null)
			{
				IntPtr byteOffset = _byteOffset;
				return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
		}
	}
	public readonly struct SequencePosition : IEquatable<SequencePosition>
	{
		private readonly object _object;

		private readonly int _integer;

		public SequencePosition(object @object, int integer)
		{
			_object = @object;
			_integer = integer;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public object GetObject()
		{
			return _object;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public int GetInteger()
		{
			return _integer;
		}

		public bool Equals(SequencePosition other)
		{
			if (_integer == other._integer)
			{
				return object.Equals(_object, other._object);
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			if (obj is SequencePosition other)
			{
				return Equals(other);
			}
			return false;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer);
		}
	}
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	[DebuggerTypeProxy(typeof(System.SpanDebugView<>))]
	[DebuggerDisplay("{ToString(),raw}")]
	public readonly ref struct Span<T>
	{
		public ref struct Enumerator
		{
			private readonly Span<T> _span;

			private int _index;

			public ref T Current
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return ref _span[_index];
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal Enumerator(Span<T> span)
			{
				_span = span;
				_index = -1;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public bool MoveNext()
			{
				int num = _index + 1;
				if (num < _span.Length)
				{
					_index = num;
					return true;
				}
				return false;
			}
		}

		private readonly Pinnable<T> _pinnable;

		private readonly IntPtr _byteOffset;

		private readonly int _length;

		public int Length => _length;

		public bool IsEmpty => _length == 0;

		public static Span<T> Empty => default(Span<T>);

		public unsafe ref T this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if ((uint)index >= (uint)_length)
				{
					System.ThrowHelper.ThrowIndexOutOfRangeException();
				}
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
			}
		}

		internal Pinnable<T> Pinnable => _pinnable;

		internal IntPtr ByteOffset => _byteOffset;

		public static bool operator !=(Span<T> left, Span<T> right)
		{
			return !(left == right);
		}

		[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj)
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan);
		}

		[Obsolete("GetHashCode() on Span will always throw an exception.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan);
		}

		public static implicit operator Span<T>(T[] array)
		{
			return new Span<T>(array);
		}

		public static implicit operator Span<T>(ArraySegment<T> segment)
		{
			return new Span<T>(segment.Array, segment.Offset, segment.Count);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span(T[] array)
		{
			if (array == null)
			{
				this = default(Span<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			_length = array.Length;
			_pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static Span<T> Create(T[] array, int start)
		{
			if (array == null)
			{
				if (start != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				return default(Span<T>);
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
			int length = array.Length - start;
			return new Span<T>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array), byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span(T[] array, int start, int length)
		{
			if (array == null)
			{
				if (start != 0 || length != 0)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
				}
				this = default(Span<T>);
				return;
			}
			if (default(T) == null && array.GetType() != typeof(T[]))
			{
				System.ThrowHelper.ThrowArrayTypeMismatchException();
			}
			if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array);
			_byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public unsafe Span(void* pointer, int length)
		{
			if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
			}
			if (length < 0)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			_length = length;
			_pinnable = null;
			_byteOffset = new IntPtr(pointer);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
		{
			_length = length;
			_pinnable = pinnable;
			_byteOffset = byteOffset;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public unsafe ref T GetPinnableReference()
		{
			if (_length != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
			}
			return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>((void*)null);
		}

		public unsafe void Clear()
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>());
			if ((System.Runtime.CompilerServices.Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
			{
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					byte* ptr = (byte*)byteOffset.ToPointer();
					System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
				}
				else
				{
					System.SpanHelpers.ClearLessThanPointerSized(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset)), byteLength);
				}
			}
			else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>() / sizeof(IntPtr));
				System.SpanHelpers.ClearPointerSizedWithReferences(ref System.Runtime.CompilerServices.Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength);
			}
			else
			{
				System.SpanHelpers.ClearPointerSizedWithoutReferences(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength);
			}
		}

		public unsafe void Fill(T value)
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			if (System.Runtime.CompilerServices.Unsafe.SizeOf<T>() == 1)
			{
				byte b = System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value);
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), b, (uint)length);
				}
				else
				{
					System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset)), b, (uint)length);
				}
				return;
			}
			ref T reference = ref DangerousGetPinnableReference();
			int i;
			for (i = 0; i < (length & -8); i += 8)
			{
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 1) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 2) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 3) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 4) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 5) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 6) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 7) = value;
			}
			if (i < (length & -4))
			{
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 1) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 2) = value;
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 3) = value;
				i += 4;
			}
			for (; i < length; i++)
			{
				System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value;
			}
		}

		public void CopyTo(Span<T> destination)
		{
			if (!TryCopyTo(destination))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
		}

		public bool TryCopyTo(Span<T> destination)
		{
			int length = _length;
			int length2 = destination._length;
			if (length == 0)
			{
				return true;
			}
			if ((uint)length > (uint)length2)
			{
				return false;
			}
			ref T src = ref DangerousGetPinnableReference();
			System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length);
			return true;
		}

		public static bool operator ==(Span<T> left, Span<T> right)
		{
			if (left._length == right._length)
			{
				return System.Runtime.CompilerServices.Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public static implicit operator ReadOnlySpan<T>(Span<T> span)
		{
			return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				fixed (char* value = &System.Runtime.CompilerServices.Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
				{
					return new string(value, 0, _length);
				}
			}
			return $"System.Span<{typeof(T).Name}>[{_length}]";
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<T> Slice(int start)
		{
			if ((uint)start > (uint)_length)
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			int length = _length - start;
			return new Span<T>(_pinnable, byteOffset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<T> Slice(int start, int length)
		{
			if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			IntPtr byteOffset = _byteOffset.Add<T>(start);
			return new Span<T>(_pinnable, byteOffset, length);
		}

		public T[] ToArray()
		{
			if (_length == 0)
			{
				return System.SpanHelpers.PerTypeValues<T>.EmptyArray;
			}
			T[] array = new T[_length];
			CopyTo(array);
			return array;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal unsafe ref T DangerousGetPinnableReference()
		{
			if (_pinnable == null)
			{
				IntPtr byteOffset = _byteOffset;
				return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
		}
	}
	internal sealed class SpanDebugView<T>
	{
		private readonly T[] _array;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items => _array;

		public SpanDebugView(Span<T> span)
		{
			_array = span.ToArray();
		}

		public SpanDebugView(ReadOnlySpan<T> span)
		{
			_array = span.ToArray();
		}
	}
	internal static class SpanHelpers
	{
		internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T>
		{
			private readonly T _value;

			private readonly TComparer _comparer;

			public ComparerComparable(T value, TComparer comparer)
			{
				_value = value;
				_comparer = comparer;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int CompareTo(T other)
			{
				return _comparer.Compare(_value, other);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 64)]
		private struct Reg64
		{
		}

		[StructLayout(LayoutKind.Sequential, Size = 32)]
		private struct Reg32
		{
		}

		[StructLayout(LayoutKind.Sequential, Size = 16)]
		private struct Reg16
		{
		}

		public static class PerTypeValues<T>
		{
			public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T));

			public static readonly T[] EmptyArray = new T[0];

			public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment();

			private static IntPtr MeasureArrayAdjustment()
			{
				T[] array = new T[1];
				return System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array).Data, ref array[0]);
			}
		}

		private const ulong XorPowerOfTwoToHighByte = 283686952306184uL;

		private const ulong XorPowerOfTwoToHighChar = 4295098372uL;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T>
		{
			if (comparable == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable);
			}
			return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable);
		}

		public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T>
		{
			int num = 0;
			int num2 = length - 1;
			while (num <= num2)
			{
				int num3 = num2 + num >>> 1;
				ref TComparable reference = ref comparable;
				TComparable val = default(TComparable);
				if (val == null)
				{
					val = reference;
					reference = ref val;
				}
				int num4 = reference.CompareTo(System.Runtime.CompilerServices.Unsafe.Add<T>(ref spanStart, num3));
				if (num4 == 0)
				{
					return num3;
				}
				if (num4 > 0)
				{
					num = num3 + 1;
				}
				else
				{
					num2 = num3 - 1;
				}
			}
			return ~num;
		}

		public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = IndexOf(ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref searchSpace, num2), value2, num3);
				if (num4 == -1)
				{
					break;
				}
				num2 += num4;
				if (SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref searchSpace, num2 + 1), ref second, num))
				{
					return num2;
				}
				num2++;
			}
			return -1;
		}

		public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			int num = -1;
			for (int i = 0; i < valueLength; i++)
			{
				int num2 = IndexOf(ref searchSpace, System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, i), searchSpaceLength);
				if ((uint)num2 < (uint)num)
				{
					num = num2;
					searchSpaceLength = num2;
					if (num == 0)
					{
						break;
					}
				}
			}
			return num;
		}

		public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			int num = -1;
			for (int i = 0; i < valueLength; i++)
			{
				int num2 = LastIndexOf(ref searchSpace, System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, i), searchSpaceLength);
				if (num2 > num)
				{
					num = num2;
				}
			}
			return num;
		}

		public unsafe static int IndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)0;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 3))
					{
						if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 4))
						{
							if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 5))
							{
								if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 6))
								{
									if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 7))
									{
										break;
									}
									intPtr += 8;
									continue;
								}
								return (int)(void*)(intPtr + 6);
							}
							return (int)(void*)(intPtr + 5);
						}
						return (int)(void*)(intPtr + 4);
					}
					goto IL_0266;
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 3))
					{
						goto IL_0266;
					}
					intPtr += 4;
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr))
					{
						intPtr += 1;
						continue;
					}
					goto IL_0242;
				}
				if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length)
				{
					intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1));
					Vector<byte> vector = GetVector(value);
					for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count)
					{
						Vector<byte> vector2 = Vector.Equals(vector, System.Runtime.CompilerServices.Unsafe.ReadUnaligned<Vector<byte>>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr)));
						if (!Vector<byte>.Zero.Equals(vector2))
						{
							return (int)(void*)intPtr + LocateFirstFoundByte(vector2);
						}
					}
					if ((int)(void*)intPtr < length)
					{
						intPtr2 = (IntPtr)(length - (int)(void*)intPtr);
						continue;
					}
				}
				return -1;
				IL_0266:
				return (int)(void*)(intPtr + 3);
				IL_0242:
				return (int)(void*)intPtr;
				IL_0258:
				return (int)(void*)(intPtr + 2);
				IL_024a:
				return (int)(void*)(intPtr + 1);
			}
			return (int)(void*)(intPtr + 7);
		}

		public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = LastIndexOf(ref searchSpace, value2, num3);
				if (num4 == -1)
				{
					break;
				}
				if (SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref searchSpace, num4 + 1), ref second, num))
				{
					return num4;
				}
				num2 += num3 - num4;
			}
			return -1;
		}

		public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)length;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					intPtr -= 8;
					if (value == System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 7))
					{
						break;
					}
					if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 6))
					{
						if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 5))
						{
							if (value != System.Runtime.CompilerServices.Unsafe.AddByteOffset<byte>(ref searchSpace, intPtr + 4))
							{
								if (value != System.Runtime.Compil

BepInEx/plugins/FaceSync/System.Numerics.Vectors.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FxResources.System.Numerics.Vectors;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDefaultAlias("System.Numerics.Vectors")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.Numerics.Vectors")]
[assembly: AssemblyFileVersion("4.600.125.16908")]
[assembly: AssemblyInformationalVersion("4.6.1+6b84308c9ad012f53240d72c1d716d7e42546483")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Numerics.Vectors")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/maintenance-packages")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.6.0")]
[assembly: TypeForwardedTo(typeof(Matrix3x2))]
[assembly: TypeForwardedTo(typeof(Matrix4x4))]
[assembly: TypeForwardedTo(typeof(Plane))]
[assembly: TypeForwardedTo(typeof(Quaternion))]
[assembly: TypeForwardedTo(typeof(Vector2))]
[assembly: TypeForwardedTo(typeof(Vector3))]
[assembly: TypeForwardedTo(typeof(Vector4))]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 FxResources.System.Numerics.Vectors
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class MathF
	{
		public const float PI = 3.1415927f;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Abs(float x)
		{
			return Math.Abs(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Acos(float x)
		{
			return (float)Math.Acos(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Cos(float x)
		{
			return (float)Math.Cos(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float IEEERemainder(float x, float y)
		{
			return (float)Math.IEEERemainder(x, y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Pow(float x, float y)
		{
			return (float)Math.Pow(x, y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Sin(float x)
		{
			return (float)Math.Sin(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Sqrt(float x)
		{
			return (float)Math.Sqrt(x);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Tan(float x)
		{
			return (float)Math.Tan(x);
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException");

		internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination");

		internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef");

		internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported");

		internal static string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements");

		private static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		internal static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object? p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object? p1, object? p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object? p1, object? p2, object? p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)]
	internal sealed class IntrinsicAttribute : Attribute
	{
	}
}
namespace System.Numerics
{
	internal class ConstantHelper
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static byte GetByteWithAllBitsSet()
		{
			byte result = 0;
			result = byte.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static sbyte GetSByteWithAllBitsSet()
		{
			sbyte result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ushort GetUInt16WithAllBitsSet()
		{
			ushort result = 0;
			result = ushort.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short GetInt16WithAllBitsSet()
		{
			short result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint GetUInt32WithAllBitsSet()
		{
			uint result = 0u;
			result = uint.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetInt32WithAllBitsSet()
		{
			int result = 0;
			result = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ulong GetUInt64WithAllBitsSet()
		{
			ulong result = 0uL;
			result = ulong.MaxValue;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static long GetInt64WithAllBitsSet()
		{
			long result = 0L;
			result = -1L;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static float GetSingleWithAllBitsSet()
		{
			float result = 0f;
			*(int*)(&result) = -1;
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static double GetDoubleWithAllBitsSet()
		{
			double result = 0.0;
			*(long*)(&result) = -1L;
			return result;
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Register
	{
		[FieldOffset(0)]
		internal byte byte_0;

		[FieldOffset(1)]
		internal byte byte_1;

		[FieldOffset(2)]
		internal byte byte_2;

		[FieldOffset(3)]
		internal byte byte_3;

		[FieldOffset(4)]
		internal byte byte_4;

		[FieldOffset(5)]
		internal byte byte_5;

		[FieldOffset(6)]
		internal byte byte_6;

		[FieldOffset(7)]
		internal byte byte_7;

		[FieldOffset(8)]
		internal byte byte_8;

		[FieldOffset(9)]
		internal byte byte_9;

		[FieldOffset(10)]
		internal byte byte_10;

		[FieldOffset(11)]
		internal byte byte_11;

		[FieldOffset(12)]
		internal byte byte_12;

		[FieldOffset(13)]
		internal byte byte_13;

		[FieldOffset(14)]
		internal byte byte_14;

		[FieldOffset(15)]
		internal byte byte_15;

		[FieldOffset(0)]
		internal sbyte sbyte_0;

		[FieldOffset(1)]
		internal sbyte sbyte_1;

		[FieldOffset(2)]
		internal sbyte sbyte_2;

		[FieldOffset(3)]
		internal sbyte sbyte_3;

		[FieldOffset(4)]
		internal sbyte sbyte_4;

		[FieldOffset(5)]
		internal sbyte sbyte_5;

		[FieldOffset(6)]
		internal sbyte sbyte_6;

		[FieldOffset(7)]
		internal sbyte sbyte_7;

		[FieldOffset(8)]
		internal sbyte sbyte_8;

		[FieldOffset(9)]
		internal sbyte sbyte_9;

		[FieldOffset(10)]
		internal sbyte sbyte_10;

		[FieldOffset(11)]
		internal sbyte sbyte_11;

		[FieldOffset(12)]
		internal sbyte sbyte_12;

		[FieldOffset(13)]
		internal sbyte sbyte_13;

		[FieldOffset(14)]
		internal sbyte sbyte_14;

		[FieldOffset(15)]
		internal sbyte sbyte_15;

		[FieldOffset(0)]
		internal ushort uint16_0;

		[FieldOffset(2)]
		internal ushort uint16_1;

		[FieldOffset(4)]
		internal ushort uint16_2;

		[FieldOffset(6)]
		internal ushort uint16_3;

		[FieldOffset(8)]
		internal ushort uint16_4;

		[FieldOffset(10)]
		internal ushort uint16_5;

		[FieldOffset(12)]
		internal ushort uint16_6;

		[FieldOffset(14)]
		internal ushort uint16_7;

		[FieldOffset(0)]
		internal short int16_0;

		[FieldOffset(2)]
		internal short int16_1;

		[FieldOffset(4)]
		internal short int16_2;

		[FieldOffset(6)]
		internal short int16_3;

		[FieldOffset(8)]
		internal short int16_4;

		[FieldOffset(10)]
		internal short int16_5;

		[FieldOffset(12)]
		internal short int16_6;

		[FieldOffset(14)]
		internal short int16_7;

		[FieldOffset(0)]
		internal uint uint32_0;

		[FieldOffset(4)]
		internal uint uint32_1;

		[FieldOffset(8)]
		internal uint uint32_2;

		[FieldOffset(12)]
		internal uint uint32_3;

		[FieldOffset(0)]
		internal int int32_0;

		[FieldOffset(4)]
		internal int int32_1;

		[FieldOffset(8)]
		internal int int32_2;

		[FieldOffset(12)]
		internal int int32_3;

		[FieldOffset(0)]
		internal ulong uint64_0;

		[FieldOffset(8)]
		internal ulong uint64_1;

		[FieldOffset(0)]
		internal long int64_0;

		[FieldOffset(8)]
		internal long int64_1;

		[FieldOffset(0)]
		internal float single_0;

		[FieldOffset(4)]
		internal float single_1;

		[FieldOffset(8)]
		internal float single_2;

		[FieldOffset(12)]
		internal float single_3;

		[FieldOffset(0)]
		internal double double_0;

		[FieldOffset(8)]
		internal double double_1;
	}
	[System.Runtime.CompilerServices.Intrinsic]
	public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct
	{
		private struct VectorSizeHelper
		{
			internal Vector<T> _placeholder;

			internal byte _byte;
		}

		private System.Numerics.Register register;

		private static readonly int s_count = InitializeCount();

		private static readonly Vector<T> s_zero = default(Vector<T>);

		private static readonly Vector<T> s_one = new Vector<T>(GetOneValue());

		private static readonly Vector<T> s_allOnes = new Vector<T>(GetAllBitsSetValue());

		public static int Count
		{
			[System.Runtime.CompilerServices.Intrinsic]
			get
			{
				return s_count;
			}
		}

		public static Vector<T> Zero
		{
			[System.Runtime.CompilerServices.Intrinsic]
			get
			{
				return s_zero;
			}
		}

		public static Vector<T> One
		{
			[System.Runtime.CompilerServices.Intrinsic]
			get
			{
				return s_one;
			}
		}

		internal static Vector<T> AllOnes => s_allOnes;

		public unsafe T this[int index]
		{
			[System.Runtime.CompilerServices.Intrinsic]
			get
			{
				if (index >= Count || index < 0)
				{
					throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index));
				}
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						return (T)(object)ptr[index];
					}
				}
				if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						return (T)(object)ptr2[index];
					}
				}
				if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						return (T)(object)ptr3[index];
					}
				}
				if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						return (T)(object)ptr4[index];
					}
				}
				if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						return (T)(object)ptr5[index];
					}
				}
				if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						return (T)(object)ptr6[index];
					}
				}
				if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						return (T)(object)ptr7[index];
					}
				}
				if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						return (T)(object)ptr8[index];
					}
				}
				if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						return (T)(object)ptr9[index];
					}
				}
				if (typeof(T) == typeof(double))
				{
					fixed (double* ptr10 = &register.double_0)
					{
						return (T)(object)ptr10[index];
					}
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
		}

		private unsafe static int InitializeCount()
		{
			VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper);
			byte* ptr = &vectorSizeHelper._placeholder.register.byte_0;
			byte* ptr2 = &vectorSizeHelper._byte;
			int num = (int)(ptr2 - ptr);
			int num2 = -1;
			if (typeof(T) == typeof(byte))
			{
				num2 = 1;
			}
			else if (typeof(T) == typeof(sbyte))
			{
				num2 = 1;
			}
			else if (typeof(T) == typeof(ushort))
			{
				num2 = 2;
			}
			else if (typeof(T) == typeof(short))
			{
				num2 = 2;
			}
			else if (typeof(T) == typeof(uint))
			{
				num2 = 4;
			}
			else if (typeof(T) == typeof(int))
			{
				num2 = 4;
			}
			else if (typeof(T) == typeof(ulong))
			{
				num2 = 8;
			}
			else if (typeof(T) == typeof(long))
			{
				num2 = 8;
			}
			else if (typeof(T) == typeof(float))
			{
				num2 = 4;
			}
			else
			{
				if (!(typeof(T) == typeof(double)))
				{
					throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
				}
				num2 = 8;
			}
			return num / num2;
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public unsafe Vector(T value)
		{
			this = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)value;
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.double_0)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[num4] = (double)(object)value;
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				register.byte_0 = (byte)(object)value;
				register.byte_1 = (byte)(object)value;
				register.byte_2 = (byte)(object)value;
				register.byte_3 = (byte)(object)value;
				register.byte_4 = (byte)(object)value;
				register.byte_5 = (byte)(object)value;
				register.byte_6 = (byte)(object)value;
				register.byte_7 = (byte)(object)value;
				register.byte_8 = (byte)(object)value;
				register.byte_9 = (byte)(object)value;
				register.byte_10 = (byte)(object)value;
				register.byte_11 = (byte)(object)value;
				register.byte_12 = (byte)(object)value;
				register.byte_13 = (byte)(object)value;
				register.byte_14 = (byte)(object)value;
				register.byte_15 = (byte)(object)value;
			}
			else if (typeof(T) == typeof(sbyte))
			{
				register.sbyte_0 = (sbyte)(object)value;
				register.sbyte_1 = (sbyte)(object)value;
				register.sbyte_2 = (sbyte)(object)value;
				register.sbyte_3 = (sbyte)(object)value;
				register.sbyte_4 = (sbyte)(object)value;
				register.sbyte_5 = (sbyte)(object)value;
				register.sbyte_6 = (sbyte)(object)value;
				register.sbyte_7 = (sbyte)(object)value;
				register.sbyte_8 = (sbyte)(object)value;
				register.sbyte_9 = (sbyte)(object)value;
				register.sbyte_10 = (sbyte)(object)value;
				register.sbyte_11 = (sbyte)(object)value;
				register.sbyte_12 = (sbyte)(object)value;
				register.sbyte_13 = (sbyte)(object)value;
				register.sbyte_14 = (sbyte)(object)value;
				register.sbyte_15 = (sbyte)(object)value;
			}
			else if (typeof(T) == typeof(ushort))
			{
				register.uint16_0 = (ushort)(object)value;
				register.uint16_1 = (ushort)(object)value;
				register.uint16_2 = (ushort)(object)value;
				register.uint16_3 = (ushort)(object)value;
				register.uint16_4 = (ushort)(object)value;
				register.uint16_5 = (ushort)(object)value;
				register.uint16_6 = (ushort)(object)value;
				register.uint16_7 = (ushort)(object)value;
			}
			else if (typeof(T) == typeof(short))
			{
				register.int16_0 = (short)(object)value;
				register.int16_1 = (short)(object)value;
				register.int16_2 = (short)(object)value;
				register.int16_3 = (short)(object)value;
				register.int16_4 = (short)(object)value;
				register.int16_5 = (short)(object)value;
				register.int16_6 = (short)(object)value;
				register.int16_7 = (short)(object)value;
			}
			else if (typeof(T) == typeof(uint))
			{
				register.uint32_0 = (uint)(object)value;
				register.uint32_1 = (uint)(object)value;
				register.uint32_2 = (uint)(object)value;
				register.uint32_3 = (uint)(object)value;
			}
			else if (typeof(T) == typeof(int))
			{
				register.int32_0 = (int)(object)value;
				register.int32_1 = (int)(object)value;
				register.int32_2 = (int)(object)value;
				register.int32_3 = (int)(object)value;
			}
			else if (typeof(T) == typeof(ulong))
			{
				register.uint64_0 = (ulong)(object)value;
				register.uint64_1 = (ulong)(object)value;
			}
			else if (typeof(T) == typeof(long))
			{
				register.int64_0 = (long)(object)value;
				register.int64_1 = (long)(object)value;
			}
			else if (typeof(T) == typeof(float))
			{
				register.single_0 = (float)(object)value;
				register.single_1 = (float)(object)value;
				register.single_2 = (float)(object)value;
				register.single_3 = (float)(object)value;
			}
			else if (typeof(T) == typeof(double))
			{
				register.double_0 = (double)(object)value;
				register.double_1 = (double)(object)value;
			}
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public Vector(T[] values)
			: this(values, 0)
		{
		}

		public unsafe Vector(T[] values, int index)
		{
			this = default(Vector<T>);
			if (values == null)
			{
				throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef);
			}
			if (index < 0 || values.Length - index < Count)
			{
				throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_InsufficientNumberOfElements, Count, "values"));
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)values[i + index];
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)values[j + index];
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)values[k + index];
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)values[l + index];
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)values[m + index];
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)values[n + index];
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)values[num + index];
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)values[num2 + index];
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)values[num3 + index];
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.double_0)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[num4] = (double)(object)values[num4 + index];
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				fixed (byte* ptr11 = &register.byte_0)
				{
					*ptr11 = (byte)(object)values[index];
					ptr11[1] = (byte)(object)values[1 + index];
					ptr11[2] = (byte)(object)values[2 + index];
					ptr11[3] = (byte)(object)values[3 + index];
					ptr11[4] = (byte)(object)values[4 + index];
					ptr11[5] = (byte)(object)values[5 + index];
					ptr11[6] = (byte)(object)values[6 + index];
					ptr11[7] = (byte)(object)values[7 + index];
					ptr11[8] = (byte)(object)values[8 + index];
					ptr11[9] = (byte)(object)values[9 + index];
					ptr11[10] = (byte)(object)values[10 + index];
					ptr11[11] = (byte)(object)values[11 + index];
					ptr11[12] = (byte)(object)values[12 + index];
					ptr11[13] = (byte)(object)values[13 + index];
					ptr11[14] = (byte)(object)values[14 + index];
					ptr11[15] = (byte)(object)values[15 + index];
				}
			}
			else if (typeof(T) == typeof(sbyte))
			{
				fixed (sbyte* ptr12 = &register.sbyte_0)
				{
					*ptr12 = (sbyte)(object)values[index];
					ptr12[1] = (sbyte)(object)values[1 + index];
					ptr12[2] = (sbyte)(object)values[2 + index];
					ptr12[3] = (sbyte)(object)values[3 + index];
					ptr12[4] = (sbyte)(object)values[4 + index];
					ptr12[5] = (sbyte)(object)values[5 + index];
					ptr12[6] = (sbyte)(object)values[6 + index];
					ptr12[7] = (sbyte)(object)values[7 + index];
					ptr12[8] = (sbyte)(object)values[8 + index];
					ptr12[9] = (sbyte)(object)values[9 + index];
					ptr12[10] = (sbyte)(object)values[10 + index];
					ptr12[11] = (sbyte)(object)values[11 + index];
					ptr12[12] = (sbyte)(object)values[12 + index];
					ptr12[13] = (sbyte)(object)values[13 + index];
					ptr12[14] = (sbyte)(object)values[14 + index];
					ptr12[15] = (sbyte)(object)values[15 + index];
				}
			}
			else if (typeof(T) == typeof(ushort))
			{
				fixed (ushort* ptr13 = &register.uint16_0)
				{
					*ptr13 = (ushort)(object)values[index];
					ptr13[1] = (ushort)(object)values[1 + index];
					ptr13[2] = (ushort)(object)values[2 + index];
					ptr13[3] = (ushort)(object)values[3 + index];
					ptr13[4] = (ushort)(object)values[4 + index];
					ptr13[5] = (ushort)(object)values[5 + index];
					ptr13[6] = (ushort)(object)values[6 + index];
					ptr13[7] = (ushort)(object)values[7 + index];
				}
			}
			else if (typeof(T) == typeof(short))
			{
				fixed (short* ptr14 = &register.int16_0)
				{
					*ptr14 = (short)(object)values[index];
					ptr14[1] = (short)(object)values[1 + index];
					ptr14[2] = (short)(object)values[2 + index];
					ptr14[3] = (short)(object)values[3 + index];
					ptr14[4] = (short)(object)values[4 + index];
					ptr14[5] = (short)(object)values[5 + index];
					ptr14[6] = (short)(object)values[6 + index];
					ptr14[7] = (short)(object)values[7 + index];
				}
			}
			else if (typeof(T) == typeof(uint))
			{
				fixed (uint* ptr15 = &register.uint32_0)
				{
					*ptr15 = (uint)(object)values[index];
					ptr15[1] = (uint)(object)values[1 + index];
					ptr15[2] = (uint)(object)values[2 + index];
					ptr15[3] = (uint)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(int))
			{
				fixed (int* ptr16 = &register.int32_0)
				{
					*ptr16 = (int)(object)values[index];
					ptr16[1] = (int)(object)values[1 + index];
					ptr16[2] = (int)(object)values[2 + index];
					ptr16[3] = (int)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(ulong))
			{
				fixed (ulong* ptr17 = &register.uint64_0)
				{
					*ptr17 = (ulong)(object)values[index];
					ptr17[1] = (ulong)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = &register.int64_0)
				{
					*ptr18 = (long)(object)values[index];
					ptr18[1] = (long)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = &register.single_0)
				{
					*ptr19 = (float)(object)values[index];
					ptr19[1] = (float)(object)values[1 + index];
					ptr19[2] = (float)(object)values[2 + index];
					ptr19[3] = (float)(object)values[3 + index];
				}
			}
			else if (typeof(T) == typeof(double))
			{
				fixed (double* ptr20 = &register.double_0)
				{
					*ptr20 = (double)(object)values[index];
					ptr20[1] = (double)(object)values[1 + index];
				}
			}
		}

		internal unsafe Vector(void* dataPointer)
			: this(dataPointer, 0)
		{
		}

		internal unsafe Vector(void* dataPointer, int offset)
		{
			this = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				byte* ptr = (byte*)dataPointer;
				ptr += offset;
				fixed (byte* ptr2 = &register.byte_0)
				{
					for (int i = 0; i < Count; i++)
					{
						ptr2[i] = ptr[i];
					}
				}
				return;
			}
			if (typeof(T) == typeof(sbyte))
			{
				sbyte* ptr3 = (sbyte*)dataPointer;
				ptr3 += offset;
				fixed (sbyte* ptr4 = &register.sbyte_0)
				{
					for (int j = 0; j < Count; j++)
					{
						ptr4[j] = ptr3[j];
					}
				}
				return;
			}
			if (typeof(T) == typeof(ushort))
			{
				ushort* ptr5 = (ushort*)dataPointer;
				ptr5 += offset;
				fixed (ushort* ptr6 = &register.uint16_0)
				{
					for (int k = 0; k < Count; k++)
					{
						ptr6[k] = ptr5[k];
					}
				}
				return;
			}
			if (typeof(T) == typeof(short))
			{
				short* ptr7 = (short*)dataPointer;
				ptr7 += offset;
				fixed (short* ptr8 = &register.int16_0)
				{
					for (int l = 0; l < Count; l++)
					{
						ptr8[l] = ptr7[l];
					}
				}
				return;
			}
			if (typeof(T) == typeof(uint))
			{
				uint* ptr9 = (uint*)dataPointer;
				ptr9 += offset;
				fixed (uint* ptr10 = &register.uint32_0)
				{
					for (int m = 0; m < Count; m++)
					{
						ptr10[m] = ptr9[m];
					}
				}
				return;
			}
			if (typeof(T) == typeof(int))
			{
				int* ptr11 = (int*)dataPointer;
				ptr11 += offset;
				fixed (int* ptr12 = &register.int32_0)
				{
					for (int n = 0; n < Count; n++)
					{
						ptr12[n] = ptr11[n];
					}
				}
				return;
			}
			if (typeof(T) == typeof(ulong))
			{
				ulong* ptr13 = (ulong*)dataPointer;
				ptr13 += offset;
				fixed (ulong* ptr14 = &register.uint64_0)
				{
					for (int num = 0; num < Count; num++)
					{
						ptr14[num] = ptr13[num];
					}
				}
				return;
			}
			if (typeof(T) == typeof(long))
			{
				long* ptr15 = (long*)dataPointer;
				ptr15 += offset;
				fixed (long* ptr16 = &register.int64_0)
				{
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr16[num2] = ptr15[num2];
					}
				}
				return;
			}
			if (typeof(T) == typeof(float))
			{
				float* ptr17 = (float*)dataPointer;
				ptr17 += offset;
				fixed (float* ptr18 = &register.single_0)
				{
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr18[num3] = ptr17[num3];
					}
				}
				return;
			}
			if (typeof(T) == typeof(double))
			{
				double* ptr19 = (double*)dataPointer;
				ptr19 += offset;
				fixed (double* ptr20 = &register.double_0)
				{
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr20[num4] = ptr19[num4];
					}
				}
				return;
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		private Vector(ref System.Numerics.Register existingRegister)
		{
			register = existingRegister;
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public void CopyTo(T[] destination)
		{
			CopyTo(destination, 0);
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public unsafe void CopyTo(T[] destination, int startIndex)
		{
			if (destination == null)
			{
				throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef);
			}
			if (startIndex < 0 || startIndex >= destination.Length)
			{
				throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex));
			}
			if (destination.Length - startIndex < Count)
			{
				throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex));
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = (byte[])(object)destination)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[startIndex + i] = (byte)(object)this[i];
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = (sbyte[])(object)destination)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[startIndex + j] = (sbyte)(object)this[j];
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = (ushort[])(object)destination)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[startIndex + k] = (ushort)(object)this[k];
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = (short[])(object)destination)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[startIndex + l] = (short)(object)this[l];
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = (uint[])(object)destination)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[startIndex + m] = (uint)(object)this[m];
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = (int[])(object)destination)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[startIndex + n] = (int)(object)this[n];
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = (ulong[])(object)destination)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[startIndex + num] = (ulong)(object)this[num];
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = (long[])(object)destination)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[startIndex + num2] = (long)(object)this[num2];
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = (float[])(object)destination)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[startIndex + num3] = (float)(object)this[num3];
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = (double[])(object)destination)
					{
						for (int num4 = 0; num4 < Count; num4++)
						{
							ptr10[startIndex + num4] = (double)(object)this[num4];
						}
					}
				}
			}
			else if (typeof(T) == typeof(byte))
			{
				fixed (byte* ptr11 = (byte[])(object)destination)
				{
					ptr11[startIndex] = register.byte_0;
					ptr11[startIndex + 1] = register.byte_1;
					ptr11[startIndex + 2] = register.byte_2;
					ptr11[startIndex + 3] = register.byte_3;
					ptr11[startIndex + 4] = register.byte_4;
					ptr11[startIndex + 5] = register.byte_5;
					ptr11[startIndex + 6] = register.byte_6;
					ptr11[startIndex + 7] = register.byte_7;
					ptr11[startIndex + 8] = register.byte_8;
					ptr11[startIndex + 9] = register.byte_9;
					ptr11[startIndex + 10] = register.byte_10;
					ptr11[startIndex + 11] = register.byte_11;
					ptr11[startIndex + 12] = register.byte_12;
					ptr11[startIndex + 13] = register.byte_13;
					ptr11[startIndex + 14] = register.byte_14;
					ptr11[startIndex + 15] = register.byte_15;
				}
			}
			else if (typeof(T) == typeof(sbyte))
			{
				fixed (sbyte* ptr12 = (sbyte[])(object)destination)
				{
					ptr12[startIndex] = register.sbyte_0;
					ptr12[startIndex + 1] = register.sbyte_1;
					ptr12[startIndex + 2] = register.sbyte_2;
					ptr12[startIndex + 3] = register.sbyte_3;
					ptr12[startIndex + 4] = register.sbyte_4;
					ptr12[startIndex + 5] = register.sbyte_5;
					ptr12[startIndex + 6] = register.sbyte_6;
					ptr12[startIndex + 7] = register.sbyte_7;
					ptr12[startIndex + 8] = register.sbyte_8;
					ptr12[startIndex + 9] = register.sbyte_9;
					ptr12[startIndex + 10] = register.sbyte_10;
					ptr12[startIndex + 11] = register.sbyte_11;
					ptr12[startIndex + 12] = register.sbyte_12;
					ptr12[startIndex + 13] = register.sbyte_13;
					ptr12[startIndex + 14] = register.sbyte_14;
					ptr12[startIndex + 15] = register.sbyte_15;
				}
			}
			else if (typeof(T) == typeof(ushort))
			{
				fixed (ushort* ptr13 = (ushort[])(object)destination)
				{
					ptr13[startIndex] = register.uint16_0;
					ptr13[startIndex + 1] = register.uint16_1;
					ptr13[startIndex + 2] = register.uint16_2;
					ptr13[startIndex + 3] = register.uint16_3;
					ptr13[startIndex + 4] = register.uint16_4;
					ptr13[startIndex + 5] = register.uint16_5;
					ptr13[startIndex + 6] = register.uint16_6;
					ptr13[startIndex + 7] = register.uint16_7;
				}
			}
			else if (typeof(T) == typeof(short))
			{
				fixed (short* ptr14 = (short[])(object)destination)
				{
					ptr14[startIndex] = register.int16_0;
					ptr14[startIndex + 1] = register.int16_1;
					ptr14[startIndex + 2] = register.int16_2;
					ptr14[startIndex + 3] = register.int16_3;
					ptr14[startIndex + 4] = register.int16_4;
					ptr14[startIndex + 5] = register.int16_5;
					ptr14[startIndex + 6] = register.int16_6;
					ptr14[startIndex + 7] = register.int16_7;
				}
			}
			else if (typeof(T) == typeof(uint))
			{
				fixed (uint* ptr15 = (uint[])(object)destination)
				{
					ptr15[startIndex] = register.uint32_0;
					ptr15[startIndex + 1] = register.uint32_1;
					ptr15[startIndex + 2] = register.uint32_2;
					ptr15[startIndex + 3] = register.uint32_3;
				}
			}
			else if (typeof(T) == typeof(int))
			{
				fixed (int* ptr16 = (int[])(object)destination)
				{
					ptr16[startIndex] = register.int32_0;
					ptr16[startIndex + 1] = register.int32_1;
					ptr16[startIndex + 2] = register.int32_2;
					ptr16[startIndex + 3] = register.int32_3;
				}
			}
			else if (typeof(T) == typeof(ulong))
			{
				fixed (ulong* ptr17 = (ulong[])(object)destination)
				{
					ptr17[startIndex] = register.uint64_0;
					ptr17[startIndex + 1] = register.uint64_1;
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = (long[])(object)destination)
				{
					ptr18[startIndex] = register.int64_0;
					ptr18[startIndex + 1] = register.int64_1;
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = (float[])(object)destination)
				{
					ptr19[startIndex] = register.single_0;
					ptr19[startIndex + 1] = register.single_1;
					ptr19[startIndex + 2] = register.single_2;
					ptr19[startIndex + 3] = register.single_3;
				}
			}
			else if (typeof(T) == typeof(double))
			{
				fixed (double* ptr20 = (double[])(object)destination)
				{
					ptr20[startIndex] = register.double_0;
					ptr20[startIndex + 1] = register.double_1;
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override bool Equals(object obj)
		{
			if (!(obj is Vector<T>))
			{
				return false;
			}
			return Equals((Vector<T>)obj);
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public bool Equals(Vector<T> other)
		{
			if (Vector.IsHardwareAccelerated)
			{
				for (int i = 0; i < Count; i++)
				{
					if (!ScalarEquals(this[i], other[i]))
					{
						return false;
					}
				}
				return true;
			}
			if (typeof(T) == typeof(byte))
			{
				if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14)
				{
					return register.byte_15 == other.register.byte_15;
				}
				return false;
			}
			if (typeof(T) == typeof(sbyte))
			{
				if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14)
				{
					return register.sbyte_15 == other.register.sbyte_15;
				}
				return false;
			}
			if (typeof(T) == typeof(ushort))
			{
				if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6)
				{
					return register.uint16_7 == other.register.uint16_7;
				}
				return false;
			}
			if (typeof(T) == typeof(short))
			{
				if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6)
				{
					return register.int16_7 == other.register.int16_7;
				}
				return false;
			}
			if (typeof(T) == typeof(uint))
			{
				if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2)
				{
					return register.uint32_3 == other.register.uint32_3;
				}
				return false;
			}
			if (typeof(T) == typeof(int))
			{
				if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2)
				{
					return register.int32_3 == other.register.int32_3;
				}
				return false;
			}
			if (typeof(T) == typeof(ulong))
			{
				if (register.uint64_0 == other.register.uint64_0)
				{
					return register.uint64_1 == other.register.uint64_1;
				}
				return false;
			}
			if (typeof(T) == typeof(long))
			{
				if (register.int64_0 == other.register.int64_0)
				{
					return register.int64_1 == other.register.int64_1;
				}
				return false;
			}
			if (typeof(T) == typeof(float))
			{
				if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2)
				{
					return register.single_3 == other.register.single_3;
				}
				return false;
			}
			if (typeof(T) == typeof(double))
			{
				if (register.double_0 == other.register.double_0)
				{
					return register.double_1 == other.register.double_1;
				}
				return false;
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		public override int GetHashCode()
		{
			int num = 0;
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					for (int i = 0; i < Count; i++)
					{
						num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(sbyte))
				{
					for (int j = 0; j < Count; j++)
					{
						num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(ushort))
				{
					for (int k = 0; k < Count; k++)
					{
						num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(short))
				{
					for (int l = 0; l < Count; l++)
					{
						num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(uint))
				{
					for (int m = 0; m < Count; m++)
					{
						num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(int))
				{
					for (int n = 0; n < Count; n++)
					{
						num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(ulong))
				{
					for (int num2 = 0; num2 < Count; num2++)
					{
						num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(long))
				{
					for (int num3 = 0; num3 < Count; num3++)
					{
						num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(float))
				{
					for (int num4 = 0; num4 < Count; num4++)
					{
						num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode());
					}
					return num;
				}
				if (typeof(T) == typeof(double))
				{
					for (int num5 = 0; num5 < Count; num5++)
					{
						num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode());
					}
					return num;
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			if (typeof(T) == typeof(byte))
			{
				num = HashHelpers.Combine(num, register.byte_0.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_1.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_2.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_3.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_4.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_5.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_6.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_7.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_8.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_9.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_10.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_11.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_12.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_13.GetHashCode());
				num = HashHelpers.Combine(num, register.byte_14.GetHashCode());
				return HashHelpers.Combine(num, register.byte_15.GetHashCode());
			}
			if (typeof(T) == typeof(sbyte))
			{
				num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode());
				num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode());
				return HashHelpers.Combine(num, register.sbyte_15.GetHashCode());
			}
			if (typeof(T) == typeof(ushort))
			{
				num = HashHelpers.Combine(num, register.uint16_0.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_1.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_2.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_3.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_4.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_5.GetHashCode());
				num = HashHelpers.Combine(num, register.uint16_6.GetHashCode());
				return HashHelpers.Combine(num, register.uint16_7.GetHashCode());
			}
			if (typeof(T) == typeof(short))
			{
				num = HashHelpers.Combine(num, register.int16_0.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_1.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_2.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_3.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_4.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_5.GetHashCode());
				num = HashHelpers.Combine(num, register.int16_6.GetHashCode());
				return HashHelpers.Combine(num, register.int16_7.GetHashCode());
			}
			if (typeof(T) == typeof(uint))
			{
				num = HashHelpers.Combine(num, register.uint32_0.GetHashCode());
				num = HashHelpers.Combine(num, register.uint32_1.GetHashCode());
				num = HashHelpers.Combine(num, register.uint32_2.GetHashCode());
				return HashHelpers.Combine(num, register.uint32_3.GetHashCode());
			}
			if (typeof(T) == typeof(int))
			{
				num = HashHelpers.Combine(num, register.int32_0.GetHashCode());
				num = HashHelpers.Combine(num, register.int32_1.GetHashCode());
				num = HashHelpers.Combine(num, register.int32_2.GetHashCode());
				return HashHelpers.Combine(num, register.int32_3.GetHashCode());
			}
			if (typeof(T) == typeof(ulong))
			{
				num = HashHelpers.Combine(num, register.uint64_0.GetHashCode());
				return HashHelpers.Combine(num, register.uint64_1.GetHashCode());
			}
			if (typeof(T) == typeof(long))
			{
				num = HashHelpers.Combine(num, register.int64_0.GetHashCode());
				return HashHelpers.Combine(num, register.int64_1.GetHashCode());
			}
			if (typeof(T) == typeof(float))
			{
				num = HashHelpers.Combine(num, register.single_0.GetHashCode());
				num = HashHelpers.Combine(num, register.single_1.GetHashCode());
				num = HashHelpers.Combine(num, register.single_2.GetHashCode());
				return HashHelpers.Combine(num, register.single_3.GetHashCode());
			}
			if (typeof(T) == typeof(double))
			{
				num = HashHelpers.Combine(num, register.double_0.GetHashCode());
				return HashHelpers.Combine(num, register.double_1.GetHashCode());
			}
			throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
		}

		public override string ToString()
		{
			return ToString("G", CultureInfo.CurrentCulture);
		}

		public string ToString(string format)
		{
			return ToString(format, CultureInfo.CurrentCulture);
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
			stringBuilder.Append('<');
			for (int i = 0; i < Count - 1; i++)
			{
				stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider));
				stringBuilder.Append(numberGroupSeparator);
				stringBuilder.Append(' ');
			}
			stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider));
			stringBuilder.Append('>');
			return stringBuilder.ToString();
		}

		public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)(uint)Count];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 + right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 + right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 + right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 + right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 + right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 + right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 + right.register.single_0;
				result.register.single_1 = left.register.single_1 + right.register.single_1;
				result.register.single_2 = left.register.single_2 + right.register.single_2;
				result.register.single_3 = left.register.single_3 + right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 + right.register.double_0;
				result.register.double_1 = left.register.double_1 + right.register.double_1;
			}
			return result;
		}

		public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)(uint)Count];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 - right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 - right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 - right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 - right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 - right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 - right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 - right.register.single_0;
				result.register.single_1 = left.register.single_1 - right.register.single_1;
				result.register.single_2 = left.register.single_2 - right.register.single_2;
				result.register.single_3 = left.register.single_3 - right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 - right.register.double_0;
				result.register.double_1 = left.register.double_1 - right.register.double_1;
			}
			return result;
		}

		public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)(uint)Count];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 * right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 * right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 * right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 * right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 * right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 * right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 * right.register.single_0;
				result.register.single_1 = left.register.single_1 * right.register.single_1;
				result.register.single_2 = left.register.single_2 * right.register.single_2;
				result.register.single_3 = left.register.single_3 * right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 * right.register.double_0;
				result.register.double_1 = left.register.double_1 * right.register.double_1;
			}
			return result;
		}

		public static Vector<T>operator *(Vector<T> value, T factor)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return new Vector<T>(factor) * value;
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor);
				result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor);
				result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor);
				result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor);
				result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor);
				result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor);
				result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor);
				result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor);
				result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor);
				result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor);
				result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor);
				result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor);
				result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor);
				result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor);
				result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor);
				result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor);
				result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor);
				result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor);
				result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor);
				result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor);
				result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor);
				result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor);
				result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor);
				result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor);
				result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor);
				result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor);
				result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor);
				result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor);
				result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor);
				result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor);
				result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor);
				result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor);
				result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor);
				result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor);
				result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor);
				result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor);
				result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor);
				result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor);
				result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor);
				result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor);
				result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor);
				result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor);
				result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor);
				result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor);
				result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor;
				result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor;
				result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor;
				result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = value.register.int32_0 * (int)(object)factor;
				result.register.int32_1 = value.register.int32_1 * (int)(object)factor;
				result.register.int32_2 = value.register.int32_2 * (int)(object)factor;
				result.register.int32_3 = value.register.int32_3 * (int)(object)factor;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor;
				result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = value.register.int64_0 * (long)(object)factor;
				result.register.int64_1 = value.register.int64_1 * (long)(object)factor;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = value.register.single_0 * (float)(object)factor;
				result.register.single_1 = value.register.single_1 * (float)(object)factor;
				result.register.single_2 = value.register.single_2 * (float)(object)factor;
				result.register.single_3 = value.register.single_3 * (float)(object)factor;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = value.register.double_0 * (double)(object)factor;
				result.register.double_1 = value.register.double_1 * (double)(object)factor;
			}
			return result;
		}

		public static Vector<T>operator *(T factor, Vector<T> value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return new Vector<T>(factor) * value;
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor);
				result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor);
				result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor);
				result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor);
				result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor);
				result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor);
				result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor);
				result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor);
				result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor);
				result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor);
				result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor);
				result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor);
				result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor);
				result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor);
				result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor);
				result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor);
				result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor);
				result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor);
				result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor);
				result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor);
				result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor);
				result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor);
				result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor);
				result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor);
				result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor);
				result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor);
				result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor);
				result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor);
				result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor);
				result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor);
				result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor);
				result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor);
				result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor);
				result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor);
				result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor);
				result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor);
				result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor);
				result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor);
				result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor);
				result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor);
				result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor);
				result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor);
				result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor);
				result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor);
				result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor;
				result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor;
				result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor;
				result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = value.register.int32_0 * (int)(object)factor;
				result.register.int32_1 = value.register.int32_1 * (int)(object)factor;
				result.register.int32_2 = value.register.int32_2 * (int)(object)factor;
				result.register.int32_3 = value.register.int32_3 * (int)(object)factor;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor;
				result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = value.register.int64_0 * (long)(object)factor;
				result.register.int64_1 = value.register.int64_1 * (long)(object)factor;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = value.register.single_0 * (float)(object)factor;
				result.register.single_1 = value.register.single_1 * (float)(object)factor;
				result.register.single_2 = value.register.single_2 * (float)(object)factor;
				result.register.single_3 = value.register.single_3 * (float)(object)factor;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = value.register.double_0 * (double)(object)factor;
				result.register.double_1 = value.register.double_1 * (double)(object)factor;
			}
			return result;
		}

		public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)(uint)Count];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]);
					}
					return new Vector<T>(ptr2);
				}
				if (typeof(T) == typeof(ushort))
				{
					ushort* ptr3 = stackalloc ushort[Count];
					for (int k = 0; k < Count; k++)
					{
						ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 = stackalloc short[Count];
					for (int l = 0; l < Count; l++)
					{
						ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]);
					}
					return new Vector<T>(ptr4);
				}
				if (typeof(T) == typeof(uint))
				{
					uint* ptr5 = stackalloc uint[Count];
					for (int m = 0; m < Count; m++)
					{
						ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]);
					}
					return new Vector<T>(ptr5);
				}
				if (typeof(T) == typeof(int))
				{
					int* ptr6 = stackalloc int[Count];
					for (int n = 0; n < Count; n++)
					{
						ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]);
					}
					return new Vector<T>(ptr6);
				}
				if (typeof(T) == typeof(ulong))
				{
					ulong* ptr7 = stackalloc ulong[Count];
					for (int num = 0; num < Count; num++)
					{
						ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]);
					}
					return new Vector<T>(ptr7);
				}
				if (typeof(T) == typeof(long))
				{
					long* ptr8 = stackalloc long[Count];
					for (int num2 = 0; num2 < Count; num2++)
					{
						ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]);
					}
					return new Vector<T>(ptr8);
				}
				if (typeof(T) == typeof(float))
				{
					float* ptr9 = stackalloc float[Count];
					for (int num3 = 0; num3 < Count; num3++)
					{
						ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]);
					}
					return new Vector<T>(ptr9);
				}
				if (typeof(T) == typeof(double))
				{
					double* ptr10 = stackalloc double[Count];
					for (int num4 = 0; num4 < Count; num4++)
					{
						ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]);
					}
					return new Vector<T>(ptr10);
				}
				throw new NotSupportedException(System.SR.Arg_TypeNotSupported);
			}
			Vector<T> result = default(Vector<T>);
			if (typeof(T) == typeof(byte))
			{
				result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0);
				result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1);
				result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2);
				result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3);
				result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4);
				result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5);
				result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6);
				result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7);
				result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8);
				result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9);
				result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10);
				result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11);
				result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12);
				result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13);
				result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14);
				result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15);
			}
			else if (typeof(T) == typeof(sbyte))
			{
				result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0);
				result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1);
				result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2);
				result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3);
				result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4);
				result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5);
				result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6);
				result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7);
				result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8);
				result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9);
				result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10);
				result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11);
				result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12);
				result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13);
				result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14);
				result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15);
			}
			else if (typeof(T) == typeof(ushort))
			{
				result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0);
				result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1);
				result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2);
				result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3);
				result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4);
				result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5);
				result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6);
				result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7);
			}
			else if (typeof(T) == typeof(short))
			{
				result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0);
				result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1);
				result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2);
				result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3);
				result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4);
				result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5);
				result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6);
				result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7);
			}
			else if (typeof(T) == typeof(uint))
			{
				result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0;
				result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1;
				result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2;
				result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3;
			}
			else if (typeof(T) == typeof(int))
			{
				result.register.int32_0 = left.register.int32_0 / right.register.int32_0;
				result.register.int32_1 = left.register.int32_1 / right.register.int32_1;
				result.register.int32_2 = left.register.int32_2 / right.register.int32_2;
				result.register.int32_3 = left.register.int32_3 / right.register.int32_3;
			}
			else if (typeof(T) == typeof(ulong))
			{
				result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0;
				result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1;
			}
			else if (typeof(T) == typeof(long))
			{
				result.register.int64_0 = left.register.int64_0 / right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 / right.register.int64_1;
			}
			else if (typeof(T) == typeof(float))
			{
				result.register.single_0 = left.register.single_0 / right.register.single_0;
				result.register.single_1 = left.register.single_1 / right.register.single_1;
				result.register.single_2 = left.register.single_2 / right.register.single_2;
				result.register.single_3 = left.register.single_3 / right.register.single_3;
			}
			else if (typeof(T) == typeof(double))
			{
				result.register.double_0 = left.register.double_0 / right.register.double_0;
				result.register.double_1 = left.register.double_1 / right.register.double_1;
			}
			return result;
		}

		public static Vector<T>operator -(Vector<T> value)
		{
			return Zero - value;
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] & ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 = left.register.int64_0 & right.register.int64_0;
				result.register.int64_1 = left.register.int64_1 & right.register.int64_1;
			}
			return result;
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right)
		{
			Vector<T> result = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				long* ptr = &result.register.int64_0;
				long* ptr2 = &left.register.int64_0;
				long* ptr3 = &right.register.int64_0;
				for (int i = 0; i < Vector<long>.Count; i++)
				{
					ptr[i] = ptr2[i] | ptr3[i];
				}
			}
			else
			{
				result.register.int64_0 

BepInEx/plugins/FaceSync/System.Runtime.CompilerServices.Unsafe.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyFileVersion("6.100.225.20307")]
[assembly: AssemblyInformationalVersion("6.1.2")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("6.0.3.0")]
namespace System.Runtime.CompilerServices
{
	public static class Unsafe
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void SkipInit<T>(out T value)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static IntPtr ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}