Decompiled source of Doom Together v0.1.0

DoomTogether.dll

Decompiled an hour ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using ManagedDoom;
using ManagedDoom.Audio;
using ManagedDoom.UserInput;
using ManagedDoom.Video;
using MeltySynth;
using Microsoft.CodeAnalysis;
using OnTogetherMods.Shared;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DoomTogether")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+7867eee29171699a3616ac7547e004ee097f891d")]
[assembly: AssemblyProduct("DoomTogether")]
[assembly: AssemblyTitle("DoomTogether")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace OnTogetherMods.Shared
{
	internal static class PanelStack
	{
		private const string TableKey = "OnTogetherMods.PanelStack.Panels";

		private const string HiddenKey = "OnTogetherMods.PanelStack.Hidden";

		private const string IconBarKey = "OnTogetherMods.IconBar.Rect";

		private const float Margin = 20f;

		private const float FromRight = 0.15f;

		private const float Gap = 10f;

		private const int WorldScene = 2;

		public const int PhotoModeOrder = 0;

		public const int EmoteSyncOrder = 10;

		public const int TeleportSpotsOrder = 20;

		public const int SongPlayerOrder = 30;

		public const int TraceOverlayOrder = 40;

		public const int NameDesignerOrder = 50;

		public const int CardDesignerOrder = 55;

		public const int OutfitSlotsOrder = 60;

		public const int DeskSwarmOrder = 70;

		public const int SessionManagerOrder = 80;

		public const int FocusAnywhereOrder = 90;

		public const int DoomTogetherOrder = 100;

		public const string CanvasPrefix = "OnTogetherMods ";

		private static int _hiddenFrame = -1;

		private static bool _gameUIHidden;

		private static FieldRef<UIManager, HideUIState> _eyeState;

		private static bool _eyeStateMissing;

		public static float Width => (float)Screen.width * 1080f / (float)Screen.height;

		public static bool Hidden
		{
			get
			{
				if (!(AppDomain.CurrentDomain.GetData("OnTogetherMods.PanelStack.Hidden") is int num) || Time.frameCount > num)
				{
					return GameUIHidden;
				}
				return true;
			}
		}

		public static bool GameUIHidden
		{
			get
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Invalid comparison between Unknown and I4
				int frameCount = Time.frameCount;
				if (_hiddenFrame != frameCount)
				{
					_hiddenFrame = frameCount;
					_gameUIHidden = false;
					Scene activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).buildIndex == 2)
					{
						UIManager i = MonoSingleton<UIManager>.I;
						_gameUIHidden = (Object)(object)i != (Object)null && (int)EyeState(i) > 0;
					}
				}
				return _gameUIHidden;
			}
		}

		public static bool IsModCanvas(Canvas canvas)
		{
			Canvas val = canvas;
			Transform parent = ((Component)canvas).transform.parent;
			while ((Object)(object)parent != (Object)null)
			{
				Canvas component = ((Component)parent).GetComponent<Canvas>();
				val = (((Object)(object)component != (Object)null) ? component : val);
				parent = parent.parent;
			}
			return ((Object)((Component)val).gameObject).name.StartsWith("OnTogetherMods ", StringComparison.Ordinal);
		}

		private static HideUIState EyeState(UIManager ui)
		{
			if (_eyeState == null && !_eyeStateMissing)
			{
				try
				{
					_eyeState = AccessTools.FieldRefAccess<UIManager, HideUIState>("_hideUIState");
				}
				catch (Exception)
				{
					_eyeStateMissing = true;
				}
			}
			if (_eyeState != null)
			{
				return _eyeState.Invoke(ui);
			}
			return (HideUIState)0;
		}

		public static void HideForCapture()
		{
			AppDomain.CurrentDomain.SetData("OnTogetherMods.PanelStack.Hidden", Time.frameCount + 1);
		}

		public static Rect Place(string id, int order, Vector2 size)
		{
			//IL_001b: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			Hashtable hashtable = Panels();
			int frameCount = Time.frameCount;
			hashtable[id] = new double[3] { order, size.y, frameCount };
			float width = Width;
			float num = Mathf.Max(20f, width * 0.85f - size.x);
			float num2 = Bottom(num + size.x, frameCount) - size.y;
			foreach (DictionaryEntry item in hashtable)
			{
				string text = (string)item.Key;
				double[] array = (double[])item.Value;
				bool flag = (double)frameCount - array[2] <= 2.0;
				bool flag2 = array[0] < (double)order || (array[0] == (double)order && string.CompareOrdinal(text, id) < 0);
				if (text != id && flag && flag2)
				{
					num2 -= (float)array[1] + 10f;
				}
			}
			return new Rect(num, num2, size.x, size.y);
		}

		private static float Bottom(float windowRight, int frame)
		{
			float num = 1060f;
			if (AppDomain.CurrentDomain.GetData("OnTogetherMods.IconBar.Rect") is double[] array && (double)frame - array[4] <= 2.0)
			{
				float num2 = 1080f / (float)Screen.height;
				if (array[0] * (double)num2 < (double)(windowRight + 10f))
				{
					num = Mathf.Min(num, (float)array[1] * num2 - 10f);
				}
			}
			return num;
		}

		public static Matrix4x4 Begin(out float width)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)Screen.height / 1080f;
			Matrix4x4 matrix = GUI.matrix;
			GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f));
			width = (float)Screen.width / num;
			return matrix;
		}

		public static void End(Matrix4x4 previous)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			GUI.matrix = previous;
		}

		public static GUIStyle MakeStyle(TextAnchor alignment)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			GUIStyle val = new GUIStyle(GUI.skin.box)
			{
				alignment = alignment,
				fontSize = 15,
				richText = true,
				wordWrap = false,
				padding = new RectOffset(12, 12, 10, 10)
			};
			val.normal.textColor = Color.white;
			return val;
		}

		private static Hashtable Panels()
		{
			Hashtable hashtable = AppDomain.CurrentDomain.GetData("OnTogetherMods.PanelStack.Panels") as Hashtable;
			if (hashtable == null)
			{
				hashtable = new Hashtable();
				AppDomain.CurrentDomain.SetData("OnTogetherMods.PanelStack.Panels", hashtable);
			}
			return hashtable;
		}
	}
	internal static class IconBar
	{
		public enum State
		{
			Plain,
			Open,
			On,
			Off
		}

		public enum Click
		{
			None,
			Left,
			Right
		}

		private struct Metrics
		{
			public float Unit;

			public int Art;

			public int Button;

			public int Gap;

			public int Margin;
		}

		private static class Patches
		{
			private static Action<InputManager, bool> _setMouse0Down;

			private static Action<InputManager, bool> _setMouse1;

			private static Action<InputManager, bool> _setMouse1Up;

			private static FieldRef<QuadPainterGPU, Vector2> _previousUV;

			private static bool _leftOnBar;

			private static bool _rightOnBar;

			public static void Apply(Harmony harmony)
			{
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Expected O, but got Unknown
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Expected O, but got Unknown
				_setMouse0Down = Setter("IsMouseButton0Down");
				_setMouse1 = Setter("IsMouseButton1");
				_setMouse1Up = Setter("IsMouseButton1Up");
				harmony.Patch((MethodBase)AccessTools.Method(typeof(InputManager), "Update", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Patches), "InputPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_previousUV = AccessTools.FieldRefAccess<QuadPainterGPU, Vector2>("previousUV");
				harmony.Patch((MethodBase)AccessTools.Method(typeof(QuadPainterGPU), "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Patches), "PaintPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}

			private static void InputPostfix(InputManager __instance)
			{
				bool mouseOver = MouseOver;
				if (Input.GetMouseButtonDown(0))
				{
					_leftOnBar = mouseOver;
				}
				if (Input.GetMouseButtonDown(1))
				{
					_rightOnBar = mouseOver;
				}
				if (mouseOver)
				{
					_setMouse0Down(__instance, arg2: false);
				}
				if (_rightOnBar)
				{
					_setMouse1(__instance, arg2: false);
					_setMouse1Up(__instance, arg2: false);
				}
				if (!Input.GetMouseButton(0))
				{
					_leftOnBar = false;
				}
				if (!Input.GetMouseButton(1))
				{
					_rightOnBar = false;
				}
			}

			private static bool PaintPrefix(QuadPainterGPU __instance)
			{
				if (__instance.IsActive && (_leftOnBar || MouseOver))
				{
					_previousUV.Invoke(__instance).x = -1f;
					return false;
				}
				return true;
			}

			private static Action<InputManager, bool> Setter(string property)
			{
				return (Action<InputManager, bool>)Delegate.CreateDelegate(typeof(Action<InputManager, bool>), AccessTools.PropertySetter(typeof(InputManager), property));
			}
		}

		public const int PhotoModeOrder = 0;

		public const int EmoteSyncOrder = 10;

		public const int TeleportSpotsOrder = 20;

		public const int NameDesignerOrder = 30;

		public const int CardDesignerOrder = 32;

		public const int OutfitSlotsOrder = 35;

		public const int DeskSnapOrder = 40;

		public const int DeskSwarmOrder = 45;

		public const int FocusAnywhereOrder = 50;

		public const int SongPlayerOrder = 60;

		public const int TraceOverlayOrder = 70;

		public const int ChatRangeOrder = 80;

		public const int DoomTogetherOrder = 85;

		public const int QuickHideOrder = 90;

		public const int SessionManagerOrder = 95;

		private const string RectKey = "OnTogetherMods.IconBar.Rect";

		private const string TableKey = "OnTogetherMods.IconBar.Icons";

		private const string PatchedKey = "OnTogetherMods.IconBar.Patched";

		private const string BlockerKey = "OnTogetherMods.IconBar.Blocker";

		private const string BlockerFrameKey = "OnTogetherMods.IconBar.BlockerFrame";

		private const string HiddenKey = "OnTogetherMods.IconBar.HiddenUntil";

		private const int WorldScene = 2;

		private const int TooltipDepth = -100;

		private static readonly Dictionary<char, Color32> Palette = new Dictionary<char, Color32>
		{
			{
				'K',
				new Color32((byte)42, (byte)36, (byte)51, byte.MaxValue)
			},
			{
				'W',
				new Color32((byte)247, (byte)243, (byte)234, byte.MaxValue)
			},
			{
				'G',
				new Color32((byte)201, (byte)198, (byte)207, byte.MaxValue)
			},
			{
				'g',
				new Color32((byte)143, (byte)138, (byte)153, byte.MaxValue)
			},
			{
				'D',
				new Color32((byte)87, (byte)82, (byte)95, byte.MaxValue)
			},
			{
				'B',
				new Color32((byte)168, (byte)107, (byte)60, byte.MaxValue)
			},
			{
				'b',
				new Color32((byte)217, (byte)160, (byte)102, byte.MaxValue)
			},
			{
				'd',
				new Color32((byte)110, (byte)67, (byte)37, byte.MaxValue)
			},
			{
				'R',
				new Color32((byte)224, (byte)90, (byte)90, byte.MaxValue)
			},
			{
				'r',
				new Color32((byte)168, (byte)58, (byte)70, byte.MaxValue)
			},
			{
				'p',
				new Color32((byte)246, (byte)165, (byte)165, byte.MaxValue)
			},
			{
				'Y',
				new Color32((byte)245, (byte)208, (byte)97, byte.MaxValue)
			},
			{
				'y',
				new Color32((byte)201, (byte)150, (byte)50, byte.MaxValue)
			},
			{
				'O',
				new Color32((byte)232, (byte)146, (byte)74, byte.MaxValue)
			},
			{
				'L',
				new Color32((byte)159, (byte)214, (byte)245, byte.MaxValue)
			},
			{
				'U',
				new Color32((byte)74, (byte)143, (byte)217, byte.MaxValue)
			},
			{
				'u',
				new Color32((byte)47, (byte)90, (byte)158, byte.MaxValue)
			},
			{
				'N',
				new Color32((byte)116, (byte)192, (byte)105, byte.MaxValue)
			},
			{
				'n',
				new Color32((byte)63, (byte)138, (byte)74, byte.MaxValue)
			},
			{
				'P',
				new Color32((byte)246, (byte)207, (byte)174, byte.MaxValue)
			},
			{
				'V',
				new Color32((byte)154, (byte)114, (byte)214, byte.MaxValue)
			},
			{
				'v',
				new Color32((byte)105, (byte)72, (byte)160, byte.MaxValue)
			},
			{
				'S',
				new Color32((byte)233, (byte)139, (byte)181, byte.MaxValue)
			},
			{
				'H',
				new Color32((byte)60, (byte)48, (byte)56, byte.MaxValue)
			}
		};

		private static readonly Color32 ButtonFill = new Color32((byte)28, (byte)26, (byte)34, (byte)200);

		private static readonly Color32 ButtonEdge = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)30);

		private static readonly Color32 HoverFill = new Color32((byte)48, (byte)45, (byte)58, (byte)225);

		private static readonly Color32 HoverEdge = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)80);

		private static readonly Color32 OpenFill = new Color32((byte)70, (byte)64, (byte)88, (byte)235);

		private static readonly Color32 OpenEdge = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)150);

		private static readonly Color32 DotFill = new Color32((byte)140, (byte)220, (byte)120, byte.MaxValue);

		private static readonly Color32 DotEdge = new Color32((byte)20, (byte)40, (byte)20, byte.MaxValue);

		private static readonly Dictionary<string[], Texture2D[]> Icons = new Dictionary<string[], Texture2D[]>();

		private static Texture2D _buttonTexture;

		private static Texture2D _hoverTexture;

		private static Texture2D _openTexture;

		private static Texture2D _dotTexture;

		private static GUIStyle _buttonStyle;

		private static GUIStyle _tipStyle;

		private static int _builtFor;

		private static int _cachedFrame = -1;

		private static bool _inWorld;

		private static bool _visible;

		private static int _pressedButton;

		private static bool RowHidden
		{
			get
			{
				if (AppDomain.CurrentDomain.GetData("OnTogetherMods.IconBar.HiddenUntil") is int num)
				{
					return Time.frameCount <= num;
				}
				return false;
			}
		}

		public static bool MouseOver
		{
			get
			{
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				if (!(AppDomain.CurrentDomain.GetData("OnTogetherMods.IconBar.Rect") is double[] array) || array[5] < 0.5 || (double)Time.frameCount - array[4] > 2.0)
				{
					return false;
				}
				Vector3 mousePosition = Input.mousePosition;
				Rect val = default(Rect);
				((Rect)(ref val))..ctor((float)array[0], (float)array[1], (float)array[2], (float)array[3]);
				return ((Rect)(ref val)).Contains(new Vector2(mousePosition.x, (float)Screen.height - mousePosition.y));
			}
		}

		public static Click Draw(string id, int order, string[] pixels, State state, string name, KeyCode key, string hint = null)
		{
			//IL_0086: 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_003d: 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_0049: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			int controlID = GUIUtility.GetControlID((FocusType)2);
			Event current = Event.current;
			Refresh();
			if (!_inWorld)
			{
				Hide(controlID, current);
				UpdateBlocker(shown: false, default(Rect));
				return Click.None;
			}
			Rect bar;
			Metrics m;
			Rect icon = Place(id, order, out bar, out m);
			Share(bar);
			UpdateBlocker(_visible, bar);
			if (!_visible)
			{
				Hide(controlID, current);
				return Click.None;
			}
			Matrix4x4 matrix = GUI.matrix;
			GUI.matrix = Matrix4x4.identity;
			try
			{
				return Handle(controlID, current, icon, m, pixels, state, name, key, hint);
			}
			finally
			{
				GUI.matrix = matrix;
			}
		}

		public static void HideRow()
		{
			AppDomain.CurrentDomain.SetData("OnTogetherMods.IconBar.HiddenUntil", Time.frameCount + 1);
		}

		public static string KeyText(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if ((int)key != 0)
			{
				return $" ({key})";
			}
			return "";
		}

		private static Click Handle(int control, Event e, Rect icon, Metrics m, string[] pixels, State state, string name, KeyCode key, string hint)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected I4, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			bool flag = ((Rect)(ref icon)).Contains(e.mousePosition);
			EventType typeForControl = e.GetTypeForControl(control);
			switch ((int)typeForControl)
			{
			default:
			{
				if ((int)typeForControl != 7)
				{
					break;
				}
				BuildStyles(m);
				bool flag2 = GUIUtility.hotControl == control;
				_buttonStyle.normal.background = ((state == State.Open || (flag2 && flag)) ? _openTexture : (flag ? _hoverTexture : _buttonTexture));
				_buttonStyle.Draw(icon, false, false, false, false);
				Texture2D[] array = IconTextures(pixels);
				GUI.DrawTexture(new Rect(((Rect)(ref icon)).x + (((Rect)(ref icon)).width - (float)m.Art) / 2f, ((Rect)(ref icon)).y + (((Rect)(ref icon)).height - (float)m.Art) / 2f, (float)m.Art, (float)m.Art), (Texture)(object)((state == State.Off) ? array[1] : array[0]));
				if (state == State.On)
				{
					float num = Mathf.Max(1, Mathf.RoundToInt(2f * m.Unit));
					float num2 = ((Texture)_dotTexture).width;
					GUI.DrawTexture(new Rect(((Rect)(ref icon)).xMax - num - num2, ((Rect)(ref icon)).yMax - num - num2, num2, num2), (Texture)(object)_dotTexture);
				}
				int num3;
				if (flag)
				{
					num3 = ((GUIUtility.hotControl == 0 || flag2) ? 1 : 0);
					if (num3 != 0)
					{
						DrawTooltip(icon, m, Tooltip(state, name, key, hint));
					}
				}
				else
				{
					num3 = 0;
				}
				GUI.depth = ((num3 != 0) ? (-100) : 0);
				break;
			}
			case 0:
				if (flag && (e.button == 0 || e.button == 1))
				{
					GUIUtility.hotControl = control;
					_pressedButton = e.button;
					e.Use();
				}
				break;
			case 3:
				if (GUIUtility.hotControl == control)
				{
					e.Use();
				}
				break;
			case 1:
				if (GUIUtility.hotControl != control)
				{
					break;
				}
				GUIUtility.hotControl = 0;
				e.Use();
				if (flag && e.button == _pressedButton)
				{
					if (e.button != 0)
					{
						return Click.Right;
					}
					return Click.Left;
				}
				break;
			case 2:
				break;
			}
			return Click.None;
		}

		private static string Tooltip(State state, string name, KeyCode key, string hint)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			string text = name + KeyText(key);
			switch (state)
			{
			case State.On:
				text += ": on";
				break;
			case State.Off:
				text += ": off";
				break;
			}
			if (hint == null)
			{
				return text;
			}
			return text + "\n" + hint;
		}

		private static void DrawTooltip(Rect icon, Metrics m, string text)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_000d: 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_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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)
			GUIContent val = new GUIContent(text);
			Vector2 val2 = _tipStyle.CalcSize(val);
			float num = Mathf.Clamp(((Rect)(ref icon)).center.x - val2.x / 2f, (float)m.Margin, Mathf.Max((float)m.Margin, (float)(Screen.width - m.Margin) - val2.x));
			float num2 = ((Rect)(ref icon)).y - (float)m.Gap - val2.y;
			_tipStyle.Draw(new Rect(Mathf.Round(num), Mathf.Round(num2), val2.x, val2.y), val, false, false, false, false);
		}

		private static void Hide(int control, Event e)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			if (GUIUtility.hotControl == control)
			{
				GUIUtility.hotControl = 0;
			}
			if ((int)e.type == 7)
			{
				GUI.depth = 0;
			}
		}

		private static Metrics Measure()
		{
			float num = (float)Screen.height / 1080f;
			int num2 = Mathf.Max(1, Mathf.RoundToInt(2f * num));
			int num3 = Mathf.Max(2, Mathf.RoundToInt(4f * num));
			return new Metrics
			{
				Unit = num,
				Art = 16 * num2,
				Button = 16 * num2 + 2 * num3,
				Gap = Mathf.Max(2, Mathf.RoundToInt(6f * num)),
				Margin = Mathf.RoundToInt(20f * num)
			};
		}

		private static Rect Place(string id, int order, out Rect bar, out Metrics m)
		{
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			Hashtable hashtable = Table();
			int frameCount = Time.frameCount;
			if (hashtable[id] is double[] array)
			{
				array[0] = order;
				array[1] = frameCount;
			}
			else
			{
				hashtable[id] = new double[2] { order, frameCount };
			}
			int num = 0;
			int num2 = 0;
			foreach (DictionaryEntry item in hashtable)
			{
				string text = (string)item.Key;
				double[] array2 = (double[])item.Value;
				if (!((double)frameCount - array2[1] > 2.0))
				{
					num2++;
					if (text != id && (array2[0] < (double)order || (array2[0] == (double)order && string.CompareOrdinal(text, id) < 0)))
					{
						num++;
					}
				}
			}
			m = Measure();
			int num3 = num2 * m.Button + (num2 - 1) * m.Gap;
			int num4 = Screen.width - m.Margin - num3;
			int num5 = Screen.height - m.Margin - m.Button;
			bar = new Rect((float)num4, (float)num5, (float)num3, (float)m.Button);
			return new Rect((float)(num4 + num * (m.Button + m.Gap)), (float)num5, (float)m.Button, (float)m.Button);
		}

		private static void Share(Rect bar)
		{
			AppDomain currentDomain = AppDomain.CurrentDomain;
			int frameCount = Time.frameCount;
			if (!(currentDomain.GetData("OnTogetherMods.IconBar.Rect") is double[] array) || (int)array[4] != frameCount || !(array[2] >= (double)((Rect)(ref bar)).width))
			{
				currentDomain.SetData("OnTogetherMods.IconBar.Rect", new double[6]
				{
					((Rect)(ref bar)).x,
					((Rect)(ref bar)).y,
					((Rect)(ref bar)).width,
					((Rect)(ref bar)).height,
					frameCount,
					_visible ? 1 : 0
				});
			}
		}

		private static Hashtable Table()
		{
			Hashtable hashtable = AppDomain.CurrentDomain.GetData("OnTogetherMods.IconBar.Icons") as Hashtable;
			if (hashtable == null)
			{
				hashtable = new Hashtable();
				AppDomain.CurrentDomain.SetData("OnTogetherMods.IconBar.Icons", hashtable);
			}
			return hashtable;
		}

		private static void Refresh()
		{
			//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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Invalid comparison between Unknown and I4
			int frameCount = Time.frameCount;
			if (_cachedFrame != frameCount)
			{
				_cachedFrame = frameCount;
				Scene activeScene = SceneManager.GetActiveScene();
				_inWorld = ((Scene)(ref activeScene)).buildIndex == 2;
				_visible = false;
				if (_inWorld && !PanelStack.Hidden && !RowHidden)
				{
					TaskManager i = MonoSingleton<TaskManager>.I;
					_visible = (Object)(object)i != (Object)null && ((int)i.LockState == 0 || (int)i.LockState == 5);
				}
			}
		}

		private static void UpdateBlocker(bool shown, Rect bar)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: 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)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			AppDomain currentDomain = AppDomain.CurrentDomain;
			int frameCount = Time.frameCount;
			if (currentDomain.GetData("OnTogetherMods.IconBar.BlockerFrame") is int num && num == frameCount)
			{
				return;
			}
			currentDomain.SetData("OnTogetherMods.IconBar.BlockerFrame", frameCount);
			object? data = currentDomain.GetData("OnTogetherMods.IconBar.Blocker");
			GameObject val = (GameObject)((data is GameObject) ? data : null);
			if ((Object)(object)val == (Object)null)
			{
				if (!shown)
				{
					return;
				}
				val = CreateBlocker();
				currentDomain.SetData("OnTogetherMods.IconBar.Blocker", val);
			}
			if (shown)
			{
				RectTransform val2 = (RectTransform)val.transform.GetChild(0);
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(((Rect)(ref bar)).x, (float)Screen.height - ((Rect)(ref bar)).yMax);
				if (val2.anchoredPosition != val3)
				{
					val2.anchoredPosition = val3;
				}
				if (val2.sizeDelta != ((Rect)(ref bar)).size)
				{
					val2.sizeDelta = ((Rect)(ref bar)).size;
				}
			}
			if (val.activeSelf != shown)
			{
				val.SetActive(shown);
			}
		}

		private static GameObject CreateBlocker()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("OnTogetherMods IconBar ClickBlocker");
			Object.DontDestroyOnLoad((Object)(object)val);
			Canvas obj = val.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 32767;
			val.AddComponent<GraphicRaycaster>();
			GameObject val2 = new GameObject("Area", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			val2.transform.SetParent(val.transform, false);
			((Graphic)val2.GetComponent<Image>()).color = Color.clear;
			RectTransform val3 = (RectTransform)val2.transform;
			val3.anchorMin = Vector2.zero;
			val3.anchorMax = Vector2.zero;
			val3.pivot = Vector2.zero;
			val.SetActive(false);
			return val;
		}

		public static void Patch()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			AppDomain currentDomain = AppDomain.CurrentDomain;
			if (currentDomain.GetData("OnTogetherMods.IconBar.Patched") != null)
			{
				return;
			}
			currentDomain.SetData("OnTogetherMods.IconBar.Patched", true);
			try
			{
				Patches.Apply(new Harmony("nelphei.ontogether.iconbar"));
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"[OnTogetherMods] Icon bar patches failed, so clicks on it may reach the game: {arg}");
			}
		}

		private static Texture2D[] IconTextures(string[] pixels)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: 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_00b2: 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_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			if (Icons.TryGetValue(pixels, out var value) && (Object)(object)value[0] != (Object)null && (Object)(object)value[1] != (Object)null)
			{
				return value;
			}
			Color32[] array = (Color32[])(object)new Color32[256];
			Color32[] array2 = (Color32[])(object)new Color32[256];
			for (int i = 0; i < 16; i++)
			{
				string text = ((i < pixels.Length) ? pixels[i] : "");
				for (int j = 0; j < 16; j++)
				{
					char key = ((j < text.Length) ? text[j] : '.');
					Color32 value2;
					Color32 val = (Color32)(Palette.TryGetValue(key, out value2) ? value2 : new Color32((byte)0, (byte)0, (byte)0, (byte)0));
					int num = (15 - i) * 16 + j;
					array[num] = val;
					byte b = (byte)Mathf.RoundToInt(0.3f * (float)(int)val.r + 0.59f * (float)(int)val.g + 0.11f * (float)(int)val.b);
					array2[num] = new Color32(b, b, b, (byte)((float)(int)val.a * 0.45f));
				}
			}
			value = (Texture2D[])(object)new Texture2D[2]
			{
				NewTexture(16, 16, array, (FilterMode)0),
				NewTexture(16, 16, array2, (FilterMode)0)
			};
			Icons[pixels] = value;
			return value;
		}

		private static void BuildStyles(Metrics m)
		{
			//IL_0078: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0105: Expected O, but got Unknown
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Expected O, but got Unknown
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			if (_builtFor != Screen.height || _buttonStyle == null || !((Object)(object)_buttonTexture != (Object)null) || !((Object)(object)_dotTexture != (Object)null))
			{
				_builtFor = Screen.height;
				int num = Mathf.Max(2, Mathf.RoundToInt(6f * m.Unit));
				Destroy(_buttonTexture);
				Destroy(_hoverTexture);
				Destroy(_openTexture);
				Destroy(_dotTexture);
				_buttonTexture = RoundedBox(num, ButtonFill, ButtonEdge);
				_hoverTexture = RoundedBox(num, HoverFill, HoverEdge);
				_openTexture = RoundedBox(num, OpenFill, OpenEdge);
				int num2 = Mathf.Max(2, Mathf.RoundToInt(3f * m.Unit));
				_dotTexture = RoundedBox(num2, DotFill, DotEdge, 2 * num2);
				int num3 = num + 1;
				_buttonStyle = new GUIStyle
				{
					border = new RectOffset(num3, num3, num3, num3)
				};
				_tipStyle = new GUIStyle
				{
					border = new RectOffset(num3, num3, num3, num3),
					padding = new RectOffset(Mathf.RoundToInt(10f * m.Unit), Mathf.RoundToInt(10f * m.Unit), Mathf.RoundToInt(6f * m.Unit), Mathf.RoundToInt(6f * m.Unit)),
					fontSize = Mathf.Max(8, Mathf.RoundToInt(15f * m.Unit)),
					alignment = (TextAnchor)3,
					wordWrap = false,
					richText = false
				};
				_tipStyle.normal.background = _hoverTexture;
				_tipStyle.normal.textColor = Color.white;
			}
		}

		private static Texture2D RoundedBox(int radius, Color32 fill, Color32 edge, int size = 0)
		{
			//IL_008c: 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_0093: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			if (size <= 0)
			{
				size = 2 * radius + 4;
			}
			Color32[] array = (Color32[])(object)new Color32[size * size];
			for (int i = 0; i < size; i++)
			{
				for (int j = 0; j < size; j++)
				{
					float num = (float)j + 0.5f;
					float num2 = (float)i + 0.5f;
					float num3 = Mathf.Max(Mathf.Max((float)radius - num, num - (float)(size - radius)), 0f);
					float num4 = Mathf.Max(Mathf.Max((float)radius - num2, num2 - (float)(size - radius)), 0f);
					float num5 = Mathf.Sqrt(num3 * num3 + num4 * num4) - (float)radius;
					float num6 = Mathf.Clamp01(0.5f - num5);
					Color val = Color.Lerp(Color32.op_Implicit(fill), Color32.op_Implicit(edge), Mathf.Clamp01(num5 + 1.5f));
					val.a *= num6;
					array[i * size + j] = Color32.op_Implicit(val);
				}
			}
			return NewTexture(size, size, array, (FilterMode)1);
		}

		private static Texture2D NewTexture(int width, int height, Color32[] pixels, FilterMode filter)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			Texture2D val = new Texture2D(width, height, (TextureFormat)4, false)
			{
				filterMode = filter,
				wrapMode = (TextureWrapMode)1,
				hideFlags = (HideFlags)61
			};
			val.SetPixels32(pixels);
			val.Apply(false, true);
			return val;
		}

		private static void Destroy(Texture2D texture)
		{
			if ((Object)(object)texture != (Object)null)
			{
				Object.Destroy((Object)(object)texture);
			}
		}
	}
	internal sealed class ClickBlocker
	{
		private readonly GameObject _root;

		private readonly RectTransform _area;

		public ClickBlocker(string name)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			_root = new GameObject(name);
			Object.DontDestroyOnLoad((Object)(object)_root);
			Canvas obj = _root.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 32767;
			_root.AddComponent<GraphicRaycaster>();
			GameObject val = new GameObject("Area", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			val.transform.SetParent(_root.transform, false);
			((Graphic)val.GetComponent<Image>()).color = Color.clear;
			_area = (RectTransform)val.transform;
			_area.anchorMin = Vector2.zero;
			_area.anchorMax = Vector2.zero;
			_area.pivot = Vector2.zero;
			_root.SetActive(false);
		}

		public void Update(bool shown, Rect screenRect)
		{
			//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)
			if (!((Object)(object)_root == (Object)null))
			{
				if (shown)
				{
					_area.anchoredPosition = new Vector2(((Rect)(ref screenRect)).x, (float)Screen.height - ((Rect)(ref screenRect)).yMax);
					_area.sizeDelta = ((Rect)(ref screenRect)).size;
				}
				if (_root.activeSelf != shown)
				{
					_root.SetActive(shown);
				}
			}
		}

		public void Destroy()
		{
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)_root);
			}
		}

		public static bool MouseIn(Rect screenRect)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			Vector3 mousePosition = Input.mousePosition;
			return ((Rect)(ref screenRect)).Contains(new Vector2(mousePosition.x, (float)Screen.height - mousePosition.y));
		}
	}
}
namespace MeltySynth
{
	internal static class ArrayMath
	{
		public static void MultiplyAdd(float a, float[] x, float[] destination)
		{
			Span<Vector<float>> span = MemoryMarshal.Cast<float, Vector<float>>(x);
			Span<Vector<float>> span2 = MemoryMarshal.Cast<float, Vector<float>>(destination);
			int num = 0;
			for (int i = 0; i < span2.Length; i++)
			{
				span2[i] += a * span[i];
				num += Vector<float>.Count;
			}
			for (int j = num; j < destination.Length; j++)
			{
				destination[j] += a * x[j];
			}
		}

		public static void MultiplyAdd(float a, float step, float[] x, float[] destination)
		{
			for (int i = 0; i < destination.Length; i++)
			{
				destination[i] += a * x[i];
				a += step;
			}
		}
	}
	public static class AudioRendererEx
	{
		public static void RenderInterleaved(this IAudioRenderer renderer, Span<float> destination)
		{
			if (renderer == null)
			{
				throw new ArgumentNullException("renderer");
			}
			if (destination.Length % 2 != 0)
			{
				throw new ArgumentException("The length of the destination buffer must be even.", "destination");
			}
			int num = destination.Length / 2;
			int length = destination.Length;
			float[] array = ArrayPool<float>.Shared.Rent(length);
			try
			{
				Span<float> left = array.AsSpan(0, num);
				Span<float> right = array.AsSpan(num, num);
				renderer.Render(left, right);
				int num2 = 0;
				for (int i = 0; i < num; i++)
				{
					destination[num2++] = left[i];
					destination[num2++] = right[i];
				}
			}
			finally
			{
				ArrayPool<float>.Shared.Return(array);
			}
		}

		public static void RenderMono(this IAudioRenderer renderer, Span<float> destination)
		{
			if (renderer == null)
			{
				throw new ArgumentNullException("renderer");
			}
			int length = destination.Length;
			int minimumLength = 2 * destination.Length;
			float[] array = ArrayPool<float>.Shared.Rent(minimumLength);
			try
			{
				Span<float> left = array.AsSpan(0, length);
				Span<float> right = array.AsSpan(length, length);
				renderer.Render(left, right);
				for (int i = 0; i < length; i++)
				{
					destination[i] = (left[i] + right[i]) / 2f;
				}
			}
			finally
			{
				ArrayPool<float>.Shared.Return(array);
			}
		}

		public static void RenderInt16(this IAudioRenderer renderer, Span<short> left, Span<short> right)
		{
			if (renderer == null)
			{
				throw new ArgumentNullException("renderer");
			}
			if (left.Length != right.Length)
			{
				throw new ArgumentException("The output buffers for the left and right must be the same length.");
			}
			int length = left.Length;
			int minimumLength = 2 * left.Length;
			float[] array = ArrayPool<float>.Shared.Rent(minimumLength);
			try
			{
				Span<float> left2 = array.AsSpan(0, length);
				Span<float> right2 = array.AsSpan(length, length);
				renderer.Render(left2, right2);
				for (int i = 0; i < length; i++)
				{
					float num = 32768f * left2[i];
					if (num < -32768f)
					{
						num = -32768f;
					}
					else if (num > 32767f)
					{
						num = 32767f;
					}
					left[i] = (short)num;
				}
				for (int j = 0; j < length; j++)
				{
					float num2 = 32768f * right2[j];
					if (num2 < -32768f)
					{
						num2 = -32768f;
					}
					else if (num2 > 32767f)
					{
						num2 = 32767f;
					}
					right[j] = (short)num2;
				}
			}
			finally
			{
				ArrayPool<float>.Shared.Return(array);
			}
		}

		public static void RenderInterleavedInt16(this IAudioRenderer renderer, Span<short> destination)
		{
			if (renderer == null)
			{
				throw new ArgumentNullException("renderer");
			}
			if (destination.Length % 2 != 0)
			{
				throw new ArgumentException("The length of the destination buffer must be even.", "destination");
			}
			int num = destination.Length / 2;
			int length = destination.Length;
			float[] array = ArrayPool<float>.Shared.Rent(length);
			try
			{
				Span<float> left = array.AsSpan(0, num);
				Span<float> right = array.AsSpan(num, num);
				renderer.Render(left, right);
				int num2 = 0;
				for (int i = 0; i < num; i++)
				{
					int num3 = (int)(32768f * left[i]);
					if (num3 < -32768)
					{
						num3 = -32768;
					}
					else if (num3 > 32767)
					{
						num3 = 32767;
					}
					int num4 = (int)(32768f * right[i]);
					if (num4 < -32768)
					{
						num4 = -32768;
					}
					else if (num4 > 32767)
					{
						num4 = 32767;
					}
					destination[num2++] = (short)num3;
					destination[num2++] = (short)num4;
				}
			}
			finally
			{
				ArrayPool<float>.Shared.Return(array);
			}
		}

		public static void RenderMonoInt16(this IAudioRenderer renderer, Span<short> destination)
		{
			if (renderer == null)
			{
				throw new ArgumentNullException("renderer");
			}
			int length = destination.Length;
			int minimumLength = 2 * destination.Length;
			float[] array = ArrayPool<float>.Shared.Rent(minimumLength);
			try
			{
				Span<float> left = array.AsSpan(0, length);
				Span<float> right = array.AsSpan(length, length);
				renderer.Render(left, right);
				for (int i = 0; i < length; i++)
				{
					int num = (int)(16384f * (left[i] + right[i]));
					if (num < -32768)
					{
						num = -32768;
					}
					else if (num > 32767)
					{
						num = 32767;
					}
					destination[i] = (short)num;
				}
			}
			finally
			{
				ArrayPool<float>.Shared.Return(array);
			}
		}
	}
	internal static class BinaryReaderEx
	{
		public static string ReadFourCC(this BinaryReader reader)
		{
			byte[] array = reader.ReadBytes(4);
			for (int i = 0; i < array.Length; i++)
			{
				byte b = array[i];
				if (32 > b || b > 126)
				{
					array[i] = 63;
				}
			}
			return Encoding.ASCII.GetString(array, 0, array.Length);
		}

		public static string ReadFixedLengthString(this BinaryReader reader, int length)
		{
			byte[] array = reader.ReadBytes(length);
			int i;
			for (i = 0; i < array.Length && array[i] != 0; i++)
			{
			}
			return Encoding.ASCII.GetString(array, 0, i);
		}

		public static short ReadInt16BigEndian(this BinaryReader reader)
		{
			short num = reader.ReadInt16();
			int num2 = 0xFF & num;
			int num3 = 0xFF & (num >> 8);
			return (short)((num2 << 8) | num3);
		}

		public static int ReadInt32BigEndian(this BinaryReader reader)
		{
			int num = reader.ReadInt32();
			int num2 = 0xFF & num;
			int num3 = 0xFF & (num >> 8);
			int num4 = 0xFF & (num >> 16);
			int num5 = 0xFF & (num >> 24);
			return (num2 << 24) | (num3 << 16) | (num4 << 8) | num5;
		}

		public static int ReadIntVariableLength(this BinaryReader reader)
		{
			int num = 0;
			int num2 = 0;
			while (true)
			{
				byte b = reader.ReadByte();
				num = (num << 7) | (b & 0x7F);
				if ((b & 0x80) == 0)
				{
					break;
				}
				num2++;
				if (num2 == 4)
				{
					throw new InvalidDataException("The length of the value must be equal to or less than 4.");
				}
			}
			return num;
		}
	}
	internal sealed class BiQuadFilter
	{
		private static readonly float resonancePeakOffset = 1f - 1f / MathF.Sqrt(2f);

		private readonly Synthesizer synthesizer;

		private bool active;

		private float a0;

		private float a1;

		private float a2;

		private float a3;

		private float a4;

		private float x1;

		private float x2;

		private float y1;

		private float y2;

		internal BiQuadFilter(Synthesizer synthesizer)
		{
			this.synthesizer = synthesizer;
		}

		public void ClearBuffer()
		{
			x1 = 0f;
			x2 = 0f;
			y1 = 0f;
			y2 = 0f;
		}

		public void SetLowPassFilter(float cutoffFrequency, float resonance)
		{
			if (cutoffFrequency < 0.499f * (float)synthesizer.SampleRate)
			{
				active = true;
				float num = resonance - resonancePeakOffset / (1f + 6f * (resonance - 1f));
				float x = MathF.PI * 2f * cutoffFrequency / (float)synthesizer.SampleRate;
				float num2 = MathF.Cos(x);
				float num3 = MathF.Sin(x) / (2f * num);
				float b = (1f - num2) / 2f;
				float b2 = 1f - num2;
				float b3 = (1f - num2) / 2f;
				float num4 = 1f + num3;
				float num5 = -2f * num2;
				float num6 = 1f - num3;
				SetCoefficients(num4, num5, num6, b, b2, b3);
			}
			else
			{
				active = false;
			}
		}

		public void Process(float[] block)
		{
			if (active)
			{
				for (int i = 0; i < block.Length; i++)
				{
					float num = block[i];
					float num2 = a0 * num + a1 * x1 + a2 * x2 - a3 * y1 - a4 * y2;
					x2 = x1;
					x1 = num;
					y2 = y1;
					y1 = num2;
					block[i] = num2;
				}
			}
			else
			{
				x2 = block[^2];
				x1 = block[^1];
				y2 = x2;
				y1 = x1;
			}
		}

		private void SetCoefficients(float a0, float a1, float a2, float b0, float b1, float b2)
		{
			this.a0 = b0 / a0;
			this.a1 = b1 / a0;
			this.a2 = b2 / a0;
			a3 = a1 / a0;
			a4 = a2 / a0;
		}
	}
	internal sealed class Channel
	{
		private enum DataType
		{
			None,
			Rpn,
			Nrpn
		}

		private readonly Synthesizer synthesizer;

		private readonly bool isPercussionChannel;

		private int bankNumber;

		private int patchNumber;

		private short modulation;

		private short volume;

		private short pan;

		private short expression;

		private bool holdPedal;

		private byte reverbSend;

		private byte chorusSend;

		private short rpn;

		private short pitchBendRange;

		private short coarseTune;

		private short fineTune;

		private float pitchBend;

		private DataType lastDataType;

		public bool IsPercussionChannel => isPercussionChannel;

		public int BankNumber => bankNumber;

		public int PatchNumber => patchNumber;

		public float Modulation => 0.003051944f * (float)modulation;

		public float Volume => 6.103888E-05f * (float)volume;

		public float Pan => 0.006103888f * (float)pan - 50f;

		public float Expression => 6.103888E-05f * (float)expression;

		public bool HoldPedal => holdPedal;

		public float ReverbSend => 1f / 127f * (float)(int)reverbSend;

		public float ChorusSend => 1f / 127f * (float)(int)chorusSend;

		public float PitchBendRange => (float)(pitchBendRange >> 7) + 0.01f * (float)(pitchBendRange & 0x7F);

		public float Tune => (float)coarseTune + 0.00012207031f * (float)(fineTune - 8192);

		public float PitchBend => PitchBendRange * pitchBend;

		internal Channel(Synthesizer synthesizer, bool isPercussionChannel)
		{
			this.synthesizer = synthesizer;
			this.isPercussionChannel = isPercussionChannel;
			Reset();
		}

		public void Reset()
		{
			bankNumber = (isPercussionChannel ? 128 : 0);
			patchNumber = 0;
			modulation = 0;
			volume = 12800;
			pan = 8192;
			expression = 16256;
			holdPedal = false;
			reverbSend = 40;
			chorusSend = 0;
			rpn = -1;
			pitchBendRange = 256;
			coarseTune = 0;
			fineTune = 8192;
			pitchBend = 0f;
			lastDataType = DataType.None;
		}

		public void ResetAllControllers()
		{
			modulation = 0;
			expression = 16256;
			holdPedal = false;
			rpn = -1;
			pitchBend = 0f;
		}

		public void SetBank(int value)
		{
			bankNumber = value;
			if (isPercussionChannel)
			{
				bankNumber += 128;
			}
		}

		public void SetPatch(int value)
		{
			patchNumber = value;
		}

		public void SetModulationCoarse(int value)
		{
			modulation = (short)((modulation & 0x7F) | (value << 7));
		}

		public void SetModulationFine(int value)
		{
			modulation = (short)((modulation & 0xFF80) | value);
		}

		public void SetVolumeCoarse(int value)
		{
			volume = (short)((volume & 0x7F) | (value << 7));
		}

		public void SetVolumeFine(int value)
		{
			volume = (short)((volume & 0xFF80) | value);
		}

		public void SetPanCoarse(int value)
		{
			pan = (short)((pan & 0x7F) | (value << 7));
		}

		public void SetPanFine(int value)
		{
			pan = (short)((pan & 0xFF80) | value);
		}

		public void SetExpressionCoarse(int value)
		{
			expression = (short)((expression & 0x7F) | (value << 7));
		}

		public void SetExpressionFine(int value)
		{
			expression = (short)((expression & 0xFF80) | value);
		}

		public void SetHoldPedal(int value)
		{
			holdPedal = value >= 64;
		}

		public void SetReverbSend(int value)
		{
			reverbSend = (byte)value;
		}

		public void SetChorusSend(int value)
		{
			chorusSend = (byte)value;
		}

		public void SetRpnCoarse(int value)
		{
			rpn = (short)((rpn & 0x7F) | (value << 7));
			lastDataType = DataType.Rpn;
		}

		public void SetRpnFine(int value)
		{
			rpn = (short)((rpn & 0xFF80) | value);
			lastDataType = DataType.Rpn;
		}

		public void SetNrpnCoarse(int value)
		{
			lastDataType = DataType.Nrpn;
		}

		public void SetNrpnFine(int value)
		{
			lastDataType = DataType.Nrpn;
		}

		public void DataEntryCoarse(int value)
		{
			if (lastDataType == DataType.Rpn)
			{
				switch (rpn)
				{
				case 0:
					pitchBendRange = (short)((pitchBendRange & 0x7F) | (value << 7));
					break;
				case 1:
					fineTune = (short)((fineTune & 0x7F) | (value << 7));
					break;
				case 2:
					coarseTune = (short)(value - 64);
					break;
				}
			}
		}

		public void DataEntryFine(int value)
		{
			if (lastDataType == DataType.Rpn)
			{
				switch (rpn)
				{
				case 0:
					pitchBendRange = (short)((pitchBendRange & 0xFF80) | value);
					break;
				case 1:
					fineTune = (short)((fineTune & 0xFF80) | value);
					break;
				}
			}
		}

		public void SetPitchBend(int value1, int value2)
		{
			pitchBend = 0.00012207031f * (float)((value1 | (value2 << 7)) - 8192);
		}
	}
	internal sealed class Chorus
	{
		private readonly float[] bufferL;

		private readonly float[] bufferR;

		private readonly float[] delayTable;

		private int bufferIndex;

		private int delayTableIndexL;

		private int delayTableIndexR;

		internal Chorus(int sampleRate, double delay, double depth, double frequency)
		{
			bufferL = new float[(int)((double)sampleRate * (delay + depth)) + 2];
			bufferR = new float[(int)((double)sampleRate * (delay + depth)) + 2];
			delayTable = new float[(int)Math.Round((double)sampleRate / frequency)];
			for (int i = 0; i < delayTable.Length; i++)
			{
				double a = Math.PI * 2.0 * (double)i / (double)delayTable.Length;
				delayTable[i] = (float)((double)sampleRate * (delay + depth * Math.Sin(a)));
			}
			bufferIndex = 0;
			delayTableIndexL = 0;
			delayTableIndexR = delayTable.Length / 4;
		}

		public void Process(float[] inputLeft, float[] inputRight, float[] outputLeft, float[] outputRight)
		{
			for (int i = 0; i < outputLeft.Length; i++)
			{
				double num = (double)bufferIndex - (double)delayTable[delayTableIndexL];
				if (num < 0.0)
				{
					num += (double)bufferL.Length;
				}
				int num2 = (int)num;
				int num3 = num2 + 1;
				if (num3 == bufferL.Length)
				{
					num3 = 0;
				}
				double num4 = bufferL[num2];
				double num5 = bufferL[num3];
				double num6 = num - (double)num2;
				outputLeft[i] = (float)(num4 + num6 * (num5 - num4));
				delayTableIndexL++;
				if (delayTableIndexL == delayTable.Length)
				{
					delayTableIndexL = 0;
				}
				double num7 = (double)bufferIndex - (double)delayTable[delayTableIndexR];
				if (num7 < 0.0)
				{
					num7 += (double)bufferR.Length;
				}
				int num8 = (int)num7;
				int num9 = num8 + 1;
				if (num9 == bufferR.Length)
				{
					num9 = 0;
				}
				double num10 = bufferR[num8];
				double num11 = bufferR[num9];
				double num12 = num7 - (double)num8;
				outputRight[i] = (float)(num10 + num12 * (num11 - num10));
				delayTableIndexR++;
				if (delayTableIndexR == delayTable.Length)
				{
					delayTableIndexR = 0;
				}
				bufferL[bufferIndex] = inputLeft[i];
				bufferR[bufferIndex] = inputRight[i];
				bufferIndex++;
				if (bufferIndex == bufferL.Length)
				{
					bufferIndex = 0;
				}
			}
		}

		public void Mute()
		{
			Array.Clear(bufferL, 0, bufferL.Length);
			Array.Clear(bufferR, 0, bufferR.Length);
		}
	}
	internal struct Generator
	{
		private readonly GeneratorType type;

		private readonly ushort value;

		public GeneratorType Type => type;

		public ushort Value => value;

		private Generator(BinaryReader reader)
		{
			type = (GeneratorType)reader.ReadUInt16();
			value = reader.ReadUInt16();
		}

		internal static Generator[] ReadFromChunk(BinaryReader reader, int size)
		{
			if (size == 0 || size % 4 != 0)
			{
				throw new InvalidDataException("The generator list is invalid.");
			}
			Generator[] array = new Generator[size / 4 - 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Generator(reader);
			}
			new Generator(reader);
			return array;
		}
	}
	internal enum GeneratorType : ushort
	{
		StartAddressOffset,
		EndAddressOffset,
		StartLoopAddressOffset,
		EndLoopAddressOffset,
		StartAddressCoarseOffset,
		ModulationLfoToPitch,
		VibratoLfoToPitch,
		ModulationEnvelopeToPitch,
		InitialFilterCutoffFrequency,
		InitialFilterQ,
		ModulationLfoToFilterCutoffFrequency,
		ModulationEnvelopeToFilterCutoffFrequency,
		EndAddressCoarseOffset,
		ModulationLfoToVolume,
		Unused1,
		ChorusEffectsSend,
		ReverbEffectsSend,
		Pan,
		Unused2,
		Unused3,
		Unused4,
		DelayModulationLfo,
		FrequencyModulationLfo,
		DelayVibratoLfo,
		FrequencyVibratoLfo,
		DelayModulationEnvelope,
		AttackModulationEnvelope,
		HoldModulationEnvelope,
		DecayModulationEnvelope,
		SustainModulationEnvelope,
		ReleaseModulationEnvelope,
		KeyNumberToModulationEnvelopeHold,
		KeyNumberToModulationEnvelopeDecay,
		DelayVolumeEnvelope,
		AttackVolumeEnvelope,
		HoldVolumeEnvelope,
		DecayVolumeEnvelope,
		SustainVolumeEnvelope,
		ReleaseVolumeEnvelope,
		KeyNumberToVolumeEnvelopeHold,
		KeyNumberToVolumeEnvelopeDecay,
		Instrument,
		Reserved1,
		KeyRange,
		VelocityRange,
		StartLoopAddressCoarseOffset,
		KeyNumber,
		Velocity,
		InitialAttenuation,
		Reserved2,
		EndLoopAddressCoarseOffset,
		CoarseTune,
		FineTune,
		SampleID,
		SampleModes,
		Reserved3,
		ScaleTuning,
		ExclusiveClass,
		OverridingRootKey,
		Unused5,
		UnusedEnd
	}
	public interface IAudioRenderer
	{
		void Render(Span<float> left, Span<float> right);
	}
	public sealed class Instrument
	{
		internal static readonly Instrument Default = new Instrument();

		private readonly string name;

		private readonly InstrumentRegion[] regions;

		public string Name => name;

		public IReadOnlyList<InstrumentRegion> Regions => regions;

		internal InstrumentRegion[] RegionArray => regions;

		private Instrument()
		{
			name = "Default";
			regions = Array.Empty<InstrumentRegion>();
		}

		private Instrument(InstrumentInfo info, Zone[] zones, SampleHeader[] samples)
		{
			name = info.Name;
			int num = info.ZoneEndIndex - info.ZoneStartIndex + 1;
			if (num <= 0)
			{
				throw new InvalidDataException("The instrument '" + info.Name + "' has no zone.");
			}
			Span<Zone> zones2 = zones.AsSpan(info.ZoneStartIndex, num);
			regions = InstrumentRegion.Create(this, zones2, samples);
		}

		internal static Instrument[] Create(InstrumentInfo[] infos, Zone[] zones, SampleHeader[] samples)
		{
			if (infos.Length <= 1)
			{
				throw new InvalidDataException("No valid instrument was found.");
			}
			Instrument[] array = new Instrument[infos.Length - 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Instrument(infos[i], zones, samples);
			}
			return array;
		}

		public override string ToString()
		{
			return name;
		}
	}
	internal sealed class InstrumentInfo
	{
		private string name;

		private int zoneStartIndex;

		private int zoneEndIndex;

		public string Name => name;

		public int ZoneStartIndex => zoneStartIndex;

		public int ZoneEndIndex => zoneEndIndex;

		private InstrumentInfo(BinaryReader reader)
		{
			name = reader.ReadFixedLengthString(20);
			zoneStartIndex = reader.ReadUInt16();
		}

		internal static InstrumentInfo[] ReadFromChunk(BinaryReader reader, int size)
		{
			if (size == 0 || size % 22 != 0)
			{
				throw new InvalidDataException("The instrument list is invalid.");
			}
			int num = size / 22;
			InstrumentInfo[] array = new InstrumentInfo[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = new InstrumentInfo(reader);
			}
			for (int j = 0; j < num - 1; j++)
			{
				array[j].zoneEndIndex = array[j + 1].zoneStartIndex - 1;
			}
			return array;
		}
	}
	public sealed class InstrumentRegion
	{
		internal static readonly InstrumentRegion Default = new InstrumentRegion();

		private readonly short[] gs;

		private readonly SampleHeader sample;

		internal short this[GeneratorType generatortType] => gs[(uint)generatortType];

		public SampleHeader Sample => sample;

		public int SampleStart => sample.Start + StartAddressOffset;

		public int SampleEnd => sample.End + EndAddressOffset;

		public int SampleStartLoop => sample.StartLoop + StartLoopAddressOffset;

		public int SampleEndLoop => sample.EndLoop + EndLoopAddressOffset;

		public int StartAddressOffset => 32768 * this[GeneratorType.StartAddressCoarseOffset] + this[GeneratorType.StartAddressOffset];

		public int EndAddressOffset => 32768 * this[GeneratorType.EndAddressCoarseOffset] + this[GeneratorType.EndAddressOffset];

		public int StartLoopAddressOffset => 32768 * this[GeneratorType.StartLoopAddressCoarseOffset] + this[GeneratorType.StartLoopAddressOffset];

		public int EndLoopAddressOffset => 32768 * this[GeneratorType.EndLoopAddressCoarseOffset] + this[GeneratorType.EndLoopAddressOffset];

		public int ModulationLfoToPitch => this[GeneratorType.ModulationLfoToPitch];

		public int VibratoLfoToPitch => this[GeneratorType.VibratoLfoToPitch];

		public int ModulationEnvelopeToPitch => this[GeneratorType.ModulationEnvelopeToPitch];

		public float InitialFilterCutoffFrequency => SoundFontMath.CentsToHertz(this[GeneratorType.InitialFilterCutoffFrequency]);

		public float InitialFilterQ => 0.1f * (float)this[GeneratorType.InitialFilterQ];

		public int ModulationLfoToFilterCutoffFrequency => this[GeneratorType.ModulationLfoToFilterCutoffFrequency];

		public int ModulationEnvelopeToFilterCutoffFrequency => this[GeneratorType.ModulationEnvelopeToFilterCutoffFrequency];

		public float ModulationLfoToVolume => 0.1f * (float)this[GeneratorType.ModulationLfoToVolume];

		public float ChorusEffectsSend => 0.1f * (float)this[GeneratorType.ChorusEffectsSend];

		public float ReverbEffectsSend => 0.1f * (float)this[GeneratorType.ReverbEffectsSend];

		public float Pan => 0.1f * (float)this[GeneratorType.Pan];

		public float DelayModulationLfo => SoundFontMath.TimecentsToSeconds(this[GeneratorType.DelayModulationLfo]);

		public float FrequencyModulationLfo => SoundFontMath.CentsToHertz(this[GeneratorType.FrequencyModulationLfo]);

		public float DelayVibratoLfo => SoundFontMath.TimecentsToSeconds(this[GeneratorType.DelayVibratoLfo]);

		public float FrequencyVibratoLfo => SoundFontMath.CentsToHertz(this[GeneratorType.FrequencyVibratoLfo]);

		public float DelayModulationEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.DelayModulationEnvelope]);

		public float AttackModulationEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.AttackModulationEnvelope]);

		public float HoldModulationEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.HoldModulationEnvelope]);

		public float DecayModulationEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.DecayModulationEnvelope]);

		public float SustainModulationEnvelope => 0.1f * (float)this[GeneratorType.SustainModulationEnvelope];

		public float ReleaseModulationEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.ReleaseModulationEnvelope]);

		public int KeyNumberToModulationEnvelopeHold => this[GeneratorType.KeyNumberToModulationEnvelopeHold];

		public int KeyNumberToModulationEnvelopeDecay => this[GeneratorType.KeyNumberToModulationEnvelopeDecay];

		public float DelayVolumeEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.DelayVolumeEnvelope]);

		public float AttackVolumeEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.AttackVolumeEnvelope]);

		public float HoldVolumeEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.HoldVolumeEnvelope]);

		public float DecayVolumeEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.DecayVolumeEnvelope]);

		public float SustainVolumeEnvelope => 0.1f * (float)this[GeneratorType.SustainVolumeEnvelope];

		public float ReleaseVolumeEnvelope => SoundFontMath.TimecentsToSeconds(this[GeneratorType.ReleaseVolumeEnvelope]);

		public int KeyNumberToVolumeEnvelopeHold => this[GeneratorType.KeyNumberToVolumeEnvelopeHold];

		public int KeyNumberToVolumeEnvelopeDecay => this[GeneratorType.KeyNumberToVolumeEnvelopeDecay];

		public int KeyRangeStart => this[GeneratorType.KeyRange] & 0xFF;

		public int KeyRangeEnd => (this[GeneratorType.KeyRange] >> 8) & 0xFF;

		public int VelocityRangeStart => this[GeneratorType.VelocityRange] & 0xFF;

		public int VelocityRangeEnd => (this[GeneratorType.VelocityRange] >> 8) & 0xFF;

		public float InitialAttenuation => 0.1f * (float)this[GeneratorType.InitialAttenuation];

		public int CoarseTune => this[GeneratorType.CoarseTune];

		public int FineTune => this[GeneratorType.FineTune] + sample.PitchCorrection;

		public LoopMode SampleModes
		{
			get
			{
				if (this[GeneratorType.SampleModes] == 2)
				{
					return LoopMode.NoLoop;
				}
				return (LoopMode)this[GeneratorType.SampleModes];
			}
		}

		public int ScaleTuning => this[GeneratorType.ScaleTuning];

		public int ExclusiveClass => this[GeneratorType.ExclusiveClass];

		public int RootKey
		{
			get
			{
				if (this[GeneratorType.OverridingRootKey] == -1)
				{
					return sample.OriginalPitch;
				}
				return this[GeneratorType.OverridingRootKey];
			}
		}

		private InstrumentRegion()
		{
			gs = new short[61];
			gs[8] = 13500;
			gs[21] = -12000;
			gs[23] = -12000;
			gs[25] = -12000;
			gs[26] = -12000;
			gs[27] = -12000;
			gs[28] = -12000;
			gs[30] = -12000;
			gs[33] = -12000;
			gs[34] = -12000;
			gs[35] = -12000;
			gs[36] = -12000;
			gs[38] = -12000;
			gs[43] = 32512;
			gs[44] = 32512;
			gs[46] = -1;
			gs[47] = -1;
			gs[56] = 100;
			gs[58] = -1;
			sample = SampleHeader.Default;
		}

		private InstrumentRegion(Instrument instrument, Zone global, Zone local, SampleHeader[] samples)
			: this()
		{
			foreach (Generator generator in global.Generators)
			{
				SetParameter(generator);
			}
			foreach (Generator generator2 in local.Generators)
			{
				SetParameter(generator2);
			}
			short num = gs[53];
			if (0 > num || num >= samples.Length)
			{
				throw new InvalidDataException($"The instrument '{instrument.Name}' contains an invalid sample ID '{num}'.");
			}
			sample = samples[num];
		}

		internal static InstrumentRegion[] Create(Instrument instrument, Span<Zone> zones, SampleHeader[] samples)
		{
			if (zones[0].Generators.Count == 0 || zones[0].Generators.Last().Type != GeneratorType.SampleID)
			{
				Zone global = zones[0];
				InstrumentRegion[] array = new InstrumentRegion[zones.Length - 1];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = new InstrumentRegion(instrument, global, zones[i + 1], samples);
				}
				return array;
			}
			InstrumentRegion[] array2 = new InstrumentRegion[zones.Length];
			for (int j = 0; j < array2.Length; j++)
			{
				array2[j] = new InstrumentRegion(instrument, Zone.Empty, zones[j], samples);
			}
			return array2;
		}

		private void SetParameter(Generator generator)
		{
			int type = (int)generator.Type;
			if (0 <= type && type < gs.Length)
			{
				gs[type] = (short)generator.Value;
			}
		}

		public bool Contains(int key, int velocity)
		{
			bool num = KeyRangeStart <= key && key <= KeyRangeEnd;
			bool flag = VelocityRangeStart <= velocity && velocity <= VelocityRangeEnd;
			return num && flag;
		}

		public override string ToString()
		{
			return $"{sample.Name} (Key: {KeyRangeStart}-{KeyRangeEnd}, Velocity: {VelocityRangeStart}-{VelocityRangeEnd})";
		}
	}
	internal sealed class Lfo
	{
		private readonly Synthesizer synthesizer;

		private bool active;

		private double delay;

		private double period;

		private int processedSampleCount;

		private float value;

		public float Value => value;

		internal Lfo(Synthesizer synthesizer)
		{
			this.synthesizer = synthesizer;
		}

		public void Start(float delay, float frequency)
		{
			if ((double)frequency > 0.001)
			{
				active = true;
				this.delay = delay;
				period = 1.0 / (double)frequency;
				processedSampleCount = 0;
				value = 0f;
			}
			else
			{
				active = false;
				value = 0f;
			}
		}

		public void Process()
		{
			if (!active)
			{
				return;
			}
			processedSampleCount += synthesizer.BlockSize;
			double num = (double)processedSampleCount / (double)synthesizer.SampleRate;
			if (num < delay)
			{
				value = 0f;
				return;
			}
			double num2 = (num - delay) % period / period;
			if (num2 < 0.25)
			{
				value = (float)(4.0 * num2);
			}
			else if (num2 < 0.75)
			{
				value = (float)(4.0 * (0.5 - num2));
			}
			else
			{
				value = (float)(4.0 * (num2 - 1.0));
			}
		}
	}
	public enum LoopMode
	{
		NoLoop = 0,
		Continuous = 1,
		LoopUntilNoteOff = 3
	}
	public sealed class MidiFile
	{
		internal struct Message
		{
			private byte channel;

			private byte command;

			private byte data1;

			private byte data2;

			public MessageType Type => channel switch
			{
				252 => MessageType.TempoChange, 
				253 => MessageType.LoopStart, 
				254 => MessageType.LoopEnd, 
				byte.MaxValue => MessageType.EndOfTrack, 
				_ => MessageType.Normal, 
			};

			public byte Channel => channel;

			public byte Command => command;

			public byte Data1 => data1;

			public byte Data2 => data2;

			public double Tempo => 60000000.0 / (double)((command << 16) | (data1 << 8) | data2);

			private Message(byte channel, byte command, byte data1, byte data2)
			{
				this.channel = channel;
				this.command = command;
				this.data1 = data1;
				this.data2 = data2;
			}

			public static Message Common(byte status, byte data1)
			{
				byte num = (byte)(status & 0xF);
				byte b = (byte)(status & 0xF0);
				byte b2 = 0;
				return new Message(num, b, data1, b2);
			}

			public static Message Common(byte status, byte data1, byte data2, MidiFileLoopType loopType)
			{
				byte b = (byte)(status & 0xF);
				byte b2 = (byte)(status & 0xF0);
				if (b2 == 176)
				{
					switch (loopType)
					{
					case MidiFileLoopType.RpgMaker:
						if (data1 == 111)
						{
							return LoopStart();
						}
						break;
					case MidiFileLoopType.IncredibleMachine:
						switch (data1)
						{
						case 110:
							return LoopStart();
						case 111:
							return LoopEnd();
						}
						break;
					case MidiFileLoopType.FinalFantasy:
						switch (data1)
						{
						case 116:
							return LoopStart();
						case 117:
							return LoopEnd();
						}
						break;
					}
				}
				return new Message(b, b2, data1, data2);
			}

			public static Message TempoChange(int tempo)
			{
				byte b = (byte)(tempo >> 16);
				byte b2 = (byte)(tempo >> 8);
				byte b3 = (byte)tempo;
				return new Message(252, b, b2, b3);
			}

			public static Message LoopStart()
			{
				return new Message(253, 0, 0, 0);
			}

			public static Message LoopEnd()
			{
				return new Message(254, 0, 0, 0);
			}

			public static Message EndOfTrack()
			{
				return new Message(byte.MaxValue, 0, 0, 0);
			}

			public override string ToString()
			{
				return channel switch
				{
					252 => "Tempo: " + Tempo, 
					253 => "LoopStart", 
					254 => "LoopEnd", 
					byte.MaxValue => "EndOfTrack", 
					_ => "CH" + channel + ": " + command.ToString("X2") + ", " + data1.ToString("X2") + ", " + data2.ToString("X2"), 
				};
			}
		}

		internal enum MessageType
		{
			Normal = 0,
			TempoChange = 252,
			LoopStart = 253,
			LoopEnd = 254,
			EndOfTrack = 255
		}

		private Message[] messages;

		private TimeSpan[] times;

		public TimeSpan Length => times.Last();

		internal Message[] Messages => messages;

		internal TimeSpan[] Times => times;

		public MidiFile(Stream stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			Load(stream, 0, MidiFileLoopType.None);
		}

		public MidiFile(Stream stream, int loopPoint)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if (loopPoint < 0)
			{
				throw new ArgumentException("The loop point must be a non-negative value.", "loopPoint");
			}
			Load(stream, loopPoint, MidiFileLoopType.None);
		}

		public MidiFile(Stream stream, MidiFileLoopType loopType)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			Load(stream, 0, loopType);
		}

		public MidiFile(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
			Load(stream, 0, MidiFileLoopType.None);
		}

		public MidiFile(string path, int loopPoint)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (loopPoint < 0)
			{
				throw new ArgumentException("The loop point must be a non-negative value.", "loopPoint");
			}
			using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
			Load(stream, loopPoint, MidiFileLoopType.None);
		}

		public MidiFile(string path, MidiFileLoopType loopType)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
			Load(stream, 0, loopType);
		}

		internal static TimeSpan GetTimeSpanFromSeconds(double value)
		{
			return new TimeSpan((long)(10000000.0 * value));
		}

		private void Load(Stream stream, int loopPoint, MidiFileLoopType loopType)
		{
			using BinaryReader reader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true);
			string text = reader.ReadFourCC();
			if (text != "MThd")
			{
				throw new InvalidDataException("The chunk type must be 'MThd', but was '" + text + "'.");
			}
			if (reader.ReadInt32BigEndian() != 6)
			{
				throw new InvalidDataException("The MThd chunk has invalid data.");
			}
			short num = reader.ReadInt16BigEndian();
			if (num != 0 && num != 1)
			{
				throw new NotSupportedException($"The format {num} is not supported.");
			}
			short num2 = reader.ReadInt16BigEndian();
			short resolution = reader.ReadInt16BigEndian();
			List<Message>[] array = new List<Message>[num2];
			List<int>[] array2 = new List<int>[num2];
			for (int i = 0; i < num2; i++)
			{
				int num3 = i;
				List<int>[] array3 = array2;
				int num4 = i;
				(List<Message>, List<int>) tuple = ReadTrack(reader, loopType);
				array[num3] = tuple.Item1;
				array3[num4] = tuple.Item2;
			}
			if (loopPoint != 0)
			{
				List<int> list = array2[0];
				List<Message> list2 = array[0];
				if (loopPoint <= list.Last())
				{
					for (int j = 0; j < list.Count; j++)
					{
						if (list[j] >= loopPoint)
						{
							list.Insert(j, loopPoint);
							list2.Insert(j, Message.LoopStart());
							break;
						}
					}
				}
				else
				{
					list.Add(loopPoint);
					list2.Add(Message.LoopStart());
				}
			}
			(messages, times) = MergeTracks(array, array2, resolution);
		}

		private static (List<Message>, List<int>) ReadTrack(BinaryReader reader, MidiFileLoopType loopType)
		{
			string text = reader.ReadFourCC();
			if (text != "MTrk")
			{
				throw new InvalidDataException("The chunk type must be 'MTrk', but was '" + text + "'.");
			}
			long num = reader.ReadInt32BigEndian();
			num += reader.BaseStream.Position;
			List<Message> list = new List<Message>();
			List<int> list2 = new List<int>();
			int num2 = 0;
			byte b = 0;
			while (true)
			{
				int num3 = reader.ReadIntVariableLength();
				byte b2 = reader.ReadByte();
				try
				{
					num2 = checked(num2 + num3);
				}
				catch (OverflowException)
				{
					throw new NotSupportedException("Long MIDI file is not supported.");
				}
				if ((b2 & 0x80) == 0)
				{
					int num4 = b & 0xF0;
					if (num4 == 192 || num4 == 208)
					{
						list.Add(Message.Common(b, b2));
						list2.Add(num2);
					}
					else
					{
						byte data = reader.ReadByte();
						list.Add(Message.Common(b, b2, data, loopType));
						list2.Add(num2);
					}
					continue;
				}
				switch (b2)
				{
				case 240:
					DiscardData(reader);
					break;
				case 247:
					DiscardData(reader);
					break;
				case byte.MaxValue:
					switch (reader.ReadByte())
					{
					case 47:
						reader.ReadByte();
						list.Add(Message.EndOfTrack());
						list2.Add(num2);
						if (reader.BaseStream.Position < num)
						{
							reader.BaseStream.Position = num;
						}
						return (list, list2);
					case 81:
						list.Add(Message.TempoChange(ReadTempo(reader)));
						list2.Add(num2);
						break;
					default:
						DiscardData(reader);
						break;
					}
					break;
				default:
				{
					int num5 = b2 & 0xF0;
					if (num5 == 192 || num5 == 208)
					{
						byte data2 = reader.ReadByte();
						list.Add(Message.Common(b2, data2));
						list2.Add(num2);
					}
					else
					{
						byte data3 = reader.ReadByte();
						byte data4 = reader.ReadByte();
						list.Add(Message.Common(b2, data3, data4, loopType));
						list2.Add(num2);
					}
					break;
				}
				}
				b = b2;
			}
		}

		private static (Message[], TimeSpan[]) MergeTracks(List<Message>[] messageLists, List<int>[] tickLists, int resolution)
		{
			List<Message> list = new List<Message>();
			List<TimeSpan> list2 = new List<TimeSpan>();
			int[] array = new int[messageLists.Length];
			int num = 0;
			TimeSpan zero = TimeSpan.Zero;
			double num2 = 120.0;
			while (true)
			{
				int num3 = int.MaxValue;
				int num4 = -1;
				for (int i = 0; i < tickLists.Length; i++)
				{
					if (array[i] < tickLists[i].Count)
					{
						int num5 = tickLists[i][array[i]];
						if (num5 < num3)
						{
							num3 = num5;
							num4 = i;
						}
					}
				}
				if (num4 == -1)
				{
					break;
				}
				int num6 = tickLists[num4][array[num4]] - num;
				TimeSpan timeSpanFromSeconds = GetTimeSpanFromSeconds(60.0 / ((double)resolution * num2) * (double)num6);
				num += num6;
				zero += timeSpanFromSeconds;
				Message item = messageLists[num4][array[num4]];
				if (item.Type == MessageType.TempoChange)
				{
					num2 = item.Tempo;
				}
				else
				{
					list.Add(item);
					list2.Add(zero);
				}
				array[num4]++;
			}
			return (list.ToArray(), list2.ToArray());
		}

		private static int ReadTempo(BinaryReader reader)
		{
			if (reader.ReadIntVariableLength() != 3)
			{
				throw new InvalidDataException("Failed to read the tempo value.");
			}
			byte num = reader.ReadByte();
			byte b = reader.ReadByte();
			byte b2 = reader.ReadByte();
			return (num << 16) | (b << 8) | b2;
		}

		private static void DiscardData(BinaryReader reader)
		{
			int num = reader.ReadIntVariableLength();
			reader.BaseStream.Position += num;
		}
	}
	public enum MidiFileLoopType
	{
		None,
		RpgMaker,
		IncredibleMachine,
		FinalFantasy
	}
	public sealed class MidiFileSequencer : IAudioRenderer
	{
		public delegate void MessageHook(Synthesizer synthesizer, int channel, int command, int data1, int data2);

		private readonly Synthesizer synthesizer;

		private float speed;

		private MidiFile? midiFile;

		private bool loop;

		private int blockWrote;

		private TimeSpan currentTime;

		private int msgIndex;

		private int loopIndex;

		private MessageHook? onSendMessage;

		public Synthesizer Synthesizer => synthesizer;

		public MidiFile? MidiFile => midiFile;

		public TimeSpan Position => currentTime;

		public bool EndOfSequence
		{
			get
			{
				if (midiFile == null)
				{
					return true;
				}
				return msgIndex == midiFile.Messages.Length;
			}
		}

		public float Speed
		{
			get
			{
				return speed;
			}
			set
			{
				if (value >= 0f)
				{
					speed = value;
					return;
				}
				throw new ArgumentOutOfRangeException("The playback speed must be a non-negative value.");
			}
		}

		public MessageHook? OnSendMessage
		{
			get
			{
				return onSendMessage;
			}
			set
			{
				onSendMessage = value;
			}
		}

		public MidiFileSequencer(Synthesizer synthesizer)
		{
			if (synthesizer == null)
			{
				throw new ArgumentNullException("synthesizer");
			}
			this.synthesizer = synthesizer;
			speed = 1f;
		}

		public void Play(MidiFile midiFile, bool loop)
		{
			if (midiFile == null)
			{
				throw new ArgumentNullException("midiFile");
			}
			this.midiFile = midiFile;
			this.loop = loop;
			blockWrote = synthesizer.BlockSize;
			currentTime = TimeSpan.Zero;
			msgIndex = 0;
			loopIndex = 0;
			synthesizer.Reset();
		}

		public void Stop()
		{
			midiFile = null;
			synthesizer.Reset();
		}

		public void Render(Span<float> left, Span<float> right)
		{
			if (left.Length != right.Length)
			{
				throw new ArgumentException("The output buffers for the left and right must be the same length.");
			}
			int num;
			for (int i = 0; i < left.Length; i += num)
			{
				if (blockWrote == synthesizer.BlockSize)
				{
					ProcessEvents();
					blockWrote = 0;
					currentTime += MeltySynth.MidiFile.GetTimeSpanFromSeconds((double)speed * (double)synthesizer.BlockSize / (double)synthesizer.SampleRate);
				}
				int val = synthesizer.BlockSize - blockWrote;
				int val2 = left.Length - i;
				num = Math.Min(val, val2);
				synthesizer.Render(left.Slice(i, num), right.Slice(i, num));
				blockWrote += num;
			}
		}

		private void ProcessEvents()
		{
			if (midiFile == null)
			{
				return;
			}
			while (msgIndex < midiFile.Messages.Length)
			{
				TimeSpan timeSpan = midiFile.Times[msgIndex];
				MidiFile.Message message = midiFile.Messages[msgIndex];
				if (!(timeSpan <= currentTime))
				{
					break;
				}
				if (message.Type == MeltySynth.MidiFile.MessageType.Normal)
				{
					if (onSendMessage == null)
					{
						synthesizer.ProcessMidiMessage(message.Channel, message.Command, message.Data1, message.Data2);
					}
					else
					{
						onSendMessage(synthesizer, message.Channel, message.Command, message.Data1, message.Data2);
					}
				}
				else if (loop)
				{
					if (message.Type == MeltySynth.MidiFile.MessageType.LoopStart)
					{
						loopIndex = msgIndex;
					}
					else if (message.Type == MeltySynth.MidiFile.MessageType.LoopEnd)
					{
						currentTime = midiFile.Times[loopIndex];
						msgIndex = loopIndex;
						synthesizer.NoteOffAll(immediate: false);
					}
				}
				msgIndex++;
			}
			if (msgIndex == midiFile.Messages.Length && loop)
			{
				currentTime = midiFile.Times[loopIndex];
				msgIndex = loopIndex;
				synthesizer.NoteOffAll(immediate: false);
			}
		}
	}
	internal sealed class ModulationEnvelope
	{
		private enum Stage
		{
			Delay,
			Attack,
			Hold,
			Decay,
			Release
		}

		private readonly Synthesizer synthesizer;

		private double attackSlope;

		private double decaySlope;

		private double releaseSlope;

		private double attackStartTime;

		private double holdStartTime;

		private double decayStartTime;

		private double decayEndTime;

		private double releaseEndTime;

		private float sustainLevel;

		private float releaseLevel;

		private int processedSampleCount;

		private Stage stage;

		private float value;

		public float Value => value;

		internal ModulationEnvelope(Synthesizer synthesizer)
		{
			this.synthesizer = synthesizer;
		}

		public void Start(float delay, float attack, float hold, float decay, float sustain, float release)
		{
			attackSlope = 1f / attack;
			decaySlope = 1f / decay;
			releaseSlope = 1f / release;
			attackStartTime = delay;
			holdStartTime = attackStartTime + (double)attack;
			decayStartTime = holdStartTime + (double)hold;
			decayEndTime = decayStartTime + (double)decay;
			releaseEndTime = release;
			sustainLevel = Math.Clamp(sustain, 0f, 1f);
			releaseLevel = 0f;
			processedSampleCount = 0;
			stage = Stage.Delay;
			value = 0f;
			Process(0);
		}

		public void Release()
		{
			stage = Stage.Release;
			releaseEndTime += (double)processedSampleCount / (double)synthesizer.SampleRate;
			releaseLevel = value;
		}

		public bool Process()
		{
			return Process(synthesizer.BlockSize);
		}

		private bool Process(int sampleCount)
		{
			processedSampleCount += sampleCount;
			double num = (double)processedSampleCount / (double)synthesizer.SampleRate;
			while (stage <= Stage.Hold && !(num < stage switch
			{
				Stage.Delay => attackStartTime, 
				Stage.Attack => holdStartTime, 
				Stage.Hold => decayStartTime, 
				_ => throw new InvalidOperationException("Invalid envelope stage."), 
			}))
			{
				stage++;
			}
			switch (stage)
			{
			case Stage.Delay:
				value = 0f;
				return true;
			case Stage.Attack:
				value = (float)(attackSlope * (num - attackStartTime));
				return true;
			case Stage.Hold:
				value = 1f;
				return true;
			case Stage.Decay:
				value = Math.Max((float)(decaySlope * (decayEndTime - num)), sustainLevel);
				return value > SoundFontMath.NonAudible;
			case Stage.Release:
				value = Math.Max((float)((double)releaseLevel * releaseSlope * (releaseEndTime - num)), 0f);
				return value > SoundFontMath.NonAudible;
			default:
				throw new InvalidOperationException("Invalid envelope stage.");
			}
		}
	}
	internal static class Modulator
	{
		internal static void DiscardData(BinaryReader reader, int size)
		{
			if (size % 10 != 0)
			{
				throw new InvalidDataException("The modulator list is invalid.");
			}
			reader.BaseStream.Position += size;
		}
	}
	internal sealed class Oscillator
	{
		private const int fracBits = 24;

		private const long fracUnit = 16777216L;

		private const float fpToSample = 1.8189894E-12f;

		private readonly Synthesizer synthesizer;

		private short[]? data;

		private LoopMode loopMode;

		private int sampleRate;

		private int start;

		private int end;

		private int startLoop;

		private int endLoop;

		private int rootKey;

		private float tune;

		private float pitchChangeScale;

		private float sampleRateRatio;

		private bool looping;

		private long position_fp;

		internal Oscillator(Synthesizer synthesizer)
		{
			this.synthesizer = synthesizer;
		}

		public void Start(short[] data, LoopMode loopMode, int sampleRate, int start, int end, int startLoop, int endLoop, int rootKey, int coarseTune, int fineTune, int scaleTuning)
		{
			this.data = data;
			this.loopMode = loopMode;
			this.sampleRate = sampleRate;
			this.start = start;
			this.end = end;
			this.startLoop = startLoop;
			this.endLoop = endLoop;
			this.rootKey = rootKey;
			tune = (float)coarseTune + 0.01f * (float)fineTune;
			pitchChangeScale = 0.01f * (float)scaleTuning;
			sampleRateRatio = (float)sampleRate / (float)synthesizer.SampleRate;
			if (loopMode == LoopMode.NoLoop)
			{
				looping = false;
			}
			else
			{
				looping = true;
			}
			position_fp = (long)start << 24;
		}

		public void Release()
		{
			if (loopMode == LoopMode.LoopUntilNoteOff)
			{
				looping = false;
			}
		}

		public bool Process(float[] block, float pitch)
		{
			float num = pitchChangeScale * (pitch - (float)rootKey) + tune;
			float num2 = sampleRateRatio * MathF.Pow(2f, num / 12f);
			return FillBlock(block, num2);
		}

		internal bool FillBlock(float[] block, double pitchRatio)
		{
			long pitchRatio_fp = (long)(16777216.0 * pitchRatio);
			if (looping)
			{
				return FillBlock_Continuous(block, pitchRatio_fp);
			}
			return FillBlock_NoLoop(block, pitchRatio_fp);
		}

		private bool FillBlock_NoLoop(float[] block, long pitchRatio_fp)
		{
			for (int i = 0; i < block.Length; i++)
			{
				long num = position_fp >> 24;
				if (num >= end)
				{
					if (i > 0)
					{
						Array.Clear(block, i, block.Length - i);
						return true;
					}
					return false;
				}
				short num2 = data[num];
				short num3 = data[num + 1];
				long num4 = position_fp & 0xFFFFFF;
				block[i] = 1.8189894E-12f * (float)(((long)num2 << 24) + num4 * (num3 - num2));
				position_fp += pitchRatio_fp;
			}
			return true;
		}

		private bool FillBlock_Continuous(float[] block, long pitchRatio_fp)
		{
			long num = (long)endLoop << 24;
			long num2 = endLoop - startLoop;
			long num3 = num2 << 24;
			for (int i = 0; i < block.Length; i++)
			{
				if (position_fp >= num)
				{
					position_fp -= num3;
				}
				long num4 = position_fp >> 24;
				long num5 = num4 + 1;
				if (num5 >= endLoop)
				{
					num5 -= num2;
				}
				short num6 = data[num4];
				short num7 = data[num5];
				long num8 = position_fp & 0xFFFFFF;
				block[i] = 1.8189894E-12f * (float)(((long)num6 << 24) + num8 * (num7 - num6));
				position_fp += pitchRatio_fp;
			}
			return true;
		}
	}
	public sealed class Preset
	{
		internal static readonly Preset Default = new Preset();

		private readonly string name;

		private readonly int patchNumber;

		private readonly int bankNumber;

		private readonly int library;

		private readonly int genre;

		private readonly int morphology;

		private readonly PresetRegion[] regions;

		public string Name => name;

		public int PatchNumber => patchNumber;

		public int BankNumber => bankNumber;

		public IReadOnlyList<PresetRegion> Regions => regions;

		internal PresetRegion[] RegionArray => regions;

		private Preset()
		{
			name = "Default";
			regions = Array.Empty<PresetRegion>();
		}

		private Preset(PresetInfo info, Zone[] zones, Instrument[] instruments)
		{
			name = info.Name;
			patchNumber = info.PatchNumber;
			bankNumber = info.BankNumber;
			library = info.Library;
			genre = info.Genre;
			morphology = info.Morphology;
			int num = info.ZoneEndIndex - info.ZoneStartIndex + 1;
			if (num <= 0)
			{
				throw new InvalidDataException("The preset '" + info.Name + "' has no zone.");
			}
			Span<Zone> zones2 = zones.AsSpan(info.ZoneStartIndex, num);
			regions = PresetRegion.Create(this, zones2, instruments);
		}

		internal static Preset[] Create(PresetInfo[] infos, Zone[] zones, Instrument[] instruments)
		{
			if (infos.Length <= 1)
			{
				throw new InvalidDataException("No valid preset was found.");
			}
			Preset[] array = new Preset[infos.Length - 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Preset(infos[i], zones, instruments);
			}
			return array;
		}

		public override string ToString()
		{
			return name;
		}
	}
	internal sealed class PresetInfo
	{
		private string name;

		private int patchNumber;

		private int bankNumber;

		private int zoneStartIndex;

		private int zoneEndIndex;

		private int library;

		private int genre;

		private int morphology;

		public string Name => name;

		public int PatchNumber => patchNumber;

		public int BankNumber => bankNumber;

		public int ZoneStartIndex => zoneStartIndex;

		public int ZoneEndIndex => zoneEndIndex;

		public int Library => library;

		public int Genre => genre;

		public int Morphology => morphology;

		private PresetInfo(BinaryReader reader)
		{
			name = reader.ReadFixedLengthString(20);
			patchNumber = reader.ReadUInt16();
			bankNumber = reader.ReadUInt16();
			zoneStartIndex = reader.ReadUInt16();
			library = reader.ReadInt32();
			genre = reader.ReadInt32();
			morphology = reader.ReadInt32();
		}

		internal static PresetInfo[] ReadFromChunk(BinaryReader reader, int size)
		{
			if (size == 0 || size % 38 != 0)
			{
				throw new InvalidDataException("The preset list is invalid.");
			}
			int num = size / 38;
			PresetInfo[] array = new PresetInfo[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = new PresetInfo(reader);
			}
			for (int j = 0; j < num - 1; j++)
			{
				array[j].zoneEndIndex = array[j + 1].zoneStartIndex - 1;
			}
			return array;
		}
	}
	public sealed class PresetRegion
	{
		internal static readonly PresetRegion Default = new PresetRegion();

		private readonly short[] gs;

		private readonly Instrument instrument;

		internal short this[GeneratorType generatortType] => gs[(uint)generatortType];

		public Instrument Instrument => instrument;

		public int ModulationLfoToPitch => this[GeneratorType.ModulationLfoToPitch];

		public int VibratoLfoToPitch => this[GeneratorType.VibratoLfoToPitch];

		public int ModulationEnvelopeToPitch => this[GeneratorType.ModulationEnvelopeToPitch];

		public float InitialFilterCutoffFrequency => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.InitialFilterCutoffFrequency]);

		public float InitialFilterQ => 0.1f * (float)this[GeneratorType.InitialFilterQ];

		public int ModulationLfoToFilterCutoffFrequency => this[GeneratorType.ModulationLfoToFilterCutoffFrequency];

		public int ModulationEnvelopeToFilterCutoffFrequency => this[GeneratorType.ModulationEnvelopeToFilterCutoffFrequency];

		public float ModulationLfoToVolume => 0.1f * (float)this[GeneratorType.ModulationLfoToVolume];

		public float ChorusEffectsSend => 0.1f * (float)this[GeneratorType.ChorusEffectsSend];

		public float ReverbEffectsSend => 0.1f * (float)this[GeneratorType.ReverbEffectsSend];

		public float Pan => 0.1f * (float)this[GeneratorType.Pan];

		public float DelayModulationLfo => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.DelayModulationLfo]);

		public float FrequencyModulationLfo => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.FrequencyModulationLfo]);

		public float DelayVibratoLfo => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.DelayVibratoLfo]);

		public float FrequencyVibratoLfo => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.FrequencyVibratoLfo]);

		public float DelayModulationEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.DelayModulationEnvelope]);

		public float AttackModulationEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.AttackModulationEnvelope]);

		public float HoldModulationEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.HoldModulationEnvelope]);

		public float DecayModulationEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.DecayModulationEnvelope]);

		public float SustainModulationEnvelope => 0.1f * (float)this[GeneratorType.SustainModulationEnvelope];

		public float ReleaseModulationEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.ReleaseModulationEnvelope]);

		public int KeyNumberToModulationEnvelopeHold => this[GeneratorType.KeyNumberToModulationEnvelopeHold];

		public int KeyNumberToModulationEnvelopeDecay => this[GeneratorType.KeyNumberToModulationEnvelopeDecay];

		public float DelayVolumeEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.DelayVolumeEnvelope]);

		public float AttackVolumeEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.AttackVolumeEnvelope]);

		public float HoldVolumeEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.HoldVolumeEnvelope]);

		public float DecayVolumeEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.DecayVolumeEnvelope]);

		public float SustainVolumeEnvelope => 0.1f * (float)this[GeneratorType.SustainVolumeEnvelope];

		public float ReleaseVolumeEnvelope => SoundFontMath.CentsToMultiplyingFactor(this[GeneratorType.ReleaseVolumeEnvelope]);

		public int KeyNumberToVolumeEnvelopeHold => this[GeneratorType.KeyNumberToVolumeEnvelopeHold];

		public int KeyNumberToVolumeEnvelopeDecay => this[GeneratorType.KeyNumberToVolumeEnvelopeDecay];

		public int KeyRangeStart => this[GeneratorType.KeyRange] & 0xFF;

		public int KeyRangeEnd => (this[GeneratorType.KeyRange] >> 8) & 0xFF;

		public int VelocityRangeStart => this[GeneratorType.VelocityRange] & 0xFF;

		public int VelocityRangeEnd => (this[GeneratorType.VelocityRange] >> 8) & 0xFF;

		public float InitialAttenuation => 0.1f * (float)this[GeneratorType.InitialAttenuation];

		public int CoarseTune => this[GeneratorType.CoarseTune];

		public int FineTune => this[GeneratorType.FineTune];

		public int ScaleTuning => this[GeneratorType.ScaleTuning];

		private PresetRegion()
		{
			gs = new short[61];
			gs[43] = 32512;
			gs[44] = 32512;
			instrument = Instrument.Default;
		}

		private PresetRegion(Preset preset, Zone global, Zone local, Instrument[] instruments)
			: this()
		{
			foreach (Generator generator in global.Generators)
			{
				SetParameter(generator);
			}
			foreach (Generator generator2 in local.Generators)
			{
				SetParameter(generator2);
			}
			short num = gs[41];
			if (0 > num || num >= instruments.Length)
			{
				throw new InvalidDataException($"The preset '{preset.Name}' contains an invalid instrument ID '{num}'.");
			}
			instrument = instruments[num];
		}

		internal static PresetRegion[] Create(Preset preset, Span<Zone> zones, Instrument[] instruments)
		{
			if (zones[0].Generators.Count == 0 || zones[0].Generators.Last().Type != GeneratorType.Instrument)
			{
				Zone global = zones[0];
				PresetRegion[] array = new PresetRegion[zones.Length - 1];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = new PresetRegion(preset, global, zones[i + 1], instruments);
				}
				return array;
			}
			PresetRegion[] array2 = new PresetRegion[zones.Length];
			for (int j = 0; j < array2.Length; j++)
			{
				array2[j] = new PresetRegion(preset, Zone.Empty, zones[j], instruments);
			}
			return array2;
		}

		private void SetParameter(Generator generator)
		{
			int type = (int)generator.Type;
			if (0 <= type && type < gs.Length)
			{
				gs[type] = (short)generator.Value;
			}
		}

		public bool Contains(int key, int velocity)
		{
			bool num = KeyRangeStart <= k