Decompiled source of CrowdControl TCGCardShopSimulator v1.2.4

BepInEx/plugins/ConfigurationManager/ConfigurationManager.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ConfigurationManager.Utilities;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("BepInEx.ConfigurationManager")]
[assembly: AssemblyTitle("BepInEx.ConfigurationManager")]
[assembly: AssemblyDescription("Universal in-game configuration manager for BepInEx plugins")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://github.com/BepInEx/BepInEx.ConfigurationManager")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("18.3.0.0")]
namespace ConfigurationManager
{
	internal static class SettingSearcher
	{
		private static readonly ICollection<string> _updateMethodNames = new string[4] { "Update", "FixedUpdate", "LateUpdate", "OnGUI" };

		public static BaseUnityPlugin[] FindPlugins()
		{
			return (from x in Chainloader.PluginInfos.Values
				select x.Instance into plugin
				where (Object)(object)plugin != (Object)null
				select plugin).Union(Object.FindObjectsOfType(typeof(BaseUnityPlugin)).Cast<BaseUnityPlugin>()).ToArray();
		}

		public static void CollectSettings(out IEnumerable<SettingEntryBase> results, out List<string> modsWithoutSettings, bool showDebug)
		{
			modsWithoutSettings = new List<string>();
			try
			{
				results = GetBepInExCoreConfig();
			}
			catch (Exception ex)
			{
				results = Enumerable.Empty<SettingEntryBase>();
				ConfigurationManager.Logger.LogError((object)ex);
			}
			BaseUnityPlugin[] array = FindPlugins();
			foreach (BaseUnityPlugin val in array)
			{
				Type type = ((object)val).GetType();
				BepInPlugin metadata = val.Info.Metadata;
				if (type.GetCustomAttributes(typeof(BrowsableAttribute), inherit: false).Cast<BrowsableAttribute>().Any((BrowsableAttribute x) => !x.Browsable))
				{
					modsWithoutSettings.Add(metadata.Name);
					continue;
				}
				List<SettingEntryBase> list = new List<SettingEntryBase>();
				list.AddRange(GetPluginConfig(val).Cast<SettingEntryBase>());
				list.RemoveAll((SettingEntryBase x) => x.Browsable == false);
				if (list.Count == 0)
				{
					modsWithoutSettings.Add(metadata.Name);
				}
				if (showDebug && type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any((MethodInfo x) => _updateMethodNames.Contains(x.Name)))
				{
					PropertySettingEntry propertySettingEntry = new PropertySettingEntry(val, type.GetProperty("enabled"), val);
					propertySettingEntry.DispName = "!Allow plugin to run on every frame";
					propertySettingEntry.Description = "Disabling this will disable some or all of the plugin's functionality.\nHooks and event-based functionality will not be disabled.\nThis setting will be lost after game restart.";
					propertySettingEntry.IsAdvanced = true;
					list.Add(propertySettingEntry);
				}
				if (list.Count > 0)
				{
					results = results.Concat(list);
				}
			}
		}

		private static IEnumerable<SettingEntryBase> GetBepInExCoreConfig()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			PropertyInfo property = typeof(ConfigFile).GetProperty("CoreConfig", BindingFlags.Static | BindingFlags.NonPublic);
			if ((object)property == null)
			{
				throw new ArgumentNullException("coreConfigProp");
			}
			ConfigFile source = (ConfigFile)property.GetValue(null, null);
			BepInPlugin bepinMeta = new BepInPlugin("BepInEx", "BepInEx", typeof(Chainloader).Assembly.GetName().Version.ToString());
			return ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)source).Select((Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, SettingEntryBase>)((KeyValuePair<ConfigDefinition, ConfigEntryBase> kvp) => new ConfigSettingEntry(kvp.Value, null)
			{
				IsAdvanced = true,
				PluginInfo = bepinMeta
			}));
		}

		private static IEnumerable<ConfigSettingEntry> GetPluginConfig(BaseUnityPlugin plugin)
		{
			return ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)plugin.Config).Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> kvp) => new ConfigSettingEntry(kvp.Value, plugin));
		}
	}
	internal sealed class ConfigSettingEntry : SettingEntryBase
	{
		public ConfigEntryBase Entry { get; }

		public override Type SettingType => Entry.SettingType;

		public ConfigSettingEntry(ConfigEntryBase entry, BaseUnityPlugin owner)
		{
			Entry = entry;
			DispName = entry.Definition.Key;
			base.Category = entry.Definition.Section;
			ConfigDescription description = entry.Description;
			base.Description = ((description != null) ? description.Description : null);
			TypeConverter converter = TomlTypeConverter.GetConverter(entry.SettingType);
			if (converter != null)
			{
				base.ObjToStr = (object o) => converter.ConvertToString(o, entry.SettingType);
				base.StrToObj = (string s) => converter.ConvertToObject(s, entry.SettingType);
			}
			ConfigDescription description2 = entry.Description;
			AcceptableValueBase val = ((description2 != null) ? description2.AcceptableValues : null);
			if (val != null)
			{
				GetAcceptableValues(val);
			}
			base.DefaultValue = entry.DefaultValue;
			ConfigDescription description3 = entry.Description;
			SetFromAttributes((description3 != null) ? description3.Tags : null, owner);
		}

		private void GetAcceptableValues(AcceptableValueBase values)
		{
			Type type = ((object)values).GetType();
			PropertyInfo property = type.GetProperty("AcceptableValues", BindingFlags.Instance | BindingFlags.Public);
			if ((object)property != null)
			{
				base.AcceptableValues = ((IEnumerable)property.GetValue(values, null)).Cast<object>().ToArray();
				return;
			}
			PropertyInfo property2 = type.GetProperty("MinValue", BindingFlags.Instance | BindingFlags.Public);
			PropertyInfo property3 = type.GetProperty("MaxValue", BindingFlags.Instance | BindingFlags.Public);
			if ((object)property2 != null && (object)property3 != null)
			{
				base.AcceptableValueRange = new KeyValuePair<object, object>(property2.GetValue(values, null), property3.GetValue(values, null));
				base.ShowRangeAsPercent = ((base.AcceptableValueRange.Key.Equals(0) || base.AcceptableValueRange.Key.Equals(1)) && base.AcceptableValueRange.Value.Equals(100)) || (base.AcceptableValueRange.Key.Equals(0f) && base.AcceptableValueRange.Value.Equals(1f));
			}
		}

		public override object Get()
		{
			return Entry.BoxedValue;
		}

		protected override void SetValue(object newVal)
		{
			Entry.BoxedValue = newVal;
		}
	}
	[BepInPlugin("com.bepis.bepinex.configurationmanager", "Configuration Manager", "18.3")]
	[Browsable(false)]
	public class ConfigurationManager : BaseUnityPlugin
	{
		private sealed class PluginSettingsData
		{
			public sealed class PluginSettingsGroupData
			{
				public string Name;

				public List<SettingEntryBase> Settings;
			}

			public BepInPlugin Info;

			public List<PluginSettingsGroupData> Categories;

			public int Height;

			public string Website;

			private bool _collapsed;

			public bool Collapsed
			{
				get
				{
					return _collapsed;
				}
				set
				{
					_collapsed = value;
					Height = 0;
				}
			}
		}

		public const string GUID = "com.bepis.bepinex.configurationmanager";

		public const string Version = "18.3";

		internal static ManualLogSource Logger;

		private static SettingFieldDrawer _fieldDrawer;

		private static readonly Color _advancedSettingColor = new Color(1f, 0.95f, 0.67f, 1f);

		private const int WindowId = -68;

		private const string SearchBoxName = "searchBox";

		private bool _focusSearchBox;

		private string _searchString = string.Empty;

		public bool OverrideHotkey;

		private bool _displayingWindow;

		private bool _obsoleteCursor;

		private string _modsWithoutSettings;

		private List<SettingEntryBase> _allSettings;

		private List<PluginSettingsData> _filteredSetings = new List<PluginSettingsData>();

		private bool _windowWasMoved;

		private bool _tipsPluginHeaderWasClicked;

		private bool _tipsWindowWasMoved;

		private Rect _screenRect;

		private Vector2 _settingWindowScrollPos;

		private int _tipsHeight;

		private PropertyInfo _curLockState;

		private PropertyInfo _curVisible;

		private int _previousCursorLockState;

		private bool _previousCursorVisible;

		private readonly ConfigEntry<bool> _showAdvanced;

		private readonly ConfigEntry<bool> _showKeybinds;

		private readonly ConfigEntry<bool> _showSettings;

		private readonly ConfigEntry<KeyboardShortcut> _keybind;

		private readonly ConfigEntry<bool> _hideSingleSection;

		private readonly ConfigEntry<bool> _pluginConfigCollapsedDefault;

		private bool _showDebug;

		internal Rect SettingWindowRect { get; private set; }

		public bool IsWindowFullscreen
		{
			get
			{
				if (DisplayingWindow)
				{
					return !_windowWasMoved;
				}
				return false;
			}
		}

		internal int LeftColumnWidth { get; private set; }

		internal int RightColumnWidth { get; private set; }

		public bool DisplayingWindow
		{
			get
			{
				return _displayingWindow;
			}
			set
			{
				if (_displayingWindow == value)
				{
					return;
				}
				_displayingWindow = value;
				SettingFieldDrawer.ClearCache();
				if (_displayingWindow)
				{
					CalculateWindowRect();
					BuildSettingList();
					_focusSearchBox = true;
					if ((object)_curLockState != null)
					{
						_previousCursorLockState = (_obsoleteCursor ? Convert.ToInt32((bool)_curLockState.GetValue(null, null)) : ((int)_curLockState.GetValue(null, null)));
						_previousCursorVisible = (bool)_curVisible.GetValue(null, null);
					}
				}
				else if (!_previousCursorVisible || _previousCursorLockState != 0)
				{
					SetUnlockCursor(_previousCursorLockState, _previousCursorVisible);
				}
				this.DisplayingWindowChanged?.Invoke(this, new ValueChangedEventArgs<bool>(value));
			}
		}

		public string SearchString
		{
			get
			{
				return _searchString;
			}
			private set
			{
				if (value == null)
				{
					value = string.Empty;
				}
				if (!(_searchString == value))
				{
					_searchString = value;
					BuildFilteredSettingList();
				}
			}
		}

		public event EventHandler<ValueChangedEventArgs<bool>> DisplayingWindowChanged;

		public ConfigurationManager()
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Expected O, but got Unknown
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			_fieldDrawer = new SettingFieldDrawer(this);
			_showAdvanced = ((BaseUnityPlugin)this).Config.Bind<bool>("Filtering", "Show advanced", false, (ConfigDescription)null);
			_showKeybinds = ((BaseUnityPlugin)this).Config.Bind<bool>("Filtering", "Show keybinds", true, (ConfigDescription)null);
			_showSettings = ((BaseUnityPlugin)this).Config.Bind<bool>("Filtering", "Show settings", true, (ConfigDescription)null);
			_keybind = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "Show config manager", new KeyboardShortcut((KeyCode)282, (KeyCode[])(object)new KeyCode[0]), new ConfigDescription("The shortcut used to toggle the config manager window on and off.\nThe key can be overridden by a game-specific plugin if necessary, in that case this setting is ignored.", (AcceptableValueBase)null, new object[0]));
			_hideSingleSection = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Hide single sections", false, new ConfigDescription("Show section title for plugins with only one section", (AcceptableValueBase)null, new object[0]));
			_pluginConfigCollapsedDefault = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Plugin collapsed default", true, new ConfigDescription("If set to true plugins will be collapsed when opening the configuration manager window", (AcceptableValueBase)null, new object[0]));
		}

		public static void RegisterCustomSettingDrawer(Type settingType, Action<SettingEntryBase> onGuiDrawer)
		{
			if ((object)settingType == null)
			{
				throw new ArgumentNullException("settingType");
			}
			if (onGuiDrawer == null)
			{
				throw new ArgumentNullException("onGuiDrawer");
			}
			if (SettingFieldDrawer.SettingDrawHandlers.ContainsKey(settingType))
			{
				Logger.LogWarning((object)("Tried to add a setting drawer for type " + settingType.FullName + " while one already exists."));
			}
			else
			{
				SettingFieldDrawer.SettingDrawHandlers[settingType] = onGuiDrawer;
			}
		}

		public void BuildSettingList()
		{
			SettingSearcher.CollectSettings(out var results, out var modsWithoutSettings, _showDebug);
			_modsWithoutSettings = string.Join(", ", (from x in modsWithoutSettings
				select x.TrimStart(new char[1] { '!' }) into x
				orderby x
				select x).ToArray());
			_allSettings = results.ToList();
			BuildFilteredSettingList();
		}

		private void BuildFilteredSettingList()
		{
			IEnumerable<SettingEntryBase> source = _allSettings;
			string[] searchStrings = SearchString.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			if (searchStrings.Length != 0)
			{
				source = source.Where((SettingEntryBase x) => ContainsSearchString(x, searchStrings));
			}
			else
			{
				if (!_showAdvanced.Value)
				{
					source = source.Where((SettingEntryBase x) => x.IsAdvanced != true);
				}
				if (!_showKeybinds.Value)
				{
					source = source.Where((SettingEntryBase x) => !IsKeyboardShortcut(x));
				}
				if (!_showSettings.Value)
				{
					source = source.Where((SettingEntryBase x) => x.IsAdvanced == true || IsKeyboardShortcut(x));
				}
			}
			bool settingsAreCollapsed = _pluginConfigCollapsedDefault.Value;
			HashSet<string> nonDefaultCollpasingStateByPluginName = new HashSet<string>();
			foreach (PluginSettingsData filteredSeting in _filteredSetings)
			{
				if (filteredSeting.Collapsed != settingsAreCollapsed)
				{
					nonDefaultCollpasingStateByPluginName.Add(filteredSeting.Info.Name);
				}
			}
			_filteredSetings = (from x in (from x in source
					group x by x.PluginInfo).Select(delegate(IGrouping<BepInPlugin, SettingEntryBase> pluginSettings)
				{
					IEnumerable<PluginSettingsData.PluginSettingsGroupData> source2 = from eb in pluginSettings
						group eb by eb.Category into x
						orderby string.Equals(x.Key, "Keyboard shortcuts", StringComparison.Ordinal), x.Key
						select new PluginSettingsData.PluginSettingsGroupData
						{
							Name = x.Key,
							Settings = (from set in x
								orderby set.Order descending, set.DispName
								select set).ToList()
						};
					string website = Utils.GetWebsite(pluginSettings.First().PluginInstance);
					return new PluginSettingsData
					{
						Info = pluginSettings.Key,
						Categories = source2.ToList(),
						Collapsed = (nonDefaultCollpasingStateByPluginName.Contains(pluginSettings.Key.Name) ? (!settingsAreCollapsed) : settingsAreCollapsed),
						Website = website
					};
				})
				orderby x.Info.Name
				select x).ToList();
		}

		private static bool IsKeyboardShortcut(SettingEntryBase x)
		{
			if ((object)x.SettingType != typeof(KeyboardShortcut))
			{
				return (object)x.SettingType == typeof(KeyCode);
			}
			return true;
		}

		private static bool ContainsSearchString(SettingEntryBase setting, string[] searchStrings)
		{
			string combinedSearchTarget = setting.PluginInfo.Name + "\n" + setting.PluginInfo.GUID + "\n" + setting.DispName + "\n" + setting.Category + "\n" + setting.Description + "\n" + setting.DefaultValue?.ToString() + "\n" + setting.Get();
			return searchStrings.All((string s) => combinedSearchTarget.IndexOf(s, StringComparison.InvariantCultureIgnoreCase) >= 0);
		}

		private void CalculateWindowRect()
		{
			//IL_005d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.Min(Screen.width, 650);
			int num2 = ((Screen.height < 560) ? Screen.height : (Screen.height - 100));
			int num3 = Mathf.RoundToInt((float)(Screen.width - num) / 2f);
			int num4 = Mathf.RoundToInt((float)(Screen.height - num2) / 2f);
			SettingWindowRect = new Rect((float)num3, (float)num4, (float)num, (float)num2);
			_screenRect = new Rect(0f, 0f, (float)Screen.width, (float)Screen.height);
			Rect settingWindowRect = SettingWindowRect;
			LeftColumnWidth = Mathf.RoundToInt(((Rect)(ref settingWindowRect)).width / 2.5f);
			settingWindowRect = SettingWindowRect;
			RightColumnWidth = (int)((Rect)(ref settingWindowRect)).width - LeftColumnWidth - 115;
			_windowWasMoved = false;
		}

		private void OnGUI()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: 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_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_0061: 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_00d6: 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)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			if (!DisplayingWindow)
			{
				return;
			}
			SetUnlockCursor(0, cursorVisible: true);
			Vector2 val = Vector2.op_Implicit(UnityInput.Current.mousePosition);
			val.y = (float)Screen.height - val.y;
			Rect settingWindowRect;
			if (!_windowWasMoved)
			{
				if (GUI.Button(_screenRect, string.Empty, GUI.skin.box))
				{
					settingWindowRect = SettingWindowRect;
					if (!((Rect)(ref settingWindowRect)).Contains(val))
					{
						DisplayingWindow = false;
					}
				}
				ImguiUtils.DrawWindowBackground(SettingWindowRect);
			}
			Rect val2 = GUILayout.Window(-68, SettingWindowRect, new WindowFunction(SettingsWindow), "Plugin / mod settings", (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (val2 != SettingWindowRect)
			{
				_windowWasMoved = true;
				SettingWindowRect = val2;
				_tipsWindowWasMoved = true;
			}
			if (SettingFieldDrawer.SettingKeyboardShortcut)
			{
				return;
			}
			if (_windowWasMoved)
			{
				settingWindowRect = SettingWindowRect;
				if (!((Rect)(ref settingWindowRect)).Contains(val))
				{
					return;
				}
			}
			Input.ResetInputAxes();
		}

		private static void DrawTooltip(Rect area)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			string tooltip = GUI.tooltip;
			if (!string.IsNullOrEmpty(tooltip))
			{
				GUIStyle val = GUI.skin.box.CreateCopy();
				val.wordWrap = true;
				val.alignment = (TextAnchor)4;
				GUIContent val2 = new GUIContent(tooltip);
				float num = val.CalcHeight(val2, 400f) + 10f;
				Vector2 mousePosition = Event.current.mousePosition;
				float num2 = ((mousePosition.x + 400f > ((Rect)(ref area)).width) ? (((Rect)(ref area)).width - 400f) : mousePosition.x);
				float num3 = ((mousePosition.y + 25f + num > ((Rect)(ref area)).height) ? (mousePosition.y - num) : (mousePosition.y + 25f));
				Rect val3 = default(Rect);
				((Rect)(ref val3))..ctor(num2, num3, 400f, num);
				ImguiUtils.DrawContolBackground(val3, Color.black);
				val.Draw(val3, val2, -1);
			}
		}

		private void SettingsWindow(int id)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Invalid comparison between Unknown and I4
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Invalid comparison between Unknown and I4
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_018d: Unknown result type (might be due to invalid IL or missing references)
			DrawWindowHeader();
			_settingWindowScrollPos = GUILayout.BeginScrollView(_settingWindowScrollPos, false, true, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			float y = _settingWindowScrollPos.y;
			Rect val = SettingWindowRect;
			float height = ((Rect)(ref val)).height;
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (string.IsNullOrEmpty(SearchString))
			{
				DrawTips();
				if (_tipsHeight == 0 && (int)Event.current.type == 7)
				{
					val = GUILayoutUtility.GetLastRect();
					_tipsHeight = (int)((Rect)(ref val)).height;
				}
			}
			int num = _tipsHeight;
			foreach (PluginSettingsData filteredSeting in _filteredSetings)
			{
				if (filteredSeting.Height == 0 || ((float)(num + filteredSeting.Height) >= y && (float)num <= y + height))
				{
					try
					{
						DrawSinglePlugin(filteredSeting);
					}
					catch (ArgumentException)
					{
					}
					if (filteredSeting.Height == 0 && (int)Event.current.type == 7)
					{
						val = GUILayoutUtility.GetLastRect();
						filteredSeting.Height = (int)((Rect)(ref val)).height;
					}
				}
				else
				{
					try
					{
						GUILayout.Space((float)filteredSeting.Height);
					}
					catch (ArgumentException)
					{
					}
				}
				num += filteredSeting.Height;
			}
			if (_showDebug)
			{
				GUILayout.Space(10f);
				GUILayout.Label("Plugins with no options available: " + _modsWithoutSettings, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
			else
			{
				GUILayout.Space(70f);
			}
			GUILayout.EndVertical();
			GUILayout.EndScrollView();
			if (!SettingFieldDrawer.DrawCurrentDropdown())
			{
				DrawTooltip(SettingWindowRect);
			}
			GUI.DragWindow();
		}

		private void DrawTips()
		{
			string text = ((!_tipsPluginHeaderWasClicked) ? "Tip: Click plugin names to expand. Click setting and group names to see their descriptions." : ((!_tipsWindowWasMoved) ? "Tip: You can drag this window to move it. It will stay open while you interact with the game." : null));
			if (text != null)
			{
				GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
				GUILayout.Label(text, (GUILayoutOption[])(object)new GUILayoutOption[0]);
				GUILayout.EndHorizontal();
			}
		}

		private void DrawWindowHeader()
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUI.enabled = SearchString == string.Empty;
			bool flag = GUILayout.Toggle(_showSettings.Value, "Normal settings", (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (_showSettings.Value != flag)
			{
				_showSettings.Value = flag;
				BuildFilteredSettingList();
			}
			flag = GUILayout.Toggle(_showKeybinds.Value, "Keyboard shortcuts", (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (_showKeybinds.Value != flag)
			{
				_showKeybinds.Value = flag;
				BuildFilteredSettingList();
			}
			Color color = GUI.color;
			GUI.color = _advancedSettingColor;
			flag = GUILayout.Toggle(_showAdvanced.Value, "Advanced settings", (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (_showAdvanced.Value != flag)
			{
				_showAdvanced.Value = flag;
				BuildFilteredSettingList();
			}
			GUI.color = color;
			GUI.enabled = true;
			GUILayout.Space(8f);
			flag = GUILayout.Toggle(_showDebug, "Debug info", (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (_showDebug != flag)
			{
				_showDebug = flag;
				BuildSettingList();
			}
			if (GUILayout.Button("Open Log", (GUILayoutOption[])(object)new GUILayoutOption[0]))
			{
				try
				{
					Utils.OpenLog();
				}
				catch (SystemException ex)
				{
					Logger.Log((LogLevel)10, (object)ex.Message);
				}
			}
			GUILayout.Space(8f);
			if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[0]))
			{
				DisplayingWindow = false;
			}
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.Label("Search: ", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			GUI.SetNextControlName("searchBox");
			SearchString = GUILayout.TextField(SearchString, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if (_focusSearchBox)
			{
				GUI.FocusWindow(-68);
				GUI.FocusControl("searchBox");
				_focusSearchBox = false;
			}
			if (GUILayout.Button("Clear", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
			{
				SearchString = string.Empty;
			}
			GUILayout.Space(8f);
			if (GUILayout.Button(_pluginConfigCollapsedDefault.Value ? "Expand All" : "Collapse All", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
			{
				bool flag2 = !_pluginConfigCollapsedDefault.Value;
				_pluginConfigCollapsedDefault.Value = flag2;
				foreach (PluginSettingsData filteredSeting in _filteredSetings)
				{
					filteredSeting.Collapsed = flag2;
				}
				_tipsPluginHeaderWasClicked = true;
			}
			GUILayout.EndHorizontal();
		}

		private void DrawSinglePlugin(PluginSettingsData plugin)
		{
			//IL_009a: 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_00a0: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0143: Expected O, but got Unknown
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUIContent content = (_showDebug ? new GUIContent($"{plugin.Info.Name.TrimStart(new char[1] { '!' })} {plugin.Info.Version}", (Texture)null, "GUID: " + plugin.Info.GUID) : new GUIContent($"{plugin.Info.Name.TrimStart(new char[1] { '!' })} {plugin.Info.Version}"));
			bool flag = !string.IsNullOrEmpty(SearchString);
			bool flag2 = plugin.Website != null;
			if (flag2)
			{
				GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
				GUILayout.Space(29f);
			}
			if (SettingFieldDrawer.DrawPluginHeader(content, plugin.Collapsed && !flag) && !flag)
			{
				_tipsPluginHeaderWasClicked = true;
				plugin.Collapsed = !plugin.Collapsed;
			}
			if (flag2)
			{
				Color color = GUI.color;
				GUI.color = Color.gray;
				if (GUILayout.Button(new GUIContent("URL", (Texture)null, plugin.Website), GUI.skin.label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
				{
					Utils.OpenWebsite(plugin.Website);
				}
				GUI.color = color;
				GUILayout.EndHorizontal();
			}
			if (flag || !plugin.Collapsed)
			{
				foreach (PluginSettingsData.PluginSettingsGroupData category in plugin.Categories)
				{
					if (!string.IsNullOrEmpty(category.Name) && (plugin.Categories.Count > 1 || !_hideSingleSection.Value))
					{
						SettingFieldDrawer.DrawCategoryHeader(category.Name);
					}
					foreach (SettingEntryBase setting in category.Settings)
					{
						DrawSingleSetting(setting);
						GUILayout.Space(2f);
					}
				}
			}
			GUILayout.EndVertical();
		}

		private void DrawSingleSetting(SettingEntryBase setting)
		{
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
			try
			{
				DrawSettingName(setting);
				_fieldDrawer.DrawSettingValue(setting);
				DrawDefaultButton(setting);
			}
			catch (Exception arg)
			{
				Logger.Log((LogLevel)2, (object)$"Failed to draw setting {setting.DispName} - {arg}");
				GUILayout.Label("Failed to draw this field, check log for details.", (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
			GUILayout.EndHorizontal();
		}

		private void DrawSettingName(SettingEntryBase setting)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0081: 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)
			if (!setting.HideSettingName)
			{
				Color color = GUI.color;
				if (setting.IsAdvanced == true)
				{
					GUI.color = _advancedSettingColor;
				}
				GUILayout.Label(new GUIContent(setting.DispName.TrimStart(new char[1] { '!' }), (Texture)null, setting.Description), (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.Width((float)LeftColumnWidth),
					GUILayout.MaxWidth((float)LeftColumnWidth)
				});
				GUI.color = color;
			}
		}

		private static void DrawDefaultButton(SettingEntryBase setting)
		{
			if (setting.HideDefaultButton)
			{
				return;
			}
			object defaultValue = setting.DefaultValue;
			if (defaultValue != null || setting.SettingType.IsClass)
			{
				GUILayout.Space(5f);
				if (GUILayout.Button("Reset", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
				{
					setting.Set(defaultValue);
				}
			}
		}

		private void Start()
		{
			Type typeFromHandle = typeof(Cursor);
			_curLockState = typeFromHandle.GetProperty("lockState", BindingFlags.Static | BindingFlags.Public);
			_curVisible = typeFromHandle.GetProperty("visible", BindingFlags.Static | BindingFlags.Public);
			if ((object)_curLockState == null && (object)_curVisible == null)
			{
				_obsoleteCursor = true;
				_curLockState = typeof(Screen).GetProperty("lockCursor", BindingFlags.Static | BindingFlags.Public);
				_curVisible = typeof(Screen).GetProperty("showCursor", BindingFlags.Static | BindingFlags.Public);
			}
			try
			{
				((BaseUnityPlugin)this).Config.Save();
			}
			catch (IOException ex)
			{
				Logger.Log((LogLevel)12, (object)("WARNING: Failed to write to config directory, expect issues!\nError message:" + ex.Message));
			}
			catch (UnauthorizedAccessException ex2)
			{
				Logger.Log((LogLevel)12, (object)("WARNING: Permission denied to write to config directory, expect issues!\nError message:" + ex2.Message));
			}
		}

		private void Update()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (DisplayingWindow)
			{
				SetUnlockCursor(0, cursorVisible: true);
			}
			if (!OverrideHotkey)
			{
				KeyboardShortcut value = _keybind.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					DisplayingWindow = !DisplayingWindow;
				}
			}
		}

		private void LateUpdate()
		{
			if (DisplayingWindow)
			{
				SetUnlockCursor(0, cursorVisible: true);
			}
		}

		private void SetUnlockCursor(int lockState, bool cursorVisible)
		{
			if ((object)_curLockState != null)
			{
				if (_obsoleteCursor)
				{
					_curLockState.SetValue(null, Convert.ToBoolean(lockState), null);
				}
				else
				{
					_curLockState.SetValue(null, lockState, null);
				}
				_curVisible.SetValue(null, cursorVisible, null);
			}
		}
	}
	internal class PropertySettingEntry : SettingEntryBase
	{
		private Type _settingType;

		public object Instance { get; internal set; }

		public PropertyInfo Property { get; internal set; }

		public override string DispName
		{
			get
			{
				if (!string.IsNullOrEmpty(base.DispName))
				{
					return base.DispName;
				}
				return Property.Name;
			}
			protected internal set
			{
				base.DispName = value;
			}
		}

		public override Type SettingType => _settingType ?? (_settingType = Property.PropertyType);

		public PropertySettingEntry(object instance, PropertyInfo settingProp, BaseUnityPlugin pluginInstance)
		{
			SetFromAttributes(settingProp.GetCustomAttributes(inherit: false), pluginInstance);
			if (!base.Browsable.HasValue)
			{
				base.Browsable = settingProp.CanRead && settingProp.CanWrite;
			}
			base.ReadOnly = settingProp.CanWrite;
			Property = settingProp;
			Instance = instance;
		}

		public override object Get()
		{
			return Property.GetValue(Instance, null);
		}

		protected override void SetValue(object newVal)
		{
			Property.SetValue(Instance, newVal, null);
		}
	}
	public abstract class SettingEntryBase
	{
		public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput);

		private static readonly PropertyInfo[] _myProperties = typeof(SettingEntryBase).GetProperties(BindingFlags.Instance | BindingFlags.Public);

		public object[] AcceptableValues { get; protected set; }

		public KeyValuePair<object, object> AcceptableValueRange { get; protected set; }

		public bool? ShowRangeAsPercent { get; protected set; }

		public Action<ConfigEntryBase> CustomDrawer { get; private set; }

		public CustomHotkeyDrawerFunc CustomHotkeyDrawer { get; private set; }

		public bool? Browsable { get; protected set; }

		public string Category { get; protected set; }

		public object DefaultValue { get; protected set; }

		public bool HideDefaultButton { get; protected set; }

		public bool HideSettingName { get; protected set; }

		public string Description { get; protected internal set; }

		public virtual string DispName { get; protected internal set; }

		public BepInPlugin PluginInfo { get; protected internal set; }

		public bool? ReadOnly { get; protected set; }

		public abstract Type SettingType { get; }

		public BaseUnityPlugin PluginInstance { get; private set; }

		public bool? IsAdvanced { get; internal set; }

		public int Order { get; protected set; }

		public Func<object, string> ObjToStr { get; internal set; }

		public Func<string, object> StrToObj { get; internal set; }

		public abstract object Get();

		public void Set(object newVal)
		{
			if (ReadOnly != true)
			{
				SetValue(newVal);
			}
		}

		protected abstract void SetValue(object newVal);

		internal void SetFromAttributes(object[] attribs, BaseUnityPlugin pluginInstance)
		{
			PluginInstance = pluginInstance;
			PluginInfo = ((pluginInstance != null) ? pluginInstance.Info.Metadata : null);
			if (attribs == null || attribs.Length == 0)
			{
				return;
			}
			foreach (object obj in attribs)
			{
				if (obj == null)
				{
					continue;
				}
				if (!(obj is DisplayNameAttribute displayNameAttribute))
				{
					if (!(obj is CategoryAttribute categoryAttribute))
					{
						if (!(obj is DescriptionAttribute descriptionAttribute))
						{
							if (!(obj is DefaultValueAttribute defaultValueAttribute))
							{
								if (!(obj is ReadOnlyAttribute readOnlyAttribute))
								{
									if (!(obj is BrowsableAttribute browsableAttribute))
									{
										Action<SettingEntryBase> action = obj as Action<SettingEntryBase>;
										if (action == null)
										{
											if (obj is string text)
											{
												switch (text)
												{
												case "ReadOnly":
													ReadOnly = true;
													break;
												case "Browsable":
													Browsable = true;
													break;
												case "Unbrowsable":
												case "Hidden":
													Browsable = false;
													break;
												case "Advanced":
													IsAdvanced = true;
													break;
												}
												continue;
											}
											Type type = obj.GetType();
											if (!(type.Name == "ConfigurationManagerAttributes"))
											{
												break;
											}
											FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
											foreach (var item in from my in _myProperties
												join other in fields on my.Name equals other.Name
												select new { my, other })
											{
												try
												{
													object obj2 = item.other.GetValue(obj);
													if (obj2 != null)
													{
														if ((object)item.my.PropertyType != item.other.FieldType && typeof(Delegate).IsAssignableFrom(item.my.PropertyType))
														{
															obj2 = Delegate.CreateDelegate(item.my.PropertyType, ((Delegate)obj2).Target, ((Delegate)obj2).Method);
														}
														item.my.SetValue(this, obj2, null);
													}
												}
												catch (Exception ex)
												{
													ConfigurationManager.Logger.LogWarning((object)("Failed to copy value " + item.my.Name + " from provided tag object " + type.FullName + " - " + ex.Message));
												}
											}
										}
										else
										{
											CustomDrawer = delegate
											{
												action(this);
											};
										}
									}
									else
									{
										Browsable = browsableAttribute.Browsable;
									}
								}
								else
								{
									ReadOnly = readOnlyAttribute.IsReadOnly;
								}
							}
							else
							{
								DefaultValue = defaultValueAttribute.Value;
							}
						}
						else
						{
							Description = descriptionAttribute.Description;
						}
					}
					else
					{
						Category = categoryAttribute.Category;
					}
				}
				else
				{
					DispName = displayNameAttribute.DisplayName;
				}
			}
		}
	}
	internal class SettingFieldDrawer
	{
		private sealed class ColorCacheEntry
		{
			public Color Last;

			public Texture2D Tex;
		}

		private static IEnumerable<KeyCode> _keysToCheck;

		private static readonly Dictionary<SettingEntryBase, ComboBox> _comboBoxCache;

		private static readonly Dictionary<SettingEntryBase, ColorCacheEntry> _colorCache;

		private static ConfigurationManager _instance;

		private static SettingEntryBase _currentKeyboardShortcutToSet;

		private static GUIStyle _categoryHeaderSkin;

		private static GUIStyle _pluginHeaderSkin;

		private readonly Dictionary<Type, bool> _canCovertCache = new Dictionary<Type, bool>();

		private static bool _drawColorHex;

		public static Dictionary<Type, Action<SettingEntryBase>> SettingDrawHandlers { get; }

		public static bool SettingKeyboardShortcut => _currentKeyboardShortcutToSet != null;

		static SettingFieldDrawer()
		{
			_comboBoxCache = new Dictionary<SettingEntryBase, ComboBox>();
			_colorCache = new Dictionary<SettingEntryBase, ColorCacheEntry>();
			SettingDrawHandlers = new Dictionary<Type, Action<SettingEntryBase>>
			{
				{
					typeof(bool),
					DrawBoolField
				},
				{
					typeof(KeyboardShortcut),
					DrawKeyboardShortcut
				},
				{
					typeof(KeyCode),
					DrawKeyCode
				},
				{
					typeof(Color),
					DrawColor
				},
				{
					typeof(Vector2),
					DrawVector2
				},
				{
					typeof(Vector3),
					DrawVector3
				},
				{
					typeof(Vector4),
					DrawVector4
				},
				{
					typeof(Quaternion),
					DrawQuaternion
				}
			};
		}

		public SettingFieldDrawer(ConfigurationManager instance)
		{
			_instance = instance;
		}

		public void DrawSettingValue(SettingEntryBase setting)
		{
			if (setting.CustomDrawer != null)
			{
				setting.CustomDrawer((setting is ConfigSettingEntry configSettingEntry) ? configSettingEntry.Entry : null);
			}
			else if (setting.CustomHotkeyDrawer != null)
			{
				bool isCurrentlyAcceptingInput = _currentKeyboardShortcutToSet == setting;
				bool flag = isCurrentlyAcceptingInput;
				setting.CustomHotkeyDrawer((setting is ConfigSettingEntry configSettingEntry2) ? configSettingEntry2.Entry : null, ref isCurrentlyAcceptingInput);
				if (isCurrentlyAcceptingInput != flag)
				{
					_currentKeyboardShortcutToSet = (isCurrentlyAcceptingInput ? setting : null);
				}
			}
			else if (setting.ShowRangeAsPercent.HasValue && setting.AcceptableValueRange.Key != null)
			{
				DrawRangeField(setting);
			}
			else if (setting.AcceptableValues != null)
			{
				DrawListField(setting);
			}
			else if (!DrawFieldBasedOnValueType(setting))
			{
				if (setting.SettingType.IsEnum)
				{
					DrawEnumField(setting);
				}
				else
				{
					DrawUnknownField(setting, _instance.RightColumnWidth);
				}
			}
		}

		public static void ClearCache()
		{
			_comboBoxCache.Clear();
			foreach (KeyValuePair<SettingEntryBase, ColorCacheEntry> item in _colorCache)
			{
				Object.Destroy((Object)(object)item.Value.Tex);
			}
			_colorCache.Clear();
		}

		public static void DrawCenteredLabel(string text, params GUILayoutOption[] options)
		{
			GUILayout.BeginHorizontal(options);
			GUILayout.FlexibleSpace();
			GUILayout.Label(text, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();
		}

		public static void DrawCategoryHeader(string text)
		{
			if (_categoryHeaderSkin == null)
			{
				_categoryHeaderSkin = GUI.skin.label.CreateCopy();
				_categoryHeaderSkin.alignment = (TextAnchor)1;
				_categoryHeaderSkin.wordWrap = true;
				_categoryHeaderSkin.stretchWidth = true;
				_categoryHeaderSkin.fontSize = 14;
			}
			GUILayout.Label(text, _categoryHeaderSkin, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}

		public static bool DrawPluginHeader(GUIContent content, bool isCollapsed)
		{
			if (_pluginHeaderSkin == null)
			{
				_pluginHeaderSkin = GUI.skin.label.CreateCopy();
				_pluginHeaderSkin.alignment = (TextAnchor)1;
				_pluginHeaderSkin.wordWrap = true;
				_pluginHeaderSkin.stretchWidth = true;
				_pluginHeaderSkin.fontSize = 15;
			}
			if (isCollapsed)
			{
				content.text += "\n...";
			}
			return GUILayout.Button(content, _pluginHeaderSkin, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
		}

		public static bool DrawCurrentDropdown()
		{
			if (ComboBox.CurrentDropdownDrawer != null)
			{
				ComboBox.CurrentDropdownDrawer();
				ComboBox.CurrentDropdownDrawer = null;
				return true;
			}
			return false;
		}

		private static void DrawListField(SettingEntryBase setting)
		{
			//IL_0073: 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)
			object[] acceptableValues = setting.AcceptableValues;
			if (acceptableValues.Length == 0)
			{
				throw new ArgumentException("AcceptableValueListAttribute returned an empty list of acceptable values. You need to supply at least 1 option.");
			}
			if (!setting.SettingType.IsInstanceOfType(acceptableValues.FirstOrDefault((object x) => x != null)))
			{
				throw new ArgumentException("AcceptableValueListAttribute returned a list with items of type other than the settng type itself.");
			}
			if ((object)setting.SettingType == typeof(KeyCode))
			{
				DrawKeyCode(setting);
				return;
			}
			Rect settingWindowRect = _instance.SettingWindowRect;
			DrawComboboxField(setting, acceptableValues, ((Rect)(ref settingWindowRect)).yMax);
		}

		private static bool DrawFieldBasedOnValueType(SettingEntryBase setting)
		{
			if (SettingDrawHandlers.TryGetValue(setting.SettingType, out var value))
			{
				value(setting);
				return true;
			}
			return false;
		}

		private static void DrawBoolField(SettingEntryBase setting)
		{
			bool flag = (bool)setting.Get();
			bool flag2 = GUILayout.Toggle(flag, flag ? "Enabled" : "Disabled", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if (flag2 != flag)
			{
				setting.Set(flag2);
			}
		}

		private static void DrawEnumField(SettingEntryBase setting)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if (setting.SettingType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any())
			{
				DrawFlagsField(setting, Enum.GetValues(setting.SettingType), _instance.RightColumnWidth);
				return;
			}
			Array values = Enum.GetValues(setting.SettingType);
			Rect settingWindowRect = _instance.SettingWindowRect;
			DrawComboboxField(setting, values, ((Rect)(ref settingWindowRect)).yMax);
		}

		private static void DrawFlagsField(SettingEntryBase setting, IList enumValues, int maxWidth)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			long num = Convert.ToInt64(setting.Get());
			var array = (from Enum x in enumValues
				select new
				{
					name = x.ToString(),
					val = Convert.ToInt64(x)
				}).ToArray();
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MaxWidth((float)maxWidth) });
			int i = 0;
			while (i < array.Length)
			{
				GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
				int num2 = 0;
				for (; i < array.Length; i++)
				{
					var anon = array[i];
					if (anon.val != 0L)
					{
						int num3 = (int)GUI.skin.toggle.CalcSize(new GUIContent(anon.name)).x;
						num2 += num3;
						if (num2 > maxWidth)
						{
							break;
						}
						GUI.changed = false;
						bool flag = GUILayout.Toggle((num & anon.val) == anon.val, anon.name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
						if (GUI.changed)
						{
							long value = (flag ? (num | anon.val) : (num & ~anon.val));
							setting.Set(Enum.ToObject(setting.SettingType, value));
						}
					}
				}
				GUILayout.EndHorizontal();
			}
			GUI.changed = false;
			GUILayout.EndVertical();
			GUILayout.FlexibleSpace();
		}

		private static void DrawComboboxField(SettingEntryBase setting, IList list, float windowYmax)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			GUIContent val = ObjectToGuiContent(setting.Get());
			Rect rect = GUILayoutUtility.GetRect(val, GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if (!_comboBoxCache.TryGetValue(setting, out var value))
			{
				value = new ComboBox(rect, val, list.Cast<object>().Select(ObjectToGuiContent).ToArray(), GUI.skin.button, windowYmax);
				_comboBoxCache[setting] = value;
			}
			else
			{
				value.Rect = rect;
				value.ButtonContent = val;
			}
			value.Show(delegate(int id)
			{
				if (id >= 0 && id < list.Count)
				{
					setting.Set(list[id]);
				}
			});
		}

		private static GUIContent ObjectToGuiContent(object x)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			if (x is Enum)
			{
				Type type = x.GetType();
				DescriptionAttribute descriptionAttribute = type.GetMember(x.ToString()).FirstOrDefault()?.GetCustomAttributes(typeof(DescriptionAttribute), inherit: false).Cast<DescriptionAttribute>().FirstOrDefault();
				if (descriptionAttribute == null)
				{
					return new GUIContent(x.ToString().ToProperCase());
				}
				return new GUIContent(descriptionAttribute.Description);
			}
			return new GUIContent(x.ToString());
		}

		private static void DrawRangeField(SettingEntryBase setting)
		{
			object obj = setting.Get();
			float num = (float)Convert.ToDouble(obj, CultureInfo.InvariantCulture);
			float num2 = (float)Convert.ToDouble(setting.AcceptableValueRange.Key, CultureInfo.InvariantCulture);
			float num3 = (float)Convert.ToDouble(setting.AcceptableValueRange.Value, CultureInfo.InvariantCulture);
			float num4 = GUILayout.HorizontalSlider(num, num2, num3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if (Math.Abs(num4 - num) > Mathf.Abs(num3 - num2) / 1000f)
			{
				object newVal = Convert.ChangeType(num4, setting.SettingType, CultureInfo.InvariantCulture);
				setting.Set(newVal);
			}
			if (setting.ShowRangeAsPercent == true)
			{
				DrawCenteredLabel(Mathf.Round(100f * Mathf.Abs(num4 - num2) / Mathf.Abs(num3 - num2)) + "%", GUILayout.Width(50f));
				return;
			}
			string text = obj.ToString().AppendZeroIfFloat(setting.SettingType);
			string text2 = GUILayout.TextField(text, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) });
			if (!(text2 != text))
			{
				return;
			}
			try
			{
				float num5 = (float)Convert.ToDouble(text2, CultureInfo.InvariantCulture);
				float num6 = Mathf.Clamp(num5, num2, num3);
				setting.Set(Convert.ChangeType(num6, setting.SettingType, CultureInfo.InvariantCulture));
			}
			catch (FormatException)
			{
			}
		}

		private void DrawUnknownField(SettingEntryBase setting, int rightColumnWidth)
		{
			if (setting.ObjToStr != null && setting.StrToObj != null)
			{
				string text = setting.ObjToStr(setting.Get()).AppendZeroIfFloat(setting.SettingType);
				string text2 = GUILayout.TextField(text, (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.Width((float)rightColumnWidth),
					GUILayout.MaxWidth((float)rightColumnWidth)
				});
				if (text2 != text)
				{
					setting.Set(setting.StrToObj(text2));
				}
			}
			else
			{
				object obj = setting.Get();
				string text3 = ((obj == null) ? "NULL" : obj.ToString().AppendZeroIfFloat(setting.SettingType));
				if (CanCovert(text3, setting.SettingType))
				{
					string text4 = GUILayout.TextField(text3, (GUILayoutOption[])(object)new GUILayoutOption[2]
					{
						GUILayout.Width((float)rightColumnWidth),
						GUILayout.MaxWidth((float)rightColumnWidth)
					});
					if (text4 != text3)
					{
						setting.Set(Convert.ChangeType(text4, setting.SettingType, CultureInfo.InvariantCulture));
					}
				}
				else
				{
					GUILayout.TextArea(text3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MaxWidth((float)rightColumnWidth) });
				}
			}
			GUILayout.FlexibleSpace();
		}

		private bool CanCovert(string value, Type type)
		{
			if (_canCovertCache.ContainsKey(type))
			{
				return _canCovertCache[type];
			}
			try
			{
				object obj = Convert.ChangeType(value, type);
				_canCovertCache[type] = true;
				return true;
			}
			catch
			{
				_canCovertCache[type] = false;
				return false;
			}
		}

		private static void DrawKeyCode(SettingEntryBase setting)
		{
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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)
			if (_currentKeyboardShortcutToSet == setting)
			{
				GUILayout.Label("Press any key", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
				GUIUtility.keyboardControl = -1;
				IInputSystem current = UnityInput.Current;
				if (_keysToCheck == null)
				{
					_keysToCheck = current.SupportedKeyCodes.Except((IEnumerable<KeyCode>)(object)new KeyCode[2]
					{
						(KeyCode)323,
						default(KeyCode)
					}).ToArray();
				}
				foreach (KeyCode item in _keysToCheck)
				{
					if (current.GetKeyUp(item))
					{
						setting.Set(item);
						_currentKeyboardShortcutToSet = null;
						break;
					}
				}
				if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
				{
					_currentKeyboardShortcutToSet = null;
				}
			}
			else
			{
				object[] acceptableValues = setting.AcceptableValues;
				Array list = ((acceptableValues != null && acceptableValues.Length > 1) ? setting.AcceptableValues : Enum.GetValues(setting.SettingType));
				Rect settingWindowRect = _instance.SettingWindowRect;
				DrawComboboxField(setting, list, ((Rect)(ref settingWindowRect)).yMax);
				if (GUILayout.Button(new GUIContent("Set...", (Texture)null, "Set the key by pressing any key on your keyboard."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
				{
					_currentKeyboardShortcutToSet = setting;
				}
			}
		}

		private static void DrawKeyboardShortcut(SettingEntryBase setting)
		{
			//IL_0125: 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_006d: 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)
			//IL_0078: 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)
			if (_currentKeyboardShortcutToSet == setting)
			{
				GUILayout.Label("Press any key combination", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
				GUIUtility.keyboardControl = -1;
				IInputSystem current = UnityInput.Current;
				if (_keysToCheck == null)
				{
					_keysToCheck = current.SupportedKeyCodes.Except((IEnumerable<KeyCode>)(object)new KeyCode[2]
					{
						(KeyCode)323,
						default(KeyCode)
					}).ToArray();
				}
				foreach (KeyCode item in _keysToCheck)
				{
					if (current.GetKeyUp(item))
					{
						setting.Set((object)new KeyboardShortcut(item, _keysToCheck.Where((Func<KeyCode, bool>)current.GetKey).ToArray()));
						_currentKeyboardShortcutToSet = null;
						break;
					}
				}
				if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
				{
					_currentKeyboardShortcutToSet = null;
				}
			}
			else
			{
				if (GUILayout.Button(setting.Get().ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
				{
					_currentKeyboardShortcutToSet = setting;
				}
				if (GUILayout.Button("Clear", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }))
				{
					setting.Set(KeyboardShortcut.Empty);
					_currentKeyboardShortcutToSet = null;
				}
			}
		}

		private static void DrawVector2(SettingEntryBase obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = (Vector2)obj.Get();
			Vector2 val2 = val;
			val.x = DrawSingleVectorSlider(val.x, "X");
			val.y = DrawSingleVectorSlider(val.y, "Y");
			if (val != val2)
			{
				obj.Set(val);
			}
		}

		private static void DrawVector3(SettingEntryBase obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (Vector3)obj.Get();
			Vector3 val2 = val;
			val.x = DrawSingleVectorSlider(val.x, "X");
			val.y = DrawSingleVectorSlider(val.y, "Y");
			val.z = DrawSingleVectorSlider(val.z, "Z");
			if (val != val2)
			{
				obj.Set(val);
			}
		}

		private static void DrawVector4(SettingEntryBase obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			Vector4 val = (Vector4)obj.Get();
			Vector4 val2 = val;
			val.x = DrawSingleVectorSlider(val.x, "X");
			val.y = DrawSingleVectorSlider(val.y, "Y");
			val.z = DrawSingleVectorSlider(val.z, "Z");
			val.w = DrawSingleVectorSlider(val.w, "W");
			if (val != val2)
			{
				obj.Set(val);
			}
		}

		private static void DrawQuaternion(SettingEntryBase obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			Quaternion val = (Quaternion)obj.Get();
			Quaternion val2 = val;
			val.x = DrawSingleVectorSlider(val.x, "X");
			val.y = DrawSingleVectorSlider(val.y, "Y");
			val.z = DrawSingleVectorSlider(val.z, "Z");
			val.w = DrawSingleVectorSlider(val.w, "W");
			if (val != val2)
			{
				obj.Set(val);
			}
		}

		private static float DrawSingleVectorSlider(float setting, string label)
		{
			GUILayout.Label(label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			float.TryParse(GUILayout.TextField(setting.ToString("F", CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }), NumberStyles.Any, CultureInfo.InvariantCulture, out var result);
			return result;
		}

		private static void DrawColor(SettingEntryBase obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: 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_0122: Unknown result type (might be due to invalid IL or missing references)
			Color val = (Color)obj.Get();
			GUI.changed = false;
			if (!_colorCache.TryGetValue(obj, out var value))
			{
				Texture2D tex2 = new Texture2D(100, 20, (TextureFormat)5, false);
				value = new ColorCacheEntry
				{
					Tex = tex2,
					Last = val
				};
				FillTex(val, tex2);
				_colorCache[obj] = value;
			}
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.Label((Texture)(object)value.Tex, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			string text = (_drawColorHex ? ("#" + ColorUtility.ToHtmlStringRGBA(val)) : $"{val.r:F2} {val.g:F2} {val.b:F2} {val.a:F2}");
			string text2 = GUILayout.TextField(text, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if (GUI.changed && text != text2)
			{
				if (_drawColorHex)
				{
					Color val2 = default(Color);
					if (ColorUtility.TryParseHtmlString(text2, ref val2))
					{
						val = val2;
					}
				}
				else
				{
					string[] array = text2.Split(new char[1] { ' ' });
					if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
					{
						((Color)(ref val))..ctor(result, result2, result3, result4);
					}
				}
			}
			_drawColorHex = GUILayout.Toggle(_drawColorHex, "Hex", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.Label("R", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			val.r = GUILayout.HorizontalSlider(val.r, 0f, 1f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUILayout.Label("G", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			val.g = GUILayout.HorizontalSlider(val.g, 0f, 1f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUILayout.Label("B", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			val.b = GUILayout.HorizontalSlider(val.b, 0f, 1f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUILayout.Label("A", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) });
			val.a = GUILayout.HorizontalSlider(val.a, 0f, 1f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUILayout.EndHorizontal();
			GUILayout.EndVertical();
			if (val != value.Last)
			{
				obj.Set(val);
				FillTex(val, value.Tex);
				value.Last = val;
			}
			static void FillTex(Color color, Texture2D tex)
			{
				//IL_0000: 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)
				if (color.a < 1f)
				{
					tex.FillTextureCheckerboard();
				}
				tex.FillTexture(color);
			}
		}
	}
	public sealed class ValueChangedEventArgs<TValue> : EventArgs
	{
		public TValue NewValue { get; }

		public ValueChangedEventArgs(TValue newValue)
		{
			NewValue = newValue;
		}
	}
}
namespace ConfigurationManager.Utilities
{
	internal class ComboBox
	{
		private static bool forceToUnShow;

		private static int useControlID = -1;

		private readonly string buttonStyle;

		private bool isClickedComboButton;

		private readonly GUIContent[] listContent;

		private readonly GUIStyle listStyle;

		private readonly int _windowYmax;

		private Vector2 _scrollPosition = Vector2.zero;

		public Rect Rect { get; set; }

		public GUIContent ButtonContent { get; set; }

		public static Action CurrentDropdownDrawer { get; set; }

		public ComboBox(Rect rect, GUIContent buttonContent, GUIContent[] listContent, GUIStyle listStyle, float windowYmax)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			Rect = rect;
			ButtonContent = buttonContent;
			this.listContent = listContent;
			buttonStyle = "button";
			this.listStyle = listStyle;
			_windowYmax = (int)windowYmax;
		}

		public void Show(Action<int> onItemSelected)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Invalid comparison between Unknown and I4
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: 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)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			if (forceToUnShow)
			{
				forceToUnShow = false;
				isClickedComboButton = false;
			}
			bool flag = false;
			int controlID = GUIUtility.GetControlID((FocusType)2);
			Vector2 val = Vector2.zero;
			if ((int)Event.current.GetTypeForControl(controlID) == 1 && isClickedComboButton)
			{
				flag = true;
				val = Event.current.mousePosition;
			}
			if (GUI.Button(Rect, ButtonContent, GUIStyle.op_Implicit(buttonStyle)))
			{
				if (useControlID == -1)
				{
					useControlID = controlID;
					isClickedComboButton = false;
				}
				if (useControlID != controlID)
				{
					forceToUnShow = true;
					useControlID = controlID;
				}
				isClickedComboButton = true;
			}
			if (isClickedComboButton)
			{
				GUI.enabled = false;
				GUI.color = new Color(1f, 1f, 1f, 2f);
				Rect rect = Rect;
				float x = ((Rect)(ref rect)).x;
				rect = Rect;
				Vector2 location = GUIUtility.GUIToScreenPoint(new Vector2(x, ((Rect)(ref rect)).y + listStyle.CalcHeight(listContent[0], 1f)));
				rect = Rect;
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor(((Rect)(ref rect)).width, listStyle.CalcHeight(listContent[0], 1f) * (float)listContent.Length);
				Rect innerRect = new Rect(0f, 0f, val2.x, val2.y);
				Rect outerRectScreen = new Rect(location.x, location.y, val2.x, val2.y);
				if (((Rect)(ref outerRectScreen)).yMax > (float)_windowYmax)
				{
					((Rect)(ref outerRectScreen)).height = (float)_windowYmax - ((Rect)(ref outerRectScreen)).y;
					ref Rect reference = ref outerRectScreen;
					((Rect)(ref reference)).width = ((Rect)(ref reference)).width + 20f;
				}
				if (val != Vector2.zero && ((Rect)(ref outerRectScreen)).Contains(GUIUtility.GUIToScreenPoint(val)))
				{
					flag = false;
				}
				CurrentDropdownDrawer = delegate
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: 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_001a: Unknown result type (might be due to invalid IL or missing references)
					//IL_003b: Unknown result type (might be due to invalid IL or missing references)
					//IL_003e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0044: Unknown result type (might be due to invalid IL or missing references)
					//IL_0050: Unknown result type (might be due to invalid IL or missing references)
					//IL_0057: 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_0064: Unknown result type (might be due to invalid IL or missing references)
					//IL_0069: Unknown result type (might be due to invalid IL or missing references)
					//IL_006f: Unknown result type (might be due to invalid IL or missing references)
					GUI.enabled = true;
					Vector2 val3 = GUIUtility.ScreenToGUIPoint(location);
					Rect val4 = default(Rect);
					((Rect)(ref val4))..ctor(val3.x, val3.y, ((Rect)(ref outerRectScreen)).width, ((Rect)(ref outerRectScreen)).height);
					ImguiUtils.DrawContolBackground(val4);
					_scrollPosition = GUI.BeginScrollView(val4, _scrollPosition, innerRect, false, false);
					int num = GUI.SelectionGrid(innerRect, -1, listContent, 1, listStyle);
					if (num != -1)
					{
						onItemSelected(num);
						isClickedComboButton = false;
					}
					GUI.EndScrollView(true);
				};
			}
			if (flag)
			{
				isClickedComboButton = false;
			}
		}
	}
	internal static class ImguiUtils
	{
		private static Texture2D _tooltipBg;

		private static Texture2D _windowBackground;

		public static void DrawWindowBackground(Rect position)
		{
			//IL_0043: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0069: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)_windowBackground))
			{
				Texture2D val = new Texture2D(1, 1, (TextureFormat)5, false);
				val.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.5f, 1f));
				val.Apply();
				_windowBackground = val;
			}
			GUI.Box(position, GUIContent.none, new GUIStyle
			{
				normal = new GUIStyleState
				{
					background = _windowBackground
				}
			});
		}

		public static void DrawContolBackground(Rect position, Color color = default(Color))
		{
			//IL_002f: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_0055: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)_tooltipBg))
			{
				Texture2D val = new Texture2D(1, 1, (TextureFormat)5, false);
				val.SetPixel(0, 0, Color.black);
				val.Apply();
				_tooltipBg = val;
			}
			GUI.Box(position, GUIContent.none, new GUIStyle
			{
				normal = new GUIStyleState
				{
					background = _tooltipBg
				}
			});
		}
	}
	internal static class Utils
	{
		public static string ToProperCase(this string str)
		{
			if (string.IsNullOrEmpty(str))
			{
				return string.Empty;
			}
			if (str.Length < 2)
			{
				return str;
			}
			string text = str.Substring(0, 1).ToUpper();
			for (int i = 1; i < str.Length; i++)
			{
				if (char.IsUpper(str[i]))
				{
					text += " ";
				}
				text += str[i];
			}
			return text;
		}

		public static string AppendZero(this string s)
		{
			if (s.Contains("."))
			{
				return s;
			}
			return s + ".0";
		}

		public static string AppendZeroIfFloat(this string s, Type type)
		{
			if ((object)type != typeof(float) && (object)type != typeof(double) && (object)type != typeof(decimal))
			{
				return s;
			}
			return s.AppendZero();
		}

		public static void FillTexture(this Texture2D tex, Color color)
		{
			//IL_0000: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (color.a < 1f)
			{
				for (int i = 0; i < ((Texture)tex).width; i++)
				{
					for (int j = 0; j < ((Texture)tex).height; j++)
					{
						Color pixel = tex.GetPixel(i, j);
						Color val = Color.Lerp(pixel, color, color.a);
						val.a = Mathf.Max(pixel.a, color.a);
						tex.SetPixel(i, j, val);
					}
				}
			}
			else
			{
				for (int k = 0; k < ((Texture)tex).width; k++)
				{
					for (int l = 0; l < ((Texture)tex).height; l++)
					{
						tex.SetPixel(k, l, color);
					}
				}
			}
			tex.Apply(false);
		}

		public static void FillTextureCheckerboard(this Texture2D tex)
		{
			//IL_0020: 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)
			for (int i = 0; i < ((Texture)tex).width; i++)
			{
				for (int j = 0; j < ((Texture)tex).height; j++)
				{
					tex.SetPixel(i, j, ((i / 10 + j / 10) % 2 == 1) ? Color.black : Color.white);
				}
			}
			tex.Apply(false);
		}

		public static void OpenLog()
		{
			List<string> list = new List<string>();
			string text = Path.Combine(Application.dataPath, "..");
			list.Add(Path.Combine(text, "output_log.txt"));
			list.Add(Path.Combine(Application.dataPath, "output_log.txt"));
			PropertyInfo property = typeof(Application).GetProperty("consoleLogPath", BindingFlags.Static | BindingFlags.Public);
			if ((object)property != null)
			{
				string item = property.GetValue(null, null) as string;
				list.Add(item);
			}
			if (Directory.Exists(Application.persistentDataPath))
			{
				string item2 = Directory.GetFiles(Application.persistentDataPath, "output_log.txt", SearchOption.AllDirectories).FirstOrDefault();
				list.Add(item2);
			}
			string path2 = list.Where(File.Exists).OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault();
			if (!TryOpen(path2))
			{
				list.Clear();
				list.AddRange(Directory.GetFiles(text, "LogOutput.log*", SearchOption.AllDirectories));
				list.AddRange(Directory.GetFiles(text, "output_log.txt", SearchOption.AllDirectories));
				path2 = list.Where(File.Exists).OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault();
				if (!TryOpen(path2))
				{
					throw new FileNotFoundException("No log files were found");
				}
			}
			static bool TryOpen(string path)
			{
				if (path == null)
				{
					return false;
				}
				try
				{
					Process.Start(new ProcessStartInfo(path)
					{
						UseShellExecute = true
					});
					return true;
				}
				catch
				{
					return false;
				}
			}
		}

		public static string GetWebsite(BaseUnityPlugin bepInPlugin)
		{
			if ((Object)(object)bepInPlugin == (Object)null)
			{
				return null;
			}
			try
			{
				string location = bepInPlugin.Info.Location;
				if (!File.Exists(location))
				{
					return null;
				}
				FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(location);
				return new string[5] { versionInfo.CompanyName, versionInfo.FileDescription, versionInfo.Comments, versionInfo.LegalCopyright, versionInfo.LegalTrademarks }.FirstOrDefault((string x) => Uri.IsWellFormedUriString(x, UriKind.Absolute));
			}
			catch (Exception ex)
			{
				ManualLogSource logger = ConfigurationManager.Logger;
				PluginInfo info = bepInPlugin.Info;
				object obj;
				if (info == null)
				{
					obj = null;
				}
				else
				{
					BepInPlugin metadata = info.Metadata;
					obj = ((metadata != null) ? metadata.Name : null);
				}
				logger.LogWarning((object)("Failed to get URI for " + (string?)obj + " - " + ex.Message));
				return null;
			}
		}

		public static void OpenWebsite(string url)
		{
			try
			{
				if (string.IsNullOrEmpty(url))
				{
					throw new Exception("Empty URL");
				}
				Process.Start(new ProcessStartInfo(url)
				{
					UseShellExecute = true
				});
			}
			catch (Exception ex)
			{
				ConfigurationManager.Logger.Log((LogLevel)12, (object)("Failed to open URL " + url + "\nCause: " + ex.Message));
			}
		}

		public static GUIStyle CreateCopy(this GUIStyle original)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			return new GUIStyle(original);
		}
	}
}

BepInEx/plugins/CrowdControl/ConnectorLib.JSON.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Warp World, Inc.")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("© 2026 Warp World, Inc.")]
[assembly: AssemblyFileVersion("5.0.9769.22788")]
[assembly: AssemblyInformationalVersion("5.0.9769.22788+27158254ba5145aa87bd444f261f30560f544050")]
[assembly: AssemblyProduct("ConnectorLib.JSON")]
[assembly: AssemblyTitle("ConnectorLib.JSON")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.0.9769.22788")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[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.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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 ConnectorLib.JSON
{
	public class CamelCaseStringEnumConverter : JsonConverter<Enum>
	{
		public override void WriteJson(JsonWriter writer, Enum? value, JsonSerializer serializer)
		{
			if (value == null)
			{
				serializer.Serialize(writer, (object)null);
			}
			else
			{
				serializer.Serialize(writer, (object)value.ToCamelCase());
			}
		}

		public override Enum ReadJson(JsonReader reader, Type objectType, Enum? existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			return ReadJToken(JToken.ReadFrom(reader), objectType);
		}

		public static Enum ReadJToken(JToken reader, Type objectType)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_000c: Invalid comparison between Unknown and I4
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			JTokenType type = reader.Type;
			JTokenType val = type;
			if ((int)val != 6)
			{
				if ((int)val == 8)
				{
					string text = Extensions.Value<string>((IEnumerable<JToken>)reader);
					if (text == null)
					{
						throw new SerializationException("The value was null.");
					}
					if (Enum.TryParse(objectType, text, ignoreCase: true, out object result))
					{
						return (Enum)result;
					}
					throw new SerializationException("The value was not recognized.");
				}
				throw new SerializationException("The value was not a string or number.");
			}
			int? num = Extensions.Value<int>((IEnumerable<JToken>)reader);
			if (!num.HasValue)
			{
				throw new SerializationException("The value was null.");
			}
			return (Enum)Enum.ToObject(objectType, num.Value);
		}
	}
	[Serializable]
	public class CustomEffectDefinition
	{
		[Serializable]
		public class Duration
		{
			public long value;

			[JsonProperty(/*Could not decode attribute arguments.*/)]
			public bool? immutable;

			public Duration()
			{
			}

			public Duration(long value, bool? immutable = null)
			{
				this.value = value;
				this.immutable = immutable;
			}
		}

		[Serializable]
		public class Range
		{
			public long min;

			public long max;

			public Range()
			{
			}

			public Range(long min, long max)
			{
				this.min = min;
				this.max = max;
			}
		}

		[Serializable]
		public class Alignment
		{
			public float orderliness;

			public float morality;

			public Alignment()
			{
			}

			public Alignment(float orderliness, float morality)
			{
				this.orderliness = orderliness;
				this.morality = morality;
			}
		}

		[Serializable]
		public class Parameter
		{
			[Serializable]
			public class Option
			{
				public string name = string.Empty;

				[JsonProperty(/*Could not decode attribute arguments.*/)]
				public float? priority;

				public Option()
				{
				}

				public Option(string name, float? priority = null)
				{
					this.name = name;
					this.priority = priority;
				}
			}

			public string name = string.Empty;

			public string type = "options";

			[JsonProperty(/*Could not decode attribute arguments.*/)]
			public Dictionary<string, Option>? options;

			public const string TYPE_OPTIONS = "options";

			public const string TYPE_HEX_COLOR = "hex-color";
		}

		public string effectID = string.Empty;

		public string name = string.Empty;

		public long price;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? description;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[]? category;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[]? group;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[]? tags;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? image;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Duration? duration;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Range? quantity;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Alignment? alignment;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public float? sessionCooldown;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public float? userCooldown;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Dictionary<string, Parameter>? parameters;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public bool? hidden;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public bool? inactive;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? note;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? clone;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public Dictionary<string, object?>? args;
	}
	public static class CustomEffectsRpc
	{
		[Serializable]
		public class AddEffectsArgs
		{
			public List<CustomEffectDefinition> effects = new List<CustomEffectDefinition>();

			public bool preserveExisting = true;
		}

		[Serializable]
		public class RemoveEffectsArgs
		{
			public List<string> effects = new List<string>();
		}

		public const string METHOD_ADD = "addEffects";

		public const string METHOD_REMOVE = "removeEffect";

		public static RpcRequest AddEffects(IEnumerable<CustomEffectDefinition> effects, bool preserveExisting = true)
		{
			RpcRequest rpcRequest = new RpcRequest();
			rpcRequest.method = "addEffects";
			rpcRequest.target = RpcTarget.Server;
			rpcRequest.args = new object[1]
			{
				new AddEffectsArgs
				{
					effects = effects.ToList(),
					preserveExisting = preserveExisting
				}
			};
			return rpcRequest;
		}

		public static RpcRequest RemoveEffects(IEnumerable<string> effectIDs)
		{
			RpcRequest rpcRequest = new RpcRequest();
			rpcRequest.method = "removeEffect";
			rpcRequest.target = RpcTarget.Server;
			rpcRequest.args = new object[1]
			{
				new RemoveEffectsArgs
				{
					effects = effectIDs.ToList()
				}
			};
			return rpcRequest;
		}
	}
	[Serializable]
	public class DataRequest : SimpleJSONRequest
	{
		public string key;

		public DataRequest(string key)
		{
			this.key = key;
			type = RequestType.DataRequest;
		}
	}
	[Serializable]
	public class DataResponse : SimpleJSONResponse
	{
		public string key;

		public JToken? value;

		public EffectStatus status;

		public long timeRemaining;

		public string? message;

		[JsonConstructor]
		public DataResponse(string key, EffectStatus status, object? value = null, long timeRemaining = 0L, string? message = null)
		{
			this.key = key;
			this.value = value.IfNotNull((Func<object, JToken?>)JToken.FromObject);
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.message = message;
			type = ResponseType.DataResponse;
		}

		public static DataResponse SuccessIfDefined(string key, object? value, string failMessage = "")
		{
			if (value == null)
			{
				return Retry(key, 0L, failMessage);
			}
			if (value is string input && input.IsNullOrWhiteSpace())
			{
				return Retry(key, 0L, failMessage);
			}
			return Success(key, value);
		}

		public static DataResponse Success(string key, object? value)
		{
			return new DataResponse(key, EffectStatus.Success, value, 0L);
		}

		public static DataResponse Success(string key, object? value, string? message)
		{
			return new DataResponse(key, EffectStatus.Success, value, 0L, message);
		}

		public static DataResponse Failure(string key)
		{
			return new DataResponse(key, EffectStatus.Failure, null, 0L);
		}

		public static DataResponse Failure(string key, string? message)
		{
			return new DataResponse(key, EffectStatus.Failure, null, 0L, message);
		}

		public static DataResponse Failure(string key, object? value, string? message = null)
		{
			return new DataResponse(key, EffectStatus.Failure, value, 0L, message);
		}

		public static DataResponse Retry(string key, long delay = 0L, string? message = null)
		{
			return new DataResponse(key, EffectStatus.Retry, null, delay, message);
		}
	}
	[Serializable]
	public class EffectRequest : SimpleJSONRequest
	{
		[Serializable]
		public class Target
		{
			public string? service;

			public string? id;

			public string? name;

			public string? avatar;
		}

		public string? code;

		public string? message;

		public JToken? parameters;

		public uint? quantity;

		public JArray? targets;

		public long? duration;

		public string? viewer;

		public JArray? viewers;

		public long? cost;

		public Dictionary<string, object?>? arguments;

		public Guid? requestID;

		[JsonConverter(typeof(IEffectSourceDetails.Converter))]
		public IEffectSourceDetails? sourceDetails;

		public EffectRequest()
		{
			type = RequestType.EffectStart;
		}
	}
	[Serializable]
	public class EffectResponse : SimpleJSONResponse
	{
		private class MetadataConverter : JsonConverter<Dictionary<string, DataResponse>?>
		{
			public override void WriteJson(JsonWriter writer, Dictionary<string, DataResponse>? value, JsonSerializer serializer)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Expected O, but got Unknown
				if (value == null)
				{
					serializer.Serialize(writer, (object)null);
					return;
				}
				JObject val = new JObject();
				foreach (KeyValuePair<string, DataResponse> item in value)
				{
					JObject val2 = JObject.FromObject((object)item.Value);
					val2.Remove("key");
					val[item.Key] = (JToken)(object)val2;
				}
				serializer.Serialize(writer, (object)val);
			}

			public override Dictionary<string, DataResponse>? ReadJson(JsonReader reader, Type objectType, Dictionary<string, DataResponse>? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Expected O, but got Unknown
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Expected O, but got Unknown
				JObject val = (JObject)serializer.Deserialize(reader);
				if (val == null)
				{
					return null;
				}
				Dictionary<string, DataResponse> dictionary = new Dictionary<string, DataResponse>();
				foreach (JProperty item in val.Properties())
				{
					JObject val2 = (JObject)item.Value;
					val2["key"] = JToken.op_Implicit(item.Name);
					dictionary.Add(item.Name, ((JToken)val2).ToObject<DataResponse>());
				}
				return dictionary;
			}
		}

		public EffectStatus status;

		public string? message;

		public StandardErrors messageID;

		public long timeRemaining;

		[JsonConverter(typeof(MetadataConverter))]
		public Dictionary<string, DataResponse>? metadata;

		public EffectResponse()
		{
		}

		public EffectResponse(uint id, EffectStatus status)
			: this(id, status, 0L)
		{
		}

		public EffectResponse(uint id, EffectStatus status, StandardErrors messageID, string? message = null)
			: this(id, status, 0L, messageID, message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, string? message)
			: this(id, status, 0L, message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds))
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining, StandardErrors messageID)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), messageID)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining, string? message)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, long timeRemaining, string? message = null)
		{
			base.id = id;
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.message = message;
			type = ResponseType.EffectRequest;
		}

		[JsonConstructor]
		public EffectResponse(uint id, EffectStatus status, long timeRemaining, StandardErrors messageID, string? message = null)
		{
			base.id = id;
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.messageID = messageID;
			this.message = message;
			type = ResponseType.EffectRequest;
		}

		public static EffectResponse Success(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, message);
		}

		public static EffectResponse Success(uint id, long delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, delay, message);
		}

		public static EffectResponse Success(uint id, TimeSpan delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, delay, message);
		}

		public static EffectResponse Failure(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Failure, message);
		}

		public static EffectResponse Failure(uint id, StandardErrors error, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Failure, error, message);
		}

		public static EffectResponse Unavailable(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Unavailable, message);
		}

		public static EffectResponse Unavailable(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Unavailable, error);
		}

		public static EffectResponse Retry(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, 0L, message);
		}

		public static EffectResponse Retry(uint id, long delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, message);
		}

		public static EffectResponse Retry(uint id, TimeSpan delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, message);
		}

		public static EffectResponse Retry(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, 0L, error);
		}

		public static EffectResponse Retry(uint id, long delay, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, error);
		}

		public static EffectResponse Retry(uint id, TimeSpan delay, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, error);
		}

		public static EffectResponse Paused(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, 0L, message);
		}

		public static EffectResponse Paused(uint id, long timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, message);
		}

		public static EffectResponse Paused(uint id, TimeSpan timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, message);
		}

		public static EffectResponse Paused(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, 0L, error);
		}

		public static EffectResponse Paused(uint id, long timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, error);
		}

		public static EffectResponse Paused(uint id, TimeSpan timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, error);
		}

		public static EffectResponse Resumed(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, 0L, message);
		}

		public static EffectResponse Resumed(uint id, long timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, message);
		}

		public static EffectResponse Resumed(uint id, TimeSpan timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, message);
		}

		public static EffectResponse Resumed(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, 0L, error);
		}

		public static EffectResponse Resumed(uint id, long timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, error);
		}

		public static EffectResponse Resumed(uint id, TimeSpan timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, error);
		}

		public static EffectResponse Finished(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Finished, 0L, message);
		}

		public static EffectResponse Finished(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Finished, 0L, error);
		}
	}
	public interface IEffectSourceDetails
	{
		public class Converter : JsonConverter<IEffectSourceDetails?>
		{
			public static readonly Converter Instance = new Converter();

			public override IEffectSourceDetails? ReadJson(JsonReader reader, Type objectType, IEffectSourceDetails? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Invalid comparison between Unknown and I4
				if ((int)reader.TokenType == 11)
				{
					return null;
				}
				JObject val = JObject.Load(reader);
				JToken obj = val["type"];
				string text = ((obj != null) ? Extensions.Value<string>((IEnumerable<JToken>)obj) : null);
				if (1 == 0)
				{
				}
				IEffectSourceDetails result = text switch
				{
					"twitch-channel-reward" => ((JToken)val).ToObject<TwitchChannelRewardSourceDetails>(), 
					"stream-labs-donation" => ((JToken)val).ToObject<StreamLabsDonationSourceDetails>(), 
					"event-hype-train" => ((JToken)val).ToObject<HypeTrainSourceDetails>(), 
					"tiktok-gift" => ((JToken)val).ToObject<TikTokGiftSourceDetails>(), 
					"tiktok-like" => ((JToken)val).ToObject<TikTokLikeSourceDetails>(), 
					"tiktok-follow" => ((JToken)val).ToObject<TikTokFollowSourceDetails>(), 
					"tiktok-share" => ((JToken)val).ToObject<TikTokShareSourceDetails>(), 
					"pulsoid-trigger" => ((JToken)val).ToObject<PulsoidTriggerSourceDetails>(), 
					"crowd-control-test" => ((JToken)val).ToObject<CrowdControlTestSourceDetails>(), 
					"crowd-control-chaos-mode" => ((JToken)val).ToObject<CrowdControlChaosModeSourceDetails>(), 
					"crowd-control-retry" => ((JToken)val).ToObject<CrowdControlRetrySourceDetails>(), 
					_ => null, 
				};
				if (1 == 0)
				{
				}
				return result;
			}

			public override void WriteJson(JsonWriter writer, IEffectSourceDetails? value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, (object)((value == null) ? null : JObject.FromObject((object)value)));
			}
		}

		[JsonProperty("type")]
		string Type { get; }
	}
	public class TwitchChannelRewardSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "twitch-channel-reward";

		[JsonProperty("rewardID")]
		public string RewardID { get; set; }

		[JsonProperty("redemptionID")]
		public string RedemptionID { get; set; }

		[JsonProperty("twitchID")]
		public string TwitchID { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("cost")]
		public int Cost { get; set; }
	}
	public class StreamLabsDonationSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "stream-labs-donation";

		[JsonProperty("donationID")]
		public string DonationID { get; set; }

		[JsonProperty("cost")]
		public string Cost { get; set; }

		[JsonProperty("currency")]
		public string Currency { get; set; }

		[JsonProperty("name")]
		public string? Name { get; set; }

		[JsonProperty("message")]
		public string? Message { get; set; }
	}
	public class HypeTrainSourceDetails : IEffectSourceDetails
	{
		public class Contribution
		{
			[JsonProperty("user_id")]
			public string UserID { get; set; }

			[JsonProperty("user_login")]
			public string UserLogin { get; set; }

			[JsonProperty("user_name")]
			public string UserName { get; set; }

			[JsonProperty("type")]
			public string Type { get; set; }

			[JsonProperty("total")]
			public int Total { get; set; }
		}

		[JsonProperty("type")]
		public string Type => "event-hype-train";

		[JsonProperty("total")]
		public int Total { get; set; }

		[JsonProperty("progress")]
		public int Progress { get; set; }

		[JsonProperty("goal")]
		public int Goal { get; set; }

		[JsonProperty("top_contributions")]
		public List<Contribution> TopContributions { get; set; }

		[JsonProperty("last_contribution")]
		public Contribution LastContribution { get; set; }

		[JsonProperty("level")]
		public int Level { get; set; }
	}
	public abstract class TikTokSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public abstract string Type { get; }

		[JsonProperty("cost")]
		public int Cost { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("userID")]
		public string UserID { get; set; }
	}
	public class TikTokGiftSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-gift";

		[JsonProperty("giftID")]
		public int GiftID { get; set; }

		[JsonProperty("giftName")]
		public string GiftName { get; set; }

		[JsonProperty("transactionID")]
		public string? TransactionID { get; set; }
	}
	public class TikTokLikeSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-like";
	}
	public class TikTokFollowSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-follow";
	}
	public class TikTokShareSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-share";
	}
	public class PulsoidTriggerSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "pulsoid-trigger";

		[JsonProperty("heartRate")]
		public int HeartRate { get; set; }

		[JsonProperty("uuid")]
		public Guid Uuid { get; set; }

		[JsonProperty("triggerType")]
		public string TriggerType { get; set; }

		[JsonProperty("targetHeartRate")]
		public int TargetHeartRate { get; set; }

		[JsonProperty("holdTime")]
		public int HoldTime { get; set; }

		[JsonProperty("cooldown")]
		public int Cooldown { get; set; }
	}
	public class CrowdControlTestSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-test";
	}
	public class CrowdControlChaosModeSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-chaos-mode";
	}
	public class CrowdControlRetrySourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-retry";
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum EffectStatus
	{
		Success = 0,
		Failure = 1,
		Unavailable = 2,
		Retry = 3,
		Queue = 4,
		Running = 5,
		Paused = 6,
		Resumed = 7,
		Finished = 8,
		Wait = 9,
		RemoteScheduled = 10,
		Visible = 128,
		NotVisible = 129,
		Selectable = 130,
		NotSelectable = 131,
		Reserved0 = 160,
		NotReady = 255
	}
	[Serializable]
	public class EffectUpdate : SimpleJSONResponse
	{
		[JsonConverter(typeof(CamelCaseStringEnumConverter))]
		public enum IdentifierType
		{
			Effect,
			Group,
			Category
		}

		[Obsolete("This field is deprecated. Please use the ids field instead.")]
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? code;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[]? ids;

		public IdentifierType idType;

		public EffectStatus status;

		public string? message;

		public EffectUpdate()
		{
		}

		public EffectUpdate(string id, EffectStatus status, string? message = null)
		{
			ids = new string[1] { id };
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(string id, IdentifierType idType, EffectStatus status, string? message = null)
		{
			ids = new string[1] { id };
			this.idType = idType;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(string[] ids, EffectStatus status, string? message = null)
		{
			this.ids = ids;
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(string[] ids, IdentifierType idType, EffectStatus status, string? message = null)
		{
			this.ids = ids;
			this.idType = idType;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(IEnumerable<string> ids, EffectStatus status, string? message = null)
		{
			this.ids = ids.ToArray();
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(IEnumerable<string> ids, IdentifierType idType, EffectStatus status, string? message = null)
		{
			this.ids = ids.ToArray();
			this.idType = idType;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}
	}
	[Serializable]
	public class EmptyRequest : SimpleJSONRequest
	{
	}
	[Serializable]
	public class EmptyResponse : SimpleJSONResponse
	{
	}
	internal static class EnumEx
	{
		internal static string ToCamelCase(this Enum value)
		{
			return value.ToString("G").ToCamelCase();
		}
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum GameState
	{
		Unknown = 0,
		Error = -1,
		Unmodded = -2,
		BadGameSettings = -3,
		WrongVersion = -4,
		NotFocused = -5,
		Loading = -6,
		InLevel = 1,
		[Obsolete("Use InLevel instead. This state is redundant and does not provide any additional information about the game state.")]
		Ready = 1,
		TitleScreen = -17,
		Credits = -18,
		Menu = -13,
		Paused = -7,
		WrongMode = -8,
		SafeArea = -9,
		StartingArea = -19,
		Dialogue = -20,
		Cutscene = -11,
		BadPlayerState = -12,
		InputLocked = -21,
		Map = -14,
		UntimedArea = -10,
		InCombat = -15,
		NotInCombat = -16,
		PipelineBusy = -128,
		NotReady = int.MinValue
	}
	[Serializable]
	public class GameUpdate : SimpleJSONResponse
	{
		public GameState state;

		public string? message;

		public GameUpdate(GameState state, string? message = null)
		{
			this.state = state;
			this.message = message;
			type = ResponseType.GameUpdate;
		}
	}
	[Serializable]
	public class GenericEventRequest : SimpleJSONRequest
	{
		[JsonProperty(PropertyName = "internal")]
		public bool @internal;

		public string eventType;

		public Dictionary<string, object?>? data;

		public GenericEventRequest(string eventType)
		{
			type = RequestType.GenericEvent;
			this.eventType = eventType;
		}

		[JsonConstructor]
		public GenericEventRequest(string eventType, IEnumerable<KeyValuePair<string, object?>>? data)
			: this(eventType)
		{
			this.data = ((data != null) ? data.ToDictionary() : null);
		}

		[JsonConstructor]
		public GenericEventRequest(string eventType, IEnumerable<KeyValuePair<string, object?>>? data, bool @internal)
			: this(eventType, data)
		{
			this.@internal = @internal;
		}
	}
	[Serializable]
	public class GenericEventResponse : SimpleJSONResponse
	{
		[JsonProperty(PropertyName = "internal")]
		public bool @internal;

		public string eventType;

		public Dictionary<string, object?>? data;

		public GenericEventResponse(string eventType)
		{
			type = ResponseType.GenericEvent;
			this.eventType = eventType;
		}

		public GenericEventResponse(string eventType, IEnumerable<KeyValuePair<string, object>>? data, bool @internal = false)
			: this(eventType)
		{
			this.data = ((data != null) ? data.ToDictionary() : null);
			this.@internal = @internal;
		}

		[JsonConstructor]
		public GenericEventResponse(string eventType, Dictionary<string, object>? data, [JsonProperty(PropertyName = "internal")] bool @internal)
			: this(eventType, data)
		{
			this.@internal = @internal;
		}
	}
	internal class HexColorConverter : JsonConverter<ParameterColorValue>
	{
		private static readonly Dictionary<char, byte> CHAR_LOOKUP = new Dictionary<char, byte>
		{
			{ '0', 0 },
			{ '1', 1 },
			{ '2', 2 },
			{ '3', 3 },
			{ '4', 4 },
			{ '5', 5 },
			{ '6', 6 },
			{ '7', 7 },
			{ '8', 8 },
			{ '9', 9 },
			{ 'A', 10 },
			{ 'B', 11 },
			{ 'C', 12 },
			{ 'D', 13 },
			{ 'E', 14 },
			{ 'F', 15 }
		};

		public override void WriteJson(JsonWriter writer, ParameterColorValue value, JsonSerializer serializer)
		{
			serializer.Serialize(writer, (object)string.Format("#{0}{1:X2}{2:X2}{3:X2}", (value.A != byte.MaxValue) ? value.A.ToString("X2") : string.Empty, value.R, value.G, value.B));
		}

		public override ParameterColorValue ReadJson(JsonReader reader, Type objectType, ParameterColorValue existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			string value = serializer.Deserialize<string>(reader);
			if (TryParse(value, out var color))
			{
				return color;
			}
			throw new SerializationException("Unrecognized color code.");
		}

		public static bool TryParse(string? value, out ParameterColorValue color)
		{
			if (value == null)
			{
				color = default(ParameterColorValue);
				return false;
			}
			value = value.TrimStart('#');
			switch (value.Length)
			{
			case 6:
			{
				string[] array2 = value.Chop(2);
				byte result2;
				byte red3 = (byte)(byte.TryParse(array2[0], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				byte green3 = (byte)(byte.TryParse(array2[1], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				byte blue3 = (byte)(byte.TryParse(array2[2], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				color = ParameterColorValue.FromArgb(red3, green3, blue3);
				return true;
			}
			case 8:
			{
				string[] array = value.Chop(2);
				byte result;
				byte alpha2 = (byte)(byte.TryParse(array[0], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte red2 = (byte)(byte.TryParse(array[1], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte green2 = (byte)(byte.TryParse(array[2], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte blue2 = (byte)(byte.TryParse(array[3], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				color = ParameterColorValue.FromArgb(alpha2, red2, green2, blue2);
				return true;
			}
			case 3:
			{
				byte value3;
				byte red4 = (byte)(CHAR_LOOKUP.TryGetValue(value[0], out value3) ? checked((byte)(value3 * 16)) : 0);
				byte green4 = (byte)(CHAR_LOOKUP.TryGetValue(value[1], out value3) ? checked((byte)(value3 * 16)) : 0);
				byte blue4 = (byte)(CHAR_LOOKUP.TryGetValue(value[2], out value3) ? checked((byte)(value3 * 16)) : 0);
				color = ParameterColorValue.FromArgb(red4, green4, blue4);
				return true;
			}
			case 4:
			{
				byte value2;
				byte alpha = (byte)(CHAR_LOOKUP.TryGetValue(value[0], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte red = (byte)(CHAR_LOOKUP.TryGetValue(value[1], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte green = (byte)(CHAR_LOOKUP.TryGetValue(value[2], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte blue = (byte)(CHAR_LOOKUP.TryGetValue(value[3], out value2) ? checked((byte)(value2 * 16)) : 0);
				color = ParameterColorValue.FromArgb(alpha, red, green, blue);
				return true;
			}
			default:
				color = default(ParameterColorValue);
				return false;
			}
		}
	}
	internal static class IEnumerableEx
	{
		internal static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> values) where TKey : notnull
		{
			Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
			foreach (KeyValuePair<TKey, TValue> value in values)
			{
				dictionary.Add(value.Key, value.Value);
			}
			return dictionary;
		}
	}
	public interface IParameterValue
	{
		string ID { get; }

		string Name { get; }

		ParameterBase.ParameterType Type { get; }

		object? Value { get; }
	}
	[Serializable]
	public class LoginRequest : SimpleJSONRequest
	{
		public string? login;

		public string? password;
	}
	[Serializable]
	public class MessageRequest : SimpleJSONRequest
	{
		public string? message;
	}
	[Serializable]
	public class MessageResponse : SimpleJSONResponse
	{
		public string? message;
	}
	internal static class ObjectEx
	{
		internal static T2? IfNotNull<T1, T2>(this T1? value, Func<T1, T2?> selector) where T2 : class
		{
			return (value != null) ? selector(value) : null;
		}
	}
	public abstract class ParameterBase
	{
		[JsonConverter(typeof(ParameterTypeConverter))]
		public enum ParameterType
		{
			Options,
			HexColor
		}

		private class ParameterTypeConverter : JsonConverter<ParameterType>
		{
			public override void WriteJson(JsonWriter writer, ParameterType value, JsonSerializer serializer)
			{
				if (1 == 0)
				{
				}
				string text = value switch
				{
					ParameterType.Options => "options", 
					ParameterType.HexColor => "hex-color", 
					_ => throw new SerializationException("Unknown parameter type."), 
				};
				if (1 == 0)
				{
				}
				string text2 = text;
				writer.WriteValue(text2);
			}

			public override ParameterType ReadJson(JsonReader reader, Type objectType, ParameterType existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				switch (reader.Value?.ToString().ToLowerInvariant())
				{
				case "options":
					return ParameterType.Options;
				case "hexcolor":
				case "hex-color":
					return ParameterType.HexColor;
				default:
					throw new SerializationException("Unknown parameter type.");
				}
			}
		}

		[JsonIgnore]
		public readonly string ID;

		[JsonProperty(PropertyName = "title")]
		public readonly string Name;

		[JsonProperty(PropertyName = "type")]
		public readonly ParameterType Type;

		protected ParameterBase(string name, string id, ParameterType type)
		{
			ID = id;
			Name = name;
			Type = type;
		}
	}
	public class ParameterColor : ParameterBase, IParameterValue
	{
		[JsonProperty(PropertyName = "value")]
		[JsonConverter(typeof(HexColorConverter))]
		public ParameterColorValue Value;

		[JsonIgnore]
		string IParameterValue.ID => ID;

		[JsonIgnore]
		string IParameterValue.Name => Name;

		[JsonIgnore]
		ParameterType IParameterValue.Type => Type;

		[JsonIgnore]
		object? IParameterValue.Value => Value;

		[JsonConstructor]
		public ParameterColor(string name, string id, ParameterColorValue value)
			: base(name, id, ParameterType.HexColor)
		{
			Value = value;
		}

		[JsonConstructor]
		public ParameterColor(string name, string id, string value)
			: base(name, id, ParameterType.HexColor)
		{
			if (!HexColorConverter.TryParse(value, out Value))
			{
				throw new ArgumentException("Unknown color code.", "value");
			}
		}
	}
	[Serializable]
	[DebuggerDisplay("{NameAndARGBValue}")]
	[TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
	public readonly struct ParameterColorValue : IEquatable<ParameterColorValue>
	{
		public static readonly ParameterColorValue Empty = default(ParameterColorValue);

		private const short StateARGBValueValid = 2;

		private const short StateValueMask = 2;

		private const short StateNameValid = 8;

		private const long NotDefinedValue = 0L;

		internal const int ARGBAlphaShift = 24;

		internal const int ARGBRedShift = 16;

		internal const int ARGBGreenShift = 8;

		internal const int ARGBBlueShift = 0;

		internal const uint ARGBAlphaMask = 4278190080u;

		internal const uint ARGBRedMask = 16711680u;

		internal const uint ARGBGreenMask = 65280u;

		internal const uint ARGBBlueMask = 255u;

		private readonly long value;

		private readonly short state;

		public byte R => (byte)(Value >> 16);

		public byte G => (byte)(Value >> 8);

		public byte B => (byte)Value;

		public byte A => (byte)(Value >> 24);

		public bool IsEmpty => state == 0;

		private long Value
		{
			get
			{
				if ((state & 2) != 0)
				{
					return value;
				}
				return 0L;
			}
		}

		private ParameterColorValue(long value, short state)
		{
			this.value = value;
			this.state = state;
		}

		private static ParameterColorValue FromArgb(uint argb)
		{
			return new ParameterColorValue(argb, 2);
		}

		public static ParameterColorValue FromArgb(int argb)
		{
			return FromArgb((uint)argb);
		}

		public static ParameterColorValue FromArgb(byte alpha, byte red, byte green, byte blue)
		{
			return FromArgb((uint)((alpha << 24) | (red << 16) | (green << 8) | blue));
		}

		public static ParameterColorValue FromArgb(int alpha, ParameterColorValue baseColor)
		{
			return FromArgb(checked(((uint)alpha << 24) | ((uint)baseColor.Value & 0xFFFFFF)));
		}

		public static ParameterColorValue FromArgb(byte red, byte green, byte blue)
		{
			return FromArgb(byte.MaxValue, red, green, blue);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void GetRgbValues(out byte r, out byte g, out byte b)
		{
			checked
			{
				uint num = (uint)Value;
				r = (byte)((num & 0xFF0000) >> 16);
				g = (byte)((num & 0xFF00) >> 8);
				b = (byte)(num & 0xFF);
			}
		}

		public float GetBrightness()
		{
			GetRgbValues(out var r, out var g, out var b);
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			return (float)checked(num2 + num) / 510f;
		}

		public float GetHue()
		{
			GetRgbValues(out var r, out var g, out var b);
			if (r == g && g == b)
			{
				return 0f;
			}
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			checked
			{
				float num3 = num2 - num;
				float num4 = ((r == num2) ? ((float)(g - b) / num3) : ((g != num2) ? ((float)(r - g) / num3 + 4f) : ((float)(b - r) / num3 + 2f)));
				num4 *= 60f;
				if (num4 < 0f)
				{
					num4 += 360f;
				}
				return num4;
			}
		}

		public float GetSaturation()
		{
			GetRgbValues(out var r, out var g, out var b);
			if (r == g && g == b)
			{
				return 0f;
			}
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			checked
			{
				int num3 = num2 + num;
				if (num3 > 255)
				{
					num3 = 510 - num2 - num;
				}
				return (float)(num2 - num) / (float)num3;
			}
		}

		public int ToArgb()
		{
			return (int)Value;
		}

		public override string ToString()
		{
			if ((state & 2) != 0)
			{
				return "ParameterColorValue [A=" + A + ", R=" + R + ", G=" + G + ", B=" + B + "]";
			}
			return "ParameterColorValue [Empty]";
		}

		public static bool operator ==(ParameterColorValue left, ParameterColorValue right)
		{
			return left.value == right.value && left.state == right.state;
		}

		public static bool operator !=(ParameterColorValue left, ParameterColorValue right)
		{
			return !(left == right);
		}

		public override bool Equals(object? obj)
		{
			return obj is ParameterColorValue other && Equals(other);
		}

		public bool Equals(ParameterColorValue other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return (value.GetHashCode() * 397) ^ state.GetHashCode();
		}
	}
	public class ParameterValue<TValue> : ParameterBase, IParameterValue
	{
		[JsonProperty(PropertyName = "value")]
		public TValue? Value;

		[JsonIgnore]
		string IParameterValue.ID => ID;

		[JsonIgnore]
		string IParameterValue.Name => Name;

		[JsonIgnore]
		ParameterType IParameterValue.Type => Type;

		[JsonIgnore]
		object? IParameterValue.Value => Value;

		[JsonConstructor]
		public ParameterValue(string name, string id, TValue? value)
			: base(name, id, ParameterType.Options)
		{
			Value = value;
		}

		public override string ToString()
		{
			return Name;
		}
	}
	[Serializable]
	public class PlayerInfo : SimpleJSONRequest
	{
		public JObject? player;

		public PlayerInfo()
		{
			type = RequestType.PlayerInfo;
		}
	}
	[Serializable]
	[JsonConverter(typeof(Converter))]
	public class RequestParameters : IReadOnlyList<string>, IEnumerable<string>, IEnumerable, IReadOnlyCollection<string>, IReadOnlyDictionary<string, IParameterValue>, IEnumerable<KeyValuePair<string, IParameterValue>>, IReadOnlyCollection<KeyValuePair<string, IParameterValue>>
	{
		private class Converter : JsonConverter<RequestParameters>
		{
			public override void WriteJson(JsonWriter writer, RequestParameters? value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, (object)value?._parameters);
			}

			public override RequestParameters? ReadJson(JsonReader reader, Type objectType, RequestParameters? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				JObject val = JObject.Load(reader);
				List<IParameterValue> list = new List<IParameterValue>();
				foreach (KeyValuePair<string, JToken> item in val)
				{
					string key = item.Key;
					string name = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"name"]);
					switch (Extensions.Value<ParameterBase.ParameterType>((IEnumerable<JToken>)item.Value[(object)"type"]))
					{
					case ParameterBase.ParameterType.Options:
					{
						string value2 = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"value"]);
						list.Add(new ParameterValue<string>(name, key, value2));
						break;
					}
					case ParameterBase.ParameterType.HexColor:
					{
						string value = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"value"]);
						if (HexColorConverter.TryParse(value, out var color))
						{
							list.Add(new ParameterColor(name, key, color));
						}
						break;
					}
					default:
						throw new SerializationException();
					}
				}
				return new RequestParameters(list);
			}
		}

		private readonly Dictionary<string, IParameterValue> _parameters;

		private readonly List<string> _parameter_list;

		int IReadOnlyCollection<string>.Count => _parameters.Count;

		int IReadOnlyCollection<KeyValuePair<string, IParameterValue>>.Count => _parameters.Count;

		public string this[int index] => _parameter_list[index];

		public IParameterValue this[string key] => _parameters[key];

		public IEnumerable<string> Keys => _parameters.Keys;

		public IEnumerable<IParameterValue> Values => _parameters.Values;

		public int Count => _parameters.Count;

		private RequestParameters()
		{
			_parameters = new Dictionary<string, IParameterValue>();
			_parameter_list = new List<string>();
		}

		public RequestParameters(IEnumerable<IParameterValue> parameters)
		{
			parameters = parameters.ToArray();
			_parameters = parameters.ToDictionary((IParameterValue d) => d.ID);
			_parameter_list = parameters.Select((IParameterValue v) => v.Value.ToString()).ToList();
		}

		public RequestParameters(IEnumerable<KeyValuePair<string, IParameterValue>> parameters)
		{
			_parameters = parameters.ToDictionary();
			_parameter_list = _parameters.Values.Select((IParameterValue p) => p.Value.ToString()).ToList();
		}

		IEnumerator<KeyValuePair<string, IParameterValue>> IEnumerable<KeyValuePair<string, IParameterValue>>.GetEnumerator()
		{
			return _parameters.GetEnumerator();
		}

		IEnumerator<string> IEnumerable<string>.GetEnumerator()
		{
			return _parameters.Values.Select((IParameterValue v) => v.Value?.ToString()).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<string>)this).GetEnumerator();
		}

		public bool ContainsKey(string key)
		{
			return _parameters.ContainsKey(key);
		}

		public bool TryGetValue(string key, out IParameterValue value)
		{
			return _parameters.TryGetValue(key, out value);
		}

		public IEnumerable<string> Where(Func<string, bool> predicate)
		{
			return Enumerable.Where(this, predicate);
		}

		public IEnumerable<TResult> Select<TResult>(Func<string, TResult> selector)
		{
			return Enumerable.Select(this, selector);
		}

		public IEnumerable<TResult> SelectMany<TResult>(Func<string, IEnumerable<TResult>> selector)
		{
			return Enumerable.SelectMany(this, selector);
		}

		public IEnumerable<TResult> SelectMany<TResult>(Func<string, int, IEnumerable<TResult>> selector)
		{
			return Enumerable.SelectMany(this, selector);
		}

		public string First()
		{
			return this.First<string>();
		}

		public string First(Func<string, bool> predicate)
		{
			return Enumerable.First(this, predicate);
		}

		public string? FirstOrDefault()
		{
			return this.FirstOrDefault<string>();
		}

		public string FirstOrDefault(string defaultValue)
		{
			return this.FirstOrDefault<string>() ?? defaultValue;
		}

		public string? FirstOrDefault(Func<string, bool> predicate)
		{
			return Enumerable.FirstOrDefault(this, predicate);
		}

		public string FirstOrDefault(Func<string, bool> predicate, string defaultValue)
		{
			return Enumerable.FirstOrDefault(this, predicate) ?? defaultValue;
		}

		public bool Any()
		{
			return this.Any<string>();
		}

		public bool Any(Func<string, bool> predicate)
		{
			return Enumerable.Any(this, predicate);
		}
	}
	public enum RequestType : byte
	{
		EffectTest = 0,
		EffectStart = 1,
		EffectStop = 2,
		[Obsolete("Use EffectTest instead.")]
		Test = 0,
		[Obsolete("Use EffectStart instead.")]
		Start = 1,
		[Obsolete("Use EffectStop instead.")]
		Stop = 2,
		GenericEvent = 16,
		DataRequest = 32,
		RpcResponse = 208,
		PlayerInfo = 224,
		Login = 240,
		Version = 252,
		GameUpdate = 253,
		KeepAlive = byte.MaxValue
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum ResponseType : byte
	{
		EffectRequest = 0,
		EffectStatus = 1,
		GenericEvent = 16,
		LoadEvent = 24,
		SaveEvent = 25,
		DataResponse = 32,
		RpcRequest = 208,
		Login = 240,
		LoginSuccess = 241,
		Version = 252,
		GameUpdate = 253,
		Disconnect = 254,
		KeepAlive = byte.MaxValue
	}
	[Serializable]
	public class RpcRequest : SimpleJSONResponse
	{
		public string? method;

		public object?[]? args;

		public RpcTarget? target;

		public RpcRequest()
		{
			type = ResponseType.RpcRequest;
		}
	}
	[Serializable]
	public class RpcResponse : SimpleJSONRequest
	{
		public object? value;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public bool exception;

		public RpcResponse()
		{
			type = RequestType.RpcResponse;
		}
	}
	[Flags]
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum RpcTarget
	{
		Game = 1,
		Pack = 2,
		Native = 4,
		Client = 8,
		Server = 0x10
	}
	public abstract class SimpleJSONMessage
	{
		public static readonly JsonSerializerSettings JSON_SERIALIZER_SETTINGS = new JsonSerializerSettings
		{
			NullValueHandling = (NullValueHandling)1,
			MissingMemberHandling = (MissingMemberHandling)0,
			Formatting = (Formatting)0
		};

		public static readonly JsonSerializer JSON_SERIALIZER = new JsonSerializer
		{
			NullValueHandling = JSON_SERIALIZER_SETTINGS.NullValueHandling,
			MissingMemberHandling = JSON_SERIALIZER_SETTINGS.MissingMemberHandling,
			Formatting = JSON_SERIALIZER_SETTINGS.Formatting
		};

		private static int _next_id = 0;

		public static uint NextID
		{
			get
			{
				uint result;
				while ((result = (uint)Interlocked.Increment(ref _next_id)) == 0)
				{
				}
				return result;
			}
		}

		public abstract uint ID { get; }

		public abstract bool IsKeepAlive { get; }

		public string Serialize()
		{
			return JsonConvert.SerializeObject((object)this, JSON_SERIALIZER_SETTINGS);
		}
	}
	[Serializable]
	public class SimpleJSONRequest : SimpleJSONMessage
	{
		public uint id = SimpleJSONMessage.NextID;

		public RequestType type;

		[JsonIgnore]
		public override uint ID => id;

		[JsonIgnore]
		public override bool IsKeepAlive => type == RequestType.KeepAlive;

		public static bool TryParse(string json, [MaybeNullWhen(false)] out SimpleJSONRequest request)
		{
			return TryParse(JObject.Parse(json), out request);
		}

		public static bool TryParse(JObject j, [MaybeNullWhen(false)] out SimpleJSONRequest request)
		{
			try
			{
				JToken value = j.GetValue("type");
				switch ((value != null) ? ((RequestType)(object)CamelCaseStringEnumConverter.ReadJToken(value, typeof(RequestType))) : RequestType.EffectTest)
				{
				case RequestType.EffectTest:
				case RequestType.EffectStart:
					request = ((JToken)j).ToObject<EffectRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.EffectStop:
					request = ((JToken)j).ToObject<EffectRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.DataRequest:
					request = ((JToken)j).ToObject<DataRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.RpcResponse:
					request = ((JToken)j).ToObject<RpcResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.PlayerInfo:
					request = ((JToken)j).ToObject<PlayerInfo>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.Login:
					request = ((JToken)j).ToObject<MessageRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.Version:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.GameUpdate:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.KeepAlive:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				}
			}
			catch
			{
			}
			request = null;
			return false;
		}
	}
	[Serializable]
	public class SimpleJSONResponse : SimpleJSONMessage
	{
		public uint id;

		public ResponseType type;

		[JsonIgnore]
		public override uint ID => id;

		[JsonIgnore]
		public override bool IsKeepAlive => type == ResponseType.KeepAlive;

		[JsonIgnore]
		public static SimpleJSONResponse KeepAlive { get; } = new EmptyResponse
		{
			type = ResponseType.KeepAlive
		};

		public static bool TryParse(string json, [MaybeNullWhen(false)] out SimpleJSONResponse response)
		{
			return TryParse(JObject.Parse(json), out response);
		}

		public static bool TryParse(JObject j, [MaybeNullWhen(false)] out SimpleJSONResponse response)
		{
			try
			{
				JToken value = j.GetValue("type");
				ResponseType responseType = ((value != null) ? ((ResponseType)(object)CamelCaseStringEnumConverter.ReadJToken(value, typeof(ResponseType))) : ResponseType.EffectRequest);
				ResponseType responseType2 = responseType;
				ResponseType responseType3 = responseType2;
				switch (responseType3)
				{
				case ResponseType.EffectStatus:
					if (responseType3 != ResponseType.EffectStatus)
					{
						break;
					}
					response = ((JToken)j).ToObject<EffectUpdate>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.EffectRequest:
					response = ((JToken)j).ToObject<EffectResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.RpcRequest:
					response = ((JToken)j).ToObject<RpcRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.GenericEvent:
					response = ((JToken)j).ToObject<GenericEventResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.DataResponse:
					response = ((JToken)j).ToObject<DataResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Login:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.LoginSuccess:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Version:
					response = ((JToken)j).ToObject<VersionResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.GameUpdate:
					response = ((JToken)j).ToObject<GameUpdate>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Disconnect:
					response = ((JToken)j).ToObject<MessageResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.KeepAlive:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				}
			}
			catch
			{
			}
			response = null;
			return false;
		}
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum StandardErrors
	{
		Unknown = 0,
		ExceptionThrown = 1,
		BadRequest = 4096,
		EffectUnknown = 4097,
		[Obsolete("Use EffectUnknown instead.")]
		UnknownEffect = 4097,
		EffectDisabled = 4098,
		AlreadyFailed = 4099,
		CannotParseNumber = 4112,
		UnknownSelection = 4113,
		ConnectorError = 8192,
		ConnectorReadFailure = 8193,
		ConnectorWriteFailure = 8194,
		ConnectorNotConnected = 8195,
		ConnectorNotSupported = 8196,
		NoResponse = 8448,
		SettingsError = 12288,
		CooldownPerEffect = 12545,
		CooldownGlobal = 12546,
		RetryMaxTime = 12291,
		RetryMaxAttempts = 12292,
		NoSession = 20480,
		SessionEnding = 20481,
		BadGameState = 16384,
		GameObjectNotFound = 16640,
		PlayerNotFound = 16641,
		CharacterNotFound = 16642,
		EnemyNotFound = 16643,
		ObjectNotFound = 16644,
		PrerequisiteNotFound = 16645,
		ObjectStateError = 16896,
		AlreadyInState = 16897,
		AlreadyAcquired = 16898,
		AlreadyFinished = 16899,
		NoEmptyContainers = 16912,
		PartyFull = 16913,
		InvalidArea = 16928,
		InvalidTarget = 16929,
		NoValidTargets = 16930,
		SpawnNotAllowedHere = 16932,
		RangeError = 17152,
		AlreadyMinimum = 17153,
		AlreadyMaximum = 17154,
		EffectNotImplemented = 24576,
		PackResourceMissing = 24577,
		EmulatorNotSupported = 28672,
		EmulatorInvalidSetting = 28673,
		ConflictingEffectRunning = 32768,
		UnqueueablePending = 32769
	}
	internal static class StringEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsNullOrWhiteSpace(this string? input)
		{
			return string.IsNullOrWhiteSpace(input);
		}

		internal static string ToCamelCase(this string input)
		{
			bool flag = false;
			string text = "";
			checked
			{
				for (int i = 0; i < input.Length; i++)
				{
					if (char.IsUpper(input[i]))
					{
						if (flag)
						{
							text += input.Substring(i);
							break;
						}
						text += char.ToLower(input[i]);
					}
					else
					{
						flag = true;
						text = ((i <= 1 || !char.IsUpper(input[i - 1]) || !char.IsUpper(input[i - 2])) ? (text + input[i]) : (text.Substring(0, text.Length - 1) + char.ToUpper(input[i - 1]) + input[i]));
					}
				}
				return text;
			}
		}

		internal unsafe static string[] Chop(this string value, int chopLength)
		{
			int length = value.Length;
			char* ptr = stackalloc char[chopLength];
			string[] array = new string[length];
			for (int i = 0; i < length; i = checked(i + chopLength))
			{
				int j;
				for (j = 0; j < chopLength; j = checked(j + 1))
				{
					int num = checked(i + j);
					if (num >= length)
					{
						break;
					}
					*(char*)((byte*)ptr + checked(unchecked((nint)j) * (nint)2)) = value[num];
				}
				array[i / chopLength] = new string(ptr, 0, j);
			}
			return array;
		}
	}
	public static class TypeEx
	{
		public static bool IsAssignableTo(this Type? type, Type? targetType)
		{
			return (object)type != null && (object)targetType != null && targetType.IsAssignableFrom(type);
		}
	}
	[Serializable]
	[JsonConverter(typeof(Converter))]
	public class VersionNumber : IEquatable<VersionNumber>, IComparable<VersionNumber>
	{
		private class Converter : JsonConverter<VersionNumber>
		{
			public override void WriteJson(JsonWriter writer, VersionNumber? value, JsonSerializer serializer)
			{
				if (value == null)
				{
					writer.WriteNull();
				}
				else
				{
					writer.WriteValue((string)value);
				}
			}

			public override VersionNumber? ReadJson(JsonReader reader, Type objectType, VersionNumber? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				object value = reader.Value;
				if (value == null)
				{
					return null;
				}
				if (!(value is string value2))
				{
					return null;
				}
				return new VersionNumber(value2);
			}
		}

		public static readonly VersionNumber Zero = new VersionNumber(new Span<uint>(new uint[1]));

		public static readonly VersionNumber One = new VersionNumber(new Span<uint>(new uint[1] { 1u }));

		private readonly uint[] _version;

		public VersionNumber(string value)
		{
			_version = (from v in value.Split('.')
				select uint.TryParse(Sanitize(v), out var result) ? result : 0u).ToArray();
		}

		public VersionNumber(IEnumerable<uint> values)
		{
			_version = values.ToArray();
		}

		public VersionNumber(VersionNumber version)
		{
			_version = version._version.ToArray();
		}

		public VersionNumber([ParamCollection] scoped Span<uint> values)
		{
			_version = values.ToArray();
		}

		public static implicit operator VersionNumber(string value)
		{
			return new VersionNumber(value);
		}

		public static implicit operator VersionNumber(uint value)
		{
			return new VersionNumber(new Span<uint>(new uint[1] { value }));
		}

		public static implicit operator VersionNumber(uint[] values)
		{
			return new VersionNumber((Span<uint>)values);
		}

		public static implicit operator VersionNumber(Span<uint> values)
		{
			return new VersionNumber(values);
		}

		public static implicit operator VersionNumber(List<uint> values)
		{
			return new VersionNumber((IEnumerable<uint>)values);
		}

		public static implicit operator string(VersionNumber value)
		{
			return value.ToString();
		}

		public static implicit operator uint[](VersionNumber value)
		{
			return value._version.ToArray();
		}

		public static bool operator ==(VersionNumber? a, VersionNumber? b)
		{
			return Equals(a, b);
		}

		public static bool operator !=(VersionNumber? a, VersionNumber? b)
		{
			return !Equals(a, b);
		}

		public static bool operator <(VersionNumber? a, VersionNumber? b)
		{
			return CompareTo(a, b) < 0;
		}

		public static bool operator >(VersionNumber? a, VersionNumber? b)
		{
			return CompareTo(a, b) > 0;
		}

		public static bool operator <=(VersionNumber? a, VersionNumber? b)
		{
			return CompareTo(a, b) <= 0;
		}

		public static bool operator >=(VersionNumber? a, VersionNumber? b)
		{
			return CompareTo(a, b) >= 0;
		}

		public override string ToString()
		{
			return string.Join('.', _version.Select((uint v) => v.ToString("D")));
		}

		public static bool Equals(VersionNumber? a, VersionNumber? b)
		{
			return a?.Equals(b) ?? ((object)b == null);
		}

		public override bool Equals(object? obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (this == obj)
			{
				return true;
			}
			if (TypeEx.IsAssignableTo(obj.GetType(), typeof(VersionNumber)))
			{
				return false;
			}
			return Equals((VersionNumber)obj);
		}

		public override int GetHashCode()
		{
			return _version.GetHashCode();
		}

		public bool Equals(VersionNumber? other)
		{
			if ((object)other == null)
			{
				return false;
			}
			if ((object)this == other)
			{
				return true;
			}
			int num = _version.Length;
			if (num != other._version.Length)
			{
				return false;
			}
			for (int i = 0; i < num; i = checked(i + 1))
			{
				if (_version[i] != other._version[i])
				{
					return false;
				}
			}
			return true;
		}

		public static int CompareTo(VersionNumber? a, VersionNumber? b)
		{
			return a?.CompareTo(b) ?? (((object)b != null) ? (-1) : 0);
		}

		public int CompareTo(VersionNumber? other)
		{
			if ((object)other == null)
			{
				return 1;
			}
			int num = _version.Length;
			int num2 = other._version.Length;
			int num3 = Math.Min(num, num2);
			checked
			{
				int i;
				for (i = 0; i < num3; i++)
				{
					uint num4 = _version[i];
					uint num5 = other._version[i];
					if (num4 != num5)
					{
						if (num4 > num5)
						{
							return 1;
						}
						return -1;
					}
				}
				if (num == num2)
				{
					return 0;
				}
				if (num > num2)
				{
					for (; i < num; i++)
					{
						if (_version[i] != 0)
						{
							return 1;
						}
					}
					return 0;
				}
				for (; i < num2; i++)
				{
					if (other._version[i] != 0)
					{
						return -1;
					}
				}
				return 0;
			}
		}

		public static VersionNumber GetAssemblyVersion(IEnumerable<Assembly> assemblies)
		{
			VersionNumber versionNumber = Zero;
			foreach (Assembly assembly in assemblies)
			{
				VersionNumber versionNumber2;
				try
				{
					versionNumber2 = GetAssemblyVersion(assembly);
				}
				catch
				{
					versionNumber2 = Zero;
				}
				if (versionNumber2 > versionNumber)
				{
					versionNumber = versionNumber2;
				}
			}
			return versionNumber;
		}

		public static VersionNumber GetAssemblyVersion(Assembly assembly)
		{
			string text = null;
			object[] customAttributes = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), inherit: false);
			if (customAttributes != null && customAttributes.Length > 0)
			{
				text = ((AssemblyInformationalVersionAttribute)customAttributes[0]).InformationalVersion;
			}
			if (text == null || text.Length == 0)
			{
				text = GetFileVersionInfo(assembly).ProductVersion?.Trim();
			}
			if (text == null || text.Length == 0)
			{
				text = Zero;
			}
			return text;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static string Sanitize(string value)
		{
			for (int i = 0; i < value.Length; i = checked(i + 1))
			{
				if (!char.IsDigit(value[i]))
				{
					return value.Substring(0, i);
				}
			}
			return value;
		}

		private static FileVersionInfo GetFileVersionInfo(Assembly assembly)
		{
			return FileVersionInfo.GetVersionInfo(assembly.Location);
		}
	}
	[Serializable]
	public class VersionResponse : SimpleJSONResponse
	{
		public VersionNumber version;

		[JsonConstructor]
		public VersionResponse(VersionNumber version)
		{
			this.version = version;
			type = ResponseType.Version;
		}

		public VersionResponse(uint id, VersionNumber version)
		{
			base.id = id;
			this.version = version;
			type = ResponseType.Version;
		}
	}
}

BepInEx/plugins/CrowdControl/CrowdControl.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CMF;
using ConnectorLib.JSON;
using CrowdControl.CustomEffects;
using CrowdControl.Delegates.Effects;
using CrowdControl.Delegates.Metadata;
using CrowdControl.Harmony;
using CrowdControl.UI;
using HarmonyLib;
using HeathenEngineering.SteamworksIntegration;
using I2.Loc;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Crowd Control for TCG Card Shop Simulator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Crowd Control for TCG Card Shop Simulator")]
[assembly: AssemblyCopyright("© 2025 Warp World, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d4f6b961-e8ae-4e4b-950c-37644e42d4ca")]
[assembly: AssemblyFileVersion("1.2.4.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.4.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[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 CrowdControl
{
	[BepInPlugin("WarpWorld.CrowdControl", "Crowd Control", "1.2.4")]
	public class CrowdControlMod : BaseUnityPlugin
	{
		public class FaceCamera : MonoBehaviour
		{
			private Camera mainCamera;

			private void Start()
			{
				Transform playerCameraTransform = GetPlayerCameraTransform();
				mainCamera = ((playerCameraTransform != null) ? ((Component)playerCameraTransform).GetComponent<Camera>() : null) ?? Camera.main ?? Object.FindObjectOfType<Camera>();
			}

			private void LateUpdate()
			{
				//IL_001a: 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_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)mainCamera == (Object)null))
				{
					Vector3 val = ((Component)mainCamera).transform.position - ((Component)this).transform.position;
					val.y = 0f;
					((Vector3)(ref val)).Normalize();
					Quaternion val2 = Quaternion.LookRotation(val);
					((Component)this).transform.rotation = val2 * Quaternion.Euler(0f, 180f, 0f);
				}
			}
		}

		public class NamePlateOwner : MonoBehaviour
		{
			public GameObject namePlate;

			private void OnDisable()
			{
				if ((Object)(object)namePlate != (Object)null)
				{
					Object.Destroy((Object)(object)namePlate);
				}
				Object.Destroy((Object)(object)this);
			}

			private void OnDestroy()
			{
				if ((Object)(object)namePlate != (Object)null)
				{
					Object.Destroy((Object)(object)namePlate);
				}
			}
		}

		public class NamePlateController : MonoBehaviour
		{
			public const float HEIGHT = 1.9f;

			private Transform cameraTransform;

			public float distanceThreshold = 15f;

			public bool mimicGamePopup = true;

			public Customer customer;

			private TMP_Text tmp;

			private static bool loggedFirstFrame;

			private void Start()
			{
				cameraTransform = GetPlayerCameraTransform();
				if ((Object)(object)customer == (Object)null)
				{
					customer = ((Component)this).GetComponentInParent<Customer>();
				}
				tmp = ((Component)this).GetComponentInChildren<TMP_Text>(true);
			}

			private void LateUpdate()
			{
				//IL_0068: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0102: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0119: 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_011f: 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)
				//IL_0136: Unknown result type (might be due to invalid IL or missing references)
				//IL_013b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bb: 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_00ca: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_016e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0158: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)customer == (Object)null || !((Component)customer).gameObject.activeInHierarchy)
				{
					Object.Destroy((Object)(object)((Component)this).gameObject);
				}
				else
				{
					if (!Object.op_Implicit((Object)(object)tmp))
					{
						return;
					}
					if ((Object)(object)cameraTransform == (Object)null)
					{
						cameraTransform = GetPlayerCameraTransform();
						if ((Object)(object)cameraTransform == (Object)null)
						{
							return;
						}
					}
					float num = Vector3.Distance(cameraTransform.position, ((Component)customer).transform.position);
					bool flag = num <= distanceThreshold;
					((Behaviour)tmp).enabled = flag;
					if (flag)
					{
						if (mimicGamePopup)
						{
							((Component)this).transform.position = ((Component)customer).transform.position + Vector3.up * 1.9f;
							((Component)this).transform.LookAt(cameraTransform.position);
						}
						else
						{
							Vector3 val = cameraTransform.position - ((Component)this).transform.position;
							val.y = 0f;
							Quaternion val2 = Quaternion.LookRotation(val);
							((Component)this).transform.rotation = val2 * Quaternion.Euler(0f, 180f, 0f);
						}
						((Graphic)tmp).color = (Color)(customer.IsSmelly() ? new Color(0f, 1f, 0f) : Color.white);
					}
					if (!loggedFirstFrame)
					{
						loggedFirstFrame = true;
						ManualLogSource mls = CrowdControlMod.mls;
						if (mls != null)
						{
							mls.LogInfo((object)$"Nameplate first frame: camera '{((Object)cameraTransform).name}' at {cameraTransform.position}, customer at {((Component)customer).transform.position}, distance {num:F1} m, visible={flag}, textActive={((Behaviour)tmp).isActiveAndEnabled}, plateActive={((Component)this).gameObject.activeInHierarchy}, text='{tmp.text}'");
						}
					}
				}
			}
		}

		public const string MOD_GUID = "WarpWorld.CrowdControl";

		public const string MOD_NAME = "Crowd Control";

		public const string MOD_VERSION = "1.2.4";

		public const bool CUSTOM_EFFECTS_SUPPORTED = false;

		private readonly Harmony harmony = new Harmony("WarpWorld.CrowdControl");

		private const double MANUAL_RECONNECT_COOLDOWN_SECONDS = 5.0;

		private DateTime m_nextManualReconnectAllowedUtc = DateTime.MinValue;

		private bool m_clientPresent;

		private float m_nextClientCheck;

		private const float CLIENT_CHECK_INTERVAL = 5f;

		private Task<bool>? m_clientCheckTask;

		private string? _modVersion;

		public static bool loadedIntoWorld = false;

		public static bool ForceMath = false;

		public static bool ForceUseCash = false;

		public static bool ForceUseCredit = false;

		public static bool ExactChange = false;

		public static bool LargeBills = false;

		public static bool isSmelly = false;

		public static Vector3 oldcashScale = new Vector3(6.408165f, 41.87513f, 8.071795f);

		public static Vector3 oldcashScaleOutline = new Vector3(6.598893f, 43.12251f, 8.312037f);

		public static Vector3 oldCardScale = new Vector3(5.760878f, 7.510158f, 3.336215f);

		public static Vector3 oldCardScaleOutline = new Vector3(5.897457f, 8.062623f, 3.415312f);

		public static bool isWarehouseUnlocked = false;

		public static string NameOverride = "";

		public static string OrgLanguage = "";

		public static string NewLanguage = "";

		public static bool autoOpenActive = false;

		public static readonly ConcurrentQueue<Action> ActionQueue = new ConcurrentQueue<Action>();

		public static readonly ConcurrentQueue<Action> SpawnQueue = new ConcurrentQueue<Action>();

		private const float SpawnInterval = 0.15f;

		private static float nextSpawnTime = 0f;

		private static bool isChatConnected = false;

		private static bool isTwitchChatAllowed = true;

		private const string twitchServer = "irc.chat.twitch.tv";

		private const int twitchPort = 6667;

		private const string twitchUsername = "justinfan1337";

		public static string twitchChannel = "";

		private static TcpClient twitchTcpClient;

		private static NetworkStream twitchStream;

		private static StreamReader twitchReader;

		private static StreamWriter twitchWriter;

		private static readonly List<string> allowedUsernames = new List<string> { "jaku", "s4turn", "crowdcontrol", "theunknowncod3r" };

		public static GameObject currentTextObject = null;

		private static bool loggedNamePlateLayout = false;

		public static float DeltaTime => Time.unscaledDeltaTime;

		public ManualLogSource Logger => ((BaseUnityPlugin)this).Logger;

		internal static CrowdControlMod Instance { get; private set; } = null;

		public GameStateManager GameStateManager { get; private set; }

		public EffectLoader EffectLoader { get; private set; }

		public CustomEffectManager CustomEffects { get; private set; }

		public bool ClientConnected => Client.Connected;

		public NetworkClient Client { get; private set; }

		public Scheduler Scheduler { get; private set; }

		public string Version
		{
			get
			{
				try
				{
					if (!string.IsNullOrEmpty(_modVersion))
					{
						return _modVersion;
					}
					string text = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ccver"));
					if (string.IsNullOrEmpty(text))
					{
						_modVersion = "1.2.4";
					}
					else
					{
						_modVersion = text;
					}
					return _modVersion;
				}
				catch (Exception arg)
				{
					Logger.LogInfo((object)$"Error retrieving mod version: {arg}");
					return "0";
				}
			}
		}

		public static ManualLogSource mls => Instance?.Logger;

		private void Awake()
		{
			Instance = this;
			Logger.LogInfo((object)"Loaded WarpWorld.CrowdControl. Patching.");
			harmony.PatchAll();
			InitializeGame();
			ModSettings.Initialize(((BaseUnityPlugin)this).Config);
			Logger.LogInfo((object)"Initializing Crowd Control");
			try
			{
				GameStateManager = new GameStateManager(this);
				Client = new NetworkClient(this);
				EffectLoader = new EffectLoader(this, Client);
				Logger.LogInfo((object)$"Registered {EffectLoader.Effects.Count} effect codes.");
				Scheduler = new Scheduler(this, Client);
				CustomEffects = new CustomEffectManager(this, Client);
				CustomEffects.LoadAll();
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Crowd Control Init Error: {arg}");
			}
			Logger.LogInfo((object)"Crowd Control Initialized");
		}

		private void OnApplicationQuit()
		{
			ShutdownGame();
			try
			{
				CustomEffects?.Dispose();
				Client?.Stop();
				Client?.Dispose();
			}
			catch
			{
			}
		}

		private void OnDestroy()
		{
			try
			{
				CustomEffects?.Dispose();
				Client?.Stop();
				Client?.Dispose();
			}
			catch
			{
			}
		}

		private void Update()
		{
			if (GameStateManager != null)
			{
				GameStateManager.InvalidateStateCache();
				GameStateManager.UpdateGameState();
				Scheduler?.Tick();
				CustomEffects?.Tick();
				UpdateGame();
				UpdateClientPresence();
				HandleOverlayToggleHotkey();
				HandleManualReconnectHotkey();
			}
		}

		private void UpdateClientPresence()
		{
			if (ClientConnected)
			{
				m_clientPresent = true;
				return;
			}
			if (m_clientCheckTask != null)
			{
				if (!m_clientCheckTask.IsCompleted)
				{
					return;
				}
				m_clientPresent = m_clientCheckTask.Status == TaskStatus.RanToCompletion && m_clientCheckTask.Result;
				m_clientCheckTask = null;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < m_nextClientCheck)
			{
				return;
			}
			m_nextClientCheck = realtimeSinceStartup + 5f;
			NetworkClient client = Client;
			if (client == null)
			{
				m_clientPresent = false;
				return;
			}
			m_clientCheckTask = Task.Run(() => client.CrowdControlClientFound);
		}

		private void OnGUI()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Invalid comparison between Unknown and I4
			try
			{
				if (!loadedIntoWorld || (Object)(object)CGameManager.m_Instance == (Object)null || !CGameManager.m_Instance.m_IsGameLevel)
				{
					return;
				}
				GameStateManager gameStateManager = GameStateManager;
				GameState val = (GameState)((gameStateManager != null) ? ((int)gameStateManager.CurrentState) : 0);
				if (((int)val != -5 && (int)val != 1) || 1 == 0)
				{
					return;
				}
			}
			catch
			{
				return;
			}
			try
			{
				Overlay.Draw(ClientConnected, m_clientPresent);
			}
			catch
			{
			}
		}

		private void HandleOverlayToggleHotkey()
		{
			if (Input.GetKeyDown((KeyCode)289))
			{
				bool flag = Overlay.Toggle();
				Logger.LogInfo((object)("F8 pressed - overlay " + (flag ? "shown" : "hidden") + "."));
				if (flag)
				{
					Overlay.Show("Crowd Control display on (F8)", force: true);
				}
			}
		}

		private void HandleManualReconnectHotkey()
		{
			if (!Input.GetKeyDown((KeyCode)290))
			{
				return;
			}
			DateTime utcNow = DateTime.UtcNow;
			if (!(utcNow < m_nextManualReconnectAllowedUtc))
			{
				m_nextManualReconnectAllowedUtc = utcNow.AddSeconds(5.0);
				Logger.LogInfo((object)"F9 pressed - manual Crowd Control reconnect requested.");
				NetworkClient client = Client;
				if (client != null && client.RequestReconnect())
				{
					Overlay.Show("Reconnecting to Crowd Control...", force: true);
					Logger.LogInfo((object)"Manual Crowd Control reconnect queued.");
				}
				else
				{
					Overlay.Show("Crowd Control client not found.", force: true);
					Logger.LogInfo((object)"Manual Crowd Control reconnect skipped because the Crowd Control client was not found.");
				}
			}
		}

		public void ShowGameUiMessage(string message)
		{
			Overlay.Show(message);
			CreateChatStatusText(message);
		}

		private void OnApplicationFocus(bool hasFocus)
		{
			try
			{
				GameStateManager?.InvalidateStateCache();
				GameStateManager?.UpdateGameState();
			}
			catch
			{
			}
		}

		private void OnApplicationPause(bool isPaused)
		{
			try
			{
				GameStateManager?.InvalidateStateCache();
				GameStateManager?.UpdateGameState();
			}
			catch
			{
			}
		}

		private void InitializeGame()
		{
			CustomerManagerPatches.ApplyPatches(harmony);
		}

		private static bool IsReadyForSpawn()
		{
			if (loadedIntoWorld && (Object)(object)CSingleton<RestockManager>.Instance != (Object)null)
			{
				return (Object)(object)CSingleton<InteractionPlayerController>.Instance != (Object)null;
			}
			return false;
		}

		private void UpdateGame()
		{
			if (Input.GetKeyDown((KeyCode)287))
			{
				isTwitchChatAllowed = !isTwitchChatAllowed;
				if (isChatConnected)
				{
					DisconnectFromTwitch();
					isChatConnected = false;
				}
				string text = (isTwitchChatAllowed ? "Twitch Chat is enabled." : "Twitch Chat is disabled.");
				Logger.LogInfo((object)text);
				CreateChatStatusText(text);
			}
			Action result;
			while (ActionQueue.TryDequeue(out result))
			{
				try
				{
					result();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Crowd Control action failed: {arg}");
				}
			}
			if (!SpawnQueue.IsEmpty && Time.unscaledTime >= nextSpawnTime && IsReadyForSpawn() && SpawnQueue.TryDequeue(out var result2))
			{
				Physics.SyncTransforms();
				try
				{
					result2();
				}
				catch (Exception arg2)
				{
					Logger.LogError((object)$"Crowd Control spawn failed: {arg2}");
				}
				Physics.SyncTransforms();
				nextSpawnTime = Time.unscaledTime + 0.15f;
			}
		}

		private void ShutdownGame()
		{
			try
			{
				DisconnectFromTwitch();
			}
			catch
			{
			}
		}

		public static void CreateChatStatusText(string message)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			if (!loadedIntoWorld)
			{
				return;
			}
			if ((Object)(object)currentTextObject != (Object)null)
			{
				Object.Destroy((Object)(object)currentTextObject);
			}
			Transform playerCameraTransform = GetPlayerCameraTransform();
			Camera val = ((playerCameraTransform != null) ? ((Component)playerCameraTransform).GetComponent<Camera>() : null);
			if ((Object)(object)val == (Object)null)
			{
				val = Object.FindObjectOfType<Camera>();
			}
			if (!((Object)(object)val == (Object)null))
			{
				currentTextObject = new GameObject("ChatStatusText");
				TextMeshPro val2 = currentTextObject.AddComponent<TextMeshPro>();
				if (!ApplyGameFont((TMP_Text)(object)val2))
				{
					Object.Destroy((Object)(object)currentTextObject);
					currentTextObject = null;
					return;
				}
				((TMP_Text)val2).fontSize = 0.05f;
				((Graphic)val2).color = new Color(0.5f, 0f, 1f);
				((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
				((TMP_Text)val2).text = message;
				((TMP_Text)val2).lineSpacing = 1.2f;
				Vector3 position = val.ViewportToWorldPoint(new Vector3(0.5f, 0.6f, 0.15f));
				currentTextObject.transform.position = position;
				currentTextObject.transform.SetParent(((Component)val).transform, true);
				currentTextObject.AddComponent<FaceCamera>();
				Object.Destroy((Object)(object)currentTextObject, 3f);
			}
		}

		public static void MakeCustomerSmellyTemporarily(Customer customer, float duration)
		{
			if (!((Behaviour)customer).enabled || !customer.IsInsideShop())
			{
				return;
			}
			customer.SetSmelly();
			new Timer(delegate
			{
				ActionQueue.Enqueue(delegate
				{
					ClearSmellyStatus(customer);
				});
			}, null, checked((int)(duration * 1000f)), -1);
		}

		private static void ClearSmellyStatus(Customer customer)
		{
			customer.m_SmellyFX.SetActive(false);
			customer.m_CleanFX.SetActive(true);
			GameActions.setProperty(customer, "m_IsSmelly", false);
			CSingleton<CustomerManager>.Instance.RemoveFromSmellyCustomerList(customer);
		}

		private static bool ApplyGameFont(TMP_Text text)
		{
			try
			{
				if ((Object)(object)text.font != (Object)null && (Object)(object)((TMP_Asset)text.font).material != (Object)null && (Object)(object)text.fontSharedMaterial != (Object)null)
				{
					return true;
				}
				TMP_FontAsset gameFontAsset = GameActions.GetGameFontAsset();
				if ((Object)(object)gameFontAsset == (Object)null)
				{
					ManualLogSource obj = mls;
					if (obj != null)
					{
						obj.LogWarning((object)"No usable TextMeshPro font found in the game; skipping on-screen text.");
					}
					return false;
				}
				text.font = gameFontAsset;
				text.fontSharedMaterial = ((TMP_Asset)gameFontAsset).material;
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource obj2 = mls;
				if (obj2 != null)
				{
					obj2.LogWarning((object)("Could not assign a font to on-screen text: " + ex.Message));
				}
				return false;
			}
		}

		public static void AddNamePlateToCustomer(Customer customer)
		{
			//IL_003b: 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_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)((Component)customer).GetComponent<NamePlateOwner>() != (Object)null)
			{
				return;
			}
			string nameOverride = NameOverride;
			if (string.IsNullOrEmpty(nameOverride))
			{
				return;
			}
			Color color = (Color)(isSmelly ? new Color(0f, 1f, 0f) : Color.white);
			GameObject val = TryCloneGamePopup(customer, nameOverride, color);
			if ((Object)(object)val == (Object)null)
			{
				val = new GameObject("NamePlate");
				val.transform.SetParent(((Component)customer).transform);
				val.transform.localPosition = Vector3.up * 1.9f;
				val.transform.localRotation = Quaternion.identity;
				TextMeshPro val2 = val.AddComponent<TextMeshPro>();
				if (!ApplyGameFont((TMP_Text)(object)val2))
				{
					Object.Destroy((Object)(object)val);
					return;
				}
				((Behaviour)val2).enabled = true;
				((TMP_Text)val2).richText = false;
				((TMP_Text)val2).fontStyle = (FontStyles)1;
				((TMP_Text)val2).text = nameOverride;
				((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
				((TMP_Text)val2).fontSize = 1f;
				try
				{
					((TMP_Text)val2).fontMaterial.EnableKeyword("OUTLINE_ON");
					((TMP_Text)val2).outlineColor = Color32.op_Implicit(Color.black);
					((TMP_Text)val2).outlineWidth = 0.2f;
				}
				catch (Exception ex)
				{
					ManualLogSource obj = mls;
					if (obj != null)
					{
						obj.LogDebug((object)("Nameplate outline not applied: " + ex.Message));
					}
				}
				((Graphic)val2).color = color;
				NamePlateController namePlateController = val.AddComponent<NamePlateController>();
				namePlateController.mimicGamePopup = false;
				namePlateController.customer = customer;
				((Component)customer).gameObject.AddComponent<NamePlateOwner>().namePlate = val;
				ManualLogSource obj2 = mls;
				if (obj2 != null)
				{
					string[] obj3 = new string[7] { "Nameplate '", nameOverride, "' attached to customer (fallback 3D text, font '", null, null, null, null };
					TMP_FontAsset font = ((TMP_Text)val2).font;
					obj3[3] = ((font != null) ? ((Object)font).name : null);
					obj3[4] = "', shader '";
					Material fontSharedMaterial = ((TMP_Text)val2).fontSharedMaterial;
					object obj4;
					if (fontSharedMaterial == null)
					{
						obj4 = null;
					}
					else
					{
						Shader shader = fontSharedMaterial.shader;
						obj4 = ((shader != null) ? ((Object)shader).name : null);
					}
					obj3[5] = (string)obj4;
					obj3[6] = "').";
					obj2.LogInfo((object)string.Concat(obj3));
				}
			}
			else
			{
				NamePlateController namePlateController2 = val.AddComponent<NamePlateController>();
				namePlateController2.mimicGamePopup = true;
				namePlateController2.customer = customer;
				((Component)customer).gameObject.AddComponent<NamePlateOwner>().namePlate = val;
				ManualLogSource obj5 = mls;
				if (obj5 != null)
				{
					obj5.LogInfo((object)("Nameplate '" + nameOverride + "' attached to customer."));
				}
			}
		}

		private static GameObject TryCloneGamePopup(Customer customer, string chatterName, Color color)
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PricePopupSpawner instance = CSingleton<PricePopupSpawner>.Instance;
				PricePopupUI val = null;
				if ((Object)(object)instance != (Object)null && instance.m_PricePopupList != null)
				{
					foreach (PricePopupUI pricePopup in instance.m_PricePopupList)
					{
						if ((Object)(object)pricePopup != (Object)null && (Object)(object)pricePopup.m_Text != (Object)null)
						{
							val = pricePopup;
							break;
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)val).transform.parent, false);
				((Object)val2).name = "NamePlate";
				val2.SetActive(false);
				val2.transform.localScale = ((Component)val).transform.localScale;
				MonoBehaviour[] componentsInChildren = val2.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val3 in componentsInChildren)
				{
					if (!(val3 is TMP_Text))
					{
						Object.DestroyImmediate((Object)(object)val3);
					}
				}
				Animator[] componentsInChildren2 = val2.GetComponentsInChildren<Animator>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
				}
				Animation[] componentsInChildren3 = val2.GetComponentsInChildren<Animation>(true);
				for (int i = 0; i < componentsInChildren3.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
				}
				CanvasGroup[] componentsInChildren4 = val2.GetComponentsInChildren<CanvasGroup>(true);
				foreach (CanvasGroup obj in componentsInChildren4)
				{
					obj.alpha = 1f;
					((Behaviour)obj).enabled = true;
				}
				TMP_Text componentInChildren = val2.GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)componentInChildren == (Object)null)
				{
					Object.Destroy((Object)(object)val2);
					return null;
				}
				componentInChildren.richText = false;
				componentInChildren.fontStyle = (FontStyles)(componentInChildren.fontStyle | 1);
				componentInChildren.text = chatterName;
				((Graphic)componentInChildren).color = color;
				((Behaviour)componentInChildren).enabled = true;
				val2.transform.position = ((Component)customer).transform.position + Vector3.up * 1.9f;
				val2.SetActive(true);
				if (!loggedNamePlateLayout)
				{
					loggedNamePlateLayout = true;
					string text = string.Join(", ", (from c in val2.GetComponentsInChildren<Component>(true)
						select ((object)c).GetType().Name).Distinct());
					ManualLogSource obj2 = mls;
					if (obj2 != null)
					{
						object[] obj3 = new object[7]
						{
							((Object)val).name,
							null,
							null,
							null,
							null,
							null,
							null
						};
						Transform parent = ((Component)val).transform.parent;
						obj3[1] = ((parent != null) ? ((Object)parent).name : null);
						obj3[2] = val2.transform.lossyScale;
						obj3[3] = val2.layer;
						TMP_FontAsset font = componentInChildren.font;
						obj3[4] = ((font != null) ? ((Object)font).name : null);
						Material fontSharedMaterial = componentInChildren.fontSharedMaterial;
						object obj4;
						if (fontSharedMaterial == null)
						{
							obj4 = null;
						}
						else
						{
							Shader shader = fontSharedMaterial.shader;
							obj4 = ((shader != null) ? ((Object)shader).name : null);
						}
						obj3[5] = obj4;
						obj3[6] = text;
						obj2.LogInfo((object)string.Format("Nameplate cloned from popup '{0}' (parent '{1}'): lossyScale={2}, layer={3}, font='{4}', shader='{5}', components=[{6}]", obj3));
					}
				}
				return val2;
			}
			catch (Exception ex)
			{
				ManualLogSource obj5 = mls;
				if (obj5 != null)
				{
					obj5.LogWarning((object)("Could not clone a game popup for the nameplate, using fallback text: " + ex.Message));
				}
				return null;
			}
		}

		public static Transform GetPlayerCameraTransform()
		{
			try
			{
				PricePopupSpawner instance = CSingleton<PricePopupSpawner>.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.m_Cam != (Object)null)
				{
					return instance.m_Cam;
				}
			}
			catch
			{
			}
			Camera val = Camera.main;
			if ((Object)(object)val == (Object)null)
			{
				val = Object.FindObjectOfType<Camera>();
			}
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return ((Component)val).transform;
		}

		public static void SetTwitchChannel(string channel, string source)
		{
			channel = (channel ?? "").Trim().TrimStart('#').ToLowerInvariant();
			if (channel.Length != 0 && !(twitchChannel == channel) && (twitchChannel.Length <= 0 || !isChatConnected))
			{
				twitchChannel = channel;
				ManualLogSource obj = mls;
				if (obj != null)
				{
					obj.LogInfo((object)("Twitch channel set to '" + channel + "' (from " + source + ")."));
				}
			}
		}

		public static void ConnectToTwitchChat()
		{
			if (isTwitchChatAllowed)
			{
				if (twitchChannel.Length == 0)
				{
					SetTwitchChannel(ModSettings.TwitchChannel, "config");
				}
				if (!isChatConnected && twitchChannel.Length >= 1)
				{
					Thread thread = new Thread(StartTwitchChatListener);
					thread.IsBackground = true;
					thread.Name = "CrowdControl-TwitchChat";
					thread.Start();
					isChatConnected = true;
				}
			}
		}

		public static void StartTwitchChatListener()
		{
			try
			{
				twitchTcpClient = new TcpClient("irc.chat.twitch.tv", 6667);
				twitchStream = twitchTcpClient.GetStream();
				twitchReader = new StreamReader(twitchStream);
				twitchWriter = new StreamWriter(twitchStream);
				twitchWriter.WriteLine("CAP REQ :twitch.tv/membership twitch.tv/tags");
				twitchWriter.WriteLine("NICK justinfan1337");
				twitchWriter.WriteLine("JOIN #" + twitchChannel);
				twitchWriter.Flush();
				mls.LogInfo((object)("Connected to Twitch channel: " + twitchChannel));
				while (true)
				{
					if (twitchStream.DataAvailable)
					{
						string text = twitchReader.ReadLine();
						if (text != null)
						{
							if (text.StartsWith("PING"))
							{
								twitchWriter.WriteLine("PONG :tmi.twitch.tv");
								twitchWriter.Flush();
							}
							else if (text.Contains("PRIVMSG"))
							{
								string[] array = text.Split(new char[1] { ' ' }, 4);
								if (array.Length >= 4)
								{
									string text2 = array[1];
									string username = text2.Substring(1, checked(text2.IndexOf('!') - 1));
									if (text.IndexOf("PRIVMSG") >= 0)
									{
										string chatMessage = array[3].Substring(1);
										string[] array2 = chatMessage.Split(new string[1] { " :" }, 2, StringSplitOptions.None);
										chatMessage = array2[1];
										HashSet<string> hashSet = ParseBadges(array[0]);
										string value = "";
										if (hashSet.Contains("broadcaster"))
										{
											value = "[BROADCASTER]";
										}
										else if (hashSet.Contains("moderator"))
										{
											value = "[MODERATOR]";
										}
										else if (hashSet.Contains("vip"))
										{
											value = "[VIP]";
										}
										else if (hashSet.Contains("subscriber"))
										{
											value = "[SUBSCRIBER]";
										}
										string[] triggerWords = new string[8] { "fart", "gas", "burp", "smell", "shit", "poo", "stank", "nasty" };
										if (!string.IsNullOrEmpty(value) || allowedUsernames.Any((string name) => name.ToLower().Equals(username, StringComparison.OrdinalIgnoreCase)))
										{
											ActionQueue.Enqueue(delegate
											{
												try
												{
													List<Customer> customerList = CSingleton<CustomerManager>.Instance.GetCustomerList();
													if (customerList != null && customerList.Count >= 1)
													{
														foreach (Customer item in customerList)
														{
															if (((Behaviour)item).isActiveAndEnabled && ((Object)item).name.ToLower() == username.ToLower())
															{
																string lowerChatMessage = chatMessage.ToLower();
																if (triggerWords.Any((string word) => lowerChatMessage.Contains(word)) && !item.IsSmelly())
																{
																	MakeCustomerSmellyTemporarily(item, 5f);
																}
																CSingleton<PricePopupSpawner>.Instance.ShowTextPopup(EffectRequestEx.SanitizeDisplayName(chatMessage), 1.8f, ((Component)item).transform);
															}
														}
														return;
													}
												}
												catch
												{
												}
											});
										}
									}
								}
							}
						}
					}
					Thread.Sleep(50);
				}
			}
			catch (Exception ex) when (ex is ObjectDisposedException || ex is IOException || ex is SocketException)
			{
				ManualLogSource obj = mls;
				if (obj != null)
				{
					obj.LogInfo((object)"Twitch chat listener stopped.");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource obj2 = mls;
				if (obj2 != null)
				{
					obj2.LogInfo((object)$"Twitch Chat Listener Error: {arg}");
				}
			}
		}

		public static void DisconnectFromTwitch()
		{
			try
			{
				if (twitchWriter != null && twitchChannel.Length >= 1)
				{
					twitchWriter.WriteLine("PART #" + twitchChannel);
					twitchWriter.Flush();
					twitchWriter.Close();
				}
				twitchReader?.Close();
				twitchStream?.Close();
				twitchTcpClient?.Close();
				ManualLogSource obj = mls;
				if (obj != null)
				{
					obj.LogInfo((object)"Disconnected from Twitch chat.");
				}
			}
			catch (Exception ex)
			{
				ManualLogSource obj2 = mls;
				if (obj2 != null)
				{
					obj2.LogError((object)("Error disconnecting from Twitch: " + ex.Message));
				}
			}
		}

		public static HashSet<string> ParseBadges(string tagsPart)
		{
			HashSet<string> hashSet = new HashSet<string>();
			string[] array = tagsPart.Split(';');
			foreach (string text in array)
			{
				if (text.StartsWith("badges="))
				{
					string[] array2 = text.Substring("badges=".Length).Split(',');
					for (int j = 0; j < array2.Length; j++)
					{
						string item = array2[j].Split('/')[0];
						hashSet.Add(item);
					}
				}
			}
			return hashSet;
		}
	}
	public class DelimitedStreamReader(NetworkStream stream) : IDisposable
	{
		private readonly MemoryStream _memory_stream = new MemoryStream();

		private const int MAX_MESSAGE_SIZE = 1048576;

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

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposing)
			{
				return;
			}
			try
			{
				_memory_stream.Dispose();
			}
			catch
			{
			}
		}

		public string ReadUntilNullTerminator()
		{
			int num;
			while ((num = stream.ReadByte()) != -1 && num != 0)
			{
				if (_memory_stream.Length >= 1048576)
				{
					_memory_stream.SetLength(0L);
					throw new InvalidDataException("Message exceeded the maximum allowed size without a null terminator. Dropping the connection.");
				}
				_memory_stream.WriteByte(checked((byte)num));
			}
			if (num == -1)
			{
				throw new EndOfStreamException("Reached end of stream without finding a null terminator.");
			}
			string result = Encoding.UTF8.GetString(_memory_stream.ToArray());
			_memory_stream.SetLength(0L);
			return result;
		}
	}
	public static class EffectRequestEx
	{
		public const string DEFAULT_VIEWER_NAME = "the crowd";

		public const int MAX_VIEWER_NAME_LENGTH = 32;

		public static string GetViewerDisplayName(this EffectRequest request, string fallback = "the crowd")
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Invalid comparison between Unknown and I4
			string text = request.viewer;
			if (string.IsNullOrWhiteSpace(text) && request.viewers != null)
			{
				foreach (JToken viewer in request.viewers)
				{
					JToken obj = ((viewer is JObject) ? viewer : null);
					string text2 = ((obj != null) ? obj.Value<string>((object)"name") : null);
					if (text2 == null)
					{
						string text3 = (((int)viewer.Type != 8) ? null : Extensions.Value<string>((IEnumerable<JToken>)viewer));
						text2 = text3;
					}
					text = text2;
					if (!string.IsNullOrWhiteSpace(text))
					{
						break;
					}
				}
			}
			string text4 = SanitizeDisplayName(text);
			if (text4.Length <= 0)
			{
				return fallback;
			}
			return text4;
		}

		public static string SanitizeDisplayName(string? name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder(Math.Min(name.Length, 32));
			bool flag = true;
			foreach (char c in name)
			{
				if (char.IsControl(c) || char.IsSurrogate(c) || ((c == '<' || c == '>') ? true : false))
				{
					continue;
				}
				if (char.IsWhiteSpace(c))
				{
					if (flag)
					{
						continue;
					}
					stringBuilder.Append(' ');
					flag = true;
				}
				else
				{
					stringBuilder.Append(c);
					flag = false;
				}
				if (stringBuilder.Length >= 32)
				{
					break;
				}
			}
			return stringBuilder.ToString().TrimEnd();
		}
	}
	public class GameActions
	{
		public class InteractableObject2 : MonoBehaviour
		{
			private static InteractableObject2 currentlyHeldObject;

			private string debugLabel = "Food";

			private bool isHeld;

			private Camera playerCameraComponent;

			private Transform playerCamera;

			private Color originalColor;

			private Renderer renderer;

			private Transform playerTransform;

			private float maxPickupDistance = 5f;

			private float moveSpeed = 5f;

			private bool isHovered;

			private float interactionDelay = 1f;

			private bool isHoldingObject;

			private Vector3 relativePositionToCamera;

			private float heightOffset = 0.5f;

			public void SetDebugLabel(string label)
			{
				if (!string.IsNullOrEmpty(label))
				{
					debugLabel = label;
				}
			}

			private bool RefreshPlayerCamera()
			{
				playerCameraComponent = CSingleton<InteractionPlayerController>.Instance.m_Cam ?? Camera.main ?? Object.FindObjectOfType<Camera>();
				if ((Object)(object)playerCameraComponent == (Object)null)
				{
					playerCamera = null;
					return false;
				}
				playerCamera = ((Component)playerCameraComponent).transform;
				return true;
			}

			private void Start()
			{
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				playerTransform = ((Component)CSingleton<InteractionPlayerController>.Instance.m_WalkerCtrl).transform;
				if (!RefreshPlayerCamera())
				{
					LogError(debugLabel + " interactable failed to initialize because no gameplay camera was found.");
					return;
				}
				int num = ((Component)this).GetComponentsInChildren<Collider>(true).Length;
				int num2 = ((Component)this).GetComponentsInChildren<Rigidbody>(true).Length;
				int num3 = ((Component)this).GetComponentsInChildren<AudioSource>(true).Length;
				LogInfo($"{debugLabel} interactable initialized on '{((Object)((Component)this).gameObject).name}' at {((Component)this).transform.position}. colliders={num}, rigidbodies={num2}, childCount={((Component)this).transform.childCount}, audioSources={num3}");
				if (num2 == 0)
				{
					LogWarning(debugLabel + " interactable has no rigidbody; TryPickupObjectUnderMouse may never see it.");
				}
			}

			private void OnGUI()
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Unknown result type (might be due to invalid IL or missing references)
				if (isHeld)
				{
					GUIStyle val = new GUIStyle();
					val.fontSize = 24;
					val.normal.textColor = Color.white;
					val.alignment = (TextAnchor)4;
					val.richText = true;
					string text = "Press F to Drop\nPress E to Eat";
					float num = 300f;
					float num2 = 100f;
					float num3 = ((float)Screen.width - num) / 2f;
					float num4 = (float)Screen.height - num2 - 20f;
					GUI.Label(new Rect(num3, num4, num, num2), text, val);
				}
			}

			private void Update()
			{
				if (isHeld)
				{
					SmoothlyHoldObjectInFront();
					if (Input.GetKeyDown((KeyCode)102))
					{
						ThrowObject();
						isHoldingObject = false;
					}
					if (Input.GetKeyDown((KeyCode)101))
					{
						EatObject();
						isHoldingObject = false;
					}
				}
				else if (Input.GetMouseButtonDown(0) && (Object)(object)currentlyHeldObject == (Object)null)
				{
					TryPickupObjectUnderMouse();
				}
			}

			private void SmoothlyHoldObjectInFront()
			{
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: 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)
				//IL_00e0: 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_0030: 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_003a: 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_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_016f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0174: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0102: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0111: Unknown result type (might be due to invalid IL or missing references)
				//IL_0145: Unknown result type (might be due to invalid IL or missing references)
				Transform transform = ((Component)CSingleton<InteractionPlayerController>.Instance.m_WalkerCtrl).transform;
				Transform transform2 = ((Component)CSingleton<InteractionPlayerController>.Instance.m_CameraController).transform;
				if (isHoldingObject)
				{
					Vector3 position = transform2.position + transform2.TransformDirection(relativePositionToCamera);
					((Component)this).transform.position = position;
					((Component)this).transform.rotation = Quaternion.LookRotation(transform2.forward);
					return;
				}
				Vector3 val = transform.position + transform2.forward * 0.7f + transform2.right * 0.5f;
				val.y = transform.position.y + heightOffset;
				((Component)this).transform.position = Vector3.MoveTowards(((Component)this).transform.position, val, moveSpeed * Time.deltaTime);
				if (Vector3.Distance(((Component)this).transform.position, val) < 0.01f)
				{
					isHoldingObject = true;
					relativePositionToCamera = transform2.InverseTransformDirection(((Component)this).transform.position - transform2.position);
					float num = (float)Random.Range(0, 4) * 90f;
					if (((Component)this).transform.childCount > 0)
					{
						((Component)((Component)this).transform.GetChild(0)).transform.Rotate(Vector3.up, num);
					}
					else
					{
						LogWarning(debugLabel + " hold animation skipped child rotation because the instance has no children.");
					}
				}
				((Component)this).transform.rotation = Quaternion.LookRotation(transform2.forward);
			}

			private void TryPickupObjectUnderMouse()
			{
				//IL_0024: 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_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				if (!RefreshPlayerCamera())
				{
					LogError(debugLabel + " pickup failed because the gameplay camera is null.");
					return;
				}
				RaycastHit[] array = Physics.RaycastAll(playerCameraComponent.ScreenPointToRay(Input.mousePosition), maxPickupDistance);
				bool flag = false;
				RaycastHit[] array2 = array;
				for (int i = 0; i < array2.Length; i++)
				{
					RaycastHit val = array2[i];
					if (!((Object)(object)((RaycastHit)(ref val)).collider == (Object)null) && (Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<InteractableObject2>() == (Object)(object)this)
					{
						flag = true;
						LogInfo($"{debugLabel} pickup matched collider '{((Object)((RaycastHit)(ref val)).collider).name}' at distance {((RaycastHit)(ref val)).distance:F3}.");
						break;
					}
				}
				if (flag)
				{
					LogInfo(debugLabel + " pickup raycast matched spawned object.");
					PickUpObject();
				}
				else if (array.Length != 0)
				{
					LogWarning($"{debugLabel} pickup raycast hit {array.Length} collider(s), but none resolved back to this object's rigidbody.");
				}
			}

			private void PickUpObject()
			{
				isHeld = true;
				currentlyHeldObject = this;
				LogInfo(debugLabel + " picked up.");
			}

			private void ReleaseObject()
			{
				isHeld = false;
				currentlyHeldObject = null;
				LogInfo(debugLabel + " released.");
				((MonoBehaviour)this).StartCoroutine(IgnorePlayerCollisionTemporarily());
			}

			private void ThrowObject()
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				_ = playerCamera.forward * 10f;
				ReleaseObject();
			}

			private void EatObject()
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				LogInfo(debugLabel + " eat started.");
				((Component)this).transform.rotation = Quaternion.LookRotation(playerCamera.forward);
				((Component)this).transform.Rotate(Vector3.right, 90f);
				((MonoBehaviour)this).StartCoroutine(EatAndDestroy());
			}

			private IEnumerator EatAndDestroy()
			{
				float elapsedTime = 0f;
				float duration = 1f;
				Vector3 initialPosition = ((Component)this).transform.position;
				AudioSource val = null;
				if (((Component)this).transform.childCount > 0)
				{
					val = ((Component)((Component)this).transform.GetChild(0)).GetComponent<AudioSource>();
				}
				else
				{
					LogWarning(debugLabel + " eat animation has no child transform for audio lookup.");
				}
				if ((Object)(object)val != (Object)null)
				{
					val.Play();
				}
				else
				{
					LogWarning(debugLabel + " eat animation did not find an AudioSource.");
				}
				while (elapsedTime < duration)
				{
					((Component)this).transform.position = Vector3.Lerp(initialPosition, playerCamera.position + playerCamera.forward * 0.5f, elapsedTime / duration);
					((Component)this).transform.localScale = new Vector3(((Component)this).transform.localScale.x, ((Component)this).transform.localScale.y * 0.95f, ((Component)this).transform.localScale.z);
					elapsedTime += Time.deltaTime;
					yield return null;
				}
				LogInfo(debugLabel + " eat finished. Destroying spawned object.");
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}

			private IEnumerator IgnorePlayerCollisionTemporarily()
			{
				if ((Object)(object)((Component)playerTransform).GetComponent<Collider>() != (Object)null)
				{
					yield return (object)new WaitForSeconds(interactionDelay);
				}
			}
		}

		public static Random rnd = new Random();

		public static int maxBoxCount = 100;

		private const string FoodBundleName = "food";

		private const string FoodBundleMilkAssetName = "MilkGroup";

		private const string FoodBundleBreadAssetName = "BreadGroup";

		private const string HypeTrainBundleName = "warpworld.hypetrain";

		private const string HypeTrainAssetName = "HypeTrain";

		public AssetBundle bundle;

		private static GameObject breadPrefab;

		private static GameObject milkPrefab;

		private static GameObject trainPrefab;

		private static GameObject hypetrainPrefab;

		private static bool loaded = false;

		private static TMP_FontAsset fallbackFontAsset;

		private static bool loggedUnknownTargets = false;

		private static readonly FieldInfo cardOpeningScreenActiveField = typeof(CardOpeningSequence).GetField("m_IsScreenActive", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo cardOpeningReadyingField = typeof(CardOpeningSequence).GetField("m_IsReadyingToOpen", BindingFlags.Instance | BindingFlags.NonPublic);

		private static void LogInfo(string message)
		{
			ManualLogSource mls = CrowdControlMod.mls;
			if (mls != null)
			{
				mls.LogInfo((object)("[GameActions] " + message));
			}
		}

		private static void LogWarning(string message)
		{
			ManualLogSource mls = CrowdControlMod.mls;
			if (mls != null)
			{
				mls.LogWarning((object)("[GameActions] " + message));
			}
		}

		private static void LogError(string message)
		{
			ManualLogSource mls = CrowdControlMod.mls;
			if (mls != null)
			{
				mls.LogError((object)("[GameActions] " + message));
			}
		}

		private static string DescribePrefab(GameObject prefab)
		{
			if ((Object)(object)prefab == (Object)null)
			{
				return "null prefab";
			}
			int num = prefab.GetComponentsInChildren<Collider>(true).Length;
			int num2 = prefab.GetComponentsInChildren<Rigidbody>(true).Length;
			int num3 = prefab.GetComponentsInChildren<Renderer>(true).Length;
			int num4 = prefab.GetComponentsInChildren<AudioSource>(true).Length;
			return $"{((Object)prefab).name} | children={prefab.transform.childCount}, colliders={num}, rigidbodies={num2}, renderers={num3}, audioSources={num4}";
		}

		private static void ValidateFoodPrefab(string label, GameObject prefab)
		{
			if ((Object)(object)prefab == (Object)null)
			{
				LogError(label + " prefab is null after bundle load.");
				return;
			}
			Collider[] componentsInChildren = prefab.GetComponentsInChildren<Collider>(true);
			Rigidbody[] componentsInChildren2 = prefab.GetComponentsInChildren<Rigidbody>(true);
			LogInfo(label + " prefab loaded: " + DescribePrefab(prefab));
			if (componentsInChildren.Length == 0)
			{
				LogWarning(label + " prefab has no colliders. Mouse pickup raycasts will never hit it.");
			}
			if (componentsInChildren2.Length == 0)
			{
				LogWarning(label + " prefab has no rigidbody. Current pickup code expects RaycastHit.rigidbody.");
			}
			if (prefab.transform.childCount == 0)
			{
				LogWarning(label + " prefab has no child transforms. Hold/eat animation code currently expects child index 0.");
			}
		}

		private static void ValidateSpawnedFoodInstance(string label, GameObject instance)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance == (Object)null)
			{
				LogError(label + " instance is null right after instantiate.");
				return;
			}
			Collider[] componentsInChildren = instance.GetComponentsInChildren<Collider>(true);
			Rigidbody[] componentsInChildren2 = instance.GetComponentsInChildren<Rigidbody>(true);
			AudioSource[] componentsInChildren3 = instance.GetComponentsInChildren<AudioSource>(true);
			LogInfo($"{label} spawned at {instance.transform.position}: {DescribePrefab(instance)}");
			if (componentsInChildren.Length == 0)
			{
				LogWarning(label + " instance has no colliders.");
			}
			if (componentsInChildren2.Length == 0)
			{
				LogWarning(label + " instance has no rigidbody; pickup will likely fail.");
			}
			if (componentsInChildren3.Length == 0)
			{
				LogWarning(label + " instance has no AudioSource. Eat SFX will be skipped.");
			}
		}

		public void LoadAssetsFromBundle()
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			if (loaded && (Object)(object)breadPrefab != (Object)null && (Object)(object)milkPrefab != (Object)null && (Object)(object)hypetrainPrefab != (Object)null)
			{
				return;
			}
			if (loaded)
			{
				LogWarning("Asset load was previously marked complete, but one or more cached prefabs are missing. Re-loading bundles.");
				loaded = false;
			}
			string path = Path.Combine(Paths.PluginPath, "CrowdControl");
			string text = Path.Combine(path, "food");
			string text2 = Path.Combine(path, "warpworld.hypetrain");
			LogInfo($"Loading food bundle from '{text}' (exists={File.Exists(text)})");
			bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)bundle == (Object)null)
			{
				LogError("Failed to load food AssetBundle from '" + text + "'.");
				return;
			}
			LogInfo($"Loaded food bundle '{((Object)bundle).name}' with {bundle.GetAllAssetNames().Length} assets.");
			milkPrefab = bundle.LoadAsset<GameObject>("MilkGroup");
			breadPrefab = bundle.LoadAsset<GameObject>("BreadGroup");
			ValidateFoodPrefab("Milk", milkPrefab);
			ValidateFoodPrefab("Bread", breadPrefab);
			new HypeTrainBoxData();
			LogInfo($"Loading HypeTrain bundle from '{text2}' (exists={File.Exists(text2)})");
			bundle = AssetBundle.LoadFromFile(text2);
			if ((Object)(object)bundle == (Object)null)
			{
				LogError("Failed to load HypeTrain AssetBundle from '" + text2 + "'.");
				return;
			}
			hypetrainPrefab = bundle.LoadAsset<GameObject>("HypeTrain");
			if ((Object)(object)hypetrainPrefab == (Object)null)
			{
				LogError("HypeTrain prefab not found in AssetBundle.");
			}
			else
			{
				LogInfo("HypeTrain prefab loaded: " + DescribePrefab(hypetrainPrefab));
			}
			loaded = true;
			LogInfo("Asset bundle load completed.");
		}

		public static Color ConvertUserNameToColor(string userName)
		{
			//IL_003a: 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)
			using SHA256 sHA = SHA256.Create();
			byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(userName));
			float num = (float)(int)array[0] / 255f;
			float num2 = (float)(int)array[1] / 255f;
			float num3 = (float)(int)array[2] / 255f;
			return new Color(num, num2, num3);
		}

		public static TMP_FontAsset GetGameFontAsset()
		{
			if ((Object)(object)fallbackFontAsset != (Object)null && (Object)(object)((TMP_Asset)fallbackFontAsset).material != (Object)null)
			{
				return fallbackFontAsset;
			}
			TMP_FontAsset val = TMP_Settings.defaultFontAsset;
			if ((Object)(object)val == (Object)null || (Object)(object)((TMP_Asset)val).material == (Object)null)
			{
				val = null;
				TMP_Text[] array = Object.FindObjectsOfType<TMP_Text>(true);
				foreach (TMP_Text val2 in array)
				{
					if ((Object)(object)val2.font != (Object)null && (Object)(object)((TMP_Asset)val2.font).material != (Object)null)
					{
						val = val2.font;
						break;
					}
				}
			}
			fallbackFontAsset = val;
			return fallbackFontAsset;
		}

		public static void FixBundleTextFonts(GameObject instance, string label)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			try
			{
				TMP_Text[] componentsInChildren = instance.GetComponentsInChildren<TMP_Text>(true);
				int num = 0;
				TMP_Text[] array = componentsInChildren;
				foreach (TMP_Text val in array)
				{
					if ((Object)(object)val.font == (Object)null || (Object)(object)((TMP_Asset)val.font).material == (Object)null || (Object)(object)val.fontSharedMaterial == (Object)null)
					{
						TMP_FontAsset gameFontAsset = GetGameFontAsset();
						if ((Object)(object)gameFontAsset == (Object)null)
						{
							LogWarning(label + ": text '" + ((Object)val).name + "' has a broken font asset and no game font was found to replace it. Disabling the text.");
							((Behaviour)val).enabled = false;
						}
						else
						{
							val.font = gameFontAsset;
							val.fontSharedMaterial = ((TMP_Asset)gameFontAsset).material;
							num = checked(num + 1);
						}
					}
				}
				if (num > 0)
				{
					object[] obj = new object[4] { label, num, componentsInChildren.Length, null };
					TMP_FontAsset gameFontAsset2 = GetGameFontAsset();
					obj[3] = ((gameFontAsset2 != null) ? ((Object)gameFontAsset2).name : null);
					LogInfo(string.Format("{0}: replaced the font on {1}/{2} text component(s) with '{3}'.", obj));
				}
			}
			catch (Exception arg)
			{
				LogError($"{label}: failed to fix text fonts: {arg}");
			}
		}

		public void Spawn_HypeTrain(Vector3 position, Quaternion rotation, HypeTrainSourceDetails sourceDetails)
		{
			//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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: 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_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: 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)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Expected O, but got Unknown
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Expected O, but got Unknown
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Expected O, but got Unknown
			if (!((Object)(object)hypetrainPrefab != (Object)null))
			{
				return;
			}
			if (sourceDetails == null || sourceDetails.TopContributions == null || sourceDetails.TopContributions.Count == 0)
			{
				CrowdControlMod.mls.LogInfo((object)"No top_contributions?");
				return;
			}
			GameObject obj = Object.Instantiate<GameObject>(hypetrainPrefab, position, rotation);
			FixBundleTextFonts(obj, "HypeTrain");
			HypeTrain component = obj.GetComponent<HypeTrain>();
			if ((Object)null == (Object)(object)component)
			{
				Debug.LogError((object)"No Train?");
				return;
			}
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(-14.5f, 0.2f, 6f);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(14.5f, 0.2f, 6f);
			Camera main = Camera.main;
			Transform val3 = ((main != null) ? ((Component)main).transform : null);
			if ((Object)(object)val3 == (Object)null)
			{
				Camera obj2 = Object.FindObjectOfType<Camera>();
				val3 = ((obj2 != null) ? ((Component)obj2).transform : null);
				if ((Object)(object)val3 == (Object)null)
				{
					return;
				}
			}
			Transform transform = ((Component)CSingleton<InteractionPlayerController>.Instance.m_WalkerCtrl).transform;
			Vector3 val4 = transform.position + val3.TransformDirection(val);
			val4.y = transform.position.y;
			Vector3 val5 = transform.position + val3.TransformDirection(val2);
			val5.y = transform.position.y;
			List<HypeTrainBoxData> list = new List<HypeTrainBoxData>();
			foreach (Contribution topContribution in sourceDetails.TopContributions)
			{
				list.Add(new HypeTrainBoxData
				{
					name = topContribution.UserName,
					box_color = ConvertUserNameToColor(topContribution.UserName),
					bit_amount = ((topContribution.Type == "bits") ? topContribution.Total : 0)
				});
			}
			if (sourceDetails.LastContribution != null)
			{
				list.Add(new HypeTrainBoxData
				{
					name = sourceDetails.LastContribution.UserName,
					box_color = ConvertUserNameToColor(sourceDetails.LastContribution.UserName),
					bit_amount = ((sourceDetails.LastContribution.Type == "bits") ? sourceDetails.LastContribution.Total : 0)
				});
			}
			float num = (float)sourceDetails.Level * 0.1f;
			float value = Mathf.Min(1f + num, 10f);
			component.StartHypeTrain(val4, val5, list.ToArray(), transform, new HypeTrainOptions
			{
				train_layer = LayerMask.NameToLayer("Obstacles"),
				max_bits_per_car = 100,
				volume = SoundManager.SFXVolume,
				distance_per_second = value
			});
		}

		public void Spawn_Bread(Vector3 position, Quaternion rotation)
		{
			//IL_0028: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)breadPrefab == (Object)null)
			{
				LogError($"Bread prefab not loaded. Spawn request at {position} cannot continue.");
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(breadPrefab, position, rotation);
			InteractableObject2 interactableObject = val.GetComponent<InteractableObject2>();
			if ((Object)(object)interactableObject == (Object)null)
			{
				interactableObject = val.AddComponent<InteractableObject2>();
			}
			interactableObject.SetDebugLabel("Bread");
			ValidateSpawnedFoodInstance("Bread", val);
		}

		public void Spawn_Milk(Vector3 position, Quaternion rotation)
		{
			//IL_0028: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)milkPrefab == (Object)null)
			{
				LogError($"Milk prefab not loaded. Spawn request at {position} cannot continue.");
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(milkPrefab, position, rotation);
			InteractableObject2 interactableObject = val.GetComponent<InteractableObject2>();
			if ((Object)(object)interactableObject == (Object)null)
			{
				interactableObject = val.AddComponent<InteractableObject2>();
			}
			interactableObject.SetDebugLabel("Milk");
			ValidateSpawnedFoodInstance("Milk", val);
		}

		public static EffectResponse ToggleLights(EffectRequest req)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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_0060: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					CSingleton<LightManager>.Instance.ToggleShopLight();
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse HeyOhh(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			List<Customer> customers = (List<Customer>)getProperty(CSingleton<CustomerManager>.Instance, "m_CustomerList");
			_ = CSingleton<CustomerManager>.Instance;
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					if (customers == null)
					{
						CrowdControlMod.mls.LogInfo((object)"Customer list not found.");
						return;
					}
					foreach (Customer item in customers)
					{
						if (((Behaviour)item).isActiveAndEnabled)
						{
							List<string> list = new List<string> { "heyooo" };
							setProperty(item, "m_IsChattyCustomer", true);
							CSingleton<PricePopupSpawner>.Instance.ShowTextPopup(list[0], 1.8f, ((Component)item).transform);
						}
					}
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		private static bool IsShopFullForSpawn()
		{
			int spawnCustomerCap = ModSettings.SpawnCustomerCap;
			if (spawnCustomerCap <= 0)
			{
				return false;
			}
			CustomerManager instance = CSingleton<CustomerManager>.Instance;
			return checked(instance.m_TotalCurrentCustomerCount - instance.m_TotalPlaytableCustomerCount - instance.m_TotalTournamentCustomerCount) >= spawnCustomerCap;
		}

		private static void ApplyTwitchChannel(EffectRequest req)
		{
			try
			{
				if (req.targets == null || ((JContainer)req.targets).Count == 0)
				{
					return;
				}
				foreach (JToken target in req.targets)
				{
					if ((((object)(((target != null) ? target[(object)"profile"] : null) ?? ((target != null) ? target[(object)"service"] : null) ?? ((target != null) ? target[(object)"type"] : null) ?? ((target != null) ? target[(object)"platform"] : null)))?.ToString() ?? "").ToLowerInvariant().Contains("twitch"))
					{
						CrowdControlMod.SetTwitchChannel(((object)(target[(object)"name"] ?? target[(object)"login"] ?? target[(object)"channel"] ?? target[(object)"displayName"]))?.ToString(), "effect request");
						return;
					}
				}
				if (!loggedUnknownTargets)
				{
					loggedUnknownTargets = true;
					ManualLogSource mls = CrowdControlMod.mls;
					if (mls != null)
					{
						mls.LogInfo((object)("Effect targets carried no Twitch channel: " + ((JToken)req.targets).ToString((Formatting)0, Array.Empty<JsonConverter>())));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource mls2 = CrowdControlMod.mls;
				if (mls2 != null)
				{
					mls2.LogDebug((object)("Could not read the Twitch channel from the request: " + ex.Message));
				}
			}
		}

		public static EffectResponse SpawnCustomer(EffectRequest req)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			CustomerManager CM = CSingleton<CustomerManager>.Instance;
			_ = CSingleton<InteractionPlayerController>.Instance;
			if (IsShopFullForSpawn())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Too Many Customers in Shop");
			}
			if (!CPlayerData.m_IsShopOpen || LightManager.GetHasDayEnded())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Store is Closed");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					ApplyTwitchChannel(req);
					string name = (CrowdControlMod.NameOverride = req.GetViewerDisplayName());
					CrowdControlMod.isSmelly = false;
					CustomerManager instance = CSingleton<CustomerManager>.Instance;
					instance.m_CustomerCountMax = checked(instance.m_CustomerCountMax + 1);
					callFunc(CSingleton<CustomerManager>.Instance, "AddCustomerPrefab", null);
					Customer newCustomer = CM.GetNewCustomer(false);
					CrowdControlMod.NameOverride = "";
					if ((Object)(object)newCustomer != (Object)null)
					{
						((Object)newCustomer).name = name;
					}
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse SpawnCustomerSmelly(EffectRequest req)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			CustomerManager CM = CSingleton<CustomerManager>.Instance;
			if (IsShopFullForSpawn())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Too Many Customers in Shop");
			}
			if (!CPlayerData.m_IsShopOpen || LightManager.GetHasDayEnded())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Store is Closed");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					ApplyTwitchChannel(req);
					string viewerDisplayName = req.GetViewerDisplayName();
					CrowdControlMod.isSmelly = true;
					CrowdControlMod.NameOverride = viewerDisplayName;
					Customer newCustomer = CM.GetNewCustomer(true);
					CrowdControlMod.NameOverride = "";
					if ((Object)(object)newCustomer != (Object)null)
					{
						newCustomer.SetSmelly();
						CSingleton<CustomerManager>.Instance.AddToSmellyCustomerList(newCustomer);
						((Object)newCustomer).name = viewerDisplayName;
					}
					CrowdControlMod.isSmelly = false;
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse HireWorker(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			bool flag = false;
			int workerCount = 0;
			Worker workerid = null;
			List<Worker> workerList = WorkerManager.GetWorkerList();
			if (!flag)
			{
				try
				{
					Worker val2 = workerList.Find((Worker x) => !x.m_IsActive);
					workerCount = workerList.IndexOf(val2);
					if ((Object)(object)val2 != (Object)null)
					{
						workerid = workerList[workerCount];
						flag = true;
					}
				}
				catch
				{
					val = (EffectStatus)3;
				}
			}
			if (!flag || (Object)(object)workerid == (Object)null)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "No Workers available");
			}
			if (flag)
			{
				try
				{
					CrowdControlMod.ActionQueue.Enqueue(delegate
					{
						//IL_0048: Unknown result type (might be due to invalid IL or missing references)
						CSingleton<WorkerManager>.Instance.ActivateWorker(workerCount, true);
						workerid.m_IsActive = true;
						((Component)workerid).gameObject.SetActive(true);
						((Component)workerid).transform.position = ((Component)CSingleton<InteractionPlayerController>.Instance.m_WalkerCtrl).transform.position;
						CPlayerData.SetIsWorkerHired(workerCount, true);
					});
				}
				catch (Exception ex)
				{
					CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
					val = (EffectStatus)3;
				}
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse FireWorker(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			bool flag = false;
			Worker workerid = null;
			int workerCount = 0;
			List<Worker> workerList = WorkerManager.GetWorkerList();
			if (!flag)
			{
				try
				{
					Worker val2 = workerList.Find((Worker x) => x.m_IsActive);
					workerCount = workerList.IndexOf(val2);
					if ((Object)(object)val2 != (Object)null && !LightManager.GetHasDayEnded())
					{
						workerid = workerList[workerCount];
						flag = true;
					}
				}
				catch
				{
					val = (EffectStatus)3;
				}
			}
			if (!flag || (Object)(object)workerid == (Object)null)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "No Workers available");
			}
			if (flag)
			{
				try
				{
					CrowdControlMod.ActionQueue.Enqueue(delegate
					{
						workerid.FireWorker();
						workerid.DeactivateWorker();
						workerid.m_IsActive = false;
						((Component)workerid).gameObject.SetActive(false);
						CPlayerData.SetIsWorkerHired(workerCount, false);
					});
				}
				catch (Exception ex)
				{
					CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
					val = (EffectStatus)3;
				}
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse LargeBills(EffectRequest req)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Invalid comparison between Unknown and I4
			CrowdControlMod.mls.LogInfo((object)"running");
			if (!CPlayerData.m_IsShopOpen || LightManager.GetHasDayEnded())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			if ((int)CSingleton<InteractionPlayerController>.Instance.m_CurrentGameState != 6)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse AllSmellyCustomers(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			if (!CPlayerData.m_IsShopOpen || LightManager.GetHasDayEnded())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			List<Customer> customers = (List<Customer>)getProperty(CSingleton<CustomerManager>.Instance, "m_CustomerList");
			CustomerManager customerManager = CSingleton<CustomerManager>.Instance;
			CrowdControlMod.mls.LogInfo((object)"Customers?");
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					if (customers == null)
					{
						CrowdControlMod.mls.LogInfo((object)"Customer list not found.");
						return;
					}
					foreach (Customer item in customers)
					{
						if (((Behaviour)item).isActiveAndEnabled)
						{
							CrowdControlMod.mls.LogInfo((object)("Customer?" + ((Object)item).name));
							customerManager.AddToSmellyCustomerList(item);
							item.SetSmelly();
						}
					}
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse TeleportPlayer(EffectRequest req)
		{
			//IL_0007: 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_0025: Invalid comparison between Unknown and I4
			//IL_0069: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			InteractionPlayerController player = CSingleton<InteractionPlayerController>.Instance;
			if ((int)player.m_CurrentGameState == 6)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Invalid comparison between Unknown and I4
					//IL_0080: Unknown result type (might be due to invalid IL or missing references)
					//IL_0096: Unknown result type (might be due to invalid IL or missing references)
					//IL_00b1: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
					//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
					//IL_0104: Unknown result type (might be due to invalid IL or missing references)
					//IL_0114: Unknown result type (might be due to invalid IL or missing references)
					if ((int)player.m_CurrentGameState == 6)
					{
						if ((bool)getProperty(player, "m_IsInUIMode"))
						{
							player.ExitUIMode();
						}
						object property = getProperty(player, "m_CurrentCashierCounter");
						InteractableCashierCounter val2 = (InteractableCashierCounter)((property is InteractableCashierCounter) ? property : null);
						if ((Object)(object)val2 != (Object)null)
						{
							((InteractableObject)val2).OnPressEsc();
						}
						else
						{
							player.OnExitCashCounterMode();
						}
					}
					Transform transform = ((Component)CSingleton<InteractionPlayerController>.Instance.m_WalkerCtrl).transform;
					CrowdControlMod.mls.LogInfo((object)$"Player POS: {transform.position}");
					Vector3 val3 = default(Vector3);
					List<Vector3> list = new List<Vector3>
					{
						new Vector3(12.81f, -0.09f, -36.44f),
						new Vector3(11.19f, -0.09f, 10.04f),
						new Vector3(12.22f, -0.09f, 0.44f)
					};
					int index = Random.Range(0, list.Count);
					val3 = list[index];
					((Component)CSingleton<InteractionPlayerController>.Instance.m_WalkerCtrl).transform.position = val3;
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse ForceMath(EffectRequest req)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			if (!CPlayerData.m_IsShopOpen || LightManager.GetHasDayEnded())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			if ((int)CSingleton<InteractionPlayerController>.Instance.m_CurrentGameState != 6)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			CrowdControlMod.ForceMath = true;
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse ForcePaymentType(EffectRequest req)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			if (!CPlayerData.m_IsShopOpen || LightManager.GetHasDayEnded())
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			if ((int)CSingleton<InteractionPlayerController>.Instance.m_CurrentGameState != 6)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, (string)null);
			}
			foreach (Customer item in (List<Customer>)getProperty(CSingleton<CustomerManager>.Instance, "m_CustomerList"))
			{
				if (((Component)item.m_CustomerCash).gameObject.activeSelf)
				{
					if (CrowdControlMod.ForceUseCredit)
					{
						item.m_CustomerCash.m_IsCard = true;
					}
					if (CrowdControlMod.ForceUseCash)
					{
						item.m_CustomerCash.m_IsCard = false;
					}
				}
			}
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse InvertX(EffectRequest req)
		{
			CrowdControlMod.mls.LogInfo((object)"running");
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse SetLanguage(EffectRequest req)
		{
			_ = CSingleton<SettingScreen>.Instance;
			string currentLanguage = LocalizationManager.CurrentLanguage;
			string text = req.code.Split('_')[1];
			string text2 = "";
			switch (text)
			{
			case "english":
				text2 = "English";
				break;
			case "french":
				text2 = "France";
				break;
			case "german":
				text2 = "Germany";
				break;
			case "italian":
				text2 = "Italian";
				break;
			case "spanish":
				text2 = "Spanish";
				break;
			case "chineset":
				text2 = "ChineseT";
				break;
			case "chineses":
				text2 = "ChineseS";
				break;
			case "korean":
				text2 = "Korean";
				break;
			}
			if (currentLanguage == text2)
			{
				return EffectResponse.Failure(((SimpleJSONMessage)req).ID, (string)null);
			}
			CrowdControlMod.NewLanguage = text2;
			CrowdControlMod.OrgLanguage = currentLanguage;
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse InvertY(EffectRequest req)
		{
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse HighFOV(EffectRequest req)
		{
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse LowFOV(EffectRequest req)
		{
			return EffectResponse.Success(((SimpleJSONMessage)req).ID, (string)null);
		}

		public static EffectResponse GiveMoney(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			int amount = 0;
			string[] array = req.code.Split('_');
			try
			{
				amount = int.Parse(array[1]);
			}
			catch
			{
				return EffectResponse.Failure(((SimpleJSONMessage)req).ID, "Player has too much money?");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					CPlayerData.m_CoinAmount += (float)amount;
					CPlayerData.m_CoinAmountDouble += (double)amount;
					CSingleton<GameUIScreen>.Instance.AddCoin((float)amount, true);
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse TakeMoney(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			int amount = 0;
			string[] array = req.code.Split('_');
			try
			{
				amount = int.Parse(array[1]);
			}
			catch
			{
				return EffectResponse.Failure(((SimpleJSONMessage)req).ID, "Player has no money to take.");
			}
			if (CPlayerData.m_CoinAmount < (float)amount)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Player doesn't have enough money to take");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					CPlayerData.m_CoinAmount -= (float)amount;
					CPlayerData.m_CoinAmountDouble -= (double)amount;
					CSingleton<GameUIScreen>.Instance.ReduceCoin((float)amount, true);
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse ShopControls(EffectRequest req)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			string[] array = req.code.Split('_');
			try
			{
				if (array[0] == "close" && CPlayerData.m_IsShopOpen)
				{
					CrowdControlMod.ActionQueue.Enqueue(delegate
					{
						CPlayerData.m_IsShopOpen = false;
						Object.FindFirstObjectByType<InteractableOpenCloseSign>().m_CloseShopMesh.SetActive(true);
						Object.FindFirstObjectByType<InteractableOpenCloseSign>().m_OpenShopMesh.SetActive(false);
						CPlayerData.m_IsShopOnceOpen = false;
					});
				}
				else if (array[0] == "open" && !CPlayerData.m_IsShopOpen)
				{
					CrowdControlMod.ActionQueue.Enqueue(delegate
					{
						CPlayerData.m_IsShopOpen = true;
						Object.FindFirstObjectByType<InteractableOpenCloseSign>().m_CloseShopMesh.SetActive(false);
						Object.FindFirstObjectByType<InteractableOpenCloseSign>().m_OpenShopMesh.SetActive(true);
						CPlayerData.m_IsShopOnceOpen = true;
					});
				}
				else if (array[0] == "renamestore")
				{
					try
					{
						TutorialManager tutorialManager = Object.FindObjectOfType<TutorialManager>();
						if ((Object)(object)tutorialManager == (Object)null)
						{
							CrowdControlMod.mls.LogInfo((object)"Failed to find Tutorial Manager..");
							return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "No Shop To Rename? What?");
						}
						if ((Object)(object)tutorialManager.m_ShopRenamer == (Object)null)
						{
							CrowdControlMod.mls.LogInfo((object)"Failed to initialize ShopRenamer.");
							return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "No Shop To Rename? What?");
						}
						CrowdControlMod.ActionQueue.Enqueue(delegate
						{
							CSingleton<InteractionPlayerController>.Instance.EnterUIMode();
							CSingleton<InteractionPlayerController>.Instance.EnterLockMoveMode();
							tutorialManager.m_ShopRenamer.OnPressGoNextButton();
							tutorialManager.m_ShopRenamer.m_SetNameInput.ActivateInputField();
						});
					}
					catch (Exception ex)
					{
						CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
						return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Failed to Rename Store");
					}
				}
			}
			catch (Exception ex2)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex2.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse UpgradeWarehouse(EffectRequest req)
		{
			//IL_0001: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			if (CPlayerData.m_UnlockWarehouseRoomCount == CSingleton<UnlockRoomManager>.Instance.m_LockedWarehouseRoomBlockerList.Count || !CPlayerData.m_IsWarehouseRoomUnlocked)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Storage is already unlocked.");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					CSingleton<UnlockRoomManager>.Instance.StartUnlockNextWarehouseRoom();
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)1;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse UpgradeStore(EffectRequest req)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			if (CPlayerData.m_UnlockRoomCount == CSingleton<UnlockRoomManager>.Instance.m_LockedRoomBlockerList.Count)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Cannot upgrade Store any more");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					CSingleton<UnlockRoomManager>.Instance.StartUnlockNextRoom();
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)1;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse UnlockWarehouse(EffectRequest req)
		{
			//IL_0001: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			if (CPlayerData.m_IsWarehouseRoomUnlocked)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Storage is already unlocked.");
			}
			try
			{
				CrowdControlMod.ActionQueue.Enqueue(delegate
				{
					CrowdControlMod.isWarehouseUnlocked = true;
					CSingleton<UnlockRoomManager>.Instance.SetUnlockWarehouseRoom(true);
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)1;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse GiveItem(EffectRequest req)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			string item = "";
			RestockData item2 = null;
			string[] array = req.code.Split('_');
			if (array.Length != 0)
			{
				try
				{
					if (array.Length == 5)
					{
						item = string.Join(" ", array[1], array[2], array[3], array[4]);
					}
					else if (array.Length == 4)
					{
						item = string.Join(" ", array[1], array[2], array[3]);
					}
					else if (array.Length == 3)
					{
						item = string.Join(" ", array[1], array[2]);
					}
					else
					{
						item = array[1];
					}
					item2 = CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_RestockDataList.Find((RestockData z) => z.name.ToLower() == item.ToLower());
				}
				catch
				{
					return EffectResponse.Failure(((SimpleJSONMessage)req).ID, "Unable to Find Item in Array.");
				}
			}
			try
			{
				if (item2 == null)
				{
					return EffectResponse.Failure(((SimpleJSONMessage)req).ID, "Unable to Find Item in Array.");
				}
				CrowdControlMod.SpawnQueue.Enqueue(delegate
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					RestockManager.SpawnPackageBoxItem(item2.itemType, item2.amount, item2.isBigBox);
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse GiveEmpty(EffectRequest req)
		{
			//IL_0007: 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_009c: 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_00a4: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			string item = "common pack (64)";
			RestockData item2 = null;
			try
			{
				item2 = CSingleton<InventoryBase>.Instance.m_StockItemData_SO.m_RestockDataList.Find((RestockData z) => z.name.ToLower() == item.ToLower());
			}
			catch
			{
				return EffectResponse.Failure(((SimpleJSONMessage)req).ID, "Unable to Find Item in Array.");
			}
			try
			{
				CrowdControlMod.SpawnQueue.Enqueue(delegate
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					RestockManager.SpawnPackageBoxItem(item2.itemType, 0, true);
				});
			}
			catch (Exception ex)
			{
				CrowdControlMod.mls.LogInfo((object)("Crowd Control Error: " + ex.ToString()));
				val = (EffectStatus)3;
			}
			return new EffectResponse(((SimpleJSONMessage)req).ID, val, text);
		}

		public static EffectResponse ThrowItem(EffectRequest req)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00ca: Expected O, but got Unknown
			EffectStatus val = (EffectStatus)0;
			string text = "";
			bool flag = (bool)getProperty(CSingleton<InteractionPlayerController>.Instance, "m_IsHoldBoxMode");
			_ = (bool)getProperty(CSingleton<InteractionPlayerController>.Instance, "m_IsMovingBoxMode");
			bool num = (bool)getProperty(CSingleton<InteractablePackagingBox>.Instance, "m_IsBeingHold");
			_ = (List<Item>)getProperty(CSingleton<InteractionPlayerController>.Instance, "m_HoldItemList");
			if (!num || !flag)
			{
				return EffectResponse.Retry(((SimpleJSONMessage)req).ID, "Player has no item in their hand");
			}
			try
			{
				CrowdControlMod.Act

BepInEx/plugins/CrowdControl/HypeTrain.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
public class HypeTrainTester : MonoBehaviour
{
	[SerializeField]
	private string[] m_names = new string[0];

	[SerializeField]
	private HypeTrain m_hypeTrainPrototype;

	[SerializeField]
	private Transform m_startTransform;

	[SerializeField]
	private Transform m_endTransform;

	[SerializeField]
	private Transform m_playerTransform;

	private HypeTrain m_createdHypeTrain;

	private void Start()
	{
		((MonoBehaviour)this).StartCoroutine(StartTest());
	}

	private IEnumerator StartTest()
	{
		yield return (object)new WaitForSeconds(0.5f);
		m_createdHypeTrain = Object.Instantiate<HypeTrain>(m_hypeTrainPrototype);
		m_createdHypeTrain.OnFinishedEvent.AddListener(new UnityAction(ResetTest));
		HypeTrainBoxData[] array = new HypeTrainBoxData[m_names.Length];
		for (int i = 0; i < m_names.Length; i++)
		{
			array[i] = new HypeTrainBoxData
			{
				name = m_names[i],
				box_color = Color.HSVToRGB(Random.value, 1f, 1f),
				box_color_rate = ((((uint)i & (true ? 1u : 0u)) != 0) ? ((Random.Range(0, 1) == 0) ? (-0.2f) : 1f) : 0f),
				bit_amount = ((i % 4 == 0) ? Random.Range(1, 1000000) : 0),
				name_color = Color.HSVToRGB(Random.value, 1f, 1f)
			};
		}
		m_createdHypeTrain.StartHypeTrain(m_startTransform.position, m_endTransform.position, array, m_playerTransform);
	}

	private void ResetTest()
	{
		if ((Object)null != (Object)(object)m_createdHypeTrain)
		{
			Object.Destroy((Object)(object)((Component)m_createdHypeTrain).gameObject);
			m_createdHypeTrain = null;
		}
		((MonoBehaviour)this).StartCoroutine(StartTest());
	}
}
public class HypeTrainBit : MonoBehaviour
{
	[SerializeField]
	private Animator m_animator;

	[SerializeField]
	private int m_bitValue;

	[SerializeField]
	private Rigidbody m_rigidbody;

	[SerializeField]
	private Collider m_collider;

	[SerializeField]
	private float m_lifeTime = 20f;

	private IEnumerator m_deathCoroutine;

	private static readonly int s_deathTrigger = Animator.StringToHash("Death");

	public int BitValue => m_bitValue;

	public Rigidbody Rigidbody => m_rigidbody;

	public Collider Collider => m_collider;

	public float LifeTime
	{
		get
		{
			return m_lifeTime;
		}
		set
		{
			m_lifeTime = value;
		}
	}

	private void Awake()
	{
		m_animator.StopPlayback();
	}

	public void StartDeathCountdown()
	{
		if (m_deathCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(m_deathCoroutine);
			m_deathCoroutine = null;
		}
		m_deathCoroutine = Death();
		((MonoBehaviour)this).StartCoroutine(m_deathCoroutine);
	}

	private IEnumerator Death()
	{
		yield return (object)new WaitForSeconds(m_lifeTime);
		m_animator.Play(s_deathTrigger, 0, 0f);
	}

	private void Kill()
	{
		Object.Destroy((Object)(object)((Component)this).gameObject);
	}
}
public class HypeTrain : MonoBehaviour
{
	[SerializeField]
	private Rigidbody m_rigidBody;

	[SerializeField]
	private HypeTrainCarAudio m_carWheelsAudio;

	[SerializeField]
	private HypeTrainLocomotive m_locomotive;

	[SerializeField]
	private HypeTrainBox m_boxPrototype;

	[SerializeField]
	private HypeTrainBitBox m_bitboxPrototype;

	[SerializeField]
	private float m_distancePerSecond = 4f;

	[SerializeField]
	private HypeTrainBit[] m_bitPrototypes = new HypeTrainBit[0];

	[SerializeField]
	private bool m_keepAliveOnFinish;

	private UnityEvent m_onFinishedEvent = new UnityEvent();

	private List<HypeTrainBox> m_activeBoxes = new List<HypeTrainBox>();

	private Queue<HypeTrainBox> m_availableBoxes = new Queue<HypeTrainBox>();

	private Queue<HypeTrainBitBox> m_availableBitBoxes = new Queue<HypeTrainBitBox>();

	private Vector3 m_startPosition = Vector3.zero;

	private Vector3 m_stopPosition = Vector3.zero;

	private Vector3 m_direction = Vector3.zero;

	private float m_trackDistance;

	private Transform m_playerRoot;

	private int m_nextBoxIndexToSpawn;

	private float m_nextBoxOffset;

	private HypeTrainBoxData[] m_boxData;

	public UnityEvent OnFinishedEvent => m_onFinishedEvent;

	private void Awake()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		m_bitPrototypes = m_bitPrototypes.OrderByDescending((HypeTrainBit bit) => bit.BitValue).ToArray();
		((Component)m_locomotive).transform.localPosition = -m_locomotive.FrontLoc.localPosition;
		((UnityEvent<HypeTrainCar, HypeTrainCar.Visibility>)m_locomotive.OnVisibilityChangedEvent).AddListener((UnityAction<HypeTrainCar, HypeTrainCar.Visibility>)OnLocomotiveFinished);
		StopHypeTrain();
		((Component)m_boxPrototype).gameObject.SetActive(false);
		((Component)m_bitboxPrototype).gameObject.SetActive(false);
	}

	private void FixedUpdate()
	{
		//IL_0019: 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_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		float num = Time.deltaTime * m_distancePerSecond;
		m_rigidBody.MovePosition(m_rigidBody.position + m_direction * num);
		m_locomotive.UpdateCar(Time.deltaTime, num);
		foreach (HypeTrainBox activeBox in m_activeBoxes)
		{
			activeBox.UpdateCar(Time.deltaTime, num);
		}
		m_carWheelsAudio.UpdateAudio(Time.deltaTime, num, m_locomotive, m_activeBoxes, m_playerRoot);
	}

	public void StartHypeTrain(Vector3 startWorldPosition, Vector3 stopWorldPosition, HypeTrainBoxData[] boxData, Transform playerRoot = null, HypeTrainOptions options = null)
	{
		//IL_0007: 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_000e: 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_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: 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_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		StopHypeTrain();
		m_startPosition = startWorldPosition;
		m_stopPosition = stopWorldPosition;
		Vector3 val = m_stopPosition - m_startPosition;
		m_trackDistance = ((Vector3)(ref val)).magnitude;
		m_direction = ((Vector3)(ref val)).normalized;
		m_boxData = boxData;
		m_playerRoot = playerRoot;
		m_nextBoxIndexToSpawn = 0;
		m_nextBoxOffset = 0f - m_locomotive.CalculateCarLength();
		m_distancePerSecond = ((options != null && options.distance_per_second.HasValue) ? options.distance_per_second.Value : m_distancePerSecond);
		m_keepAliveOnFinish = ((options != null && options.keep_alive_on_finish.HasValue) ? options.keep_alive_on_finish.Value : m_keepAliveOnFinish);
		if (options != null && options.train_layer.HasValue)
		{
			SetLayerRecursive(((Component)this).gameObject, options.train_layer.Value);
			HypeTrainBit[] bitPrototypes = m_bitPrototypes;
			foreach (HypeTrainBit hypeTrainBit in bitPrototypes)
			{
				SetLayerRecursive(((Component)hypeTrainBit).gameObject, options.train_layer.Value);
			}
		}
		if (options != null && options.volume.HasValue)
		{
			SetVolume(options.volume.Value);
		}
		Transform transform = ((Component)this).transform;
		Vector3 position = (m_rigidBody.position = startWorldPosition);
		transform.position = position;
		Transform transform2 = ((Component)this).transform;
		Quaternion rotation = (m_rigidBody.rotation = Quaternion.LookRotation(m_direction));
		transform2.rotation = rotation;
		int num = Mathf.Min(Mathf.CeilToInt((m_trackDistance + m_boxPrototype.CalculateCarLength()) / m_boxPrototype.CalculateCarLength()), boxData.Length);
		for (int j = 0; j < num; j++)
		{
			HypeTrainBox hypeTrainBox = Object.Instantiate<HypeTrainBox>(m_boxPrototype, ((Component)m_boxPrototype).transform.parent, false);
			((UnityEvent<HypeTrainCar, HypeTrainCar.Visibility>)hypeTrainBox.OnVisibilityChangedEvent).AddListener((UnityAction<HypeTrainCar, HypeTrainCar.Visibility>)OnBoxFinished);
			m_availableBoxes.Enqueue(hypeTrainBox);
		}
		num = Mathf.Min(Mathf.CeilToInt((m_trackDistance + m_bitboxPrototype.CalculateCarLength()) / m_bitboxPrototype.CalculateCarLength()), boxData.Length);
		for (int k = 0; k < num; k++)
		{
			HypeTrainBitBox hypeTrainBitBox = Object.Instantiate<HypeTrainBitBox>(m_bitboxPrototype, ((Component)m_bitboxPrototype).transform.parent, false);
			hypeTrainBitBox.Init(m_bitPrototypes, playerRoot, options?.player_collider_radius, options?.max_bits_per_car, options?.bit_lifetime_in_seconds);
			((UnityEvent<HypeTrainCar, HypeTrainCar.Visibility>)hypeTrainBitBox.OnVisibilityChangedEvent).AddListener((UnityAction<HypeTrainCar, HypeTrainCar.Visibility>)OnBoxFinished);
			m_availableBitBoxes.Enqueue(hypeTrainBitBox);
		}
		m_carWheelsAudio.StartPersistentSounds();
		((Component)m_locomotive).gameObject.SetActive(true);
		m_locomotive.Engage(0f, m_trackDistance + m_locomotive.CalculateCarLength(), 0);
		FlushAvailableBoxes();
	}

	public void StopHypeTrain()
	{
		m_carWheelsAudio.StopPersistentSounds();
		foreach (HypeTrainBox availableBox in m_availableBoxes)
		{
			Object.Destroy((Object)(object)((Component)availableBox).gameObject);
		}
		m_availableBoxes.Clear();
		foreach (HypeTrainBitBox availableBitBox in m_availableBitBoxes)
		{
			Object.Destroy((Object)(object)((Component)availableBitBox).gameObject);
		}
		m_availableBitBoxes.Clear();
		foreach (HypeTrainBox activeBox in m_activeBoxes)
		{
			Object.Destroy((Object)(object)((Component)activeBox).gameObject);
		}
		m_activeBoxes.Clear();
		((Component)m_locomotive).gameObject.SetActive(false);
	}

	public void SetDistancePerSecond(float distancePerSecond)
	{
		m_distancePerSecond = distancePerSecond;
	}

	public void SetKeepAliveOnFinish(bool keepAlive)
	{
		m_keepAliveOnFinish = keepAlive;
	}

	public void SetVolume(float volume)
	{
		m_locomotive.SetBaseVolume(volume);
		m_carWheelsAudio.SetBaseVolume(volume);
	}

	private void OnLocomotiveFinished(HypeTrainCar car, HypeTrainCar.Visibility visibility)
	{
		if (visibility == HypeTrainCar.Visibility.Hidden)
		{
			FlushAvailableBoxes();
		}
	}

	private void OnBoxFinished(HypeTrainCar car, HypeTrainCar.Visibility visibility)
	{
		if (visibility == HypeTrainCar.Visibility.Hidden)
		{
			m_activeBoxes.Remove((HypeTrainBox)car);
			if (((object)car).GetType() == typeof(HypeTrainBitBox))
			{
				HypeTrainBitBox item = (HypeTrainBitBox)car;
				m_availableBitBoxes.Enqueue(item);
			}
			else
			{
				m_availableBoxes.Enqueue((HypeTrainBox)car);
			}
			FlushAvailableBoxes();
		}
	}

	private void FlushAvailableBoxes()
	{
		//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_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		while (m_nextBoxIndexToSpawn < m_boxData.Length && m_availableBoxes.Count != 0)
		{
			HypeTrainBoxData hypeTrainBoxData = m_boxData[m_nextBoxIndexToSpawn];
			HypeTrainBox hypeTrainBox = null;
			hypeTrainBox = ((hypeTrainBoxData.bit_amount <= 0) ? m_availableBoxes.Dequeue() : m_availableBitBoxes.Dequeue());
			((Component)hypeTrainBox).transform.localPosition = Vector3.forward * m_nextBoxOffset - hypeTrainBox.FrontLoc.localPosition;
			float num = hypeTrainBox.CalculateCarLength();
			float num2 = Mathf.Abs(m_nextBoxOffset);
			Vector3 val = ((Component)this).transform.position - m_startPosition;
			float num3 = num2 - ((Vector3)(ref val)).magnitude;
			hypeTrainBox.Engage(hypeTrainBoxData, num3, num3 + m_trackDistance + num, m_nextBoxIndexToSpawn + 1);
			m_activeBoxes.Add(hypeTrainBox);
			m_nextBoxIndexToSpawn++;
			m_nextBoxOffset -= num;
		}
		bool flag = false;
		flag |= ((Component)m_locomotive).gameObject.activeSelf;
		foreach (HypeTrainBox activeBox in m_activeBoxes)
		{
			flag |= ((Component)activeBox).gameObject.activeSelf;
		}
		if (!flag)
		{
			OnFinishedEvent.Invoke();
			StopHypeTrain();
			if (!m_keepAliveOnFinish)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}

	private void SetLayerRecursive(GameObject go, int layer)
	{
		go.layer = layer;
		for (int i = 0; i < go.transform.childCount; i++)
		{
			SetLayerRecursive(((Component)go.transform.GetChild(i)).gameObject, layer);
		}
	}
}
public class HypeTrainBitBox : HypeTrainBox
{
	[SerializeField]
	private BoxCollider m_bitSpawnZone;

	[SerializeField]
	private int m_maxBitBreaks = 100;

	[SerializeField]
	private TextMeshPro[] m_bitsTexts = (TextMeshPro[])(object)new TextMeshPro[0];

	[SerializeField]
	private HypeTrainBitBoxPlayerCollider m_playerCollider;

	private List<HypeTrainBit> m_createdBits = new List<HypeTrainBit>();

	private HypeTrainBit[] m_bitPrototypes;

	private int? m_maxBitsToSpawn;

	private float? m_bitLifetimeInSeconds;

	public void Init(HypeTrainBit[] bitPrototypes, Transform playerRoot, float? playerColliderRadius = null, int? maxBitsToSpawn = null, float? bitLifetimeInSeconds = null)
	{
		m_bitPrototypes = bitPrototypes;
		m_maxBitsToSpawn = maxBitsToSpawn;
		m_bitLifetimeInSeconds = bitLifetimeInSeconds;
		m_playerCollider.Init(this, playerRoot, playerColliderRadius);
	}

	public override void Engage(HypeTrainBoxData data, float distanceToStart, float distanceToStop, int index)
	{
		base.Engage(data, distanceToStart, distanceToStop, index);
		TextMeshPro[] bitsTexts = m_bitsTexts;
		for (int i = 0; i < bitsTexts.Length; i++)
		{
			((TMP_Text)bitsTexts[i]).SetText($"BITS: {data.bit_amount}", true);
		}
		SpawnBits(data.bit_amount);
	}

	public void SpawnBits(int amount)
	{
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: 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)
		RelinquishCreatedBits();
		if (m_bitPrototypes == null)
		{
			return;
		}
		int num = (m_maxBitsToSpawn.HasValue ? m_maxBitsToSpawn.Value : amount);
		int num2 = m_maxBitBreaks;
		Vector3 localPosition = default(Vector3);
		while (amount > 0 && num > 0)
		{
			int num3 = amount;
			if (0 < num2)
			{
				num3 = Random.Range(1, amount + 1);
			}
			amount -= num3;
			while (0 < num3 && num > 0)
			{
				HypeTrainBit[] bitPrototypes = m_bitPrototypes;
				foreach (HypeTrainBit hypeTrainBit in bitPrototypes)
				{
					if (hypeTrainBit.BitValue <= num3)
					{
						num3 -= hypeTrainBit.BitValue;
						num--;
						((Vector3)(ref localPosition))..ctor(Random.Range((0f - m_bitSpawnZone.size.x) * 0.5f, m_bitSpawnZone.size.x * 0.5f), 0f, Random.Range((0f - m_bitSpawnZone.size.z) * 0.5f, m_bitSpawnZone.size.z * 0.5f));
						HypeTrainBit hypeTrainBit2 = Object.Instantiate<HypeTrainBit>(hypeTrainBit, ((Component)m_bitSpawnZone).transform, false);
						((Component)hypeTrainBit2).transform.localPosition = localPosition;
						hypeTrainBit2.Rigidbody.isKinematic = true;
						hypeTrainBit2.Collider.enabled = true;
						m_createdBits.Add(hypeTrainBit2);
					}
				}
			}
			num2--;
		}
	}

	protected override void OnShowFinished()
	{
		base.OnShowFinished();
		if (m_createdBits.Count == 0)
		{
			SpawnBits(100);
		}
	}

	protected override void OnHideFinished()
	{
		base.OnHideFinished();
		foreach (HypeTrainBit createdBit in m_createdBits)
		{
			Object.Destroy((Object)(object)((Component)createdBit).gameObject);
		}
		m_createdBits.Clear();
	}

	public void RelinquishCreatedBits()
	{
		foreach (HypeTrainBit createdBit in m_createdBits)
		{
			createdBit.Rigidbody.isKinematic = false;
			createdBit.Collider.enabled = true;
			((Component)createdBit).transform.SetParent((Transform)null, true);
			if (m_bitLifetimeInSeconds.HasValue)
			{
				createdBit.LifeTime = m_bitLifetimeInSeconds.Value;
			}
			createdBit.StartDeathCountdown();
		}
		m_createdBits.Clear();
	}
}
public class HypeTrainBitBoxPlayerCollider : MonoBehaviour
{
	[SerializeField]
	private SphereCollider m_collider;

	private HypeTrainBitBox m_owner;

	private Transform m_playerRoot;

	public void Init(HypeTrainBitBox owner, Transform playerRoot, float? playerColliderRadius = null)
	{
		m_owner = owner;
		m_playerRoot = playerRoot;
		if (playerColliderRadius.HasValue)
		{
			m_collider.radius = playerColliderRadius.Value;
		}
	}

	private void OnCollisionEnter(Collision other)
	{
		if ((Object)null != (Object)(object)m_owner && (Object)(object)other.transform == (Object)(object)m_playerRoot)
		{
			m_owner.RelinquishCreatedBits();
		}
	}

	private void OnTriggerEnter(Collider other)
	{
		if ((Object)null != (Object)(object)m_owner && (Object)(object)((Component)other).transform == (Object)(object)m_playerRoot)
		{
			m_owner.RelinquishCreatedBits();
		}
	}
}
public class HypeTrainBox : HypeTrainCar
{
	[SerializeField]
	private TextMeshPro[] m_nameTexts;

	private Material m_carMaterial;

	private Color m_carColor;

	private float m_carColorRate;

	private static int s_trimColorMaterialPropertyID = Shader.PropertyToID("_TrimColor");

	public virtual void Engage(HypeTrainBoxData data, float distanceToStart, float distanceToStop, int index)
	{
		//IL_0012: 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)
		Engage(distanceToStart, distanceToStop, index);
		SetName(data.name, data.name_color);
		SetBoxColor(data.box_color, data.box_color_rate);
	}

	public override void UpdateCar(float dt, float delta)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		base.UpdateCar(dt, delta);
		if (m_carColorRate != 0f)
		{
			float num2 = default(float);
			float num3 = default(float);
			float num = default(float);
			Color.RGBToHSV(m_carColor, ref num, ref num2, ref num3);
			for (num += m_carColorRate * delta; num > 1f; num -= 1f)
			{
			}
			for (; num < 0f; num += 1f)
			{
			}
			SetBoxColor(Color.HSVToRGB(num, num2, num3), m_carColorRate);
		}
	}

	public void SetName(string name, Color nameColor)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		TextMeshPro[] nameTexts = m_nameTexts;
		foreach (TextMeshPro obj in nameTexts)
		{
			((TMP_Text)obj).SetText(name, true);
			((Graphic)obj).color = nameColor;
		}
	}

	public void SetBoxColor(Color color, float carColorRate)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)null == (Object)(object)m_carMaterial)
		{
			m_carMaterial = new Material(((Renderer)base.Meshes[0]).material);
			MeshRenderer[] meshes = base.Meshes;
			for (int i = 0; i < meshes.Length; i++)
			{
				((Renderer)meshes[i]).material = m_carMaterial;
			}
		}
		m_carColor = color;
		if ((Object)null != (Object)(object)m_carMaterial)
		{
			m_carMaterial.SetColor(s_trimColorMaterialPropertyID, color);
		}
		m_carColorRate = carColorRate;
	}
}
[Serializable]
public class HypeTrainBoxData
{
	public string name = "";

	public Color name_color = new Color(1f, 1f, 1f);

	public Color box_color = new Color(0.3803921f, 0.7960785f, 0.545098f);

	public float box_color_rate;

	public int bit_amount;
}
public class HypeTrainCar : MonoBehaviour
{
	public enum Visibility
	{
		Visible,
		Hidden
	}

	public class VisibilityChangedEvent : UnityEvent<HypeTrainCar, Visibility>
	{
	}

	[SerializeField]
	private Animator m_animatorRoot;

	[SerializeField]
	private Animator m_animatorCar;

	[SerializeField]
	private Transform m_frontLoc;

	[SerializeField]
	private Transform m_backLoc;

	[SerializeField]
	private MeshRenderer[] m_meshes = (MeshRenderer[])(object)new MeshRenderer[0];

	private VisibilityChangedEvent m_onVisibilityChangedEvent = new VisibilityChangedEvent();

	private float m_distanceToStart;

	private float m_distanceToStop;

	private static readonly int s_animShowTag = Animator.StringToHash("Show");

	private static readonly int s_animHideTag = Animator.StringToHash("Hide");

	private static readonly int s_animWobbleTag = Animator.StringToHash("Wobble");

	protected MeshRenderer[] Meshes => m_meshes;

	public Transform FrontLoc => m_frontLoc;

	public Transform BackLoc => m_backLoc;

	public VisibilityChangedEvent OnVisibilityChangedEvent => m_onVisibilityChangedEvent;

	public void Engage(float distanceToStart, float distanceToStop, int index)
	{
		m_distanceToStart = distanceToStart;
		m_distanceToStop = distanceToStop;
		if (m_distanceToStart <= 0f)
		{
			Show();
			float num = 5f;
			m_animatorCar.Play(s_animWobbleTag, 0, (float)index % (num + 1f) / num);
		}
		if (m_distanceToStop <= 0f)
		{
			Hide();
		}
	}

	public virtual void UpdateCar(float dt, float delta)
	{
		if (m_distanceToStart > 0f)
		{
			m_distanceToStart -= delta;
			if (m_distanceToStart <= 0f)
			{
				m_distanceToStart = 0f;
				Show();
			}
		}
		if (m_distanceToStop > 0f)
		{
			m_distanceToStop -= delta;
			if (m_distanceToStop <= 0f)
			{
				m_distanceToStop = 0f;
				Hide();
			}
		}
	}

	public virtual void Show()
	{
		((Component)this).gameObject.SetActive(true);
		m_animatorRoot.Play(s_animShowTag, 0, 0f);
	}

	public virtual void Hide()
	{
		m_animatorRoot.Play(s_animHideTag, 0, 0f);
	}

	public float CalculateCarLength()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = m_frontLoc.localPosition - m_backLoc.localPosition;
		return ((Vector3)(ref val)).magnitude;
	}

	protected virtual void OnShowFinished()
	{
		((UnityEvent<HypeTrainCar, Visibility>)m_onVisibilityChangedEvent).Invoke(this, Visibility.Visible);
	}

	protected virtual void OnHideFinished()
	{
		((Component)this).gameObject.SetActive(false);
		((UnityEvent<HypeTrainCar, Visibility>)m_onVisibilityChangedEvent).Invoke(this, Visibility.Hidden);
	}
}
public class HypeTrainCarAudio : MonoBehaviour
{
	[SerializeField]
	private AudioSource m_carWheelsAudio;

	[SerializeField]
	private AudioSource m_carWheelsClankAudio;

	[SerializeField]
	private AudioClip[] m_carWheelsClankAudioClips = (AudioClip[])(object)new AudioClip[0];

	[SerializeField]
	private int m_maxSimultaneousClanks = 3;

	[SerializeField]
	private float m_clankMinInterval = 0.1f;

	[SerializeField]
	private float m_clankMaxInterval = 0.5f;

	private float m_nextClankTimer;

	private float[] m_clankTimers;

	private float m_wheelVolume = 1f;

	private float m_baseVolume = 1f;

	private void Awake()
	{
		m_clankTimers = new float[m_maxSimultaneousClanks];
	}

	public void StartPersistentSounds()
	{
		m_carWheelsAudio.Play();
	}

	public void StopPersistentSounds()
	{
		m_carWheelsAudio.Stop();
	}

	public void UpdateAudio(float dt, float delta, HypeTrainLocomotive locomotive, List<HypeTrainBox> activeBoxes, Transform playerRoot)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: 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_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = ((Component)locomotive).transform.position;
		float x = ((Component)locomotive).transform.lossyScale.x;
		if ((Object)null != (Object)(object)playerRoot)
		{
			float num = Vector3.SqrMagnitude(playerRoot.position - position);
			foreach (HypeTrainBox activeBox in activeBoxes)
			{
				float num2 = Vector3.SqrMagnitude(playerRoot.position - ((Component)activeBox).transform.position);
				if (num2 < num)
				{
					num = num2;
					position = ((Component)activeBox).transform.position;
					x = ((Component)activeBox).transform.lossyScale.x;
				}
			}
		}
		position.y += 0.75f;
		((Component)this).transform.position = Vector3.MoveTowards(((Component)m_carWheelsAudio).transform.position, position, delta * 4f);
		m_wheelVolume = Mathf.MoveTowards(m_wheelVolume, x, dt * 2f);
		AudioSource carWheelsAudio = m_carWheelsAudio;
		float volume = (m_carWheelsClankAudio.volume = m_baseVolume * m_wheelVolume);
		carWheelsAudio.volume = volume;
		if (m_nextClankTimer > 0f)
		{
			m_nextClankTimer -= dt;
			if (m_nextClankTimer <= 0f)
			{
				for (int i = 0; i < m_maxSimultaneousClanks; i++)
				{
					if (m_clankTimers[i] <= 0f)
					{
						AudioClip val = m_carWheelsClankAudioClips[Random.Range(0, m_carWheelsClankAudioClips.Length)];
						m_clankTimers[i] = val.length;
						m_carWheelsClankAudio.PlayOneShot(val);
						break;
					}
				}
			}
		}
		for (int j = 0; j < m_maxSimultaneousClanks; j++)
		{
			m_clankTimers[j] -= dt;
			if (m_clankTimers[j] <= 0f)
			{
				while (m_nextClankTimer <= 0f)
				{
					m_nextClankTimer += Random.Range(m_clankMinInterval, m_clankMaxInterval);
				}
			}
		}
	}

	public void SetBaseVolume(float volume)
	{
		m_baseVolume = volume;
		AudioSource carWheelsAudio = m_carWheelsAudio;
		float volume2 = (m_carWheelsClankAudio.volume = m_baseVolume * m_wheelVolume);
		carWheelsAudio.volume = volume2;
	}
}
public class HypeTrainLocomotive : HypeTrainCar
{
	[SerializeField]
	private AudioSource m_audioSource;

	private float m_baseVolume = 1f;

	public override void Show()
	{
		base.Show();
		m_audioSource.Play();
	}

	protected override void OnHideFinished()
	{
		base.OnHideFinished();
		m_audioSource.Stop();
	}

	public override void UpdateCar(float dt, float delta)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		base.UpdateCar(dt, delta);
		m_audioSource.volume = m_baseVolume * Mathf.Clamp01(((Component)this).transform.lossyScale.x);
	}

	public void SetBaseVolume(float volume)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		m_baseVolume = volume;
		m_audioSource.volume = m_baseVolume * Mathf.Clamp01(((Component)this).transform.lossyScale.x);
	}
}
[Serializable]
public class HypeTrainOptions
{
	public int? train_layer;

	public float? distance_per_second;

	public float? player_collider_radius;

	public int? max_bits_per_car;

	public float? bit_lifetime_in_seconds;

	public float? volume;

	public bool? keep_alive_on_finish;
}