Decompiled source of SoulPvEServerClientModPack1 v1.0.3

Bloodstone.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using Bloodstone.API;
using Bloodstone.Features;
using Bloodstone.Hooks;
using Bloodstone.Network;
using Bloodstone.Util;
using Costura;
using HarmonyLib;
using Iced.Intel;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using ProjectM;
using ProjectM.Network;
using ProjectM.UI;
using Standart.Hash.xxHash;
using StunShared.UI;
using Stunlock.Localization;
using Stunlock.Network;
using TMPro;
using Unity.Collections;
using Unity.Entities;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("deca")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Plugin framework and general utilities for V Rising mods.")]
[assembly: AssemblyFileVersion("0.1.6.0")]
[assembly: AssemblyInformationalVersion("0.1.6+2.Branch.main.Sha.474421f29a881b45f9a167d759c1021dfc3f3f4c")]
[assembly: AssemblyProduct("Bloodstone")]
[assembly: AssemblyTitle("Bloodstone")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.6.0")]
[module: UnverifiableCode]
internal class <Module>
{
	static <Module>()
	{
		AssemblyLoader.Attach();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	public class IsUnmanagedAttribute : Attribute
	{
	}
	public class IsExternalInit
	{
	}
}
namespace Bloodstone
{
	[BepInPlugin("gg.deca.Bloodstone", "Bloodstone", "0.1.6")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BloodstonePlugin : BasePlugin
	{
		private ConfigEntry<bool> _enableReloadCommand;

		private ConfigEntry<string> _reloadCommand;

		private ConfigEntry<string> _reloadPluginsFolder;

		public static ManualLogSource Logger { get; private set; }

		internal static BloodstonePlugin Instance { get; private set; }

		public BloodstonePlugin()
		{
			Logger = ((BasePlugin)this).Log;
			Instance = this;
			_enableReloadCommand = ((BasePlugin)this).Config.Bind<bool>("General", "EnableReloading", true, "Whether to enable the reloading feature (both client and server).");
			_reloadCommand = ((BasePlugin)this).Config.Bind<string>("General", "ReloadCommand", "!reload", "Server text command to reload plugins. User must be an admin.");
			_reloadPluginsFolder = ((BasePlugin)this).Config.Bind<string>("General", "ReloadablePluginsFolder", "BepInEx/BloodstonePlugins", "The folder to (re)load plugins from, relative to the game directory.");
		}

		public override void Load()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			if (VWorld.IsServer)
			{
				Chat.Initialize();
			}
			if (VWorld.IsClient)
			{
				KeybindManager.Load();
				Keybindings.Initialize();
			}
			OnInitialize.Initialize();
			GameFrame.Initialize();
			SerializationHooks.Initialize();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(20, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Bloodstone v");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("0.1.6");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded.");
			}
			logger.LogInfo(val);
			if (VWorld.IsClient || _enableReloadCommand.Value)
			{
				Reload.Initialize(_reloadCommand.Value, _reloadPluginsFolder.Value);
			}
		}

		public override bool Unload()
		{
			if (VWorld.IsServer)
			{
				Chat.Uninitialize();
			}
			if (VWorld.IsClient)
			{
				KeybindManager.Save();
				Keybindings.Uninitialize();
			}
			OnInitialize.Uninitialize();
			GameFrame.Uninitialize();
			SerializationHooks.Uninitialize();
			return true;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "gg.deca.Bloodstone";

		public const string PLUGIN_NAME = "Bloodstone";

		public const string PLUGIN_VERSION = "0.1.6";
	}
}
namespace Bloodstone.Util
{
	public class Il2CppMethodResolver
	{
		private static ulong ExtractTargetAddress(in Instruction instruction)
		{
			//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_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			OpKind op0Kind = ((Instruction)(ref instruction)).Op0Kind;
			if ((int)op0Kind != 4)
			{
				if ((int)op0Kind == 5)
				{
					return ((Instruction)(ref instruction)).FarBranch32;
				}
				return ((Instruction)(ref instruction)).NearBranchTarget;
			}
			return ((Instruction)(ref instruction)).FarBranch16;
		}

		private unsafe static IntPtr ResolveMethodPointer(IntPtr methodPointer)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0043: 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_00ab: Invalid comparison between Unknown and I4
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Invalid comparison between Unknown and I4
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Invalid comparison between Unknown and I4
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Invalid comparison between Unknown and I4
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Invalid comparison between Unknown and I4
			StreamCodeReader val = new StreamCodeReader((Stream)new UnmanagedMemoryStream((byte*)(void*)methodPointer, 256L, 256L, FileAccess.Read));
			Decoder val2 = Decoder.Create((IntPtr.Size == 8) ? 64 : 32, (CodeReader)(object)val, (DecoderOptions)0);
			val2.IP = (ulong)methodPointer.ToInt64();
			Instruction instruction = default(Instruction);
			while ((int)((Instruction)(ref instruction)).Mnemonic != 1620)
			{
				val2.Decode(ref instruction);
				if ((int)((Instruction)(ref instruction)).Mnemonic != 308 && (int)((Instruction)(ref instruction)).Mnemonic != 7)
				{
					return methodPointer;
				}
				if ((int)((Instruction)(ref instruction)).Mnemonic == 7 && ((Instruction)(ref instruction)).Immediate32 != 16)
				{
					return methodPointer;
				}
				if ((int)((Instruction)(ref instruction)).Mnemonic == 308)
				{
					return new IntPtr((long)ExtractTargetAddress(in instruction));
				}
			}
			return methodPointer;
		}

		public static IntPtr ResolveFromMethodInfo(INativeMethodInfoStruct methodInfo)
		{
			return ResolveMethodPointer(methodInfo.MethodPointer);
		}

		public unsafe static IntPtr ResolveFromMethodInfo(MethodInfo method)
		{
			FieldInfo il2CppMethodInfoPointerFieldForGeneratedMethod = Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod((MethodBase)method);
			if (il2CppMethodInfoPointerFieldForGeneratedMethod == null)
			{
				throw new Exception($"Couldn't obtain method info for {method}");
			}
			return ResolveFromMethodInfo(UnityVersionHandler.Wrap((Il2CppMethodInfo*)(void*)(IntPtr)(il2CppMethodInfoPointerFieldForGeneratedMethod.GetValue(null) ?? ((object)IntPtr.Zero))) ?? throw new Exception($"Method info for {method} is invalid"));
		}
	}
	public static class NativeHookUtil
	{
		public static INativeDetour Detour<T>(string typeName, string methodName, T to, out T original) where T : Delegate?
		{
			return Detour(Type.GetType(typeName), methodName, to, out original);
		}

		public static INativeDetour Detour<T>(Type type, string methodName, T to, out T original) where T : Delegate?
		{
			return Detour(type.GetMethod(methodName, AccessTools.all), to, out original);
		}

		public static INativeDetour Detour<T>(MethodInfo method, T to, out T original) where T : Delegate?
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			IntPtr intPtr = Il2CppMethodResolver.ResolveFromMethodInfo(method);
			ManualLogSource logger = BloodstonePlugin.Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(15, 3, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Detouring ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method.DeclaringType?.FullName);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method.Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" at ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(intPtr.ToString("X"));
			}
			logger.LogInfo(val);
			return INativeDetour.CreateAndApply<T>(intPtr, to, ref original);
		}
	}
}
namespace Bloodstone.Network
{
	internal class VBlittableNetworkMessage<T> : VNetworkMessage where T : unmanaged
	{
		public T Value { get; private set; }

		public VBlittableNetworkMessage()
		{
			Value = default(T);
		}

		public VBlittableNetworkMessage(T instance)
		{
			Value = instance;
		}

		public unsafe void Deserialize(NetBufferIn reader)
		{
			int num = ((NetBufferIn)(ref reader)).ReadInt32();
			if (num != Marshal.SizeOf<T>())
			{
				throw new Exception($"Received a message with invalid size {num} for type {typeof(T)}");
			}
			byte* ptr = stackalloc byte[(int)(uint)num];
			for (int i = 0; i < num; i++)
			{
				ptr[i] = ((NetBufferIn)(ref reader)).ReadByte();
			}
			Value = Marshal.PtrToStructure<T>(new IntPtr(ptr));
		}

		public unsafe void Serialize(ref NetBufferOut writer)
		{
			int num = Marshal.SizeOf<T>();
			byte* ptr = stackalloc byte[(int)(uint)num];
			Marshal.StructureToPtr(Value, new IntPtr(ptr), fDeleteOld: false);
			((NetBufferOut)(ref writer)).Write(num);
			for (int i = 0; i < num; i++)
			{
				((NetBufferOut)(ref writer)).Write(ptr[i]);
			}
		}
	}
	internal class CustomNetworkEvent : Object
	{
		private static bool _isInitialized;

		private static ComponentType _componentType;

		public VNetworkMessage? Message;

		public static ComponentType ComponentType
		{
			get
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				if (!_isInitialized)
				{
					Inject();
				}
				return _componentType;
			}
		}

		public CustomNetworkEvent()
			: base(ClassInjector.DerivedConstructorPointer<CustomNetworkEvent>())
		{
			ClassInjector.DerivedConstructorBody((Il2CppObjectBase)(object)this);
		}

		internal void Serialize(ref NetBufferOut netBuffer)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			if (Message == null)
			{
				throw new Exception("Tried to serialize a CustomNetworkEvent with no message");
			}
			string text = MessageRegistry.DeriveKey(Message.GetType());
			((NetBufferOut)(ref netBuffer)).Write(text, (Allocator)2);
			try
			{
				Message.Serialize(ref netBuffer);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = BloodstonePlugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(35, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to serialize network event ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(":");
				}
				logger.LogError(val);
				BloodstonePlugin.Logger.LogError((object)ex);
			}
		}

		private static void Inject()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			ClassInjector.RegisterTypeInIl2Cpp(typeof(CustomNetworkEvent));
			Type val = Il2CppType.From(typeof(CustomNetworkEvent));
			if (TypeManager.FindTypeIndex(val) == -1)
			{
				TypeInfo val2 = TypeManager.BuildComponentType(val);
				TypeManager.AddTypeInfoToTables(val, val2, "CustomNetworkEvent");
			}
			_componentType = new ComponentType(val, (AccessMode)0);
			_isInitialized = true;
		}
	}
	internal static class EventDispatcher
	{
		internal static void SendToClient(int userIndex, VNetworkMessage msg)
		{
			//IL_0046: 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_0056: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007a: 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_0084: 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_008c: 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_009d: 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_00a8: 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_00d3: 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)
			if (!VWorld.IsServer)
			{
				throw new Exception("Cannot send network messages to client if not on the server");
			}
			string text = MessageRegistry.DeriveKey(msg.GetType());
			if (!MessageRegistry._eventHandlers.ContainsKey(text))
			{
				throw new Exception("Network event " + text + " is not registered");
			}
			EntityManager entityManager = VWorld.Server.EntityManager;
			Entity val = ((EntityManager)(ref entityManager)).CreateEntity((ComponentType[])(object)new ComponentType[4]
			{
				ComponentType.ReadOnly<SendNetworkEventTag>(),
				ComponentType.ReadOnly<NetworkEventType>(),
				ComponentType.ReadOnly<SendEventToUser>(),
				CustomNetworkEvent.ComponentType
			});
			((EntityManager)(ref entityManager)).SetComponentData<SendEventToUser>(val, new SendEventToUser
			{
				UserIndex = userIndex
			});
			((EntityManager)(ref entityManager)).SetComponentData<NetworkEventType>(val, new NetworkEventType
			{
				EventId = 1036301,
				IsAdminEvent = false,
				IsDebugEvent = false
			});
			((EntityManager)(ref entityManager)).SetComponentObject(val, CustomNetworkEvent.ComponentType, (Object)(object)new CustomNetworkEvent
			{
				Message = msg
			});
		}

		internal static void SendToServer(VNetworkMessage msg)
		{
			//IL_0046: 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_0056: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			if (!VWorld.IsClient)
			{
				throw new Exception("Cannot send network messages to server if not on the client");
			}
			string text = MessageRegistry.DeriveKey(msg.GetType());
			if (!MessageRegistry._eventHandlers.ContainsKey(text))
			{
				throw new Exception("Network event " + text + " is not registered");
			}
			EntityManager entityManager = VWorld.Client.EntityManager;
			Entity val = ((EntityManager)(ref entityManager)).CreateEntity((ComponentType[])(object)new ComponentType[3]
			{
				ComponentType.ReadOnly<NetworkEventType>(),
				ComponentType.ReadOnly<SendNetworkEventTag>(),
				CustomNetworkEvent.ComponentType
			});
			((EntityManager)(ref entityManager)).SetComponentData<NetworkEventType>(val, new NetworkEventType
			{
				EventId = 1036301,
				IsAdminEvent = false,
				IsDebugEvent = false
			});
			((EntityManager)(ref entityManager)).SetComponentObject(val, CustomNetworkEvent.ComponentType, (Object)(object)new CustomNetworkEvent
			{
				Message = msg
			});
		}
	}
	internal class MessageRegistry
	{
		internal static Dictionary<string, RegisteredEventHandler> _eventHandlers = new Dictionary<string, RegisteredEventHandler>();

		internal static string DeriveKey(Type name)
		{
			return name.ToString();
		}

		internal static void Register<T>(RegisteredEventHandler handler)
		{
			string text = DeriveKey(typeof(T));
			if (_eventHandlers.ContainsKey(text))
			{
				throw new Exception("Network event " + text + " is already registered");
			}
			_eventHandlers.Add(text, handler);
		}

		internal static void Unregister<T>()
		{
			string key = DeriveKey(typeof(T));
			_eventHandlers.Remove(key);
		}
	}
	internal class RegisteredEventHandler
	{
		internal Action<NetBufferIn> OnReceiveFromServer { get; init; }

		internal Action<FromCharacter, NetBufferIn> OnReceiveFromClient { get; init; }
	}
	internal static class SerializationHooks
	{
		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		public delegate void SerializeEvent(IntPtr entityManager, NetworkEventType networkEventType, ref NetBufferOut netBufferOut, Entity entity);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		public delegate void DeserializeEvent(IntPtr entityManager, IntPtr commandBuffer, ref NetBufferIn netBuffer, DeserializeNetworkEventParams eventParams);

		[UnmanagedFunctionPointer(CallingConvention.StdCall)]
		public delegate void EventsReceived(IntPtr _this, ref NetBufferIn netBuffer);

		private static class SerializeAndSendServerEventsSystem_Patch
		{
			[HarmonyPrefix]
			[HarmonyPatch(typeof(SerializeAndSendServerEventsSystem), "OnUpdate")]
			private unsafe static void OnUpdatePrefix(SerializeAndSendServerEventsSystem __instance)
			{
				//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_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_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_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: 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_0042: 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_0056: 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_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: 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_007d: 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_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b7: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d6: 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_00e2: 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)
				EntityQuery query = __instance._Query;
				NativeArray<Entity> val = ((EntityQuery)(ref query)).ToEntityArray((Allocator)2);
				int typeIndex = ComponentType.ReadOnly<SendEventToUser>().TypeIndex;
				Enumerator<Entity> enumerator = val.GetEnumerator();
				NetBufferOut netBuffer = default(NetBufferOut);
				while (enumerator.MoveNext())
				{
					Entity current = enumerator.Current;
					EntityManager entityManager = ((ComponentSystemBase)__instance).EntityManager;
					NetworkEventType componentData = ((EntityManager)(ref entityManager)).GetComponentData<NetworkEventType>(current);
					if (componentData.EventId == 1036301)
					{
						entityManager = ((ComponentSystemBase)__instance).EntityManager;
						CustomNetworkEvent componentObject = ((EntityManager)(ref entityManager)).GetComponentObject<CustomNetworkEvent>(current);
						entityManager = ((ComponentSystemBase)__instance).EntityManager;
						SendEventToUser componentDataRawRO = (SendEventToUser)(*((EntityManager)(ref entityManager)).GetComponentDataRawRO(current, typeIndex));
						((NetBufferOut)(ref netBuffer))..ctor(new NativeList<byte>(16384, (Allocator)2), 0);
						((NetBufferOut)(ref netBuffer)).Write((byte)1);
						((NetBufferOut)(ref netBuffer)).Write(componentData.EventId);
						componentObject.Serialize(ref netBuffer);
						__instance._ServerBootstrapSystem.SendPacketToUser(((NetBufferOut)(ref netBuffer)).Data, ((NetBufferOut)(ref netBuffer)).Data.Length * 8, componentDataRawRO.UserIndex, true);
						entityManager = ((ComponentSystemBase)__instance).EntityManager;
						((EntityManager)(ref entityManager)).DestroyEntity(current);
					}
				}
			}
		}

		internal const int BLOODSTONE_NETWORK_EVENT_ID = 1036301;

		private static INativeDetour? _serializeDetour;

		private static INativeDetour? _deserializeDetour;

		private static INativeDetour? _eventsReceivedDetour;

		private static Harmony? _harmony;

		public static SerializeEvent? SerializeOriginal;

		public static DeserializeEvent? DeserializeOriginal;

		public static EventsReceived? EventsReceivedOriginal;

		public static void Initialize()
		{
			_serializeDetour = NativeHookUtil.Detour<SerializeEvent>(typeof(NetworkEvents_Serialize), "SerializeEvent", SerializeHook, out SerializeOriginal);
			_deserializeDetour = NativeHookUtil.Detour<DeserializeEvent>(typeof(NetworkEvents_Serialize), "DeserializeEvent", DeserializeHook, out DeserializeOriginal);
			if (VWorld.IsClient)
			{
				_eventsReceivedDetour = NativeHookUtil.Detour<EventsReceived>(typeof(ClientBootstrapSystem), "OnReliableEventsReceived", EventsReceivedHook, out EventsReceivedOriginal);
			}
			else if (VWorld.IsServer)
			{
				_harmony = Harmony.CreateAndPatchAll(typeof(SerializeAndSendServerEventsSystem_Patch), (string)null);
			}
		}

		public static void Uninitialize()
		{
			((IDisposable)_serializeDetour)?.Dispose();
			((IDisposable)_deserializeDetour)?.Dispose();
			((IDisposable)_eventsReceivedDetour)?.Dispose();
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		public static void SerializeHook(IntPtr entityManager, NetworkEventType networkEventType, ref NetBufferOut netBufferOut, Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_0013: 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)
			if (networkEventType.EventId != 1036301)
			{
				SerializeOriginal(entityManager, networkEventType, ref netBufferOut, entity);
				return;
			}
			EntityManager entityManager2 = VWorld.Server.EntityManager;
			CustomNetworkEvent obj = (CustomNetworkEvent)(object)((EntityManager)(ref entityManager2)).GetComponentObject<Object>(entity, CustomNetworkEvent.ComponentType);
			((NetBufferOut)(ref netBufferOut)).Write(1036301u);
			obj.Serialize(ref netBufferOut);
		}

		public static void DeserializeHook(IntPtr entityManager, IntPtr commandBuffer, ref NetBufferIn netBufferIn, DeserializeNetworkEventParams eventParams)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_0057: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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 (((NetBufferIn)(ref netBufferIn)).ReadUInt32() != 1036301)
			{
				netBufferIn.m_readPosition -= 32;
				DeserializeOriginal(entityManager, commandBuffer, ref netBufferIn, eventParams);
				return;
			}
			string text = ((NetBufferIn)(ref netBufferIn)).ReadString((Allocator)2);
			if (!MessageRegistry._eventHandlers.ContainsKey(text))
			{
				return;
			}
			RegisteredEventHandler registeredEventHandler = MessageRegistry._eventHandlers[text];
			bool flag = eventParams.FromCharacter.User == Entity.Null;
			try
			{
				if (flag)
				{
					registeredEventHandler.OnReceiveFromServer(netBufferIn);
				}
				else
				{
					registeredEventHandler.OnReceiveFromClient(eventParams.FromCharacter, netBufferIn);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = BloodstonePlugin.Logger;
				bool flag2 = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error handling incoming network event ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(":");
				}
				logger.LogError(val);
				BloodstonePlugin.Logger.LogError((object)ex);
			}
		}

		public static void EventsReceivedHook(IntPtr _this, ref NetBufferIn netBuffer)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (((NetBufferIn)(ref netBuffer)).ReadInt32() != 1036301)
			{
				netBuffer.m_readPosition -= 32;
				EventsReceivedOriginal(_this, ref netBuffer);
				return;
			}
			string text = ((NetBufferIn)(ref netBuffer)).ReadString((Allocator)2);
			if (!MessageRegistry._eventHandlers.ContainsKey(text))
			{
				return;
			}
			RegisteredEventHandler registeredEventHandler = MessageRegistry._eventHandlers[text];
			try
			{
				registeredEventHandler.OnReceiveFromServer(netBuffer);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = BloodstonePlugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error handling incoming network event ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(":");
				}
				logger.LogError(val);
				BloodstonePlugin.Logger.LogError((object)ex);
			}
		}
	}
}
namespace Bloodstone.Hooks
{
	public static class Chat
	{
		public delegate void ChatEventHandler(VChatEvent e);

		private static Harmony? _harmony;

		public static event ChatEventHandler? OnChatMessage;

		public static void Initialize()
		{
			if (_harmony != null)
			{
				throw new Exception("Detour already initialized. You don't need to call this. The Bloodstone plugin will do it for you.");
			}
			_harmony = Harmony.CreateAndPatchAll(typeof(Chat), "gg.deca.Bloodstone");
		}

		public static void Uninitialize()
		{
			if (_harmony == null)
			{
				throw new Exception("Detour wasn't initialized. Are you trying to unload Bloodstone twice?");
			}
			_harmony.UnpatchSelf();
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ChatMessageSystem), "OnUpdate")]
		public static void OnUpdatePrefix(ChatMessageSystem __instance)
		{
			//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_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0033: 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_0039: 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_0045: 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_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)
			//IL_0051: 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_005a: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//IL_00a4: 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_00c3: 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_0117: Unknown result type (might be due to invalid IL or missing references)
			EntityQuery chatMessageQuery = __instance._ChatMessageQuery;
			Enumerator<Entity> enumerator = ((EntityQuery)(ref chatMessageQuery)).ToEntityArray((Allocator)2).GetEnumerator();
			bool flag = default(bool);
			while (enumerator.MoveNext())
			{
				Entity current = enumerator.Current;
				EntityManager entityManager = VWorld.Server.EntityManager;
				ChatMessageEvent componentData = ((EntityManager)(ref entityManager)).GetComponentData<ChatMessageEvent>(current);
				entityManager = VWorld.Server.EntityManager;
				FromCharacter componentData2 = ((EntityManager)(ref entityManager)).GetComponentData<FromCharacter>(current);
				VChatEvent vChatEvent = new VChatEvent(componentData2.User, componentData2.Character, ((object)(FixedString512)(ref componentData.MessageText)).ToString(), componentData.MessageType);
				ManualLogSource logger = BloodstonePlugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(12, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[Chat] [");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ChatMessageType>(vChatEvent.Type);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("] ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<FixedString64>(vChatEvent.User.CharacterName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(vChatEvent.Message);
				}
				logger.LogInfo(val);
				try
				{
					Chat.OnChatMessage?.Invoke(vChatEvent);
					if (vChatEvent.Cancelled)
					{
						entityManager = VWorld.Server.EntityManager;
						((EntityManager)(ref entityManager)).DestroyEntity(current);
					}
				}
				catch (Exception ex)
				{
					BloodstonePlugin.Logger.LogError((object)"Error dispatching chat event:");
					BloodstonePlugin.Logger.LogError((object)ex);
				}
			}
		}
	}
	public class VChatEvent
	{
		public Entity SenderUserEntity { get; }

		public Entity SenderCharacterEntity { get; }

		public string Message { get; }

		public ChatMessageType Type { get; }

		public bool Cancelled { get; private set; }

		public User User
		{
			get
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				EntityManager entityManager = VWorld.Server.EntityManager;
				return ((EntityManager)(ref entityManager)).GetComponentData<User>(SenderUserEntity);
			}
		}

		internal VChatEvent(Entity userEntity, Entity characterEntity, string message, ChatMessageType type)
		{
			//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_001c: 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)
			SenderUserEntity = userEntity;
			SenderCharacterEntity = characterEntity;
			Message = message;
			Type = type;
		}

		public void Cancel()
		{
			Cancelled = true;
		}
	}
	public delegate void GameFrameUpdateEventHandler();
	public class GameFrame : MonoBehaviour
	{
		private static GameFrame? _instance;

		public static event GameFrameUpdateEventHandler? OnUpdate;

		public static event GameFrameUpdateEventHandler? OnLateUpdate;

		private void Update()
		{
			try
			{
				GameFrame.OnUpdate?.Invoke();
			}
			catch (Exception ex)
			{
				BloodstonePlugin.Logger.LogError((object)"Error dispatching OnUpdate event:");
				BloodstonePlugin.Logger.LogError((object)ex);
			}
		}

		private void LateUpdate()
		{
			try
			{
				GameFrame.OnLateUpdate?.Invoke();
			}
			catch (Exception ex)
			{
				BloodstonePlugin.Logger.LogError((object)"Error dispatching OnLateUpdate event:");
				BloodstonePlugin.Logger.LogError((object)ex);
			}
		}

		public static void Initialize()
		{
			if (!ClassInjector.IsTypeRegisteredInIl2Cpp<GameFrame>())
			{
				ClassInjector.RegisterTypeInIl2Cpp<GameFrame>();
			}
			_instance = ((BasePlugin)BloodstonePlugin.Instance).AddComponent<GameFrame>();
		}

		public static void Uninitialize()
		{
			GameFrame.OnUpdate = null;
			GameFrame.OnLateUpdate = null;
			Object.Destroy((Object)(object)_instance);
			_instance = null;
		}
	}
	internal static class Keybindings
	{
		private unsafe delegate bool TryGetInputFlagLocalization_t(IntPtr instance, InputFlag inputFlag, LocalizationKey* key);

		private static TryGetInputFlagLocalization_t TryGetInputFlagLocalization_Original;

		private static Harmony _harmony;

		private static INativeDetour _detour;

		public unsafe static void Initialize()
		{
			if (VWorld.IsClient)
			{
				_detour = NativeHookUtil.Detour<TryGetInputFlagLocalization_t>(typeof(InputSystem), "TryGetInputFlagLocalization", TryGetInputFlagLocalization_Hook, out TryGetInputFlagLocalization_Original);
				_harmony = Harmony.CreateAndPatchAll(typeof(Keybindings), (string)null);
			}
		}

		public static void Uninitialize()
		{
			if (VWorld.IsClient)
			{
				((IDisposable)_detour).Dispose();
				_harmony.UnpatchSelf();
			}
		}

		[HarmonyPatch(typeof(Options_ControlsPanel), "Start")]
		[HarmonyPostfix]
		public static void Start(Options_ControlsPanel __instance)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			foreach (IGrouping<string, Keybinding> item in from x in KeybindManager._keybindingsById.Values
				group x by x.Description.Category)
			{
				((TMP_Text)((Component)UIHelper.InstantiatePrefabUnderAnchor<OptionsCategoryHeader>(__instance.CategoryHeaderPrefab, __instance.ContentNode)).GetComponentInChildren<TextMeshProUGUI>()).text = item.Key;
				foreach (Keybinding item2 in item)
				{
					__instance.AddEntry(item2.InputFlag);
				}
			}
		}

		[HarmonyPatch(typeof(InputSystem), "ModifyKeyInputSetting")]
		[HarmonyPrefix]
		public static bool ModifyKeyInputSetting(InputFlag inputFlag, KeyCode newKey, bool primary)
		{
			//IL_0005: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			Keybinding valueOrDefault = KeybindManager._keybindingsByFlags.GetValueOrDefault(inputFlag);
			if (valueOrDefault != null)
			{
				if (primary)
				{
					KeybindManager._keybindingValues[valueOrDefault.Description.Id].Primary = newKey;
				}
				else
				{
					KeybindManager._keybindingValues[valueOrDefault.Description.Id].Secondary = newKey;
				}
				KeybindManager.Save();
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(InputSystem), "GetKeyInputMap")]
		[HarmonyPrefix]
		public static bool GetKeyInputMap(InputFlag input, ref string inputText, ref Sprite inputIcon, bool primary, InputSystem __instance)
		{
			//IL_0005: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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)
			Keybinding valueOrDefault = KeybindManager._keybindingsByFlags.GetValueOrDefault(input);
			if (valueOrDefault != null)
			{
				KeyCode keybindingValue = (primary ? valueOrDefault.Primary : valueOrDefault.Secondary);
				if ((int)keybindingValue == 0)
				{
					return false;
				}
				KeycodeMapping val = ((IEnumerable<KeycodeMapping>)__instance._ControlsVisualMapping.KeysData).FirstOrDefault((Func<KeycodeMapping, bool>)((KeycodeMapping x) => x.KeyCode == keybindingValue));
				if (val != null)
				{
					inputText = Localization.Get(val.TextKey, true);
					inputIcon = val.KeySprite;
				}
				else
				{
					inputText = __instance.GetKeyCodeString(keybindingValue);
				}
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Localization), "Get", new Type[]
		{
			typeof(AssetGuid),
			typeof(bool)
		})]
		[HarmonyPrefix]
		public static bool Get(AssetGuid guid, ref string __result)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			Keybinding valueOrDefault = KeybindManager._keybindingsByGuid.GetValueOrDefault(guid._a);
			if (valueOrDefault != null)
			{
				__result = valueOrDefault.Description.Name;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Options_ControlsPanel), "OnResetButtonClicked")]
		[HarmonyPrefix]
		public static bool OnResetButtonClicked()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<string, KeybindingBindings> keybindingValue in KeybindManager._keybindingValues)
			{
				keybindingValue.Deconstruct(out var key, out var value);
				string key2 = key;
				KeybindingBindings keybindingBindings = value;
				keybindingBindings.Primary = KeybindManager._keybindingsById[key2].Description.DefaultKeybinding;
				keybindingBindings.Secondary = (KeyCode)0;
			}
			KeybindManager.Save();
			return true;
		}

		private unsafe static bool TryGetInputFlagLocalization_Hook(IntPtr instance, InputFlag inputFlag, LocalizationKey* key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_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)
			Keybinding valueOrDefault = KeybindManager._keybindingsByFlags.GetValueOrDefault(inputFlag);
			if (valueOrDefault != null)
			{
				Unsafe.Write(key, new LocalizationKey(new AssetGuid
				{
					_a = valueOrDefault.AssetGuid
				}));
				return true;
			}
			return TryGetInputFlagLocalization_Original(instance, inputFlag, key);
		}
	}
	internal static class OnInitialize
	{
		private static class ServerDetours
		{
			[HarmonyPatch(typeof(GameBootstrap), "Start")]
			[HarmonyPostfix]
			public static void Initialize()
			{
				InvokePlugins();
			}
		}

		private static class ClientDetours
		{
			[HarmonyPatch(typeof(CustomWorldSpawning), "AddSystemsToWorld")]
			[HarmonyPostfix]
			public static void Initialize()
			{
				InvokePlugins();
			}
		}

		private static Harmony _harmony;

		public static bool HasInitialized { get; private set; }

		public static void Initialize()
		{
			_harmony = Harmony.CreateAndPatchAll(VWorld.IsServer ? typeof(ServerDetours) : typeof(ClientDetours), (string)null);
		}

		public static void Uninitialize()
		{
			_harmony.UnpatchSelf();
		}

		private static void InvokePlugins()
		{
			BloodstonePlugin.Logger.LogInfo((object)"Game has bootstrapped. Worlds and systems now exist.");
			if (HasInitialized)
			{
				return;
			}
			HasInitialized = true;
			foreach (KeyValuePair<string, PluginInfo> plugin in ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins)
			{
				plugin.Deconstruct(out var _, out var value);
				if (value.Instance is IRunOnInitialized runOnInitialized)
				{
					runOnInitialized.OnGameInitialized();
				}
			}
			foreach (BasePlugin loadedPlugin in Reload._loadedPlugins)
			{
				if (loadedPlugin is IRunOnInitialized runOnInitialized2)
				{
					runOnInitialized2.OnGameInitialized();
				}
			}
		}
	}
}
namespace Bloodstone.Features
{
	internal static class Reload
	{
		private class ReloadBehaviour : MonoBehaviour
		{
			private void Update()
			{
				if (_clientReloadKeybinding.IsPressed)
				{
					BloodstonePlugin.Logger.LogInfo((object)"Reloading client plugins...");
					UnloadPlugins();
					LoadPlugins();
				}
			}
		}

		private static string _reloadCommand;

		private static string _reloadPluginsFolder;

		private static ReloadBehaviour _clientBehavior;

		private static Keybinding _clientReloadKeybinding;

		internal static List<BasePlugin> _loadedPlugins = new List<BasePlugin>();

		internal static void Initialize(string reloadCommand, string reloadPluginsFolder)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			_reloadCommand = reloadCommand;
			_reloadPluginsFolder = reloadPluginsFolder;
			Chat.OnChatMessage += HandleReloadCommand;
			if (VWorld.IsClient)
			{
				KeybindingDescription description = default(KeybindingDescription);
				description.Id = "gg.deca.Bloodstone.reload";
				description.Category = "Bloodstone";
				description.Name = "Reload Plugins";
				description.DefaultKeybinding = (KeyCode)287;
				_clientReloadKeybinding = KeybindManager.Register(description);
				_clientBehavior = ((BasePlugin)BloodstonePlugin.Instance).AddComponent<ReloadBehaviour>();
			}
			LoadPlugins();
		}

		internal static void Uninitialize()
		{
			Chat.OnChatMessage -= HandleReloadCommand;
			if ((Object)(object)_clientBehavior != (Object)null)
			{
				Object.Destroy((Object)(object)_clientBehavior);
			}
		}

		private static void HandleReloadCommand(VChatEvent ev)
		{
			//IL_0014: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			if (!(ev.Message != _reloadCommand) && ev.User.IsAdmin)
			{
				ev.Cancel();
				UnloadPlugins();
				List<string> list = LoadPlugins();
				if (list.Count > 0)
				{
					ev.User.SendSystemMessage("Reloaded " + string.Join(", ", list) + ". See console for details.");
				}
				else
				{
					ev.User.SendSystemMessage("Did not reload any plugins because no reloadable plugins were found. Check the console for more details.");
				}
			}
		}

		private static void UnloadPlugins()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			bool flag = default(bool);
			for (int num = _loadedPlugins.Count - 1; num >= 0; num--)
			{
				BasePlugin val = _loadedPlugins[num];
				if (!val.Unload())
				{
					ManualLogSource logger = BloodstonePlugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(47, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Plugin ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((object)val).GetType().FullName);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" does not support unloading, skipping...");
					}
					logger.LogWarning(val2);
				}
				else
				{
					_loadedPlugins.RemoveAt(num);
				}
			}
		}

		private static List<string> LoadPlugins()
		{
			if (!Directory.Exists(_reloadPluginsFolder))
			{
				return new List<string>();
			}
			return Directory.GetFiles(_reloadPluginsFolder, "*.dll").SelectMany(LoadPlugin).ToList();
		}

		private static List<string> LoadPlugin(string path)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Expected O, but got Unknown
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Expected O, but got Unknown
			DefaultAssemblyResolver val = new DefaultAssemblyResolver();
			((BaseAssemblyResolver)val).AddSearchDirectory(_reloadPluginsFolder);
			((BaseAssemblyResolver)val).AddSearchDirectory(Paths.ManagedPath);
			((BaseAssemblyResolver)val).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
			((BaseAssemblyResolver)val).AddSearchDirectory(Path.Combine(Paths.BepInExRootPath, "interop"));
			AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(path, new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)val
			});
			try
			{
				((AssemblyNameReference)val2.Name).Name = $"{((AssemblyNameReference)val2.Name).Name}-{DateTime.Now.Ticks}";
				using MemoryStream memoryStream = new MemoryStream();
				val2.Write((Stream)memoryStream);
				List<string> list = new List<string>();
				bool flag = default(bool);
				foreach (Type pluginType in from x in Assembly.Load(memoryStream.ToArray()).GetTypes()
					where typeof(BasePlugin).IsAssignableFrom(x)
					select x)
				{
					if (!pluginType.GetCustomAttributes<ReloadableAttribute>().Any())
					{
						ManualLogSource logger = BloodstonePlugin.Logger;
						BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(48, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Plugin ");
							((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(pluginType.FullName);
							((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" is not marked as reloadable, skipping...");
						}
						logger.LogWarning(val3);
					}
					else
					{
						if (_loadedPlugins.Any((BasePlugin x) => ((object)x).GetType() == pluginType))
						{
							continue;
						}
						try
						{
							BasePlugin val4 = (BasePlugin)Activator.CreateInstance(pluginType);
							BepInPlugin metadata = MetadataHelper.GetMetadata((object)val4);
							_loadedPlugins.Add(val4);
							val4.Load();
							list.Add(metadata.Name);
							if (OnInitialize.HasInitialized && val4 is IRunOnInitialized runOnInitialized)
							{
								runOnInitialized.OnGameInitialized();
							}
							ManualLogSource logger2 = BloodstonePlugin.Logger;
							BepInExInfoLogInterpolatedStringHandler val5 = new BepInExInfoLogInterpolatedStringHandler(14, 1, ref flag);
							if (flag)
							{
								((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("Loaded plugin ");
								((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<string>(pluginType.FullName);
							}
							logger2.LogInfo(val5);
						}
						catch (Exception ex)
						{
							ManualLogSource logger3 = BloodstonePlugin.Logger;
							BepInExErrorLogInterpolatedStringHandler val6 = new BepInExErrorLogInterpolatedStringHandler(49, 1, ref flag);
							if (flag)
							{
								((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Plugin ");
								((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(pluginType.FullName);
								((BepInExLogInterpolatedStringHandler)val6).AppendLiteral(" threw an exception during initialization:");
							}
							logger3.LogError(val6);
							BloodstonePlugin.Logger.LogError((object)ex);
						}
					}
				}
				return list;
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}
}
namespace Bloodstone.API
{
	public interface IRunOnInitialized
	{
		void OnGameInitialized();
	}
	public static class KeybindManager
	{
		private static string KeybindingsPath = Path.Join(Paths.ConfigPath, "keybindings.json");

		internal static Dictionary<InputFlag, Keybinding> _keybindingsByFlags = new Dictionary<InputFlag, Keybinding>();

		internal static Dictionary<int, Keybinding> _keybindingsByGuid = new Dictionary<int, Keybinding>();

		internal static Dictionary<string, Keybinding> _keybindingsById = new Dictionary<string, Keybinding>();

		internal static Dictionary<string, KeybindingBindings> _keybindingValues = new Dictionary<string, KeybindingBindings>();

		public static Keybinding Register(KeybindingDescription description)
		{
			//IL_005c: 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)
			if (_keybindingsById.ContainsKey(description.Id))
			{
				throw new ArgumentException("Keybinding with id " + description.Id + " already registered");
			}
			Keybinding keybinding = new Keybinding(description);
			_keybindingsById.Add(description.Id, keybinding);
			_keybindingsByGuid.Add(keybinding.AssetGuid, keybinding);
			_keybindingsByFlags.Add(keybinding.InputFlag, keybinding);
			if (!_keybindingValues.ContainsKey(description.Id))
			{
				_keybindingValues.Add(description.Id, new KeybindingBindings
				{
					Id = description.Id,
					Primary = description.DefaultKeybinding,
					Secondary = (KeyCode)0
				});
			}
			return keybinding;
		}

		public static void Unregister(Keybinding keybinding)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (!_keybindingsById.ContainsKey(keybinding.Description.Id))
			{
				throw new ArgumentException("There was no keybinding with id " + keybinding.Description.Id + " registered");
			}
			_keybindingsByFlags.Remove(keybinding.InputFlag);
			_keybindingsByGuid.Remove(keybinding.AssetGuid);
			_keybindingsById.Remove(keybinding.Description.Id);
		}

		internal static void Load()
		{
			try
			{
				if (File.Exists(KeybindingsPath))
				{
					Dictionary<string, KeybindingBindings> dictionary = JsonSerializer.Deserialize<Dictionary<string, KeybindingBindings>>(File.ReadAllText(KeybindingsPath));
					if (dictionary != null)
					{
						_keybindingValues = dictionary;
					}
				}
			}
			catch (Exception ex)
			{
				BloodstonePlugin.Logger.LogError((object)"Error loading keybindings, using defaults: ");
				BloodstonePlugin.Logger.LogError((object)ex);
				_keybindingValues = new Dictionary<string, KeybindingBindings>();
			}
		}

		internal static void Save()
		{
			try
			{
				string contents = JsonSerializer.Serialize(_keybindingValues);
				File.WriteAllText(KeybindingsPath, contents);
			}
			catch (Exception ex)
			{
				BloodstonePlugin.Logger.LogError((object)"Error saving custom keybindings: ");
				BloodstonePlugin.Logger.LogError((object)ex);
			}
		}
	}
	public struct KeybindingDescription
	{
		public string Id;

		public string Category;

		public string Name;

		public KeyCode DefaultKeybinding;
	}
	public class Keybinding
	{
		public KeybindingDescription Description { get; }

		public KeyCode Primary => KeybindManager._keybindingValues[Description.Id].Primary;

		public KeyCode Secondary => KeybindManager._keybindingValues[Description.Id].Secondary;

		public bool IsPressed
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				if (!Input.GetKeyDown(Primary))
				{
					return Input.GetKeyDown(Secondary);
				}
				return true;
			}
		}

		internal InputFlag InputFlag { get; private set; }

		internal int AssetGuid { get; private set; }

		public Keybinding(KeybindingDescription description)
		{
			Description = description;
			ComputeInputFlag();
			ComputeAssetGuid();
		}

		private void ComputeInputFlag()
		{
			//IL_0031: 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)
			byte[] bytes = Encoding.UTF8.GetBytes(Description.Id);
			ulong num = xxHash64.ComputeHash(bytes, bytes.Length, 0uL);
			bool flag = false;
			do
			{
				flag = false;
				InputFlag[] values = Enum.GetValues<InputFlag>();
				foreach (InputFlag val in values)
				{
					if (num == (ulong)(long)val)
					{
						flag = true;
						num--;
					}
				}
			}
			while (flag);
			InputFlag = (InputFlag)num;
		}

		private void ComputeAssetGuid()
		{
			byte[] bytes = Encoding.UTF8.GetBytes(Description.Id);
			AssetGuid = (int)xxHash32.ComputeHash(bytes, bytes.Length, 0u);
		}
	}
	internal class KeybindingBindings
	{
		public string Id { get; set; }

		public KeyCode Primary { get; set; }

		public KeyCode Secondary { get; set; }
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class ReloadableAttribute : Attribute
	{
	}
	public static class VExtensions
	{
		public delegate void ActionRef<T>(ref T item);

		public static void SendSystemMessage(this User user, string message)
		{
			//IL_0017: 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)
			if (!VWorld.IsServer)
			{
				throw new Exception("SendSystemMessage can only be called on the server.");
			}
			ServerChatUtils.SendSystemMessageToClient(VWorld.Server.EntityManager, user, message);
		}

		public static void WithComponentData<T>(this Entity entity, ActionRef<T> action) where T : struct
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Game.EntityManager;
			T item = ((EntityManager)(ref entityManager)).GetComponentData<T>(entity);
			action(ref item);
			entityManager = VWorld.Game.EntityManager;
			((EntityManager)(ref entityManager)).SetComponentData<T>(entity, item);
		}
	}
	public interface VNetworkMessage
	{
		void Serialize(ref NetBufferOut writer);

		void Deserialize(NetBufferIn reader);
	}
	public static class VNetworkRegistry
	{
		public static void Unregister<T>()
		{
			MessageRegistry.Unregister<T>();
		}

		public static void UnregisterStruct<T>() where T : unmanaged
		{
			Unregister<VBlittableNetworkMessage<T>>();
		}

		public static void RegisterServerbound<T>(Action<FromCharacter, T> onMessageFromClient) where T : VNetworkMessage, new()
		{
			Action<FromCharacter, T> onMessageFromClient2 = onMessageFromClient;
			MessageRegistry.Register<T>(new RegisteredEventHandler
			{
				OnReceiveFromServer = delegate
				{
				},
				OnReceiveFromClient = delegate(FromCharacter user, NetBufferIn buf)
				{
					//IL_0008: 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)
					T arg = new T();
					arg.Deserialize(buf);
					onMessageFromClient2(user, arg);
				}
			});
		}

		public static void RegisterServerboundStruct<T>(Action<FromCharacter, T> onMessageFromClient) where T : unmanaged
		{
			Action<FromCharacter, T> onMessageFromClient2 = onMessageFromClient;
			RegisterServerbound(delegate(FromCharacter user, VBlittableNetworkMessage<T> msg)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				onMessageFromClient2(user, msg.Value);
			});
		}

		public static void RegisterClientbound<T>(Action<T> onMessageFromServer) where T : VNetworkMessage, new()
		{
			Action<T> onMessageFromServer2 = onMessageFromServer;
			MessageRegistry.Register<T>(new RegisteredEventHandler
			{
				OnReceiveFromServer = delegate(NetBufferIn buf)
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					T obj = new T();
					obj.Deserialize(buf);
					onMessageFromServer2(obj);
				},
				OnReceiveFromClient = delegate
				{
				}
			});
		}

		public static void RegisterClientboundStruct<T>(Action<T> onMessageFromServer) where T : unmanaged
		{
			Action<T> onMessageFromServer2 = onMessageFromServer;
			RegisterClientbound(delegate(VBlittableNetworkMessage<T> msg)
			{
				onMessageFromServer2(msg.Value);
			});
		}

		public static void RegisterBiDirectional<T>(Action<T> onMessageFromServer, Action<FromCharacter, T> onMessageFromClient) where T : VNetworkMessage, new()
		{
			Action<T> onMessageFromServer2 = onMessageFromServer;
			Action<FromCharacter, T> onMessageFromClient2 = onMessageFromClient;
			MessageRegistry.Register<T>(new RegisteredEventHandler
			{
				OnReceiveFromServer = delegate(NetBufferIn buf)
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					T obj = new T();
					obj.Deserialize(buf);
					onMessageFromServer2(obj);
				},
				OnReceiveFromClient = delegate(FromCharacter user, NetBufferIn buf)
				{
					//IL_0008: 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)
					T arg = new T();
					arg.Deserialize(buf);
					onMessageFromClient2(user, arg);
				}
			});
		}

		public static void RegisterBiDirectionalStruct<T>(Action<T> onMessageFromServer, Action<FromCharacter, T> onMessageFromClient) where T : unmanaged
		{
			Action<T> onMessageFromServer2 = onMessageFromServer;
			Action<FromCharacter, T> onMessageFromClient2 = onMessageFromClient;
			RegisterBiDirectional(delegate(VBlittableNetworkMessage<T> msg)
			{
				onMessageFromServer2(msg.Value);
			}, delegate(FromCharacter user, VBlittableNetworkMessage<T> msg)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				onMessageFromClient2(user, msg.Value);
			});
		}
	}
	public static class VNetwork
	{
		public static void SendToClient(int userIndex, VNetworkMessage msg)
		{
			EventDispatcher.SendToClient(userIndex, msg);
		}

		public static void SendToClient(User user, VNetworkMessage msg)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			EventDispatcher.SendToClient(user.Index, msg);
		}

		public static void SendToClient(FromCharacter fromCharacter, VNetworkMessage msg)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			EventDispatcher.SendToClient(((EntityManager)(ref entityManager)).GetComponentData<User>(fromCharacter.User).Index, msg);
		}

		public static void SendToClientStruct<T>(int userIndex, T msg) where T : unmanaged
		{
			SendToClient(userIndex, new VBlittableNetworkMessage<T>(msg));
		}

		public static void SendToClientStruct<T>(User user, T msg) where T : unmanaged
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			SendToClient(user, new VBlittableNetworkMessage<T>(msg));
		}

		public static void SendToClientStruct<T>(FromCharacter fromCharacter, T msg) where T : unmanaged
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			SendToClient(fromCharacter, new VBlittableNetworkMessage<T>(msg));
		}

		public static void SendToServer(VNetworkMessage msg)
		{
			EventDispatcher.SendToServer(msg);
		}

		public static void SendToServerStruct<T>(T msg) where T : unmanaged
		{
			SendToServer(new VBlittableNetworkMessage<T>(msg));
		}
	}
	public static class VWorld
	{
		private static World? _clientWorld;

		private static World? _serverWorld;

		public static World Server
		{
			get
			{
				if (_serverWorld != null && _serverWorld.IsCreated)
				{
					return _serverWorld;
				}
				_serverWorld = GetWorld("Server") ?? throw new Exception("There is no Server world (yet). Did you install a server mod on the client?");
				return _serverWorld;
			}
		}

		public static World Client
		{
			get
			{
				if (_clientWorld != null && _clientWorld.IsCreated)
				{
					return _clientWorld;
				}
				_clientWorld = GetWorld("Client_0") ?? throw new Exception("There is no Client world (yet). Did you install a client mod on the server?");
				return _clientWorld;
			}
		}

		public static World Default => World.DefaultGameObjectInjectionWorld;

		public static World Game
		{
			get
			{
				if (!IsClient)
				{
					return Server;
				}
				return Client;
			}
		}

		public static bool IsServer => Application.productName == "VRisingServer";

		public static bool IsClient => Application.productName == "VRising";

		private static World? GetWorld(string name)
		{
			Enumerator<World> enumerator = World.s_AllWorlds.GetEnumerator();
			while (enumerator.MoveNext())
			{
				World current = enumerator.Current;
				if (current.Name == name)
				{
					_serverWorld = current;
					return current;
				}
			}
			return null;
		}
	}
}
namespace Costura
{
	[CompilerGenerated]
	internal static class AssemblyLoader
	{
		private static object nullCacheLock = new object();

		private static Dictionary<string, bool> nullCache = new Dictionary<string, bool>();

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

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

		private static int isAttached;

		private static string CultureToString(CultureInfo culture)
		{
			if (culture == null)
			{
				return "";
			}
			return culture.Name;
		}

		private static Assembly ReadExistingAssembly(AssemblyName name)
		{
			AppDomain currentDomain = AppDomain.CurrentDomain;
			Assembly[] assemblies = currentDomain.GetAssemblies();
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				AssemblyName name2 = assembly.GetName();
				if (string.Equals(name2.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) && string.Equals(CultureToString(name2.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase))
				{
					return assembly;
				}
			}
			return null;
		}

		private static void CopyTo(Stream source, Stream destination)
		{
			byte[] array = new byte[81920];
			int count;
			while ((count = source.Read(array, 0, array.Length)) != 0)
			{
				destination.Write(array, 0, count);
			}
		}

		private static Stream LoadStream(string fullName)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			if (fullName.EndsWith(".compressed"))
			{
				using (Stream stream = executingAssembly.GetManifestResourceStream(fullName))
				{
					using DeflateStream source = new DeflateStream(stream, CompressionMode.Decompress);
					MemoryStream memoryStream = new MemoryStream();
					CopyTo(source, memoryStream);
					memoryStream.Position = 0L;
					return memoryStream;
				}
			}
			return executingAssembly.GetManifestResourceStream(fullName);
		}

		private static Stream LoadStream(Dictionary<string, string> resourceNames, string name)
		{
			if (resourceNames.TryGetValue(name, out var value))
			{
				return LoadStream(value);
			}
			return null;
		}

		private static byte[] ReadStream(Stream stream)
		{
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			return array;
		}

		private static Assembly ReadFromEmbeddedResources(Dictionary<string, string> assemblyNames, Dictionary<string, string> symbolNames, AssemblyName requestedAssemblyName)
		{
			string text = requestedAssemblyName.Name.ToLowerInvariant();
			if (requestedAssemblyName.CultureInfo != null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name))
			{
				text = requestedAssemblyName.CultureInfo.Name + "." + text;
			}
			byte[] rawAssembly;
			using (Stream stream = LoadStream(assemblyNames, text))
			{
				if (stream == null)
				{
					return null;
				}
				rawAssembly = ReadStream(stream);
			}
			using (Stream stream2 = LoadStream(symbolNames, text))
			{
				if (stream2 != null)
				{
					byte[] rawSymbolStore = ReadStream(stream2);
					return Assembly.Load(rawAssembly, rawSymbolStore);
				}
			}
			return Assembly.Load(rawAssembly);
		}

		public static Assembly ResolveAssembly(object sender, ResolveEventArgs e)
		{
			lock (nullCacheLock)
			{
				if (nullCache.ContainsKey(e.Name))
				{
					return null;
				}
			}
			AssemblyName assemblyName = new AssemblyName(e.Name);
			Assembly assembly = ReadExistingAssembly(assemblyName);
			if ((object)assembly != null)
			{
				return assembly;
			}
			assembly = ReadFromEmbeddedResources(assemblyNames, symbolNames, assemblyName);
			if ((object)assembly == null)
			{
				lock (nullCacheLock)
				{
					nullCache[e.Name] = true;
				}
				if ((assemblyName.Flags & AssemblyNameFlags.Retargetable) != 0)
				{
					assembly = Assembly.Load(assemblyName);
				}
			}
			return assembly;
		}

		static AssemblyLoader()
		{
			assemblyNames.Add("standart.hash.xxhash", "costura.standart.hash.xxhash.dll.compressed");
			assemblyNames.Add("system.text.json", "costura.system.text.json.dll.compressed");
		}

		public static void Attach()
		{
			if (Interlocked.Exchange(ref isAttached, 1) == 1)
			{
				return;
			}
			AppDomain currentDomain = AppDomain.CurrentDomain;
			currentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
			{
				lock (nullCacheLock)
				{
					if (nullCache.ContainsKey(e.Name))
					{
						return null;
					}
				}
				AssemblyName assemblyName = new AssemblyName(e.Name);
				Assembly assembly = ReadExistingAssembly(assemblyName);
				if ((object)assembly != null)
				{
					return assembly;
				}
				assembly = ReadFromEmbeddedResources(assemblyNames, symbolNames, assemblyName);
				if ((object)assembly == null)
				{
					lock (nullCacheLock)
					{
						nullCache[e.Name] = true;
					}
					if ((assemblyName.Flags & AssemblyNameFlags.Retargetable) != 0)
					{
						assembly = Assembly.Load(assemblyName);
					}
				}
				return assembly;
			};
		}
	}
}
internal class Bloodstone_ProcessedByFody
{
	internal const string FodyVersion = "6.6.2.0";

	internal const string Costura = "5.7.0";
}

BloodyEncounters.dll

Decompiled 5 months ago
#define DEBUG
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Bloodstone.API;
using Bloodstone.Hooks;
using BloodyEncounters.Commands;
using BloodyEncounters.Components;
using BloodyEncounters.Configuration;
using BloodyEncounters.DB;
using BloodyEncounters.DB.Models;
using BloodyEncounters.Exceptions;
using BloodyEncounters.Patch;
using BloodyEncounters.Services;
using BloodyEncounters.Systems;
using BloodyEncounters.Utils;
using BloodyEncounters_VRising.GameData;
using BloodyEncounters_VRising.GameData.Methods;
using BloodyEncounters_VRising.GameData.Models;
using BloodyEncounters_VRising.GameData.Models.Base;
using BloodyEncounters_VRising.GameData.Models.Data;
using BloodyEncounters_VRising.GameData.Models.Internals;
using BloodyEncounters_VRising.GameData.Patch;
using BloodyEncounters_VRising.GameData.Utils;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.Auth;
using ProjectM.Behaviours;
using ProjectM.CastleBuilding;
using ProjectM.CastleBuilding.Placement;
using ProjectM.Gameplay;
using ProjectM.Gameplay.Clan;
using ProjectM.Gameplay.Scripting;
using ProjectM.Hybrid;
using ProjectM.Network;
using ProjectM.Pathfinding;
using ProjectM.Physics;
using ProjectM.Portrait;
using ProjectM.Roofs;
using ProjectM.Scripting;
using ProjectM.Sequencer;
using ProjectM.Shared;
using ProjectM.Terrain;
using ProjectM.Tiles;
using ProjectM.UI;
using Stunlock.Core;
using Stunlock.Localization;
using Stunlock.Sequencer;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Systems;
using Unity.Scenes;
using Unity.Transforms;
using UnityEngine;
using VampireCommandFramework;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BloodyEncounters")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A server side mod for V Rising which spawns a random NPC near a random online player at random intervals, and the player wins a random item reward if the NPC is killed within the given time limit.")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("1.5.0")]
[assembly: AssemblyProduct("BloodyEncounters")]
[assembly: AssemblyTitle("BloodyEncounters")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[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 BloodyEncounters
{
	public static class ECSExtensions
	{
		public unsafe static void Write<T>(this Entity entity, T componentData) where T : struct
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			byte[] array = StructureToByteArray(componentData);
			int num = Marshal.SizeOf<T>();
			fixed (byte* ptr = array)
			{
				EntityManager entityManager = VWorld.Server.EntityManager;
				((EntityManager)(ref entityManager)).SetComponentDataRaw(entity, val.TypeIndex, (void*)ptr, num);
			}
		}

		public static byte[] StructureToByteArray<T>(T structure) where T : struct
		{
			int num = Marshal.SizeOf(structure);
			byte[] array = new byte[num];
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			Marshal.StructureToPtr(structure, intPtr, fDeleteOld: true);
			Marshal.Copy(intPtr, array, 0, num);
			Marshal.FreeHGlobal(intPtr);
			return array;
		}

		public unsafe static T Read<T>(this Entity entity) where T : struct
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			void* componentDataRawRO = ((EntityManager)(ref entityManager)).GetComponentDataRawRO(entity, val.TypeIndex);
			return Marshal.PtrToStructure<T>(new IntPtr(componentDataRawRO));
		}

		public static DynamicBuffer<T> ReadBuffer<T>(this Entity entity) where T : struct
		{
			//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_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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			return ((EntityManager)(ref entityManager)).GetBuffer<T>(entity);
		}

		public static void Add<T>(this Entity entity)
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			((EntityManager)(ref entityManager)).AddComponent(entity, val);
		}

		public static void Remove<T>(this Entity entity)
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			((EntityManager)(ref entityManager)).RemoveComponent(entity, val);
		}

		public static bool Has<T>(this Entity entity)
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			return ((EntityManager)(ref entityManager)).HasComponent(entity, val);
		}

		public static void LogComponentTypes(this Entity entity)
		{
			//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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			Enumerator<ComponentType> enumerator = ((EntityManager)(ref entityManager)).GetComponentTypes(entity, (Allocator)2).GetEnumerator();
			bool flag = default(bool);
			while (enumerator.MoveNext())
			{
				ComponentType current = enumerator.Current;
				ManualLogSource logger = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(0, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ComponentType>(current);
				}
				logger.LogInfo(val);
			}
			Plugin.Logger.LogInfo((object)"===");
		}

		public static void LogComponentTypes(this EntityQuery entityQuery)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0040: 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_0078: Expected O, but got Unknown
			Il2CppStructArray<ComponentType> queryTypes = ((EntityQuery)(ref entityQuery)).GetQueryTypes();
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val;
			foreach (ComponentType item in (Il2CppArrayBase<ComponentType>)(object)queryTypes)
			{
				ManualLogSource logger = Plugin.Logger;
				val = new BepInExInfoLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Query Component Type: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ComponentType>(item);
				}
				logger.LogInfo(val);
			}
			ManualLogSource logger2 = Plugin.Logger;
			val = new BepInExInfoLogInterpolatedStringHandler(3, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("===");
			}
			logger2.LogInfo(val);
		}

		public static string LookupName(this PrefabGUID prefabGuid)
		{
			//IL_0012: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			PrefabCollectionSystem existingSystem = VWorld.Server.GetExistingSystem<PrefabCollectionSystem>();
			object obj;
			if (!((PrefabCollectionSystem_Base)existingSystem).PrefabGuidToNameDictionary.ContainsKey(prefabGuid))
			{
				obj = "GUID Not Found";
			}
			else
			{
				string text = ((PrefabCollectionSystem_Base)existingSystem).PrefabGuidToNameDictionary[prefabGuid];
				PrefabGUID val = prefabGuid;
				obj = text + " " + ((object)(PrefabGUID)(ref val)).ToString();
			}
			return obj.ToString();
		}
	}
	[BepInPlugin("BloodyEncounters", "BloodyEncounters", "1.5.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin, IRunOnInitialized
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static OnGameDataInitializedEventHandler <0>__GameDataOnInitialize;

			public static OnGameDataDestroyedEventHandler <1>__GameDataOnDestroy;

			public static GameFrameUpdateEventHandler <2>__GameFrameUpdate;
		}

		public static ManualLogSource Logger;

		private static Harmony _harmony;

		public static World World;

		internal static Plugin Instance { get; private set; }

		public override void Load()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			_harmony = new Harmony("BloodyEncounters");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			_harmony.PatchAll(typeof(BloodyEncounters.Patch.ServerEvents));
			_harmony.PatchAll(typeof(UnitSpawnerService));
			GameData.OnInitialize += GameDataOnInitialize;
			GameData.OnDestroy += GameDataOnDestroy;
			CommandRegistry.RegisterAll();
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(18, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("BloodyEncounters");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
			}
			log.LogInfo(val);
		}

		public override bool Unload()
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			GameData.OnInitialize -= GameDataOnInitialize;
			GameData.OnDestroy -= GameDataOnDestroy;
			((BasePlugin)this).Config.Clear();
			TimerSystem._encounterTimer?.Stop();
			EncounterSystem.Destroy();
			GameFrame.Uninitialize();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(20, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("BloodyEncounters");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is unloaded!");
			}
			logger.LogInfo(val);
			return true;
		}

		public void OnGameInitialized()
		{
			World = VWorld.Server;
		}

		private static void GameDataOnInitialize(World world)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			Logger.LogInfo((object)"Loading main data");
			Database.Initialize();
			Logger.LogInfo((object)"Binding configuration");
			PluginConfig.Initialize();
			EncounterSystem.Initialize();
			TimerSystem._encounterTimer = new Timer();
			if (PluginConfig.Enabled.Value)
			{
				TimerSystem.StartEncounterTimer();
			}
			GameFrame.Initialize();
			object obj = <>O.<2>__GameFrameUpdate;
			if (obj == null)
			{
				GameFrameUpdateEventHandler val = WorldBossSystem.GameFrameUpdate;
				<>O.<2>__GameFrameUpdate = val;
				obj = (object)val;
			}
			GameFrame.OnUpdate += (GameFrameUpdateEventHandler)obj;
		}

		private static void GameDataOnDestroy()
		{
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "BloodyEncounters";

		public const string PLUGIN_NAME = "BloodyEncounters";

		public const string PLUGIN_VERSION = "1.5.0";
	}
}
namespace BloodyEncounters.Utils
{
	internal static class DataFactory
	{
		private static readonly Random Random = new Random();

		private static List<NpcEncounterModel> _npcs;

		private static List<ItemEncounterModel> _items;

		internal static NpcEncounterModel GetRandomNpc()
		{
			_npcs = Database.NPCS;
			return _npcs.GetRandomItem();
		}

		internal static ItemEncounterModel GetRandomItem(NpcEncounterModel npc)
		{
			_items = npc.items;
			return _items.GetRandomItem();
		}

		private static T GetRandomItem<T>(this List<T> items)
		{
			if (items == null || items.Count == 0)
			{
				return default(T);
			}
			return items[Random.Next(items.Count)];
		}
	}
}
namespace BloodyEncounters.Systems
{
	internal class BuffSystem
	{
		public const int NO_DURATION = 0;

		public const int DEFAULT_DURATION = -1;

		public const int RANDOM_POWER = -1;

		public static bool BuffBoss(Entity character, Entity user, PrefabGUID buff, int duration = -1)
		{
			//IL_000e: 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_0017: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0045: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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_0095: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_00d2: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: 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_011e: 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_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			DebugEventsSystem existingSystem = VWorld.Server.GetExistingSystem<DebugEventsSystem>();
			ApplyBuffDebugEvent val = default(ApplyBuffDebugEvent);
			val.BuffPrefabGUID = buff;
			ApplyBuffDebugEvent val2 = val;
			FromCharacter val3 = default(FromCharacter);
			val3.User = user;
			val3.Character = character;
			FromCharacter val4 = val3;
			Entity entity = default(Entity);
			if (!BuffUtility.TryGetBuff(VWorld.Server.EntityManager, character, buff, ref entity))
			{
				existingSystem.ApplyBuff(val4, val2);
				if (BuffUtility.TryGetBuff(VWorld.Server.EntityManager, character, buff, ref entity))
				{
					if (entity.Has<CreateGameplayEventsOnSpawn>())
					{
						entity.Remove<CreateGameplayEventsOnSpawn>();
					}
					if (entity.Has<GameplayEventListeners>())
					{
						entity.Remove<GameplayEventListeners>();
					}
					if (duration > 0 && duration != -1)
					{
						if (entity.Has<LifeTime>())
						{
							LifeTime componentData = entity.Read<LifeTime>();
							componentData.Duration = duration;
							entity.Write<LifeTime>(componentData);
						}
					}
					else if (duration == 0)
					{
						if (entity.Has<LifeTime>())
						{
							LifeTime componentData2 = entity.Read<LifeTime>();
							componentData2.Duration = -1f;
							componentData2.EndAction = (LifeTimeEndAction)0;
							entity.Write<LifeTime>(componentData2);
						}
						if (entity.Has<RemoveBuffOnGameplayEvent>())
						{
							entity.Remove<RemoveBuffOnGameplayEvent>();
						}
						if (entity.Has<RemoveBuffOnGameplayEventEntry>())
						{
							entity.Remove<RemoveBuffOnGameplayEventEntry>();
						}
					}
					return true;
				}
				return false;
			}
			return false;
		}

		public static bool BuffPlayer(Entity character, Entity user, PrefabGUID buff, int duration = -1, bool persistsThroughDeath = false)
		{
			//IL_0001: 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_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_0023: 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_0028: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_006f: 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_0075: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: 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_010e: 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_011f: 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_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: 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_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			ClearExtraBuffs(character);
			DebugEventsSystem existingSystem = VWorld.Server.GetExistingSystem<DebugEventsSystem>();
			ApplyBuffDebugEvent val = default(ApplyBuffDebugEvent);
			val.BuffPrefabGUID = buff;
			ApplyBuffDebugEvent val2 = val;
			FromCharacter val3 = default(FromCharacter);
			val3.User = user;
			val3.Character = character;
			FromCharacter val4 = val3;
			Entity entity = default(Entity);
			if (!BuffUtility.TryGetBuff(VWorld.Server.EntityManager, character, buff, ref entity))
			{
				existingSystem.ApplyBuff(val4, val2);
				if (BuffUtility.TryGetBuff(VWorld.Server.EntityManager, character, buff, ref entity))
				{
					if (entity.Has<CreateGameplayEventsOnSpawn>())
					{
						entity.Remove<CreateGameplayEventsOnSpawn>();
					}
					if (entity.Has<GameplayEventListeners>())
					{
						entity.Remove<GameplayEventListeners>();
					}
					if (persistsThroughDeath)
					{
						entity.Add<Buff_Persists_Through_Death>();
						if (entity.Has<RemoveBuffOnGameplayEvent>())
						{
							entity.Remove<RemoveBuffOnGameplayEvent>();
						}
						if (entity.Has<RemoveBuffOnGameplayEventEntry>())
						{
							entity.Remove<RemoveBuffOnGameplayEventEntry>();
						}
					}
					if (duration > 0 && duration != -1)
					{
						if (entity.Has<LifeTime>())
						{
							LifeTime componentData = entity.Read<LifeTime>();
							componentData.Duration = duration;
							entity.Write<LifeTime>(componentData);
						}
					}
					else if (duration == 0)
					{
						if (entity.Has<LifeTime>())
						{
							LifeTime componentData2 = entity.Read<LifeTime>();
							componentData2.Duration = -1f;
							componentData2.EndAction = (LifeTimeEndAction)0;
							entity.Write<LifeTime>(componentData2);
						}
						if (entity.Has<RemoveBuffOnGameplayEvent>())
						{
							entity.Remove<RemoveBuffOnGameplayEvent>();
						}
						if (entity.Has<RemoveBuffOnGameplayEventEntry>())
						{
							entity.Remove<RemoveBuffOnGameplayEventEntry>();
						}
					}
					return true;
				}
				return false;
			}
			return false;
		}

		public static void ClearExtraBuffs(Entity player)
		{
			//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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: 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_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)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			DynamicBuffer<BuffBuffer> buffer = ((EntityManager)(ref entityManager)).GetBuffer<BuffBuffer>(player);
			List<string> list = new List<string> { "BloodBuff", "SetBonus", "EquipBuff", "Combat", "VBlood_Ability_Replace", "Shapeshift", "Interact", "AB_Consumable" };
			Enumerator<BuffBuffer> enumerator = buffer.GetEnumerator();
			while (enumerator.MoveNext())
			{
				BuffBuffer current = enumerator.Current;
				bool flag = true;
				foreach (string item in list)
				{
					if (current.PrefabGuid.LookupName().Contains(item))
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					DestroyUtility.Destroy(VWorld.Server.EntityManager, current.Entity, (DestroyDebugReason)13, (string)null, 0);
				}
			}
			Equipment val = player.Read<Equipment>();
			EquipmentType val2 = default(EquipmentType);
			if (!((Equipment)(ref val)).IsEquipped(new PrefabGUID(1063517722), ref val2) && BuffUtility.HasBuff(VWorld.Server.EntityManager, player, new PrefabGUID(476186894)))
			{
				UnbuffCharacter(player, new PrefabGUID(476186894));
			}
		}

		public static void UnbuffCharacter(Entity Character, PrefabGUID buffGUID)
		{
			//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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Entity val = default(Entity);
			if (BuffUtility.TryGetBuff(VWorld.Server.EntityManager, Character, buffGUID, ref val))
			{
				DestroyUtility.Destroy(VWorld.Server.EntityManager, val, (DestroyDebugReason)13, (string)null, 0);
			}
		}
	}
	internal class EncounterSystem
	{
		private static readonly ConcurrentDictionary<ulong, ConcurrentDictionary<int, ItemEncounterModel>> RewardsMap = new ConcurrentDictionary<ulong, ConcurrentDictionary<int, ItemEncounterModel>>();

		private static readonly ConcurrentDictionary<int, UserModel> NpcPlayerMap = new ConcurrentDictionary<int, UserModel>();

		internal static Dictionary<long, (float actualDuration, Action<Entity> Actions)> PostActions = new Dictionary<long, (float, Action<Entity>)>();

		public static Random Random = new Random();

		private static string MessageTemplate => PluginConfig.EncounterMessageTemplate.Value;

		internal static void Initialize()
		{
			BloodyEncounters.Patch.ServerEvents.OnDeath += ServerEvents_OnDeath;
			BloodyEncounters.Patch.ServerEvents.OnUnitSpawned += ServerEvents_OnUnitSpawned;
		}

		internal static void Destroy()
		{
			BloodyEncounters.Patch.ServerEvents.OnDeath -= ServerEvents_OnDeath;
			BloodyEncounters.Patch.ServerEvents.OnUnitSpawned -= ServerEvents_OnUnitSpawned;
		}

		internal static void StartEncounter(UserModel user = null)
		{
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			World world = Plugin.World;
			if (user == null)
			{
				IEnumerable<UserModel> source = GameData.Users.Online.Where((UserModel u) => GameData.Users.FromEntity(u.Entity).Character.Equipment.Level >= (float)PluginConfig.EncounterMinLevel.Value);
				if (PluginConfig.SkipPlayersInCastle.Value)
				{
					source = source.Where((UserModel u) => !u.IsInCastle());
				}
				if (PluginConfig.SkipPlayersInCombat.Value)
				{
					source = source.Where((UserModel u) => !u.IsInCombat());
				}
				user = source.OrderBy((UserModel _) => Random.Next()).FirstOrDefault();
			}
			if (user == null)
			{
				Plugin.Logger.LogMessage((object)"Could not find any eligible players for a random encounter...");
				return;
			}
			NpcEncounterModel randomNpc = DataFactory.GetRandomNpc();
			bool flag = default(bool);
			if (randomNpc == null)
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(23, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not find any NPCs");
				}
				logger.LogWarning(val);
				return;
			}
			ManualLogSource logger2 = Plugin.Logger;
			BepInExMessageLogInterpolatedStringHandler val2 = new BepInExMessageLogInterpolatedStringHandler(46, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Attempting to start a new encounter for ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(user.CharacterName);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" with ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(randomNpc.name);
			}
			logger2.LogMessage(val2);
			try
			{
				NpcPlayerMap[randomNpc.PrefabGUID] = user;
				randomNpc.SpawnWithLocation(user.Entity, user.Position);
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
		}

		public static void ServerEvents_OnUnitSpawned(World world, Entity entity)
		{
			//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_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: 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_0081: 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_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = world.EntityManager;
			if (!((EntityManager)(ref entityManager)).HasComponent<PrefabGUID>(entity))
			{
				return;
			}
			PrefabGUID componentData = ((EntityManager)(ref entityManager)).GetComponentData<PrefabGUID>(entity);
			if (!NpcPlayerMap.TryGetValue(componentData.GuidHash, out var value) || !((EntityManager)(ref entityManager)).HasComponent<LifeTime>(entity) || !Database.GetNPCFromEntity(entity, out var npc))
			{
				return;
			}
			LifeTime componentData2 = ((EntityManager)(ref entityManager)).GetComponentData<LifeTime>(entity);
			if ((double)Math.Abs(componentData2.Duration - npc.Lifetime) > 0.001)
			{
				return;
			}
			NpcPlayerMap.TryRemove(componentData.GuidHash, out var _);
			if (!RewardsMap.ContainsKey(value.PlatformId))
			{
				RewardsMap[value.PlatformId] = new ConcurrentDictionary<int, ItemEncounterModel>();
			}
			string message = string.Format(MessageTemplate, npc.name, npc.Lifetime);
			value.SendSystemMessage(message);
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(25, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Encounters started: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(value.CharacterName);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" vs. ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(npc.name);
			}
			logger.LogDebug(val);
			if (PluginConfig.NotifyAdminsAboutEncountersAndRewards.Value)
			{
				IEnumerable<UserModel> enumerable = GameData.Users.Online.Where((UserModel x) => x.IsAdmin);
				foreach (UserModel item in enumerable)
				{
					item.SendSystemMessage("Encounter started: " + value.CharacterName + " vs. " + npc.name);
				}
			}
			RewardsMap[value.PlatformId][entity.Index] = DataFactory.GetRandomItem(npc);
		}

		public static void ServerEvents_OnDeath(DeathEventListenerSystem sender, NativeArray<DeathEvent> deathEvents)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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)
			//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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_0057: 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_005f: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Expected O, but got Unknown
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<DeathEvent> enumerator = deathEvents.GetEnumerator();
			PrefabGUID itemGuid = default(PrefabGUID);
			bool flag = default(bool);
			while (enumerator.MoveNext())
			{
				DeathEvent current = enumerator.Current;
				EntityManager entityManager = ((ComponentSystemBase)sender).EntityManager;
				if (!((EntityManager)(ref entityManager)).HasComponent<PlayerCharacter>(current.Killer))
				{
					continue;
				}
				entityManager = ((ComponentSystemBase)sender).EntityManager;
				PlayerCharacter componentData = ((EntityManager)(ref entityManager)).GetComponentData<PlayerCharacter>(current.Killer);
				UserModel userModel = GameData.Users.FromEntity(componentData.UserEntity);
				if (!RewardsMap.TryGetValue(userModel.PlatformId, out var value) || !value.TryGetValue(current.Died.Index, out var value2))
				{
					continue;
				}
				((PrefabGUID)(ref itemGuid))..ctor(value2.ItemID);
				int stack = value2.Stack;
				if (!userModel.TryGiveItem(new PrefabGUID(value2.ItemID), stack, out var _))
				{
					userModel.DropItemNearby(itemGuid, stack);
				}
				string message = string.Format(PluginConfig.RewardMessageTemplate.Value, value2.Color, value2.name);
				userModel.SendSystemMessage(message);
				value.TryRemove(current.Died.Index, out var _);
				ManualLogSource logger = Plugin.Logger;
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(16, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(userModel.CharacterName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" earned reward: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(value2.name);
				}
				logger.LogDebug(val);
				string message2 = string.Format(PluginConfig.RewardAnnouncementMessageTemplate.Value, userModel.CharacterName, value2.Color, value2.name);
				if (PluginConfig.NotifyAllPlayersAboutRewards.Value)
				{
					IEnumerable<UserModel> online = GameData.Users.Online;
					foreach (UserModel item in online.Where((UserModel u) => u.PlatformId != userModel.PlatformId))
					{
						item.SendSystemMessage(message2);
					}
				}
				else
				{
					if (!PluginConfig.NotifyAdminsAboutEncountersAndRewards.Value)
					{
						continue;
					}
					IEnumerable<UserModel> enumerable = GameData.Users.Online.Where((UserModel x) => x.IsAdmin);
					foreach (UserModel item2 in enumerable)
					{
						item2.SendSystemMessage($"{userModel.CharacterName} earned an encounter reward: <color={value2.Color}>{value2.name}</color>");
					}
				}
			}
		}
	}
	internal class FontColorChatSystem
	{
		public static string Color(string hexColor, string text)
		{
			return $"<color={hexColor}>{text}</color>";
		}

		public static string Red(string text)
		{
			return Color("#E90000", text);
		}

		public static string Blue(string text)
		{
			return Color("#0000ff", text);
		}

		public static string Green(string text)
		{
			return Color("#7FE030", text);
		}

		public static string Yellow(string text)
		{
			return Color("#FBC01E", text);
		}
	}
	internal class TimerSystem
	{
		public static Timer _encounterTimer;

		public static void StartEncounterTimer()
		{
			_encounterTimer.Start(delegate
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Expected O, but got Unknown
				ManualLogSource logger2 = Plugin.Logger;
				bool flag2 = default(bool);
				BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(23, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(DateTime.Now.ToString());
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" Starting an encounter.");
				}
				logger2.LogDebug(val2);
				EncounterSystem.StartEncounter();
			}, delegate(object input)
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Expected O, but got Unknown
				if (!(input is int num) || 1 == 0)
				{
					Plugin.Logger.LogError((object)"Encounter timer delay function parameter is not a valid integer");
					return TimeSpan.MaxValue;
				}
				if (num < 1)
				{
					num = 1;
				}
				int num2 = new Random().Next(PluginConfig.EncounterTimerMin.Value, PluginConfig.EncounterTimerMax.Value);
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(39, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(DateTime.Now.ToString());
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Next encounter will start in ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num2 / num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" seconds.");
				}
				logger.LogDebug(val);
				return TimeSpan.FromSeconds(num2) / num;
			});
		}
	}
	internal class WorldBossSystem
	{
		public static Dictionary<string, HashSet<string>> vbloodKills = new Dictionary<string, HashSet<string>>();

		private static DateTime lastDateMinute = DateTime.Now;

		private static DateTime lastDateSecond = DateTime.Now;

		public static void AddKiller(string vblood, string killerCharacterName)
		{
			if (!vbloodKills.ContainsKey(vblood))
			{
				vbloodKills[vblood] = new HashSet<string>();
			}
			vbloodKills[vblood].Add(killerCharacterName);
		}

		public static void RemoveKillers(string vblood)
		{
			vbloodKills[vblood] = new HashSet<string>();
		}

		public static List<string> GetKillers(string vblood)
		{
			return vbloodKills[vblood].ToList();
		}

		public static void SendAnnouncementMessage(string vblood, BossEncounterModel bossModel)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			string announcementMessage = GetAnnouncementMessage(vblood, bossModel.name);
			if (announcementMessage == null)
			{
				return;
			}
			IEnumerable<UserModel> online = GameData.Users.Online;
			bossModel.DropItems(vblood);
			foreach (UserModel item in online)
			{
				ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, announcementMessage);
			}
			RemoveKillers(vblood);
		}

		public static string GetAnnouncementMessage(string vblood, string name)
		{
			List<string> killers = GetKillers(vblood);
			StringBuilder stringBuilder = new StringBuilder();
			if (killers.Count == 0)
			{
				return null;
			}
			if (killers.Count == 1)
			{
				stringBuilder.Append(FontColorChatSystem.Yellow(killers[0]));
			}
			if (killers.Count == 2)
			{
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder3 = stringBuilder2;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(2, 3, stringBuilder2);
				handler.AppendFormatted(FontColorChatSystem.Yellow(killers[0]));
				handler.AppendLiteral(" ");
				handler.AppendFormatted(PluginConfig.VBloodFinalConcatCharacters.Value);
				handler.AppendLiteral(" ");
				handler.AppendFormatted(FontColorChatSystem.Yellow(killers[1]));
				stringBuilder3.Append(ref handler);
			}
			if (killers.Count > 2)
			{
				for (int i = 0; i < killers.Count; i++)
				{
					if (i == killers.Count - 1)
					{
						StringBuilder stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder4 = stringBuilder2;
						StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(1, 2, stringBuilder2);
						handler.AppendFormatted(PluginConfig.VBloodFinalConcatCharacters.Value);
						handler.AppendLiteral(" ");
						handler.AppendFormatted(FontColorChatSystem.Yellow(killers[i]));
						stringBuilder4.Append(ref handler);
					}
					else
					{
						StringBuilder stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder5 = stringBuilder2;
						StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(2, 1, stringBuilder2);
						handler.AppendFormatted(FontColorChatSystem.Yellow(killers[i]));
						handler.AppendLiteral(", ");
						stringBuilder5.Append(ref handler);
					}
				}
			}
			string value = PluginConfig.KillMessageBossTemplate.Value;
			value = value.Replace("#user#", $"{stringBuilder}");
			value = value.Replace("#vblood#", FontColorChatSystem.Red(name) ?? "");
			return FontColorChatSystem.Green(value ?? "");
		}

		public static void GameFrameUpdate()
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			DateTime date = DateTime.Now;
			if (lastDateMinute.ToString("HH:mm") != date.ToString("HH:mm"))
			{
				lastDateMinute = date;
				List<BossEncounterModel> list = Database.WORLDBOSS.Where((BossEncounterModel x) => x.Hour == date.ToString("HH:mm")).ToList();
				if (list != null && GameData.Users.Online.Count() > 0)
				{
					UserModel userModel = GameData.Users.Online.FirstOrDefault();
					foreach (BossEncounterModel item in list)
					{
						item.Spawn(userModel.Entity);
						WorldBossCommand._lastBossSpawnModel = item;
					}
				}
			}
			if (!(lastDateSecond.ToString("HH:mm:ss") != date.ToString("HH:mm:ss")))
			{
				return;
			}
			lastDateSecond = date;
			List<BossEncounterModel> list2 = Database.WORLDBOSS.Where((BossEncounterModel x) => x.HourDespawn == date.ToString("HH:mm:ss") && x.bossEntity.HasValue).ToList();
			if (list2 == null || GameData.Users.Online.Count() <= 0)
			{
				return;
			}
			foreach (BossEncounterModel item2 in list2)
			{
				string value = PluginConfig.DespawnMessageBossTemplate.Value;
				value = value.Replace("#worldbossname#", FontColorChatSystem.Yellow(WorldBossCommand._lastBossSpawnModel.name ?? ""));
				ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChatSystem.Green(value ?? ""));
				WorldBossCommand._lastBossSpawnModel = null;
			}
		}
	}
}
namespace BloodyEncounters.Services
{
	internal class UnitSpawnerService
	{
		[HarmonyPatch(typeof(UnitSpawnerReactSystem), "OnUpdate")]
		public static class UnitSpawnerReactSystem_Patch
		{
			public static bool Enabled { get; set; }

			public static void Prefix(UnitSpawnerReactSystem __instance)
			{
				//IL_0013: 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_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Expected O, but got Unknown
				//IL_006d: 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_007b: 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_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Expected O, but got Unknown
				//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_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)
				//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0105: 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_0122: Unknown result type (might be due to invalid IL or missing references)
				//IL_0129: Expected O, but got Unknown
				//IL_0153: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b8: Expected O, but got Unknown
				//IL_0220: Unknown result type (might be due to invalid IL or missing references)
				//IL_0224: Unknown result type (might be due to invalid IL or missing references)
				//IL_0235: Unknown result type (might be due to invalid IL or missing references)
				//IL_0237: Unknown result type (might be due to invalid IL or missing references)
				//IL_023c: Unknown result type (might be due to invalid IL or missing references)
				//IL_023e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0245: Unknown result type (might be due to invalid IL or missing references)
				//IL_024a: Unknown result type (might be due to invalid IL or missing references)
				//IL_024e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0250: Unknown result type (might be due to invalid IL or missing references)
				//IL_025a: Unknown result type (might be due to invalid IL or missing references)
				if (!Enabled)
				{
					return;
				}
				EntityQuery _OnUpdate_LambdaJob0_entityQuery = __instance.__OnUpdate_LambdaJob0_entityQuery;
				NativeArray<Entity> val = ((EntityQuery)(ref _OnUpdate_LambdaJob0_entityQuery)).ToEntityArray((Allocator)2);
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(40, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Processing ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(val.Length);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" in UnitSpawnerReactionSystem");
				}
				logger.LogDebug(val2);
				Enumerator<Entity> enumerator = val.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Entity current = enumerator.Current;
					ManualLogSource logger2 = Plugin.Logger;
					val2 = new BepInExDebugLogInterpolatedStringHandler(27, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Checking if ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(current.Index);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" has lifetime..");
					}
					logger2.LogDebug(val2);
					EntityManager entityManager = Plugin.World.EntityManager;
					if (!((EntityManager)(ref entityManager)).HasComponent<LifeTime>(current))
					{
						break;
					}
					entityManager = Plugin.World.EntityManager;
					LifeTime componentData = ((EntityManager)(ref entityManager)).GetComponentData<LifeTime>(current);
					long num = (long)Mathf.Round(componentData.Duration);
					ManualLogSource logger3 = Plugin.Logger;
					val2 = new BepInExDebugLogInterpolatedStringHandler(34, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Found durationKey ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<long>(num);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" from LifeTime(");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(componentData.Duration);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(")");
					}
					logger3.LogDebug(val2);
					if (UnitSpawner.PostActions.TryGetValue(num, out (float, Action<Entity>) value))
					{
						(float, Action<Entity>) tuple = value;
						float item = tuple.Item1;
						Action<Entity> item2 = tuple.Item2;
						ManualLogSource logger4 = Plugin.Logger;
						val2 = new BepInExDebugLogInterpolatedStringHandler(38, 2, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Found post actions for ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<long>(num);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" with ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(item);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" duration");
						}
						logger4.LogDebug(val2);
						UnitSpawner.PostActions.Remove(num);
						LifeTimeEndAction endAction = (LifeTimeEndAction)((!(item < 0f)) ? 2 : 0);
						LifeTime val3 = default(LifeTime);
						val3.Duration = item;
						val3.EndAction = endAction;
						LifeTime val4 = val3;
						entityManager = Plugin.World.EntityManager;
						((EntityManager)(ref entityManager)).SetComponentData<LifeTime>(current, val4);
						item2(current);
					}
				}
			}
		}

		private static Entity empty_entity = default(Entity);

		internal const int DEFAULT_MINRANGE = 1;

		internal const int DEFAULT_MAXRANGE = 1;

		internal Dictionary<long, (float actualDuration, Action<Entity> Actions)> PostActions = new Dictionary<long, (float, Action<Entity>)>();

		public static UnitSpawnerService UnitSpawner { get; internal set; } = new UnitSpawnerService();


		public void SpawnWithCallback(Entity user, PrefabGUID unit, float2 position, float duration, Action<Entity> postActions)
		{
			//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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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_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_0029: 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_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)
			EntityManager entityManager = Plugin.World.EntityManager;
			Translation componentData = ((EntityManager)(ref entityManager)).GetComponentData<Translation>(user);
			float3 val = default(float3);
			((float3)(ref val))..ctor(position.x, componentData.Value.y, position.y);
			UnitSpawnerUpdateSystem existingSystem = Plugin.World.GetExistingSystem<UnitSpawnerUpdateSystem>();
			UnitSpawnerReactSystem_Patch.Enabled = true;
			long num = NextKey();
			existingSystem.SpawnUnit(empty_entity, unit, val, 1, 1f, 1f, (float)num);
			PostActions.Add(num, (duration, postActions));
		}

		internal long NextKey()
		{
			Random random = new Random();
			int num = 5;
			long num2;
			do
			{
				num2 = random.NextInt64(10000L) * 3;
				num--;
				if (num < 0)
				{
					throw new Exception("Failed to generate a unique key for UnitSpawnerService");
				}
			}
			while (PostActions.ContainsKey(num2));
			return num2;
		}
	}
}
namespace BloodyEncounters.Patch
{
	[HarmonyPatch]
	public class VBloodSystem_Patch
	{
		private const double SendMessageDelay = 2.0;

		private static bool checkKiller = false;

		private static Dictionary<string, DateTime> lastKillerUpdate = new Dictionary<string, DateTime>();

		private static EntityManager entityManager = VWorld.Server.EntityManager;

		[HarmonyPatch(typeof(VBloodSystem), "OnUpdate")]
		[HarmonyPrefix]
		public static void OnUpdate_Prefix(VBloodSystem __instance)
		{
			//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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_003e: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: 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_0248: 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)
			if (__instance.EventList.Length > 0)
			{
				Enumerator<VBloodConsumed> enumerator = __instance.EventList.GetEnumerator();
				while (enumerator.MoveNext())
				{
					VBloodConsumed current = enumerator.Current;
					if (((EntityManager)(ref entityManager)).HasComponent<PlayerCharacter>(current.Target))
					{
						PlayerCharacter componentData = ((EntityManager)(ref entityManager)).GetComponentData<PlayerCharacter>(current.Target);
						User componentData2 = ((EntityManager)(ref entityManager)).GetComponentData<User>(componentData.UserEntity);
						FixedString128 vblood = ((PrefabCollectionSystem_Base)__instance._PrefabCollectionSystem).PrefabDataLookup[current.Source].AssetName;
						BossEncounterModel bossEncounterModel = Database.WORLDBOSS.Where((BossEncounterModel x) => x.AssetName == ((object)(FixedString128)(ref vblood)).ToString() && x.bossEntity.HasValue).FirstOrDefault();
						if (bossEncounterModel != null)
						{
							WorldBossSystem.AddKiller(((object)(FixedString128)(ref vblood)).ToString(), ((object)(FixedString64)(ref componentData2.CharacterName)).ToString());
							lastKillerUpdate[((object)(FixedString128)(ref vblood)).ToString()] = DateTime.Now;
							checkKiller = true;
						}
					}
				}
			}
			else
			{
				if (!checkKiller)
				{
					return;
				}
				bool flag = false;
				foreach (KeyValuePair<string, DateTime> kvp in lastKillerUpdate)
				{
					DateTime value = kvp.Value;
					if (DateTime.Now - value < TimeSpan.FromSeconds(2.0))
					{
						flag = true;
						continue;
					}
					BossEncounterModel bossEncounterModel2 = Database.WORLDBOSS.Where((BossEncounterModel x) => x.AssetName == kvp.Key && x.bossEntity.HasValue).FirstOrDefault();
					if (bossEncounterModel2 == null)
					{
						continue;
					}
					EntityManager val = ((ComponentSystemBase)__instance).EntityManager;
					EntityQueryDesc[] array = new EntityQueryDesc[1];
					EntityQueryDesc val2 = new EntityQueryDesc();
					val2.All = Il2CppStructArray<ComponentType>.op_Implicit((ComponentType[])(object)new ComponentType[2]
					{
						ComponentType.ReadOnly<VBloodUnit>(),
						ComponentType.ReadOnly<LifeTime>()
					});
					val2.Options = (EntityQueryOptions)27;
					array[0] = val2;
					EntityQuery val3 = ((EntityManager)(ref val)).CreateEntityQuery((EntityQueryDesc[])(object)array);
					Enumerator<Entity> enumerator3 = ((EntityQuery)(ref val3)).ToEntityArray((Allocator)2).GetEnumerator();
					while (enumerator3.MoveNext())
					{
						Entity current2 = enumerator3.Current;
						if (((object)(Entity)(ref current2)).Equals((object?)bossEncounterModel2.bossEntity))
						{
							WorldBossCommand._lastBossSpawnModel = null;
							WorldBossSystem.SendAnnouncementMessage(kvp.Key, bossEncounterModel2);
							break;
						}
					}
				}
				checkKiller = flag;
			}
		}
	}
	public delegate void OnUnitSpawnedEventHandler(World world, Entity entity);
	public delegate void DeathEventHandler(DeathEventListenerSystem sender, NativeArray<DeathEvent> deathEvents);
	public static class ServerEvents
	{
		public static event DeathEventHandler OnDeath;

		public static event OnUnitSpawnedEventHandler OnUnitSpawned;

		[HarmonyPatch(typeof(DeathEventListenerSystem), "OnUpdate")]
		[HarmonyPostfix]
		private static void DeathEventListenerSystemPatch_Postfix(DeathEventListenerSystem __instance)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0058: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(33, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("DeathEventListenerSystem.OnUpdate");
			}
			logger.LogDebug(val);
			try
			{
				EntityQuery deathEventQuery = __instance._DeathEventQuery;
				NativeArray<DeathEvent> deathEvents = ((EntityQuery)(ref deathEventQuery)).ToComponentDataArray<DeathEvent>((Allocator)2);
				if (deathEvents.Length > 0)
				{
					ServerEvents.OnDeath?.Invoke(__instance, deathEvents);
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
		}

		[HarmonyPatch(typeof(UnitSpawnerReactSystem), "OnUpdate")]
		[HarmonyPostfix]
		public static void Prefix(UnitSpawnerReactSystem __instance)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(31, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("UnitSpawnerReactSystem.OnUpdate");
			}
			logger.LogDebug(val);
			EntityQuery _OnUpdate_LambdaJob0_entityQuery = __instance.__OnUpdate_LambdaJob0_entityQuery;
			Enumerator<Entity> enumerator = ((EntityQuery)(ref _OnUpdate_LambdaJob0_entityQuery)).ToEntityArray((Allocator)2).GetEnumerator();
			while (enumerator.MoveNext())
			{
				Entity current = enumerator.Current;
				try
				{
					ServerEvents.OnUnitSpawned?.Invoke(((ComponentSystemBase)__instance).World, current);
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogError((object)ex);
				}
			}
		}
	}
}
namespace BloodyEncounters.Exceptions
{
	internal class NPCDontExistException : Exception
	{
		public NPCDontExistException()
		{
		}

		public NPCDontExistException(string message)
			: base(message)
		{
		}

		public NPCDontExistException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected NPCDontExistException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal class NPCExistException : Exception
	{
		public NPCExistException()
		{
		}

		public NPCExistException(string message)
			: base(message)
		{
		}

		public NPCExistException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected NPCExistException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal class ProductDontExistException : Exception
	{
		public ProductDontExistException()
		{
		}

		public ProductDontExistException(string message)
			: base(message)
		{
		}

		public ProductDontExistException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected ProductDontExistException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal class ProductExistException : Exception
	{
		public ProductExistException()
		{
		}

		public ProductExistException(string message)
			: base(message)
		{
		}

		public ProductExistException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected ProductExistException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal class WorldBossDontExistException : Exception
	{
		public WorldBossDontExistException()
		{
		}

		public WorldBossDontExistException(string message)
			: base(message)
		{
		}

		public WorldBossDontExistException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected WorldBossDontExistException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal class WorldBossExistException : Exception
	{
		public WorldBossExistException()
		{
		}

		public WorldBossExistException(string message)
			: base(message)
		{
		}

		public WorldBossExistException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected WorldBossExistException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
}
namespace BloodyEncounters.DB
{
	internal static class Database
	{
		private static readonly Random Random = new Random();

		public static readonly string ConfigPath = Path.Combine(Paths.ConfigPath, "BloodyEncounters");

		public static string NPCSListFile = Path.Combine(ConfigPath, "NPCS.json");

		public static string WORLDBOSSListFile = Path.Combine(ConfigPath, "WORLDBOSS.json");

		public static List<NpcEncounterModel> NPCS { get; set; } = new List<NpcEncounterModel>();


		public static List<BossEncounterModel> WORLDBOSS { get; set; } = new List<BossEncounterModel>();


		public static void Initialize()
		{
			createDatabaseFiles();
			loadDatabase();
		}

		public static bool createDatabaseFiles()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			if (!Directory.Exists(ConfigPath))
			{
				Directory.CreateDirectory(ConfigPath);
			}
			if (!File.Exists(NPCSListFile))
			{
				File.WriteAllText(NPCSListFile, "[]");
			}
			if (!File.Exists(WORLDBOSSListFile))
			{
				File.WriteAllText(WORLDBOSSListFile, "[]");
			}
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(19, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Create Database: OK");
			}
			logger.LogDebug(val);
			return true;
		}

		public static bool saveDatabase()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				string contents = JsonSerializer.Serialize(NPCS, new JsonSerializerOptions
				{
					WriteIndented = true
				});
				File.WriteAllText(NPCSListFile, contents);
				contents = JsonSerializer.Serialize(WORLDBOSS, new JsonSerializerOptions
				{
					WriteIndented = true
				});
				File.WriteAllText(WORLDBOSSListFile, contents);
				ManualLogSource logger = Plugin.Logger;
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(17, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Save Database: OK");
				}
				logger.LogDebug(val);
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(20, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error SaveDatabase: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				logger2.LogError(val2);
				return false;
			}
		}

		public static bool loadDatabase()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				string json = File.ReadAllText(NPCSListFile);
				NPCS = JsonSerializer.Deserialize<List<NpcEncounterModel>>(json);
				json = File.ReadAllText(WORLDBOSSListFile);
				WORLDBOSS = JsonSerializer.Deserialize<List<BossEncounterModel>>(json);
				ManualLogSource logger = Plugin.Logger;
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(17, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Load Database: OK");
				}
				logger.LogDebug(val);
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(20, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error LoadDatabase: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				logger2.LogError(val2);
				return false;
			}
		}

		public static bool GetNPC(string NPCName, out NpcEncounterModel npc)
		{
			npc = NPCS.Where((NpcEncounterModel x) => x.name == NPCName).FirstOrDefault();
			if (npc == null)
			{
				return false;
			}
			return true;
		}

		public static bool GetNPCFromEntity(Entity npcEntity, out NpcEncounterModel npc)
		{
			//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)
			npc = NPCS.Where(delegate(NpcEncounterModel x)
			{
				//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_000a: Unknown result type (might be due to invalid IL or missing references)
				Entity npcEntity2 = x.npcEntity;
				return ((Entity)(ref npcEntity2)).Equals(npcEntity);
			}).FirstOrDefault();
			if (npc == null)
			{
				return false;
			}
			return true;
		}

		public static bool AddNPC(string NPCName, int prefabGUIDOfNPC, int levelAbove, int lifetime)
		{
			if (GetNPC(NPCName, out var npc))
			{
				throw new NPCExistException();
			}
			npc = new NpcEncounterModel();
			npc.name = NPCName;
			npc.PrefabGUID = prefabGUIDOfNPC;
			npc.levelAbove = levelAbove;
			npc.Lifetime = lifetime;
			NPCS.Add(npc);
			saveDatabase();
			return true;
		}

		public static bool RemoveNPC(string NPCName)
		{
			if (GetNPC(NPCName, out var npc))
			{
				NPCS.Remove(npc);
				saveDatabase();
				return true;
			}
			throw new NPCDontExistException();
		}

		public static bool GetBoss(string NPCName, out BossEncounterModel boss)
		{
			boss = WORLDBOSS.Where((BossEncounterModel x) => x.name == NPCName).FirstOrDefault();
			if (boss == null)
			{
				return false;
			}
			return true;
		}

		public static bool GetBOSSFromEntity(Entity npcEntity, out BossEncounterModel boss)
		{
			//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)
			boss = WORLDBOSS.Where((BossEncounterModel x) => x.bossEntity.Equals(npcEntity)).FirstOrDefault();
			if (boss == null)
			{
				return false;
			}
			return true;
		}

		public static bool AddBoss(string NPCName, int prefabGUIDOfNPC, int level, int multiplier, int lifetime)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if (GetBoss(NPCName, out var boss))
			{
				throw new WorldBossExistException();
			}
			ConvertedAssetData val = ((PrefabCollectionSystem_Base)VWorld.Server.GetExistingSystem<PrefabCollectionSystem>()).PrefabDataLookup[new PrefabGUID(prefabGUIDOfNPC)];
			string assetName = ((object)(FixedString128)(ref val.AssetName)).ToString();
			boss = new BossEncounterModel();
			boss.name = NPCName;
			boss.PrefabGUID = prefabGUIDOfNPC;
			boss.AssetName = assetName;
			boss.level = level;
			boss.multiplier = multiplier;
			boss.Lifetime = lifetime;
			WORLDBOSS.Add(boss);
			saveDatabase();
			return true;
		}

		public static bool RemoveBoss(string BossName)
		{
			if (GetBoss(BossName, out var boss))
			{
				WORLDBOSS.Remove(boss);
				saveDatabase();
				return true;
			}
			throw new WorldBossDontExistException();
		}

		public static T GetRandomItem<T>(this List<T> items)
		{
			if (items == null || items.Count == 0)
			{
				return default(T);
			}
			return items[Random.Next(items.Count)];
		}
	}
}
namespace BloodyEncounters.DB.Models
{
	internal class BossEncounterModel
	{
		public string name { get; set; } = string.Empty;


		public string AssetName { get; set; } = string.Empty;


		public string Hour { get; set; } = string.Empty;


		public string HourDespawn { get; set; } = string.Empty;


		public int PrefabGUID { get; set; }

		public int level { get; set; }

		public int multiplier { get; set; }

		public List<ItemEncounterModel> items { get; set; } = new List<ItemEncounterModel>();


		public Entity? bossEntity { get; set; } = null;


		public NpcModel npcModel { get; set; }

		public float Lifetime { get; set; }

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public List<ItemEncounterModel> GetItems()
		{
			return items;
		}

		public bool GetItem(int itemPrefabID, out ItemEncounterModel item)
		{
			item = items.Where((ItemEncounterModel x) => x.ItemID == itemPrefabID).FirstOrDefault();
			if (item == null)
			{
				return false;
			}
			return true;
		}

		public bool GetItemFromName(string ItemName, out ItemEncounterModel item)
		{
			item = items.Where((ItemEncounterModel x) => x.name == ItemName).FirstOrDefault();
			if (item == null)
			{
				return false;
			}
			return true;
		}

		public bool AddItem(string ItemName, int ItemPrefabID, int Stack, int Chance = 1)
		{
			if (!GetItem(ItemPrefabID, out var item))
			{
				item = new ItemEncounterModel();
				item.name = ItemName;
				item.ItemID = ItemPrefabID;
				item.Stack = Stack;
				item.Chance = Chance;
				items.Add(item);
				Database.saveDatabase();
				return true;
			}
			throw new ProductExistException();
		}

		public bool RemoveItem(string ItemName)
		{
			if (GetItemFromName(ItemName, out var item))
			{
				items.Remove(item);
				Database.saveDatabase();
				return true;
			}
			throw new ProductDontExistException();
		}

		public bool SpawnWithLocation(Entity sender, float3 pos)
		{
			//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_001b: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			UnitSpawnerService.UnitSpawner.SpawnWithCallback(sender, new PrefabGUID(PrefabGUID), new float2(pos.x, pos.z), Lifetime, delegate(Entity e)
			{
				//IL_000c: 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_0024: Unknown result type (might be due to invalid IL or missing references)
				npcModel = GameData.Npcs.FromEntity(e);
				ModifyBoss(sender, e);
			});
			return true;
		}

		public bool Spawn(Entity sender)
		{
			//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_001b: 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_0037: 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)
			UnitSpawnerService.UnitSpawner.SpawnWithCallback(sender, new PrefabGUID(PrefabGUID), new float2(x, z), Lifetime, delegate(Entity e)
			{
				//IL_000c: 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_0024: Unknown result type (might be due to invalid IL or missing references)
				npcModel = GameData.Npcs.FromEntity(e);
				ModifyBoss(sender, e);
			});
			string value = PluginConfig.SpawnMessageBossTemplate.Value;
			value = value.Replace("#time#", FontColorChatSystem.Yellow($"{Lifetime / 60f}"));
			value = value.Replace("#worldbossname#", FontColorChatSystem.Yellow(name ?? ""));
			ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChatSystem.Green(value ?? ""));
			return true;
		}

		public bool DropItems(string vblood)
		{
			//IL_0070: 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)
			PrefabGUID itemGuid = default(PrefabGUID);
			foreach (ItemEncounterModel item in items)
			{
				if (!probabilityGeneratingReward(item.Chance))
				{
					continue;
				}
				List<string> killers = WorldBossSystem.GetKillers(vblood);
				foreach (string item2 in killers)
				{
					((PrefabGUID)(ref itemGuid))..ctor(item.ItemID);
					int stack = item.Stack;
					UserModel userByCharacterName = GameData.Users.GetUserByCharacterName(item2);
					if (!userByCharacterName.TryGiveItem(itemGuid, stack, out var _))
					{
						userByCharacterName.DropItemNearby(itemGuid, stack);
					}
				}
			}
			bossEntity = null;
			HourDespawn = DateTime.Parse(Hour).AddSeconds(Lifetime).ToString("HH:mm:ss");
			return true;
		}

		private static bool probabilityGeneratingReward(int percentage)
		{
			int num = new Random().Next(1, 100);
			if (num <= percentage * 100)
			{
				return true;
			}
			return false;
		}

		public void ModifyBoss(Entity user, Entity boss)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_0071: 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_007d: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			int num = GameData.Users.Online.Count();
			UnitLevel componentData = boss.Read<UnitLevel>();
			componentData.Level = level;
			boss.Write<UnitLevel>(componentData);
			Health val = boss.Read<Health>();
			((ModifiableFloat)(ref val.MaxHealth)).Value = ModifiableFloat.op_Implicit(val.MaxHealth) * (float)(num * multiplier);
			val.Value = ((ModifiableFloat)(ref val.MaxHealth)).Value;
			boss.Write<Health>(val);
			if (BuffSystem.BuffBoss(boss, user, new PrefabGUID(PluginConfig.BuffForWorldBoss.Value), 0))
			{
			}
			RenameBoss(boss, name);
			bossEntity = boss;
		}

		public void SetLocation(float3 position)
		{
			//IL_0002: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			x = position.x;
			z = position.z;
			y = position.y;
			Database.saveDatabase();
		}

		private static void RenameBoss(Entity merchant, string nameMerchant)
		{
		}

		internal void SetAssetName(string v)
		{
			AssetName = v;
			Database.saveDatabase();
		}

		internal void SetHour(string hour)
		{
			Hour = hour;
			HourDespawn = DateTime.Parse(hour).AddSeconds(Lifetime).ToString("HH:mm:ss");
			Database.saveDatabase();
		}

		internal void SetHourDespawn()
		{
			HourDespawn = DateTime.Now.AddSeconds(Lifetime).ToString("HH:mm:ss");
			Database.saveDatabase();
		}
	}
	internal class ItemEncounterModel
	{
		public string name { get; set; }

		public int ItemID { get; set; }

		public int Stack { get; set; }

		public int Chance { get; set; } = 1;


		public string Color { get; set; } = "#daa520";

	}
	internal class NpcEncounterModel
	{
		public string name { get; set; } = string.Empty;


		public int PrefabGUID { get; set; }

		public int levelAbove { get; set; }

		public List<ItemEncounterModel> items { get; set; } = new List<ItemEncounterModel>();


		public Entity npcEntity { get; set; } = default(Entity);


		public NpcModel npcModel { get; set; }

		public float Lifetime { get; set; }

		public List<ItemEncounterModel> GetItems()
		{
			return items;
		}

		public bool GetItem(int itemPrefabID, out ItemEncounterModel item)
		{
			item = items.Where((ItemEncounterModel x) => x.ItemID == itemPrefabID).FirstOrDefault();
			if (item == null)
			{
				return false;
			}
			return true;
		}

		public bool GetItemFromName(string ItemName, out ItemEncounterModel item)
		{
			item = items.Where((ItemEncounterModel x) => x.name == ItemName).FirstOrDefault();
			if (item == null)
			{
				return false;
			}
			return true;
		}

		public bool AddItem(string ItemName, int ItemPrefabID, int Stack)
		{
			if (!GetItem(ItemPrefabID, out var item))
			{
				item = new ItemEncounterModel();
				item.name = ItemName;
				item.ItemID = ItemPrefabID;
				item.Stack = Stack;
				items.Add(item);
				Database.saveDatabase();
				return true;
			}
			throw new ProductExistException();
		}

		public bool RemoveItem(string ItemName)
		{
			if (GetItemFromName(ItemName, out var item))
			{
				items.Remove(item);
				Database.saveDatabase();
				return true;
			}
			throw new ProductDontExistException();
		}

		public bool SpawnWithLocation(Entity sender, float3 pos)
		{
			//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_001b: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			UnitSpawnerService.UnitSpawner.SpawnWithCallback(sender, new PrefabGUID(PrefabGUID), new float2(pos.x, pos.z), Lifetime, delegate(Entity e)
			{
				//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_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)
				npcEntity = e;
				npcModel = GameData.Npcs.FromEntity(npcEntity);
				ModifyNPC(sender, e);
			});
			return true;
		}

		public void ModifyNPC(Entity user, Entity npc)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_0046: 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_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_0056: Unknown result type (might be due to invalid IL or missing references)
			float level = GameData.Users.FromEntity(user).Character.Equipment.Level;
			EntityManager entityManager = Plugin.World.EntityManager;
			UnitLevel componentData = ((EntityManager)(ref entityManager)).GetComponentData<UnitLevel>(npc);
			componentData.Level = (int)(level + (float)levelAbove);
			entityManager = Plugin.World.EntityManager;
			((EntityManager)(ref entityManager)).SetComponentData<UnitLevel>(npc, componentData);
			RenameNPCt(npc, name);
		}

		private static void RenameNPCt(Entity merchant, string nameMerchant)
		{
		}
	}
}
namespace BloodyEncounters.Configuration
{
	internal class PluginConfig
	{
		private static ConfigFile _mainConfig;

		public static ConfigEntry<bool> Enabled { get; private set; }

		public static ConfigEntry<bool> SkipPlayersInCastle { get; private set; }

		public static ConfigEntry<int> EncounterTimerMin { get; private set; }

		public static ConfigEntry<int> EncounterTimerMax { get; private set; }

		public static ConfigEntry<int> EncounterMinLevel { get; private set; }

		public static ConfigEntry<int> BuffForWorldBoss { get; private set; }

		public static ConfigEntry<string> EncounterMessageTemplate { get; private set; }

		public static ConfigEntry<string> RewardMessageTemplate { get; private set; }

		public static ConfigEntry<string> SpawnMessageBossTemplate { get; private set; }

		public static ConfigEntry<string> DespawnMessageBossTemplate { get; private set; }

		public static ConfigEntry<string> KillMessageBossTemplate { get; private set; }

		public static ConfigEntry<string> RewardAnnouncementMessageTemplate { get; private set; }

		public static ConfigEntry<string> VBloodFinalConcatCharacters { get; private set; }

		public static ConfigEntry<bool> NotifyAdminsAboutEncountersAndRewards { get; private set; }

		public static ConfigEntry<bool> NotifyAllPlayersAboutRewards { get; private set; }

		public static ConfigEntry<bool> SkipPlayersInCombat { get; private set; }

		public static void Initialize()
		{
			//IL_005b: 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_0065: Expected O, but got Unknown
			string path = Paths.ConfigPath ?? Path.Combine("BepInEx", "config");
			string text = Path.Combine(path, "BloodyEncounters");
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			string text2 = Path.Combine(text, "BloodyEncounters.cfg");
			_mainConfig = (File.Exists(text2) ? new ConfigFile(text2, false) : new ConfigFile(text2, true));
			Enabled = _mainConfig.Bind<bool>("Main", "Enabled", true, "Determines whether the random encounter timer is enabled or not.");
			SkipPlayersInCastle = _mainConfig.Bind<bool>("Main", "SkipPlayersInCastle", true, "When enabled, players who are in a castle are excluded from encounters");
			SkipPlayersInCombat = _mainConfig.Bind<bool>("Main", "SkipPlayersInCombat", false, "When enabled, players who are in combat are excluded from the random encounters.");
			EncounterTimerMin = _mainConfig.Bind<int>("Main", "EncounterTimerMin", 1200, "Minimum seconds before a new encounter is initiated. This value is divided by the online users count.");
			EncounterTimerMax = _mainConfig.Bind<int>("Main", "EncounterTimerMax", 2400, "Maximum seconds before a new encounter is initiated. This value is divided by the online users count.");
			EncounterMinLevel = _mainConfig.Bind<int>("Main", "EncounterMinLevel", 10, "The lower value for the Player level for encounter.");
			EncounterMessageTemplate = _mainConfig.Bind<string>("Main", "EncounterMessageTemplate", "You have encountered a <color=#daa520>{0}</color>. You have <color=#daa520>{1}</color> seconds to kill it for a chance of a random reward.", "System message template for the encounter.");
			RewardMessageTemplate = _mainConfig.Bind<string>("Main", "RewardMessageTemplate", "Congratulations. Your reward: <color={0}>{1}</color>.", "System message template for the reward.");
			RewardAnnouncementMessageTemplate = _mainConfig.Bind<string>("Main", "RewardAnnouncementMessageTemplate", "{0} earned an encounter reward: <color={1}>{2}</color>.", "System message template for the reward announcement.");
			NotifyAdminsAboutEncountersAndRewards = _mainConfig.Bind<bool>("Main", "NotifyAdminsAboutEncountersAndRewards", true, "If enabled, all online admins are notified about encounters and rewards.");
			NotifyAllPlayersAboutRewards = _mainConfig.Bind<bool>("Main", "NotifyAllPlayersAboutRewards", false, "When enabled, all online players are notified about any player's rewards.");
			KillMessageBossTemplate = _mainConfig.Bind<string>("Main", "KillMessageBossTemplate", "The World Boss has been defeated. Congratulations to #user# for beating #vblood#!", "The message that will appear globally once the boss gets killed.");
			SpawnMessageBossTemplate = _mainConfig.Bind<string>("Main", "SpawnMessageBossTemplate", "A World Boss #worldbossname# has been summon you got #time# minutes to defeat it!. Use the command <color=#FBC01E>.encounter worldboss tp</color> to teleport to his position and start the fight!", "The message that will appear globally one the boss gets spawned.");
			DespawnMessageBossTemplate = _mainConfig.Bind<string>("Main", "DespawnMessageBossTemplate", "You failed to kill the World Boss #worldbossname# in time.", "The message that will appear globally if the players failed to kill the boss.");
			BuffForWorldBoss = _mainConfig.Bind<int>("Main", "BuffForWorldBoss", 1163490655, "Buff that applies to each of the World Bosses that we create with our mod.");
			VBloodFinalConcatCharacters = _mainConfig.Bind<string>("Main", "WorldBossFinalConcatCharacters", "and", "Final string for concat two or more players kill a WorldBoss Boss.");
		}

		public static void Destroy()
		{
			_mainConfig.Clear();
		}

		private static string CleanupName(string name)
		{
			Regex regex = new Regex("[^a-zA-Z0-9 -]");
			return regex.Replace(name, "");
		}
	}
}
namespace BloodyEncounters.Components
{
	public class Timer : IDisposable
	{
		private bool _enabled;

		private bool _isRunning;

		private DateTime _lastRunTime;

		private TimeSpan _delay;

		private Action<World> _action;

		private Func<object, TimeSpan> _delayAction;

		public void Start(Action<World> action, TimeSpan delay)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			_delay = delay;
			_lastRunTime = DateTime.UtcNow - delay;
			_action = action;
			_enabled = true;
			GameFrame.OnUpdate += new GameFrameUpdateEventHandler(GameFrame_OnUpdate);
		}

		public void Start(Action<World> action, Func<object, TimeSpan> delayAction)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			_delayAction = delayAction;
			_delay = _delayAction(1);
			_lastRunTime = DateTime.UtcNow;
			_action = action;
			_enabled = true;
			GameFrame.OnUpdate += new GameFrameUpdateEventHandler(GameFrame_OnUpdate);
		}

		private void GameFrame_OnUpdate()
		{
			Update(GameData.World);
		}

		private void Update(World world)
		{
			if (!_enabled || _isRunning || _lastRunTime + _delay >= DateTime.UtcNow)
			{
				return;
			}
			_isRunning =

BloodyShop.dll

Decompiled 5 months ago
#define DEBUG
using System;
using System.CodeDom.Compiler;
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.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BloodShop_NAudio.Dmo;
using BloodShop_NAudio.FileFormats.Wav;
using BloodShop_NAudio.Utils;
using BloodShop_NAudio.Wave;
using BloodShop_UniverseLib;
using BloodShop_UniverseLib.Config;
using BloodShop_UniverseLib.Input;
using BloodShop_UniverseLib.Reflection;
using BloodShop_UniverseLib.Runtime;
using BloodShop_UniverseLib.Runtime.Il2Cpp;
using BloodShop_UniverseLib.UI;
using BloodShop_UniverseLib.UI.Models;
using BloodShop_UniverseLib.UI.ObjectPool;
using BloodShop_UniverseLib.UI.Panels;
using BloodShop_UniverseLib.UI.Widgets;
using BloodShop_UniverseLib.UI.Widgets.ScrollView;
using BloodShop_UniverseLib.Utility;
using BloodShop_VRising.GameData;
using BloodShop_VRising.GameData.Methods;
using BloodShop_VRising.GameData.Models;
using BloodShop_VRising.GameData.Models.Base;
using BloodShop_VRising.GameData.Models.Data;
using BloodShop_VRising.GameData.Models.Internals;
using BloodShop_VRising.GameData.Patch;
using BloodShop_VRising.GameData.Utils;
using Bloodstone.API;
using Bloodstone.Hooks;
using BloodyShop.AutoAnnouncer;
using BloodyShop.AutoAnnouncer.Timers;
using BloodyShop.Client;
using BloodyShop.Client.DB;
using BloodyShop.Client.Network;
using BloodyShop.Client.Patch;
using BloodyShop.Client.UI;
using BloodyShop.Client.UI.Panels.Admin;
using BloodyShop.Client.UI.Panels.User;
using BloodyShop.Client.Utils;
using BloodyShop.DB;
using BloodyShop.DB.Models;
using BloodyShop.Network.Messages;
using BloodyShop.Properties;
using BloodyShop.Server;
using BloodyShop.Server.Commands;
using BloodyShop.Server.Core;
using BloodyShop.Server.DB;
using BloodyShop.Server.DB.Model;
using BloodyShop.Server.Network;
using BloodyShop.Server.Patch;
using BloodyShop.Server.Systems;
using BloodyShop.Utils;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Common.Attributes;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.Auth;
using ProjectM.Behaviours;
using ProjectM.CastleBuilding;
using ProjectM.CastleBuilding.Placement;
using ProjectM.Gameplay;
using ProjectM.Gameplay.Clan;
using ProjectM.Gameplay.Scripting;
using ProjectM.Hybrid;
using ProjectM.Network;
using ProjectM.Pathfinding;
using ProjectM.Physics;
using ProjectM.Portrait;
using ProjectM.Roofs;
using ProjectM.Scripting;
using ProjectM.Sequencer;
using ProjectM.Shared;
using ProjectM.Terrain;
using ProjectM.Tiles;
using ProjectM.UI;
using Stunlock.Core;
using Stunlock.Localization;
using Stunlock.Network;
using Stunlock.Sequencer;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Systems;
using Unity.Scenes;
using Unity.Transforms;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using VampireCommandFramework;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BloodyShop")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Mod to create a store in VRising")]
[assembly: AssemblyFileVersion("0.9.92.0")]
[assembly: AssemblyInformationalVersion("0.9.92")]
[assembly: AssemblyProduct("BloodyShop")]
[assembly: AssemblyTitle("BloodyShop")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.9.92.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BloodyShop
{
	public class BloodyShop
	{
		public static readonly string ConfigPath = Path.Combine(Paths.ConfigPath, "BloodyShop");

		public static void serverInitMod(Harmony _harmony)
		{
			_harmony.PatchAll(typeof(global::BloodyShop.Server.Patch.ServerEvents));
			global::BloodyShop.Server.Patch.ServerEvents.OnDeath += DropSystem.ServerEvents_OnDeath;
			global::BloodyShop.Server.Patch.ServerEvents.OnVampireDowned += DropSystem.ServerEvents_OnVampireDowned;
			ServerMod.CreateFilesConfig();
			CommandRegistry.RegisterCommandType(typeof(ShopCommands));
		}

		public static void clientInitMod(Harmony _harmony)
		{
			_harmony.PatchAll(typeof(global::BloodyShop.Client.Patch.ClientEvents));
			UIManager.Initialize();
			KeyBinds.Initialize();
			global::BloodyShop.Client.Patch.ClientEvents.OnClientConnected += ClientMod.ClientEvents_OnClientUserConnected;
			global::BloodyShop.Client.Patch.ClientEvents.OnClientDisconected += ClientMod.ClientEvents_OnClientUserDisconnected;
			KeyBinds.OnKeyPressed += KeyBindPressed.OnKeyPressedOpenPanel;
		}

		public static void onServerGameInitialized()
		{
			ServerMod.SetConfigMod();
		}

		public static void onClientGameInitialized()
		{
			NetworkMessages.RegisterMessage();
		}

		public static void serverUnloadMod()
		{
			global::BloodyShop.Server.Patch.ServerEvents.OnDeath -= DropSystem.ServerEvents_OnDeath;
		}

		public static void clientUnloadMod()
		{
			global::BloodyShop.Client.Patch.ClientEvents.OnClientConnected -= ClientMod.ClientEvents_OnClientUserConnected;
			global::BloodyShop.Client.Patch.ClientEvents.OnClientDisconected -= ClientMod.ClientEvents_OnClientUserDisconnected;
			KeyBinds.OnKeyPressed -= KeyBindPressed.OnKeyPressedOpenPanel;
		}

		public static void onServerGameDataOnInitialize()
		{
			NetworkMessages.RegisterMessage();
			ServerMod.LoadConfigToDB();
			ServerMod.LoadCurrenciesToDB();
			ServerMod.LoadUserCurrenciesPerDayToDB();
		}

		public static void onClientGameDataOnInitialize()
		{
			ClientMod.ClientEvents_OnGameDataInitialized();
		}
	}
	public static class ECSExtensions
	{
		public unsafe static void Write<T>(this Entity entity, T componentData) where T : struct
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			byte[] array = StructureToByteArray(componentData);
			int num = Marshal.SizeOf<T>();
			fixed (byte* ptr = array)
			{
				EntityManager entityManager = VWorld.Server.EntityManager;
				((EntityManager)(ref entityManager)).SetComponentDataRaw(entity, val.TypeIndex, (void*)ptr, num);
			}
		}

		public static byte[] StructureToByteArray<T>(T structure) where T : struct
		{
			int num = Marshal.SizeOf(structure);
			byte[] array = new byte[num];
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			Marshal.StructureToPtr(structure, intPtr, fDeleteOld: true);
			Marshal.Copy(intPtr, array, 0, num);
			Marshal.FreeHGlobal(intPtr);
			return array;
		}

		public unsafe static T Read<T>(this Entity entity) where T : struct
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			void* componentDataRawRO = ((EntityManager)(ref entityManager)).GetComponentDataRawRO(entity, val.TypeIndex);
			return Marshal.PtrToStructure<T>(new IntPtr(componentDataRawRO));
		}

		public static DynamicBuffer<T> ReadBuffer<T>(this Entity entity) where T : struct
		{
			//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_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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			return ((EntityManager)(ref entityManager)).GetBuffer<T>(entity);
		}

		public static void Add<T>(this Entity entity)
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			((EntityManager)(ref entityManager)).AddComponent(entity, val);
		}

		public static void Remove<T>(this Entity entity)
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			((EntityManager)(ref entityManager)).RemoveComponent(entity, val);
		}

		public static bool Has<T>(this Entity entity)
		{
			//IL_0013: 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_001b: 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)
			ComponentType val = default(ComponentType);
			((ComponentType)(ref val))..ctor(Il2CppType.Of<T>(), (AccessMode)0);
			EntityManager entityManager = VWorld.Server.EntityManager;
			return ((EntityManager)(ref entityManager)).HasComponent(entity, val);
		}

		public static void LogComponentTypes(this Entity entity)
		{
			//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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			Enumerator<ComponentType> enumerator = ((EntityManager)(ref entityManager)).GetComponentTypes(entity, (Allocator)2).GetEnumerator();
			bool flag = default(bool);
			while (enumerator.MoveNext())
			{
				ComponentType current = enumerator.Current;
				ManualLogSource logger = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(0, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ComponentType>(current);
				}
				logger.LogInfo(val);
			}
			Plugin.Logger.LogInfo((object)"===");
		}

		public static void LogComponentTypes(this EntityQuery entityQuery)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0040: 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_0078: Expected O, but got Unknown
			Il2CppStructArray<ComponentType> queryTypes = ((EntityQuery)(ref entityQuery)).GetQueryTypes();
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val;
			foreach (ComponentType item in (Il2CppArrayBase<ComponentType>)(object)queryTypes)
			{
				ManualLogSource logger = Plugin.Logger;
				val = new BepInExInfoLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Query Component Type: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ComponentType>(item);
				}
				logger.LogInfo(val);
			}
			ManualLogSource logger2 = Plugin.Logger;
			val = new BepInExInfoLogInterpolatedStringHandler(3, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("===");
			}
			logger2.LogInfo(val);
		}

		public static string LookupName(this PrefabGUID prefabGuid)
		{
			//IL_0012: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			PrefabCollectionSystem existingSystem = VWorld.Server.GetExistingSystem<PrefabCollectionSystem>();
			object obj;
			if (!((PrefabCollectionSystem_Base)existingSystem).PrefabGuidToNameDictionary.ContainsKey(prefabGuid))
			{
				obj = "GUID Not Found";
			}
			else
			{
				string text = ((PrefabCollectionSystem_Base)existingSystem).PrefabGuidToNameDictionary[prefabGuid];
				PrefabGUID val = prefabGuid;
				obj = text + " " + ((object)(PrefabGUID)(ref val)).ToString();
			}
			return obj.ToString();
		}
	}
	[BepInPlugin("BloodyShop", "BloodyShop", "0.9.92")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin, IRunOnInitialized
	{
		internal static Plugin Instance;

		internal static string Name = "BloodyShop";

		internal static string Guid = "BloodyShop";

		internal static string Version = "0.9.92";

		public static ManualLogSource Logger;

		private Harmony _harmony;

		public static ConfigEntry<bool> ShopEnabled;

		public static ConfigEntry<bool> AnnounceAddRemovePublic;

		public static ConfigEntry<bool> AnnounceBuyPublic;

		public static ConfigEntry<string> StoreName;

		public static ConfigEntry<bool> DropEnabled;

		public static ConfigEntry<int> DropNpcPercentage;

		public static ConfigEntry<int> IncrementPercentageDropEveryTenLevelsNpc;

		public static ConfigEntry<int> DropdNpcCurrenciesMin;

		public static ConfigEntry<int> DropNpcCurrenciesMax;

		public static ConfigEntry<int> MaxCurrenciesPerDayPerPlayerNpc;

		public static ConfigEntry<int> DropdVBloodPercentage;

		public static ConfigEntry<int> IncrementPercentageDropEveryTenLevelsVBlood;

		public static ConfigEntry<int> DropVBloodCurrenciesMin;

		public static ConfigEntry<int> DropVBloodCurrenciesMax;

		public static ConfigEntry<int> MaxCurrenciesPerDayPerPlayerVBlood;

		public static ConfigEntry<int> DropPvpPercentage;

		public static ConfigEntry<int> IncrementPercentageDropEveryTenLevelsPvp;

		public static ConfigEntry<int> DropPvpCurrenciesMin;

		public static ConfigEntry<int> DropPvpCurrenciesMax;

		public static ConfigEntry<int> MaxCurrenciesPerDayPerPlayerPvp;

		public static ConfigEntry<bool> Sounds;

		private static World _serverWorld;

		private static World _clientWorld;

		public static World Server
		{
			get
			{
				if (_serverWorld != null)
				{
					return _serverWorld;
				}
				_serverWorld = GetWorld("Server") ?? throw new Exception("There is no Server world (yet). Did you install a server mod on the client?");
				return _serverWorld;
			}
		}

		public static World Client
		{
			get
			{
				if (_clientWorld != null)
				{
					return _clientWorld;
				}
				_clientWorld = GetWorld("Client") ?? throw new Exception("There is no Client world (yet). Did you install a client mod on the server?");
				return _clientWorld;
			}
		}

		public static bool IsServer => Application.productName == "VRisingServer";

		public static bool IsClient => Application.productName == "VRisingClient";

		private static World GetWorld(string name)
		{
			Enumerator<World> enumerator = World.s_AllWorlds.GetEnumerator();
			while (enumerator.MoveNext())
			{
				World current = enumerator.Current;
				if (current.Name == name)
				{
					return current;
				}
			}
			return null;
		}

		public override void Load()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			Instance = this;
			Logger = ((BasePlugin)this).Log;
			_harmony = new Harmony("BloodyShop");
			GameData.OnInitialize += GameDataOnInitialize;
			GameData.OnDestroy += GameDataOnDestroy;
			if (VWorld.IsServer)
			{
				InitConfigServer();
				BloodyShop.serverInitMod(_harmony);
			}
			else
			{
				InitConfigClient();
				BloodyShop.clientInitMod(_harmony);
			}
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(21, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("BloodyShop is loaded!");
			}
			log.LogInfo(val);
		}

		public override bool Unload()
		{
			if (VWorld.IsServer)
			{
				((BasePlugin)this).Config.Clear();
				BloodyShop.serverUnloadMod();
				CommandRegistry.UnregisterAssembly();
			}
			else
			{
				BloodyShop.clientUnloadMod();
			}
			_harmony.UnpatchSelf();
			GameData.OnDestroy -= GameDataOnDestroy;
			GameData.OnInitialize -= GameDataOnInitialize;
			return true;
		}

		private static void GameDataOnInitialize(World world)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (VWorld.IsServer)
			{
				BloodyShop.onServerGameDataOnInitialize();
				return;
			}
			try
			{
				BloodyShop.onClientGameDataOnInitialize();
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(27, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error GameDataOnInitialize ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
			}
		}

		private static void GameDataOnDestroy()
		{
		}

		private void InitConfigClient()
		{
			Sounds = ((BasePlugin)this).Config.Bind<bool>("Client", "enabled", true, "Enable Sounds");
		}

		private void InitConfigServer()
		{
			ShopEnabled = ((BasePlugin)this).Config.Bind<bool>("ConfigShop", "enabled", true, "Enable Shop");
			StoreName = ((BasePlugin)this).Config.Bind<string>("ConfigShop", "name", "Bloody Shop", "Store's name");
			AnnounceAddRemovePublic = ((BasePlugin)this).Config.Bind<bool>("ConfigShop", "announceAddRemovePublic", true, "Public announcement when an item is added or removed from the store");
			AnnounceBuyPublic = ((BasePlugin)this).Config.Bind<bool>("ConfigShop", "announceBuyPublic", true, "Public announcement when someone buys an item from the store");
			DropEnabled = ((BasePlugin)this).Config.Bind<bool>("DropSystem", "enabled", true, "Enable Drop System");
			DropNpcPercentage = ((BasePlugin)this).Config.Bind<int>("DropSystem", "minPercentageDropNpc", 5, "Percent chance that an NPC will drop the type of currency from the shop");
			IncrementPercentageDropEveryTenLevelsNpc = ((BasePlugin)this).Config.Bind<int>("DropSystem", "IncrementPercentageDropEveryTenLevelsNpc", 5, "Percentage increase for every rank of 10 levels of the NPC");
			DropdNpcCurrenciesMin = ((BasePlugin)this).Config.Bind<int>("DropSystem", "DropdNpcCurrenciesMin", 1, "Minimum currency an NPC can drop");
			DropNpcCurrenciesMax = ((BasePlugin)this).Config.Bind<int>("DropSystem", "DropNpcCurrenciesMax", 5, "Maximum currency an NPC can drop");
			MaxCurrenciesPerDayPerPlayerNpc = ((BasePlugin)this).Config.Bind<int>("DropSystem", "MaxCurrenciesPerDayPerPlayerNpc", 5, "Maximum number of currency that a user can get per day by NPC death");
			DropdVBloodPercentage = ((BasePlugin)this).Config.Bind<int>("DropSystem", "minPercentageDropVBlood", 20, "Percent chance that an VBlood will drop the type of currency from the shop");
			IncrementPercentageDropEveryTenLevelsVBlood = ((BasePlugin)this).Config.Bind<int>("DropSystem", "IncrementPercentageDropEveryTenLevelsVBlood", 5, "Percentage increase for every rank of 10 levels of the VBlood");
			DropVBloodCurrenciesMin = ((BasePlugin)this).Config.Bind<int>("DropSystem", "DropVBloodCurrenciesMin", 10, "Minimum currency an VBlood can drop");
			DropVBloodCurrenciesMax = ((BasePlugin)this).Config.Bind<int>("DropSystem", "DropVBloodCurrenciesMax", 20, "Maximum currency an VBlood can drop");
			MaxCurrenciesPerDayPerPlayerVBlood = ((BasePlugin)this).Config.Bind<int>("DropSystem", "MaxCurrenciesPerDayPerPlayerVBlood", 20, "Maximum number of currency that a user can get per day by VBlood death");
			DropPvpPercentage = ((BasePlugin)this).Config.Bind<int>("DropSystem", "minPercentageDropPvp", 100, "Percent chance that victory in a PVP duel will drop the type of currency in the store");
			IncrementPercentageDropEveryTenLevelsPvp = ((BasePlugin)this).Config.Bind<int>("DropSystem", "IncrementPercentageDropEveryTenLevelsPvp", 5, "Percentage increase for every rank of 10 levels of the Player killed in pvp duel");
			DropPvpCurrenciesMin = ((BasePlugin)this).Config.Bind<int>("DropSystem", "DropPvpCurrenciesMin", 15, "Minimum currency can drop victory in PVP");
			DropPvpCurrenciesMax = ((BasePlugin)this).Config.Bind<int>("DropSystem", "DropPvpCurrenciesMax", 20, "Maximum currency can drop victory in PVP");
			MaxCurrenciesPerDayPerPlayerPvp = ((BasePlugin)this).Config.Bind<int>("DropSystem", "MaxCurrenciesPerDayPerPlayerPvp", 20, "Maximum number of currency that a user can get per day by victory in PVP");
		}

		public void OnGameInitialized()
		{
			if (VWorld.IsServer)
			{
				BloodyShop.onServerGameInitialized();
			}
			else
			{
				BloodyShop.onClientGameInitialized();
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "BloodyShop";

		public const string PLUGIN_NAME = "BloodyShop";

		public const string PLUGIN_VERSION = "0.9.92";
	}
}
namespace BloodyShop.Utils
{
	internal class FontColorChat
	{
		public static string Color(string hexColor, string text)
		{
			return $"<color={hexColor}>{text}</color>";
		}

		public static string Red(string text)
		{
			return Color("#E90000", text);
		}

		public static string Blue(string text)
		{
			return Color("#0000ff", text);
		}

		public static string Green(string text)
		{
			return Color("#7FE030", text);
		}

		public static string Yellow(string text)
		{
			return Color("#FBC01E", text);
		}

		public static string White(string text)
		{
			return Color("#FFFFFF", text);
		}
	}
	public static class RectTransformExtensions
	{
		public static Vector2 GetSize(this RectTransform source)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = source.rect;
			return ((Rect)(ref rect)).size;
		}

		public static float GetWidth(this RectTransform source)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = source.rect;
			return ((Rect)(ref rect)).size.x;
		}

		public static float GetHeight(this RectTransform source)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = source.rect;
			return ((Rect)(ref rect)).size.y;
		}

		public static void SetSize(this RectTransform source, RectTransform toCopy)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			source.SetSize(toCopy.GetSize());
		}

		public static void SetSize(this RectTransform source, Vector2 newSize)
		{
			//IL_0002: 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)
			source.SetSize(newSize.x, newSize.y);
		}

		public static void SetSize(this RectTransform source, float width, float height)
		{
			source.SetSizeWithCurrentAnchors((Axis)0, width);
			source.SetSizeWithCurrentAnchors((Axis)1, height);
		}

		public static void SetWidth(this RectTransform source, float width)
		{
			source.SetSizeWithCurrentAnchors((Axis)0, width);
		}

		public static void SetHeight(this RectTransform source, float height)
		{
			source.SetSizeWithCurrentAnchors((Axis)1, height);
		}
	}
}
namespace BloodyShop.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("BloodyShop.Properties.Resources", typeof(Resources).Assembly);
					resourceMan = resourceManager;
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static UnmanagedMemoryStream cash_register_x => ResourceManager.GetStream("cash_register_x", resourceCulture);

		internal static byte[] close
		{
			get
			{
				object @object = ResourceManager.GetObject("close", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static UnmanagedMemoryStream coin => ResourceManager.GetStream("coin", resourceCulture);

		internal static byte[] config
		{
			get
			{
				object @object = ResourceManager.GetObject("config", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] elixir
		{
			get
			{
				object @object = ResourceManager.GetObject("elixir", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static UnmanagedMemoryStream floop2_x => ResourceManager.GetStream("floop2_x", resourceCulture);

		internal static byte[] open
		{
			get
			{
				object @object = ResourceManager.GetObject("open", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] shop_close
		{
			get
			{
				object @object = ResourceManager.GetObject("shop_close", resourceCulture);
				return (byte[])@object;
			}
		}

		internal static byte[] shop_open
		{
			get
			{
				object @object = ResourceManager.GetObject("shop_open", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace BloodyShop.Server
{
	public class ServerMod
	{
		public static ConfigEntry<bool> ShopEnabled;

		public static ConfigEntry<int> CurrencyGUID;

		public static readonly string ConfigPath = Path.Combine(Paths.ConfigPath, "BloodyShop");

		public static readonly string DropSystemPath = Path.Combine(ConfigPath, "DropSystem");

		public static string ProductListFile = Path.Combine(ConfigPath, "products_list.json");

		public static string CurrencyListFile = Path.Combine(ConfigPath, "currency_list.json");

		public static string UserCurrenciesPerDayFile = Path.Combine(ConfigPath, "user_currencies_per_day.json");

		public static void CreateFilesConfig()
		{
			if (!Directory.Exists(ConfigPath))
			{
				Directory.CreateDirectory(ConfigPath);
			}
			if (!File.Exists(ProductListFile))
			{
				File.WriteAllText(ProductListFile, "[]");
			}
			if (!File.Exists(CurrencyListFile))
			{
				File.WriteAllText(CurrencyListFile, "[{\"id\":1,\"name\":\"Silver Coin\",\"guid\":-949672483}]");
			}
			if (!Directory.Exists(DropSystemPath))
			{
				Directory.CreateDirectory(DropSystemPath);
			}
			if (!File.Exists(UserCurrenciesPerDayFile))
			{
				File.WriteAllText(UserCurrenciesPerDayFile, "");
			}
		}

		public static void LoadConfigToDB()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (!LoadDataFromFiles.loadProductList())
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(25, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error loading ProductList");
				}
				logger.LogError(val);
			}
		}

		public static void LoadCurrenciesToDB()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (!LoadDataFromFiles.loadCurrencies())
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(28, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error loading CurrenciesList");
				}
				logger.LogError(val);
			}
		}

		public static void LoadUserCurrenciesPerDayToDB()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (!LoadDataFromFiles.loadUserCurrenciesPerDay())
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(38, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error loading loadUserCurrenciesPerDay");
				}
				logger.LogError(val);
			}
		}

		public static void SetConfigMod()
		{
			ConfigDB.ShopEnabled = Plugin.ShopEnabled.Value;
			ConfigDB.AnnounceAddRemovePublic = Plugin.AnnounceAddRemovePublic.Value;
			ConfigDB.AnnounceBuyPublic = Plugin.AnnounceBuyPublic.Value;
			string value = Plugin.StoreName.Value;
			if (value != string.Empty)
			{
				ConfigDB.StoreName = value;
			}
			ConfigDB.DropEnabled = Plugin.DropEnabled.Value;
			ConfigDB.DropNpcPercentage = Plugin.DropNpcPercentage.Value;
			ConfigDB.IncrementPercentageDropEveryTenLevelsNpc = Plugin.IncrementPercentageDropEveryTenLevelsNpc.Value;
			ConfigDB.DropdNpcCurrenciesMin = Plugin.DropdNpcCurrenciesMin.Value;
			ConfigDB.DropNpcCurrenciesMax = Plugin.DropNpcCurrenciesMax.Value;
			ConfigDB.MaxCurrenciesPerDayPerPlayerNpc = Plugin.MaxCurrenciesPerDayPerPlayerNpc.Value;
			ConfigDB.DropdVBloodPercentage = Plugin.DropdVBloodPercentage.Value;
			ConfigDB.IncrementPercentageDropEveryTenLevelsVBlood = Plugin.IncrementPercentageDropEveryTenLevelsVBlood.Value;
			ConfigDB.DropVBloodCurrenciesMin = Plugin.DropVBloodCurrenciesMin.Value;
			ConfigDB.DropVBloodCurrenciesMax = Plugin.DropVBloodCurrenciesMax.Value;
			ConfigDB.MaxCurrenciesPerDayPerPlayerVBlood = Plugin.MaxCurrenciesPerDayPerPlayerVBlood.Value;
			ConfigDB.DropPvpPercentage = Plugin.DropPvpPercentage.Value;
			ConfigDB.IncrementPercentageDropEveryTenLevelsPvp = Plugin.IncrementPercentageDropEveryTenLevelsPvp.Value;
			ConfigDB.DropPvpCurrenciesMin = Plugin.DropPvpCurrenciesMin.Value;
			ConfigDB.DropPvpCurrenciesMax = Plugin.DropPvpCurrenciesMax.Value;
			ConfigDB.MaxCurrenciesPerDayPerPlayerPvp = Plugin.MaxCurrenciesPerDayPerPlayerPvp.Value;
		}
	}
}
namespace BloodyShop.Server.Systems
{
	public class DropSystem
	{
		private static EntityManager em = VWorld.Server.EntityManager;

		private static Random rnd = new Random();

		private static PrefabGUID vBloodType = new PrefabGUID(1557174542);

		public static void ServerEvents_OnDeath(DeathEventListenerSystem sender, NativeArray<DeathEvent> deathEvents)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_0052: 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_0068: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if (!ConfigDB.DropEnabled)
			{
				return;
			}
			Enumerator<DeathEvent> enumerator = deathEvents.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DeathEvent current = enumerator.Current;
				if (((EntityManager)(ref em)).HasComponent<PlayerCharacter>(current.Killer) && ((EntityManager)(ref em)).HasComponent<Movement>(current.Died) && ((EntityManager)(ref em)).HasComponent<UnitLevel>(current.Died))
				{
					pveReward(current.Killer, current.Died);
				}
			}
		}

		public static void ServerEvents_OnVampireDowned(VampireDownedServerEventSystem sender, NativeArray<Entity> vampireDownedEntitys)
		{
			//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_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)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_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_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)
			if (!ConfigDB.DropEnabled)
			{
				return;
			}
			Enumerator<Entity> enumerator = vampireDownedEntitys.GetEnumerator();
			Entity val = default(Entity);
			Entity val2 = default(Entity);
			while (enumerator.MoveNext())
			{
				Entity current = enumerator.Current;
				VampireDownedServerEventSystem.TryFindRootOwner(current, 1, em, ref val);
				Entity source = ((EntityManager)(ref em)).GetComponentData<VampireDownedBuff>(current).Source;
				VampireDownedServerEventSystem.TryFindRootOwner(source, 1, em, ref val2);
				if (((EntityManager)(ref em)).HasComponent<PlayerCharacter>(val2) && ((EntityManager)(ref em)).HasComponent<PlayerCharacter>(val) && !((Entity)(ref val2)).Equals(val))
				{
					pvpReward(val2, val);
				}
			}
		}

		private static void pveReward(Entity killer, Entity died)
		{
			//IL_0006: 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_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_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_0039: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (!((EntityManager)(ref em)).HasComponent<Minion>(died))
			{
				PlayerCharacter componentData = ((EntityManager)(ref em)).GetComponentData<PlayerCharacter>(killer);
				UserModel userModelKiller = GameData.Users.FromEntity(componentData.UserEntity);
				UnitLevel componentData2 = ((EntityManager)(ref em)).GetComponentData<UnitLevel>(died);
				int level = componentData2.Level;
				bool flag;
				if (((EntityManager)(ref em)).HasComponent<BloodConsumeSource>(died))
				{
					BloodConsumeSource componentData3 = ((EntityManager)(ref em)).GetComponentData<BloodConsumeSource>(died);
					flag = ((PrefabGUID)(ref componentData3.UnitBloodType)).Equals(vBloodType);
				}
				else
				{
					flag = false;
				}
				if (flag)
				{
					rewardForVBlood(userModelKiller, level);
				}
				else
				{
					rewardForNPC(userModelKiller, level);
				}
			}
		}

		private static void pvpReward(Entity killer, Entity died)
		{
			//IL_0006: 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_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_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_0091: 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_0097: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			if (((EntityManager)(ref em)).HasComponent<Minion>(died))
			{
				return;
			}
			PlayerCharacter componentData = ((EntityManager)(ref em)).GetComponentData<PlayerCharacter>(killer);
			UserModel userModel = GameData.Users.FromEntity(componentData.UserEntity);
			List<CurrencyModel> list = (from currency in ShareDB.getCurrencyList()
				where currency.drop
				select currency).ToList();
			Random random = new Random();
			int index = random.Next(list.Count);
			PrefabGUID itemGuid = default(PrefabGUID);
			((PrefabGUID)(ref itemGuid))..ctor(list[index].guid);
			PlayerCharacter componentData2 = ((EntityManager)(ref em)).GetComponentData<PlayerCharacter>(died);
			UserModel userModel2 = GameData.Users.FromEntity(componentData.UserEntity);
			float level = userModel2.Character.Equipment.Level;
			int percentage = calculateDropPercentage((int)level, ConfigDB.DropPvpPercentage, ConfigDB.IncrementPercentageDropEveryTenLevelsPvp);
			if (!probabilityOeneratingReward(percentage))
			{
				return;
			}
			int num = rnd.Next(ConfigDB.DropPvpCurrenciesMin, ConfigDB.DropPvpCurrenciesMax);
			if (ConfigDB.searchUserCurrencyPerDay(userModel.CharacterName, out var userCurrenciesPerDayModel))
			{
				int num2 = userCurrenciesPerDayModel.AmountPvp + num;
				if (num2 <= ConfigDB.MaxCurrenciesPerDayPerPlayerPvp)
				{
					userCurrenciesPerDayModel.AmountPvp = num2;
					userModel.DropItemNearby(itemGuid, num);
					ConfigDB.addUserCurrenciesPerDayToList(userCurrenciesPerDayModel);
					SaveDataToFiles.saveUsersCurrenciesPerDay();
				}
				else if (userCurrenciesPerDayModel.AmountNpc < ConfigDB.MaxCurrenciesPerDayPerPlayerPvp)
				{
					num = ConfigDB.MaxCurrenciesPerDayPerPlayerPvp - userCurrenciesPerDayModel.AmountPvp;
					userCurrenciesPerDayModel.AmountPvp += num;
					userModel.DropItemNearby(itemGuid, num);
					ConfigDB.addUserCurrenciesPerDayToList(userCurrenciesPerDayModel);
					SaveDataToFiles.saveUsersCurrenciesPerDay();
				}
			}
		}

		private static void rewardForNPC(UserModel userModelKiller, int diedLevel)
		{
			//IL_00d1: 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)
			List<CurrencyModel> list = (from currency in ShareDB.getCurrencyList()
				where currency.drop
				select currency).ToList();
			Random random = new Random();
			int index = random.Next(list.Count);
			PrefabGUID itemGuid = default(PrefabGUID);
			((PrefabGUID)(ref itemGuid))..ctor(list[index].guid);
			int percentage = calculateDropPercentage(diedLevel, ConfigDB.DropNpcPercentage, ConfigDB.IncrementPercentageDropEveryTenLevelsNpc);
			if (!probabilityOeneratingReward(percentage))
			{
				return;
			}
			int num = rnd.Next(ConfigDB.DropdNpcCurrenciesMin, ConfigDB.DropNpcCurrenciesMax);
			if (ConfigDB.searchUserCurrencyPerDay(userModelKiller.CharacterName, out var userCurrenciesPerDayModel))
			{
				int num2 = userCurrenciesPerDayModel.AmountNpc + num;
				if (num2 <= ConfigDB.MaxCurrenciesPerDayPerPlayerNpc)
				{
					userCurrenciesPerDayModel.AmountNpc = num2;
					userModelKiller.DropItemNearby(itemGuid, num);
					ConfigDB.addUserCurrenciesPerDayToList(userCurrenciesPerDayModel);
					SaveDataToFiles.saveUsersCurrenciesPerDay();
				}
				else if (userCurrenciesPerDayModel.AmountNpc < ConfigDB.MaxCurrenciesPerDayPerPlayerNpc)
				{
					num = ConfigDB.MaxCurrenciesPerDayPerPlayerNpc - userCurrenciesPerDayModel.AmountNpc;
					userCurrenciesPerDayModel.AmountNpc += num;
					userModelKiller.DropItemNearby(itemGuid, num);
					ConfigDB.addUserCurrenciesPerDayToList(userCurrenciesPerDayModel);
					SaveDataToFiles.saveUsersCurrenciesPerDay();
				}
			}
		}

		private static void rewardForVBlood(UserModel userModelKiller, int diedLevel)
		{
			//IL_00d0: 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)
			List<CurrencyModel> list = (from currency in ShareDB.getCurrencyList()
				where currency.drop
				select currency).ToList();
			Random random = new Random();
			int index = random.Next(list.Count);
			PrefabGUID itemGuid = default(PrefabGUID);
			((PrefabGUID)(ref itemGuid))..ctor(list[index].guid);
			int percentage = calculateDropPercentage(diedLevel, ConfigDB.DropdVBloodPercentage, ConfigDB.IncrementPercentageDropEveryTenLevelsVBlood);
			if (!probabilityOeneratingReward(percentage))
			{
				return;
			}
			int num = rnd.Next(ConfigDB.DropVBloodCurrenciesMin, ConfigDB.DropVBloodCurrenciesMax);
			if (ConfigDB.searchUserCurrencyPerDay(userModelKiller.CharacterName, out var userCurrenciesPerDayModel))
			{
				int num2 = userCurrenciesPerDayModel.AmountVBlood + num;
				if (num2 <= ConfigDB.MaxCurrenciesPerDayPerPlayerVBlood)
				{
					userCurrenciesPerDayModel.AmountVBlood = num2;
					userModelKiller.DropItemNearby(itemGuid, num);
					ConfigDB.addUserCurrenciesPerDayToList(userCurrenciesPerDayModel);
					SaveDataToFiles.saveUsersCurrenciesPerDay();
				}
				else if (userCurrenciesPerDayModel.AmountVBlood < ConfigDB.MaxCurrenciesPerDayPerPlayerVBlood)
				{
					num = ConfigDB.MaxCurrenciesPerDayPerPlayerVBlood - userCurrenciesPerDayModel.AmountVBlood;
					userCurrenciesPerDayModel.AmountVBlood += num;
					userModelKiller.DropItemNearby(itemGuid, num);
					ConfigDB.addUserCurrenciesPerDayToList(userCurrenciesPerDayModel);
					SaveDataToFiles.saveUsersCurrenciesPerDay();
				}
			}
		}

		private static int calculateDropPercentage(int level, int initialPercent, int incremental)
		{
			decimal d = level / 10;
			decimal num = Math.Ceiling(d);
			return decimal.ToInt32(num * (decimal)incremental) + initialPercent;
		}

		private static bool probabilityOeneratingReward(int percentage)
		{
			int num = rnd.Next(1, 100);
			if (num <= percentage)
			{
				return true;
			}
			return false;
		}
	}
	internal class UserUI
	{
		private static Dictionary<string, User> _users = new Dictionary<string, User>();

		public static void RegisterUserWithUI(User user)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			User? val = null;
			_users.TryAdd(((object)(FixedString64)(ref user.CharacterName)).ToString(), user);
		}

		public static Dictionary<string, User> GetUsersWithUI()
		{
			return _users;
		}
	}
}
namespace BloodyShop.Server.Patch
{
	public delegate void DeathEventHandler(DeathEventListenerSystem sender, NativeArray<DeathEvent> deathEvents);
	public delegate void VampireDownedHandler(VampireDownedServerEventSystem sender, NativeArray<Entity> deathEvents);
	[HarmonyPatch]
	public class ServerEvents
	{
		public static event DeathEventHandler OnDeath;

		public static event VampireDownedHandler OnVampireDowned;

		[HarmonyPatch(typeof(DeathEventListenerSystem), "OnUpdate")]
		[HarmonyPostfix]
		private static void DeathEventListenerSystemPatch_Postfix(DeathEventListenerSystem __instance)
		{
			//IL_0003: 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_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_002d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				EntityQuery deathEventQuery = __instance._DeathEventQuery;
				NativeArray<DeathEvent> deathEvents = ((EntityQuery)(ref deathEventQuery)).ToComponentDataArray<DeathEvent>((Allocator)2);
				if (deathEvents.Length > 0)
				{
					ServerEvents.OnDeath?.Invoke(__instance, deathEvents);
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
		}

		[HarmonyPatch(typeof(VampireDownedServerEventSystem), "OnUpdate")]
		[HarmonyPostfix]
		public static void VampireDownedServerEventSystem_Postfix(VampireDownedServerEventSystem __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_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_0043: Unknown result type (might be due to invalid IL or missing references)
			_ = __instance.__OnUpdate_LambdaJob0_entityQuery;
			if (0 == 0)
			{
				EntityManager entityManager = ((ComponentSystemBase)__instance).EntityManager;
				EntityQuery _OnUpdate_LambdaJob0_entityQuery = __instance.__OnUpdate_LambdaJob0_entityQuery;
				NativeArray<Entity> deathEvents = ((EntityQuery)(ref _OnUpdate_LambdaJob0_entityQuery)).ToEntityArray((Allocator)2);
				if (deathEvents.Length > 0)
				{
					ServerEvents.OnVampireDowned?.Invoke(__instance, deathEvents);
				}
			}
		}
	}
}
namespace BloodyShop.Server.DB
{
	public class ConfigDB
	{
		public static List<(string name, DateTime date, UserCurrenciesPerDayModel model)> _normalizedUsersCurrenciesPerDay = new List<(string, DateTime, UserCurrenciesPerDayModel)>();

		public static bool ShopEnabled { get; set; } = true;


		public static bool AnnounceAddRemovePublic { get; set; } = true;


		public static bool AnnounceBuyPublic { get; set; } = true;


		public static string StoreName { get; set; } = "Bloody Shop";


		public static bool DropEnabled { get; set; } = true;


		public static int DropNpcPercentage { get; set; } = 0;


		public static int IncrementPercentageDropEveryTenLevelsNpc { get; set; } = 0;


		public static int DropdNpcCurrenciesMin { get; set; } = 0;


		public static int DropNpcCurrenciesMax { get; set; } = 0;


		public static int MaxCurrenciesPerDayPerPlayerNpc { get; set; } = 0;


		public static int DropdVBloodPercentage { get; set; } = 0;


		public static int IncrementPercentageDropEveryTenLevelsVBlood { get; set; } = 0;


		public static int DropVBloodCurrenciesMin { get; set; } = 0;


		public static int DropVBloodCurrenciesMax { get; set; } = 0;


		public static int MaxCurrenciesPerDayPerPlayerVBlood { get; set; } = 0;


		public static int DropPvpPercentage { get; set; } = 0;


		public static int IncrementPercentageDropEveryTenLevelsPvp { get; set; } = 0;


		public static int DropPvpCurrenciesMin { get; set; } = 0;


		public static int DropPvpCurrenciesMax { get; set; } = 0;


		public static int MaxCurrenciesPerDayPerPlayerPvp { get; set; } = 0;


		public static List<UserCurrenciesPerDayModel> UsersCurrenciesPerDay { get; set; } = new List<UserCurrenciesPerDayModel>();


		public static bool setUsersCurrenciesPerDay(List<UserCurrenciesPerDayModel> listUsersCurrenciesPerDay)
		{
			UsersCurrenciesPerDay = new List<UserCurrenciesPerDayModel>();
			foreach (UserCurrenciesPerDayModel item in listUsersCurrenciesPerDay)
			{
				DateTime dateTime = DateTime.Parse(item.date);
				if (!(dateTime != DateTime.Today))
				{
					_normalizedUsersCurrenciesPerDay.Add((item.CharacterName, dateTime, item));
					UsersCurrenciesPerDay.Add(item);
				}
			}
			return true;
		}

		public static void addUserCurrenciesPerDayToList(UserCurrenciesPerDayModel userCurrenciesPerDay)
		{
			foreach (var (text, item, userCurrenciesPerDayModel) in _normalizedUsersCurrenciesPerDay)
			{
				if (text == userCurrenciesPerDay.CharacterName)
				{
					UsersCurrenciesPerDay.Remove(userCurrenciesPerDayModel);
					_normalizedUsersCurrenciesPerDay.Remove((text, item, userCurrenciesPerDayModel));
					UsersCurrenciesPerDay.Add(userCurrenciesPerDay);
					_normalizedUsersCurrenciesPerDay.Add((userCurrenciesPerDay.CharacterName, DateTime.Parse(userCurrenciesPerDay.date), userCurrenciesPerDay));
					break;
				}
			}
		}

		public static bool searchUserCurrencyPerDay(string characterName, out UserCurrenciesPerDayModel userCurrenciesPerDayModel)
		{
			userCurrenciesPerDayModel = null;
			if (characterName == "")
			{
				return false;
			}
			DateTime today = DateTime.Today;
			string date = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}";
			foreach (var (text, dateTime, userCurrenciesPerDayModel2) in _normalizedUsersCurrenciesPerDay)
			{
				if (text == characterName)
				{
					if (today == dateTime)
					{
						userCurrenciesPerDayModel = userCurrenciesPerDayModel2;
						break;
					}
					UsersCurrenciesPerDay.Remove(userCurrenciesPerDayModel2);
					_normalizedUsersCurrenciesPerDay.Remove((text, dateTime, userCurrenciesPerDayModel2));
					userCurrenciesPerDayModel = new UserCurrenciesPerDayModel
					{
						CharacterName = userCurrenciesPerDayModel2.CharacterName,
						date = date
					};
					UsersCurrenciesPerDay.Add(userCurrenciesPerDayModel2);
					_normalizedUsersCurrenciesPerDay.Add((characterName, today, userCurrenciesPerDayModel));
					break;
				}
			}
			if (userCurrenciesPerDayModel == null)
			{
				userCurrenciesPerDayModel = new UserCurrenciesPerDayModel
				{
					CharacterName = characterName,
					date = date
				};
				UsersCurrenciesPerDay.Add(userCurrenciesPerDayModel);
				_normalizedUsersCurrenciesPerDay.Add((characterName, today, userCurrenciesPerDayModel));
				return true;
			}
			return true;
		}
	}
	internal class LoadDataFromFiles
	{
		public static bool loadProductList()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			try
			{
				string json = File.ReadAllText(ServerMod.ProductListFile);
				List<ItemShopModel> productList = JsonSerializer.Deserialize<List<ItemShopModel>>(json);
				return ItemsDB.setProductList(productList);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}

		public static bool loadCurrencies()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			try
			{
				string json = File.ReadAllText(ServerMod.CurrencyListFile);
				List<CurrencyModel> currencyList = JsonSerializer.Deserialize<List<CurrencyModel>>(json);
				return ShareDB.setCurrencyList(currencyList);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}

		public static bool loadUserCurrenciesPerDay()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			try
			{
				string json = File.ReadAllText(ServerMod.UserCurrenciesPerDayFile);
				List<UserCurrenciesPerDayModel> usersCurrenciesPerDay = JsonSerializer.Deserialize<List<UserCurrenciesPerDayModel>>(json);
				return ConfigDB.setUsersCurrenciesPerDay(usersCurrenciesPerDay);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}
	}
	internal class SaveDataToFiles
	{
		public static bool saveProductList()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			try
			{
				List<ItemShopModel> productListForSaveJSON = ItemsDB.getProductListForSaveJSON();
				string contents = JsonSerializer.Serialize(productListForSaveJSON);
				File.WriteAllText(ServerMod.ProductListFile, contents);
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}

		public static bool saveCurrenciesList()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			try
			{
				List<CurrencyModel> currencyList = ShareDB.getCurrencyList();
				string contents = JsonSerializer.Serialize(currencyList);
				File.WriteAllText(ServerMod.CurrencyListFile, contents);
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}

		public static bool saveUsersCurrenciesPerDay()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			try
			{
				List<UserCurrenciesPerDayModel> usersCurrenciesPerDay = ConfigDB.UsersCurrenciesPerDay;
				string contents = JsonSerializer.Serialize(usersCurrenciesPerDay);
				File.WriteAllText(ServerMod.UserCurrenciesPerDayFile, contents);
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}
	}
}
namespace BloodyShop.Server.DB.Model
{
	public class UserCurrenciesPerDayModel
	{
		public string CharacterName { get; set; }

		public string date { get; set; }

		public int AmountNpc { get; set; } = 0;


		public int AmountVBlood { get; set; } = 0;


		public int AmountPvp { get; set; } = 0;

	}
}
namespace BloodyShop.Server.Core
{
	internal class BuffSystem
	{
		public const int NO_DURATION = 0;

		public const int DEFAULT_DURATION = -1;

		public const int RANDOM_POWER = -1;

		public static bool BuffPlayer(Entity character, Entity user, PrefabGUID buff, int duration = -1, bool persistsThroughDeath = false)
		{
			//IL_0001: 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_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_0023: 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_0028: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_006f: 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_0075: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: 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_010e: 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_011f: 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_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: 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_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			ClearExtraBuffs(character);
			DebugEventsSystem existingSystem = VWorld.Server.GetExistingSystem<DebugEventsSystem>();
			ApplyBuffDebugEvent val = default(ApplyBuffDebugEvent);
			val.BuffPrefabGUID = buff;
			ApplyBuffDebugEvent val2 = val;
			FromCharacter val3 = default(FromCharacter);
			val3.User = user;
			val3.Character = character;
			FromCharacter val4 = val3;
			Entity entity = default(Entity);
			if (!BuffUtility.TryGetBuff(VWorld.Server.EntityManager, character, buff, ref entity))
			{
				existingSystem.ApplyBuff(val4, val2);
				if (BuffUtility.TryGetBuff(VWorld.Server.EntityManager, character, buff, ref entity))
				{
					if (entity.Has<CreateGameplayEventsOnSpawn>())
					{
						entity.Remove<CreateGameplayEventsOnSpawn>();
					}
					if (entity.Has<GameplayEventListeners>())
					{
						entity.Remove<GameplayEventListeners>();
					}
					if (persistsThroughDeath)
					{
						entity.Add<Buff_Persists_Through_Death>();
						if (entity.Has<RemoveBuffOnGameplayEvent>())
						{
							entity.Remove<RemoveBuffOnGameplayEvent>();
						}
						if (entity.Has<RemoveBuffOnGameplayEventEntry>())
						{
							entity.Remove<RemoveBuffOnGameplayEventEntry>();
						}
					}
					if (duration > 0 && duration != -1)
					{
						if (entity.Has<LifeTime>())
						{
							LifeTime componentData = entity.Read<LifeTime>();
							componentData.Duration = duration;
							entity.Write<LifeTime>(componentData);
						}
					}
					else if (duration == 0)
					{
						if (entity.Has<LifeTime>())
						{
							LifeTime componentData2 = entity.Read<LifeTime>();
							componentData2.Duration = -1f;
							componentData2.EndAction = (LifeTimeEndAction)0;
							entity.Write<LifeTime>(componentData2);
						}
						if (entity.Has<RemoveBuffOnGameplayEvent>())
						{
							entity.Remove<RemoveBuffOnGameplayEvent>();
						}
						if (entity.Has<RemoveBuffOnGameplayEventEntry>())
						{
							entity.Remove<RemoveBuffOnGameplayEventEntry>();
						}
					}
					return true;
				}
				return false;
			}
			return false;
		}

		public static void ClearExtraBuffs(Entity player)
		{
			//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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: 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_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)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = VWorld.Server.EntityManager;
			DynamicBuffer<BuffBuffer> buffer = ((EntityManager)(ref entityManager)).GetBuffer<BuffBuffer>(player);
			List<string> list = new List<string> { "BloodBuff", "SetBonus", "EquipBuff", "Combat", "VBlood_Ability_Replace", "Shapeshift", "Interact", "AB_Consumable" };
			Enumerator<BuffBuffer> enumerator = buffer.GetEnumerator();
			while (enumerator.MoveNext())
			{
				BuffBuffer current = enumerator.Current;
				bool flag = true;
				foreach (string item in list)
				{
					if (current.PrefabGuid.LookupName().Contains(item))
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					DestroyUtility.Destroy(VWorld.Server.EntityManager, current.Entity, (DestroyDebugReason)13, (string)null, 0);
				}
			}
			Equipment val = player.Read<Equipment>();
			EquipmentType val2 = default(EquipmentType);
			if (!((Equipment)(ref val)).IsEquipped(new PrefabGUID(1063517722), ref val2) && BuffUtility.HasBuff(VWorld.Server.EntityManager, player, new PrefabGUID(476186894)))
			{
				UnbuffCharacter(player, new PrefabGUID(476186894));
			}
		}

		public static void UnbuffCharacter(Entity Character, PrefabGUID buffGUID)
		{
			//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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Entity val = default(Entity);
			if (BuffUtility.TryGetBuff(VWorld.Server.EntityManager, Character, buffGUID, ref val))
			{
				DestroyUtility.Destroy(VWorld.Server.EntityManager, val, (DestroyDebugReason)13, (string)null, 0);
			}
		}
	}
	public class InventorySystem
	{
		public static bool searchPrefabsInInventory(string characterName, PrefabGUID prefabCurrencyGUID, out int total)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_0017: 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_001f: 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_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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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)
			total = 0;
			try
			{
				UserModel userByCharacterName = GameData.Users.GetUserByCharacterName(characterName);
				Entity entity = userByCharacterName.Character.Entity;
				NativeArray<InventoryBuffer> val = default(NativeArray<InventoryBuffer>);
				InventoryUtilities.TryGetInventory(Plugin.Server.EntityManager, entity, ref val, 0);
				total = InventoryUtilities.GetItemAmount(Plugin.Server.EntityManager, entity, prefabCurrencyGUID, default(Nullable_Unboxed<int>));
				if (total >= 0)
				{
					return true;
				}
				return false;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val2);
				return false;
			}
		}

		public static bool verifyHaveSuficientPrefabsInInventory(string characterName, PrefabGUID prefabCurrencyGUID, int quantity = 1)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (searchPrefabsInInventory(characterName, prefabCurrencyGUID, out var total))
				{
					if (total >= quantity)
					{
						return true;
					}
					return false;
				}
				return false;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}

		public static bool getPrefabFromInventory(string characterName, PrefabGUID prefabGUID, int quantity)
		{
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			//IL_0015: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int num = quantity;
				UserModel userByCharacterName = GameData.Users.GetUserByCharacterName(characterName);
				ItemModel prefabById = GameData.Items.GetPrefabById(prefabGUID);
				Entity entity = userByCharacterName.Character.Entity;
				int inventorySize = InventoryUtilities.GetInventorySize(Plugin.Server.EntityManager, entity);
				GameDataSystem existingSystem = Plugin.Server.GetExistingSystem<GameDataSystem>();
				InventoryBuffer val = default(InventoryBuffer);
				for (int i = 0; i < inventorySize; i++)
				{
					if (!InventoryUtilities.TryGetItemAtSlot(Plugin.Server.EntityManager, entity, i, ref val))
					{
						continue;
					}
					ManagedItemData orDefault = existingSystem.ManagedDataRegistry.GetOrDefault<ManagedItemData>(val.ItemType, (ManagedItemData)null);
					if (orDefault != null && orDefault.PrefabName == prefabById.PrefabName)
					{
						if (val.Amount >= num)
						{
							InventoryUtilitiesServer.TryRemoveItemAtIndex(Plugin.Server.EntityManager, entity, val.ItemType, num, i, false);
							num = 0;
							break;
						}
						if (val.Amount < num)
						{
							InventoryUtilitiesServer.TryRemoveItemAtIndex(Plugin.Server.EntityManager, entity, val.ItemType, val.Amount, i, true);
							num -= val.Amount;
						}
						if (num == 0)
						{
							break;
						}
					}
				}
				if (num > 0)
				{
					AdditemToInventory(userByCharacterName.CharacterName, prefabGUID, quantity - num);
					return false;
				}
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(6, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val2);
				return false;
			}
		}

		public static bool AdditemToInventory(string characterName, PrefabGUID prefabGUID, int quantity)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0014: 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)
			try
			{
				UserModel userByCharacterName = GameData.Users.GetUserByCharacterName(characterName);
				for (int i = 0; i < quantity; i++)
				{
					if (!userByCharacterName.TryGiveItem(prefabGUID, 1, out var _))
					{
						userByCharacterName.DropItemNearby(prefabGUID, 1);
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(6, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				return false;
			}
		}
	}
}
namespace BloodyShop.Server.Commands
{
	[CommandGroup("shop", null)]
	internal class ShopCommands
	{
		public static CurrencyModel currency { get; private set; }

		public static List<CurrencyModel> currencies { get; private set; }

		[Command("currency add", null, "\"<Name>\" <PrefabGuid>", "Add a currency to the store. To know the PrefabGuid of an item you must look for the item in the following URL <#4acc45><u>https://gaming.tools/v-rising/items</u></color>", null, true)]
		public static void AddCurrency(ChatCommandContext ctx, string name, int item, bool drop)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			PrefabGUID prefabGuid = default(PrefabGUID);
			((PrefabGUID)(ref prefabGuid))..ctor(item);
			ItemModel prefabById = GameData.Items.GetPrefabById(prefabGuid);
			if (prefabById == null)
			{
				throw ctx.Error("Invalid item type");
			}
			if (!ShareDB.addCurrencyList(name, item, drop))
			{
				throw ctx.Error("Invalid item type");
			}
			SaveDataToFiles.saveCurrenciesList();
			ctx.Reply(FontColorChat.Yellow("Added currency " + FontColorChat.White(name ?? "") + " to the store"));
			Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
			foreach (KeyValuePair<string, User> item2 in usersWithUI)
			{
				User value = item2.Value;
				if (value.IsConnected && value.IsAdmin)
				{
					ListSerializedMessage msg = ServerListMessageAction.createMsg();
					ServerListMessageAction.Send(value, msg);
				}
			}
		}

		[Command("currency list", null, "", "List of products available to buy in the store", null, true)]
		public static void ListCurrency(ChatCommandContext ctx)
		{
			if (!ConfigDB.ShopEnabled)
			{
				throw ctx.Error(FontColorChat.Yellow(FontColorChat.White(ConfigDB.StoreName ?? "") + " is closed"));
			}
			List<string> currencyListMessage = ShareDB.GetCurrencyListMessage();
			if (currencyListMessage.Count <= 0)
			{
				throw ctx.Error("No currency available in the store");
			}
			foreach (string item in currencyListMessage)
			{
				ctx.Reply(item);
			}
		}

		[Command("currency remove", "crm", "<NumberItem>", "Delete a currency from the store", null, true)]
		public static void RemoveCurrency(ChatCommandContext ctx, int index)
		{
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (ShareDB.currenciesList.Count == 1)
				{
					throw ctx.Error(FontColorChat.Yellow("Do not remove all currency from the store."));
				}
				if (!ShareDB.SearchCurrencyByCommand(index, out var currencyModel))
				{
					throw ctx.Error(FontColorChat.Yellow("Currency removed error."));
				}
				if (!ShareDB.RemoveCurrencyyByCommand(index))
				{
					throw ctx.Error(FontColorChat.Yellow("Item " + FontColorChat.White(currencyModel.name ?? "") + " removed error."));
				}
				SaveDataToFiles.saveCurrenciesList();
				LoadDataFromFiles.loadCurrencies();
				ctx.Reply(FontColorChat.Yellow("Currency " + FontColorChat.White(currencyModel.name ?? "") + " removed successful."));
				Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
				foreach (KeyValuePair<string, User> item in usersWithUI)
				{
					User value = item.Value;
					if (value.IsConnected && value.IsAdmin)
					{
						ListSerializedMessage msg = ServerListMessageAction.createMsg();
						ServerListMessageAction.Send(value, msg);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				throw ctx.Error("Error: " + ex.Message);
			}
		}

		[Command("add", null, "\"<Name>\" <PrefabGuid> <Currency> <Price> <Stock> <Stack> <Buff|true/false>", "Add a product to the store. To know the PrefabGuid of an item you must look for the item in the following URL <#4acc45><u>https://gaming.tools/v-rising/items</u></color>", null, true)]
		public static void AddItem(ChatCommandContext ctx, string name, int item, int currencyId, int price, int stock, int stack = 1, bool isBuff = false)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_005a: 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_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(32, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Estamos añadiendo un buff o no? ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(isBuff);
				}
				logger.LogInfo(val);
				if (!isBuff)
				{
					PrefabGUID prefabGuid = default(PrefabGUID);
					((PrefabGUID)(ref prefabGuid))..ctor(item);
					ItemModel prefabById = GameData.Items.GetPrefabById(prefabGuid);
					if (prefabById == null)
					{
						throw ctx.Error("Invalid item type");
					}
				}
				currencies = ShareDB.getCurrencyList();
				currency = currencies.FirstOrDefault((CurrencyModel currency) => currency.id == currencyId);
				if (currency == null)
				{
					throw ctx.Error("Error loading currency type");
				}
				if (stock <= 0)
				{
					stock = -1;
				}
				if (!ItemsDB.addProductList(item, price, stock, name, currency.guid, stack, isBuff))
				{
					throw ctx.Error("Invalid item type");
				}
				SaveDataToFiles.saveProductList();
				ctx.Reply(FontColorChat.Yellow("Added item " + FontColorChat.White($"{stack}x {name} ({stock})") + " to the store with a price of " + FontColorChat.White($"{price} {currency?.name.ToString()}")));
				if (!ConfigDB.ShopEnabled)
				{
					return;
				}
				if (ConfigDB.AnnounceAddRemovePublic)
				{
					ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChat.Yellow(FontColorChat.White($"{stack}x {name} ({stock})") + " have been added to the Store for " + FontColorChat.White($"{price} {currency?.name.ToString()}")));
				}
				Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
				foreach (KeyValuePair<string, User> item2 in usersWithUI)
				{
					User value = item2.Value;
					if (value.IsConnected)
					{
						ListSerializedMessage msg = ServerListMessageAction.createMsg();
						ServerListMessageAction.Send(value, msg);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex.Message);
				throw ctx.Error("Error saving the item in the store ");
			}
		}

		[Command("buy", null, "<NumberItem> <Quantity> ", "Buy an object from the shop", null, false)]
		public static void BuyItem(ChatCommandContext ctx, int indexPosition, int quantity)
		{
			//IL_05d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d8: Expected O, but got Unknown
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: 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_00f5: 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_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: 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_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d6: Expected O, but got Unknown
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_048f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0494: Unknown result type (might be due to invalid IL or missing references)
			//IL_0496: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Unknown result type (might be due to invalid IL or missing references)
			bool flag = default(bool);
			try
			{
				Entity senderCharacterEntity = ctx.Event.SenderCharacterEntity;
				if (!ConfigDB.ShopEnabled)
				{
					throw ctx.Error(FontColorChat.Yellow(FontColorChat.White(ConfigDB.StoreName ?? "") + " is closed"));
				}
				if (quantity <= 0)
				{
					throw ctx.Error("The minimum purchase quantity of a product is 1");
				}
				if (!ItemsDB.SearchItemByCommand(indexPosition, out var itemShopModel))
				{
					throw ctx.Error("This item is not available in the store");
				}
				currency = ShareDB.getCurrency(itemShopModel.currency);
				if (currency == null)
				{
					throw ctx.Error("Error loading currency type");
				}
				int num = itemShopModel.PrefabPrice * quantity;
				if (!itemShopModel.CheckStockAvailability(quantity))
				{
					throw ctx.Error("There is not enough stock of this item");
				}
				ItemModel prefabById = GameData.Items.GetPrefabById(new PrefabGUID(currency.guid));
				User user = ctx.Event.User;
				if (!InventorySystem.verifyHaveSuficientPrefabsInInventory(((object)(FixedString64)(ref user.CharacterName)).ToString(), prefabById.PrefabGUID, num))
				{
					throw ctx.Error("You need " + FontColorChat.White($"{num} {currency.name}") + " in your inventory for this purchase");
				}
				user = ctx.Event.User;
				if (!InventorySystem.getPrefabFromInventory(((object)(FixedString64)(ref user.CharacterName)).ToString(), prefabById.PrefabGUID, num))
				{
					throw ctx.Error("You need " + FontColorChat.White($"{num} {currency.name}") + " in your inventory for this purchase");
				}
				int num2 = itemShopModel.PrefabStack * quantity;
				if (itemShopModel.isBuff)
				{
					BuffSystem.BuffPlayer(senderCharacterEntity, ctx.Event.SenderUserEntity, new PrefabGUID(itemShopModel.PrefabGUID), 0, persistsThroughDeath: true);
				}
				else
				{
					user = ctx.Event.User;
					if (!InventorySystem.AdditemToInventory(((object)(FixedString64)(ref user.CharacterName)).ToString(), new PrefabGUID(itemShopModel.PrefabGUID), num2))
					{
						ManualLogSource logger = Plugin.Logger;
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(58, 4, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error buying an item User: ");
							BepInExErrorLogInterpolatedStringHandler obj = val;
							user = ctx.Event.User;
							((BepInExLogInterpolatedStringHandler)obj).AppendFormatted<string>(((object)(FixedString64)(ref user.CharacterName)).ToString());
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Item: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(itemShopModel.PrefabName);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Quantity: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(quantity);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" TotalPrice: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
						}
						logger.LogError(val);
						throw ctx.Error("An error has occurred when delivering the items, please contact an administrator");
					}
				}
				ctx.Reply(FontColorChat.Yellow("Transaction successful. You have purchased " + FontColorChat.White($"{quantity}x {itemShopModel.PrefabName}") + " for a total of  " + FontColorChat.White($"{num} {currency.name}")));
				if (!ItemsDB.ModifyStockByCommand(indexPosition, quantity))
				{
					ManualLogSource logger2 = Plugin.Logger;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(59, 4, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error ModifyStockByCommand: ");
						BepInExErrorLogInterpolatedStringHandler obj2 = val;
						user = ctx.Event.User;
						((BepInExLogInterpolatedStringHandler)obj2).AppendFormatted<string>(((object)(FixedString64)(ref user.CharacterName)).ToString());
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Item: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(itemShopModel.PrefabName);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Quantity: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(quantity);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" TotalPrice: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					}
					logger2.LogError(val);
					return;
				}
				SaveDataToFiles.saveProductList();
				LoadDataFromFiles.loadProductList();
				Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
				foreach (KeyValuePair<string, User> item in usersWithUI)
				{
					User value = item.Value;
					if (value.IsConnected)
					{
						ListSerializedMessage msg = ServerListMessageAction.createMsg();
						ServerListMessageAction.Send(value, msg);
					}
				}
				if (ConfigDB.AnnounceBuyPublic)
				{
					ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChat.Yellow($"{ctx.Event.User.CharacterName} has purchased {FontColorChat.White($"{num2}x {itemShopModel.PrefabName}")} for a total of  {FontColorChat.White($"{num} {currency.name}")}"));
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger3 = Plugin.Logger;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger3.LogError(val);
				throw ctx.Error("Error: " + ex.Message);
			}
		}

		[Command("remove", "rm", "<NumberItem>", "Delete a product from the store", null, true)]
		public static void removeItemFromShop(ChatCommandContext ctx, int index)
		{
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: 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_010b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!ItemsDB.SearchItemByCommand(index, out var itemShopModel))
				{
					throw ctx.Error(FontColorChat.Yellow("Item removed error."));
				}
				if (!ItemsDB.RemoveItemByCommand(index))
				{
					throw ctx.Error(FontColorChat.Yellow("Item " + FontColorChat.White(itemShopModel.PrefabName ?? "") + " removed error."));
				}
				SaveDataToFiles.saveProductList();
				LoadDataFromFiles.loadProductList();
				ctx.Reply(FontColorChat.Yellow("Item " + FontColorChat.White(itemShopModel.PrefabName ?? "") + " removed successful."));
				Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
				foreach (KeyValuePair<string, User> item in usersWithUI)
				{
					User value = item.Value;
					if (value.IsConnected)
					{
						ListSerializedMessage msg = ServerListMessageAction.createMsg();
						ServerListMessageAction.Send(value, msg);
					}
				}
				if (ConfigDB.AnnounceAddRemovePublic)
				{
					ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChat.Yellow("Item " + FontColorChat.White(itemShopModel.PrefabName ?? "") + " removed successful."));
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(7, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
				throw ctx.Error("Error: " + ex.Message);
			}
		}

		[Command("list", null, "", "List of products available to buy in the store", null, false)]
		public static void list(ChatCommandContext ctx)
		{
			if (!ConfigDB.ShopEnabled)
			{
				throw ctx.Error(FontColorChat.Yellow(FontColorChat.White(ConfigDB.StoreName ?? "") + " is closed"));
			}
			List<string> productListMessage = ItemsDB.GetProductListMessage();
			if (productListMessage.Count <= 0)
			{
				throw ctx.Error("No products available in the store");
			}
			foreach (string item in productListMessage)
			{
				ctx.Reply(item);
			}
			ctx.Reply(FontColorChat.Yellow("To buy an object you must have in your inventory the number of currency indicated by each product."));
			ctx.Reply(FontColorChat.Yellow("Use the chat command \"" + FontColorChat.White("shop buy <NumberItem> <Quantity> ") + "\""));
		}

		[Command("open", null, "", "Open store", null, true)]
		public static void OpenShop(ChatCommandContext ctx)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007b: Unknown result type (might be due to invalid IL or missing references)
			ConfigDB.ShopEnabled = true;
			ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChat.Yellow(" " + FontColorChat.White(" " + ConfigDB.StoreName + " ") + " just opened"));
			Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
			OpenSerializedMessage msg = new OpenSerializedMessage();
			foreach (KeyValuePair<string, User> item in usersWithUI)
			{
				User value = item.Value;
				if (value.IsConnected)
				{
					ServerOpenMessageAction.Send(value, msg);
				}
			}
		}

		[Command("close", null, "", "Close store", null, true)]
		public static void CloseShop(ChatCommandContext ctx)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007b: Unknown result type (might be due to invalid IL or missing references)
			ConfigDB.ShopEnabled = false;
			ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, FontColorChat.Yellow(" " + FontColorChat.White(" " + ConfigDB.StoreName + " ") + " just closed"));
			Dictionary<string, User> usersWithUI = UserUI.GetUsersWithUI();
			CloseSerializedMessage msg = new CloseSerializedMessage();
			foreach (KeyValuePair<string, User> item in usersWithUI)
			{
				User value = item.Value;
				if (value.IsConnected)
				{
					ServerCloseMessageAction.Send(value, msg);
				}
			}
		}

		[Command("reload", null, "", "Reload products and currencies files from server", null, true)]
		public static void ReloadShop(ChatCommandContext ctx)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missin

ChatLineColorMod.dll

Decompiled 5 months ago
#define DEBUG
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Bloodstone.API;
using ChatLineColorMod.Hooks;
using ChatLineColorMod.Timers;
using ChatLineColorMod.UI;
using ChatLineColorMod.UI.Panels;
using ChatLineColorMod.Utils;
using ChatLineColorMod_UniverseLib;
using ChatLineColorMod_UniverseLib.Config;
using ChatLineColorMod_UniverseLib.Input;
using ChatLineColorMod_UniverseLib.Reflection;
using ChatLineColorMod_UniverseLib.Runtime;
using ChatLineColorMod_UniverseLib.Runtime.Il2Cpp;
using ChatLineColorMod_UniverseLib.UI;
using ChatLineColorMod_UniverseLib.UI.Models;
using ChatLineColorMod_UniverseLib.UI.ObjectPool;
using ChatLineColorMod_UniverseLib.UI.Panels;
using ChatLineColorMod_UniverseLib.UI.Widgets;
using ChatLineColorMod_UniverseLib.UI.Widgets.ScrollView;
using ChatLineColorMod_UniverseLib.Utility;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Common.Attributes;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.Auth;
using ProjectM.Network;
using ProjectM.UI;
using TMPro;
using Unity.Entities;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ChatLineColorMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A client mod that adds channel name and change the color of the chat input text as the color of the cannel where you are typing, AutoClean Chat Window and replace text string with emojis.")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("ChatLineColorMod")]
[assembly: AssemblyTitle("ChatLineColorMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[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 ChatLineColorMod
{
	[BepInProcess("VRising.exe")]
	[BepInPlugin("ChatLineColorMod", "ChatLineColorMod", "2.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[Reloadable]
	public class Plugin : BasePlugin, IRunOnInitialized
	{
		public static ManualLogSource Logger;

		private Harmony _harmony;

		public static ConfigEntry<bool> ChatColorEnabled;

		public static ConfigEntry<bool> ChatChannelEnabled;

		public static ConfigEntry<bool> ButtonCleanChat;

		public static ConfigEntry<bool> EmojiEnabled;

		public static ConfigEntry<bool> AutoCleanEnabled;

		public static ConfigEntry<int> AutoCleanInterval;

		private static AutoCleanTimer _autoCleanTimer;

		public static int _autocleanInterval { get; set; }

		public static bool UIInit { get; set; }

		internal static Plugin Instance { get; private set; }

		public override void Load()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			Instance = this;
			Logger = ((BasePlugin)this).Log;
			_harmony = new Harmony("ChatLineColorMod");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			InitConfig();
			GameFrame.Initialize();
			UIManager.Initialize();
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(18, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("ChatLineColorMod");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
			}
			log.LogInfo(val);
		}

		private void InitConfig()
		{
			ButtonCleanChat = ((BasePlugin)this).Config.Bind<bool>("ButtonCleanChat", "enabled", true, "Enabled button when you hover in the chat window");
			ChatColorEnabled = ((BasePlugin)this).Config.Bind<bool>("ChatColor", "enabled", true, "Enable change the color of the chat input text as the color of the channel where you are typing");
			ChatChannelEnabled = ((BasePlugin)this).Config.Bind<bool>("ChatChannel", "enabled", true, "Enable adds channel name in input where you are typing. This option will disable the ability to select a text or move within it.");
			EmojiEnabled = ((BasePlugin)this).Config.Bind<bool>("Emojis", "enabled", true, "Enable Emojis replace");
			AutoCleanEnabled = ((BasePlugin)this).Config.Bind<bool>("AutoCleanChat", "enabled", false, "Enable AutoCleanChat");
			AutoCleanInterval = ((BasePlugin)this).Config.Bind<int>("AutoCleanChat", "interval", 3600, "Time interval in seconds in which the chat is cleared");
			if (AutoCleanEnabled.Value)
			{
				_autocleanInterval = AutoCleanInterval.Value;
			}
		}

		public override bool Unload()
		{
			((BasePlugin)this).Config.Clear();
			GameFrame.Uninitialize();
			_harmony.UnpatchSelf();
			return true;
		}

		public void OnGameInitialized()
		{
			((BasePlugin)this).Log.LogInfo((object)"Game has initialized!");
		}

		public static void StartAutoAnnouncer()
		{
			_autoCleanTimer.Start(delegate
			{
				Logger.LogInfo((object)"Starting AutoAnnouncer");
				HUDChatWindow_Path.clearChat = true;
			}, delegate(object input)
			{
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Expected O, but got Unknown
				if (!(input is int) || 1 == 0)
				{
					Logger.LogError((object)"AutoCleanChat timer delay function parameter is not a valid integer");
					return TimeSpan.MaxValue;
				}
				int autocleanInterval = _autocleanInterval;
				ManualLogSource logger = Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(42, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Next AutoCleanChat will start in ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(autocleanInterval);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" seconds.");
				}
				logger.LogInfo(val);
				return TimeSpan.FromSeconds(autocleanInterval);
			});
		}

		public static void StopAutoAnnouncer()
		{
			_autoCleanTimer.Stop();
		}

		public static void GameDataOnInitialize(World world)
		{
			UIInit = true;
			Logger.LogInfo((object)"GameData Init");
			_autoCleanTimer = new AutoCleanTimer();
			UIManager.CreateAllPanels();
			if (AutoCleanEnabled.Value)
			{
				StartAutoAnnouncer();
			}
		}

		private static void GameDataOnDestroy()
		{
			Logger.LogInfo((object)"GameData Destroy");
			StopAutoAnnouncer();
			GameFrame.Uninitialize();
			UIManager.DestroyAllPanels();
			if (AutoCleanEnabled.Value)
			{
				StartAutoAnnouncer();
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "ChatLineColorMod";

		public const string PLUGIN_NAME = "ChatLineColorMod";

		public const string PLUGIN_VERSION = "2.0.0";
	}
}
namespace ChatLineColorMod.Utils
{
	internal class Emoji
	{
		public const string Grin = "\ud83d\ude01";

		public const string Joy = "\ud83d\ude02";

		public const string Smiley = "\ud83d\ude03";

		public const string Smile = "\ud83d\ude04";

		public const string Sweat_Smile = "\ud83d\ude05";

		public const string Laughing = "\ud83d\ude06";

		public const string Wink = "\ud83d\ude09";

		public const string Blush = "\ud83d\ude0a";

		public const string Yum = "\ud83d\ude0b";

		public const string Heart_Eyes = "\ud83d\ude0d";

		public const string Kissing_Heart = "\ud83d\ude18";

		private static RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline;

		public static string convertCharactersToEoji(string text)
		{
			string pattern = "(\ud83d\ude02)[D]+";
			IEnumerator enumerator = Regex.Matches(text, pattern, options).GetEnumerator();
			try
			{
				if (enumerator.MoveNext())
				{
					Match match = (Match)enumerator.Current;
					text = text.Replace("\ud83d\ude02D", "\ud83d\ude02");
				}
			}
			finally
			{
				IDisposable disposable = enumerator as IDisposable;
				if (disposable != null)
				{
					disposable.Dispose();
				}
			}
			return text.Replace("xE", "\ud83d\ude01").Replace("xD", "\ud83d\ude02").Replace("XD", "\ud83d\ude02")
				.Replace(":)", "\ud83d\ude03")
				.Replace(":D", "\ud83d\ude04")
				.Replace(";D", "\ud83d\ude05")
				.Replace("lol", "\ud83d\ude06")
				.Replace("Lol", "\ud83d\ude06")
				.Replace("LoL", "\ud83d\ude06")
				.Replace("LOL", "\ud83d\ude06")
				.Replace(";)", "\ud83d\ude09")
				.Replace("x)", "\ud83d\ude0a")
				.Replace(":P", "\ud83d\ude0b")
				.Replace("<3)", "\ud83d\ude0d")
				.Replace(":*", "\ud83d\ude18");
		}
	}
}
namespace ChatLineColorMod.UI
{
	internal class UIManager
	{
		public static UIBase UiBase { get; private set; }

		public static ClearChatPanel ClearChat { get; private set; }

		public static int SizeOfProdutcs { get; set; }

		internal static void Initialize()
		{
			UniverseLibConfig universeLibConfig = default(UniverseLibConfig);
			universeLibConfig.Disable_EventSystem_Override = false;
			universeLibConfig.Force_Unlock_Mouse = false;
			universeLibConfig.Allow_UI_Selection_Outside_UIBase = true;
			universeLibConfig.Unhollowed_Modules_Folder = Path.Combine(Paths.BepInExRootPath, "interop");
			UniverseLibConfig config = universeLibConfig;
			Universe.Init(3f, OnInitialized, LogHandler, config);
		}

		private static void OnInitialized()
		{
			UiBase = UniversalUI.RegisterUI(((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString(), UiUpdate);
		}

		public static void CreateAllPanels()
		{
			CreateClearChatPanel();
		}

		public static void DestroyAllPanels()
		{
			DestroyClearChatPanel();
		}

		public static void CreateClearChatPanel()
		{
			ClearChat = new ClearChatPanel(UiBase);
			ClearChat.SetActive(active: false);
		}

		public static void ShowClearChatPanel()
		{
			ClearChat.SetActive(active: true);
		}

		public static void HideClearChatPanel()
		{
			ClearChat.SetActive(active: false);
		}

		public static void DestroyClearChatPanel()
		{
			ClearChat.Destroy();
		}

		private static void UiUpdate()
		{
		}

		private static void LogHandler(string message, LogType type)
		{
		}
	}
}
namespace ChatLineColorMod.UI.Panels
{
	internal class ClearChatPanel : PanelBase
	{
		public enum VerticalAnchor
		{
			Top,
			Bottom
		}

		public static VerticalAnchor NavbarAnchor = VerticalAnchor.Bottom;

		private static readonly Vector2 NAVBAR_DIMENSIONS = new Vector2(1020f, 35f);

		public static float PositionX = Screen.width * -545 / 2560;

		public static float PositionY = Screen.height * 60 / 1440 - 150;

		public static ClearChatPanel Instance { get; private set; }

		public override string Name => "Clear Chat";

		public override int MinWidth => 90;

		public override int MinHeight => 40;

		public override Vector2 DefaultAnchorMin => new Vector2(0.5f, 1f);

		public override Vector2 DefaultAnchorMax => new Vector2(0.5f, 1f);

		public override Vector2 DefaultPosition => new Vector2(PositionX, PositionY);

		public override bool CanDragAndResize => false;

		public static RectTransform NavBarRect { get; private set; }

		public GameObject NavbarTabButtonHolder { get; private set; }

		public ButtonRef clearChatBtn { get; private set; }

		public ClearChatPanel(UIBase owner)
			: base(owner)
		{
			Instance = this;
		}

		protected override void ConstructPanelContent()
		{
			//IL_000e: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = UIFactory.CreateUIObject("MainNavbar", UIRoot);
			UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(val, (bool?)true, (bool?)true, (bool?)true, (bool?)true, (int?)5, (int?)4, (int?)4, (int?)4, (int?)4, (TextAnchor?)(TextAnchor)4);
			((Graphic)val.AddComponent<Image>()).color = new Color(0.1f, 0.1f, 0.1f);
			NavBarRect = val.GetComponent<RectTransform>();
			NavBarRect.pivot = new Vector2(0.5f, 1f);
			SetNavBarAnchor();
			clearChatBtn = UIFactory.CreateButton(val, "clearChatBtn", "Clear Chat");
			UIFactory.SetLayoutElement(((Component)clearChatBtn.Component).gameObject, 80, 30, preferredWidth: 80, preferredHeight: 30, flexibleWidth: 0, flexibleHeight: 0);
			ButtonRef buttonRef = clearChatBtn;
			buttonRef.OnClick = (Action)Delegate.Combine(buttonRef.OnClick, new Action(ClearChatAction));
		}

		public static void SetNavBarAnchor()
		{
			//IL_0026: 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_0055: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: 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)
			switch (NavbarAnchor)
			{
			case VerticalAnchor.Top:
				NavBarRect.anchorMin = new Vector2(0.5f, 1f);
				NavBarRect.anchorMax = new Vector2(0.5f, 1f);
				NavBarRect.anchoredPosition = new Vector2(NavBarRect.anchoredPosition.x, 0f);
				NavBarRect.sizeDelta = NAVBAR_DIMENSIONS;
				break;
			case VerticalAnchor.Bottom:
				NavBarRect.anchorMin = new Vector2(0.5f, 0f);
				NavBarRect.anchorMax = new Vector2(0.5f, 0f);
				NavBarRect.anchoredPosition = new Vector2(NavBarRect.anchoredPosition.x, 200f);
				NavBarRect.sizeDelta = NAVBAR_DIMENSIONS;
				break;
			}
		}

		public static void ClearChatAction()
		{
			Plugin.Logger.LogInfo((object)"Clear Chat Action");
			HUDChatWindow_Path.clearChat = true;
		}
	}
}
namespace ChatLineColorMod.Timers
{
	public class AutoCleanTimer
	{
		private bool _enabled;

		private bool _isRunning;

		private DateTime _lastRunTime;

		private TimeSpan _delay;

		private Action<World> _action;

		private Func<object, TimeSpan> _delayAction;

		public void Start(Action<World> action, TimeSpan delay)
		{
			_delay = delay;
			_lastRunTime = DateTime.UtcNow - delay;
			_action = action;
			_enabled = true;
			GameFrame.OnUpdate += GameFrame_OnUpdate;
		}

		public void Start(Action<World> action, Func<object, TimeSpan> delayAction)
		{
			_delayAction = delayAction;
			_delay = _delayAction(1);
			_lastRunTime = DateTime.UtcNow;
			_action = action;
			_enabled = true;
			GameFrame.OnUpdate += GameFrame_OnUpdate;
		}

		private void GameFrame_OnUpdate()
		{
			Update(VWorld.Client);
		}

		private void Update(World world)
		{
			if (!_enabled || _isRunning || _lastRunTime + _delay >= DateTime.UtcNow)
			{
				return;
			}
			_isRunning = true;
			try
			{
				Plugin.Logger.LogDebug((object)"Executing timer.");
				_action(world);
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
			finally
			{
				int autocleanInterval = Plugin._autocleanInterval;
				if (_delayAction != null)
				{
					_delay = _delayAction(autocleanInterval);
				}
				_lastRunTime = DateTime.UtcNow;
				_isRunning = false;
			}
		}

		public void Stop()
		{
			GameFrame.OnUpdate -= GameFrame_OnUpdate;
			_enabled = false;
		}

		public void Dispose()
		{
			if (_enabled)
			{
				Stop();
			}
		}
	}
	internal class GameFrame : MonoBehaviour
	{
		public delegate void GameFrameUpdateEventHandler();

		private static GameFrame _instance;

		public static event GameFrameUpdateEventHandler OnUpdate;

		public static event GameFrameUpdateEventHandler OnLateUpdate;

		private void Update()
		{
			try
			{
				GameFrame.OnUpdate?.Invoke();
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)"Error dispatching OnUpdate event:");
				Plugin.Logger.LogError((object)ex);
			}
		}

		private void LateUpdate()
		{
			try
			{
				GameFrame.OnLateUpdate?.Invoke();
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)"Error dispatching OnLateUpdate event:");
				Plugin.Logger.LogError((object)ex);
			}
		}

		public static void Initialize()
		{
			if (!ClassInjector.IsTypeRegisteredInIl2Cpp<GameFrame>())
			{
				ClassInjector.RegisterTypeInIl2Cpp<GameFrame>();
			}
			_instance = ((BasePlugin)Plugin.Instance).AddComponent<GameFrame>();
		}

		public static void Uninitialize()
		{
			GameFrame.OnUpdate = null;
			GameFrame.OnLateUpdate = null;
			Object.Destroy((Object)(object)_instance);
			_instance = null;
		}
	}
}
namespace ChatLineColorMod.Hooks
{
	[HarmonyPatch]
	public class HUDChatWindow_Path
	{
		private static TMP_InputField chatLine = null;

		private static Color colorLocal = new Color(0.85490197f, 67f / 85f, 64f / 85f);

		private static Color colorGLobal = new Color(0.6f, 0.8f, 1f);

		private static Color colorTeam = new Color(0.4745098f, 0.85490197f, 0.6509804f);

		private static Color colorWhisper = new Color(1f, 53f / 85f, 1f);

		private static Color colorSystem = new Color(76f / 85f, 47f / 85f, 8f / 51f);

		private static string lastChannel = "Local";

		private static string pattern = "(\\:(\\w|\\+|\\-)+\\:)(?=|[\\!\\.\\?]|$)";

		private static string textEmoji = "";

		private static bool insertChannel = false;

		private static string whispTo = "";

		public static bool clearChat { get; set; } = false;


		public static bool testLoadChat { get; set; } = false;


		[HarmonyPatch(typeof(HUDChatWindow), "FocusInputField")]
		[HarmonyPrefix]
		public static void FocusInputField_Postfix(HUDChatWindow __instance)
		{
			chatLine = __instance.ChatInputField;
		}

		[HarmonyPatch(typeof(ClientChatSystem), "_OnInputChanged")]
		[HarmonyPrefix]
		public static void OnInputChanged_Prefix(ClientChatSystem __instance, ref string text)
		{
			if (Plugin.ChatChannelEnabled.Value && text != textEmoji)
			{
				if (lastChannel == "Whisper")
				{
					if (!text.Contains("[" + whispTo + "]: "))
					{
						if (insertChannel)
						{
							text = "[" + whispTo + "]: ";
						}
						else
						{
							text = text.Insert(0, "[" + whispTo + "]: ");
							insertChannel = true;
						}
					}
				}
				else if (!text.Contains("[" + lastChannel + "]: "))
				{
					if (insertChannel)
					{
						text = "[" + lastChannel + "]: ";
					}
					else
					{
						text = text.Insert(0, "[" + lastChannel + "]: ");
						insertChannel = true;
					}
				}
			}
			if (Plugin.EmojiEnabled.Value)
			{
				if (text != textEmoji)
				{
					textEmoji = convertEmoji(text);
				}
			}
			else
			{
				textEmoji = text;
			}
		}

		[HarmonyPatch(typeof(ClientChatSystem), "_OnInputSubmit")]
		[HarmonyPrefix]
		public static void OnInputSubmit_Prefix(ClientChatSystem __instance, ref string text)
		{
			textEmoji = "";
			if (Plugin.ChatChannelEnabled.Value)
			{
				if (lastChannel == "Whisper")
				{
					text = text.Replace("[" + whispTo + "]:", "");
				}
				else
				{
					text = text.Replace("[" + lastChannel + "]:", "");
				}
				insertChannel = false;
			}
		}

		[HarmonyPatch(typeof(ClientChatSystem), "OnUpdate")]
		[HarmonyPrefix]
		public static void CheckedState_PrefixAsync(ClientChatSystem __instance)
		{
			//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_01f0: 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_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			ChatMessageType defaultMode = __instance._DefaultMode;
			string text = ((object)(ChatMessageType)(ref defaultMode)).ToString();
			if (Plugin.UIInit && Plugin.ButtonCleanChat.Value)
			{
				if (__instance._Hovered)
				{
					UIManager.ShowClearChatPanel();
				}
				else
				{
					UIManager.HideClearChatPanel();
				}
			}
			if ((Plugin.AutoCleanEnabled.Value || Plugin.ButtonCleanChat.Value) && clearChat)
			{
				int count = __instance._ChatMessages.Count;
				__instance._ChatMessages.RemoveRange(0, count);
				clearChat = false;
			}
			if (text == "Team")
			{
				text = "Clan";
			}
			if (text != lastChannel)
			{
				textEmoji = textEmoji.Replace(lastChannel, text);
				lastChannel = text;
			}
			if (!((Object)(object)chatLine != (Object)null))
			{
				return;
			}
			chatLine.textComponent.text = textEmoji;
			chatLine.text = textEmoji;
			if (Plugin.ChatColorEnabled.Value)
			{
				switch (text)
				{
				case "Local":
					((Graphic)chatLine.textComponent).color = colorLocal;
					break;
				case "Global":
					((Graphic)chatLine.textComponent).color = colorGLobal;
					break;
				case "Clan":
					((Graphic)chatLine.textComponent).color = colorTeam;
					break;
				case "Whisper":
					try
					{
						whispTo = __instance._WhisperUserName;
					}
					catch
					{
						whispTo = "Whisper";
					}
					((Graphic)chatLine.textComponent).color = colorWhisper;
					break;
				case "System":
					((Graphic)chatLine.textComponent).color = colorSystem;
					break;
				}
			}
			if (Plugin.ChatChannelEnabled.Value)
			{
				chatLine.MoveToEndOfLine(false, false);
			}
		}

		public static string convertEmoji(string text)
		{
			RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline;
			Emoji obj = new Emoji();
			text = Emoji.convertCharactersToEoji(text);
			foreach (Match item in Regex.Matches(text, pattern, options))
			{
				string name = stringUpper(item.Value.Replace(":", ""));
				try
				{
					string newValue = Convert.ToString(typeof(Emoji).GetField(name).GetValue(obj));
					text = text.Replace(item.Value, newValue);
				}
				catch
				{
				}
			}
			return text;
		}

		public static string stringUpper(string str)
		{
			return string.Join("_", from str in str.Split('_')
				select char.ToUpper(str[0]) + str.Substring(1));
		}
	}
	[HarmonyPatch]
	internal class ClientEvents
	{
		private static bool _onGameDataInitializedTriggered;

		[HarmonyPatch(typeof(GameDataManager), "OnUpdate")]
		[HarmonyPostfix]
		private static void GameDataManagerOnUpdatePostfix(GameDataManager __instance)
		{
			if (_onGameDataInitializedTriggered)
			{
				return;
			}
			try
			{
				if (__instance.GameDataInitialized)
				{
					_onGameDataInitializedTriggered = true;
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Debug.WriteLine("GameDataManagerOnUpdatePostfix Trigger");
					Plugin.GameDataOnInitialize(VWorld.Client);
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
		}

		[HarmonyPatch(typeof(ClientBootstrapSystem), "OnDestroy")]
		[HarmonyPostfix]
		private static void ClientBootstrapSystemOnDestroyPostfix(ClientBootstrapSystem __instance)
		{
			_onGameDataInitializedTriggered = false;
			try
			{
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
		}

		[HarmonyPatch(typeof(SteamPlatformSystem), "TryInitClient")]
		[HarmonyPostfix]
		private static void SteamPlatformSystemOnTryInitClientPostfix(SteamPlatformSystem __instance)
		{
			try
			{
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)ex);
			}
		}
	}
}
namespace ChatLineColorMod_UniverseLib.UI
{
	internal class UIBase
	{
		internal static readonly int TOP_SORTORDER = 30000;

		public string ID { get; }

		public GameObject RootObject { get; }

		public RectTransform RootRect { get; }

		public Canvas Canvas { get; }

		public Action UpdateMethod { get; }

		public PanelManager Panels { get; }

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

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

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

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

		internal void Update()
		{
			try
			{
				Panels.Update();
				UpdateMethod?.Invoke();
			}
			catch (Exception value)
			{
				Universe.LogWarning($"Exception invoking update method for {ID}: {value}");
			}
		}
	}
}
namespace ChatLineColorMod_UniverseLib.UI.Panels
{
	internal class PanelManager
	{
		protected internal static readonly List<PanelDragger> allDraggers = new List<PanelDragger>();

		protected internal static UIBase resizeCursorUIBase;

		protected internal static GameObject resizeCursor;

		protected internal static bool focusHandledThisFrame;

		protected internal static bool draggerHandledThisFrame;

		protected internal static bool wasAnyDragging;

		protected readonly List<PanelBase> panelInstances = new List<PanelBase>();

		protected readonly Dictionary<int, PanelBase> transformIDToUIPanel = new Dictionary<int, PanelBase>();

		protected readonly List<PanelDragger> draggerInstances = new List<PanelDragger>();

		public static bool Resizing { get; internal set; }

		public static bool ResizePrompting => Object.op_Implicit((Object)(object)resizeCursor) && resizeCursorUIBase.Enabled;

		public UIBase Owner { get; }

		public GameObject PanelHolder { get; }

		protected virtual bool ShouldUpdateFocus => MouseInTargetDisplay && (InputManager.GetMouseButtonDown(0) || InputManager.GetMouseButtonDown(1));

		protected internal virtual Vector3 MousePosition => InputManager.MousePosition;

		protected internal virtual Vector2 ScreenDimensions => new Vector2((float)Screen.width, (float)Screen.height);

		protected virtual bool MouseInTargetDisplay => true;

		public event Action OnPanelsReordered;

		public event Action OnClickedOutsidePanels;

		public static void ForceEndResize()
		{
			if (!Object.op_Implicit((Object)(object)resizeCursor) || resizeCursorUIBase == null)
			{
				return;
			}
			resizeCursorUIBase.Enabled = false;
			resizeCursor.SetActive(false);
			wasAnyDragging = false;
			Resizing = false;
			foreach (PanelDragger allDragger in allDraggers)
			{
				allDragger.WasDragging = false;
				allDragger.WasResizing = false;
			}
		}

		protected static void CreateResizeCursorUI()
		{
			//IL_003f: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				resizeCursorUIBase = UniversalUI.RegisterUI("com.sinai.universelib.resizeCursor", null);
				GameObject rootObject = resizeCursorUIBase.RootObject;
				rootObject.transform.SetParent(UniversalUI.CanvasRoot.transform);
				Text val = UIFactory.CreateLabel(rootObject, "ResizeCursor", "↔", (TextAnchor)4, Color.white, supportRichText: true, 35);
				resizeCursor = ((Component)val).gameObject;
				Outline val2 = ((Component)val).gameObject.AddComponent<Outline>();
				((Shadow)val2).effectColor = Color.black;
				((Shadow)val2).effectDistance = new Vector2(1f, 1f);
				RectTransform component = resizeCursor.GetComponent<RectTransform>();
				component.SetSizeWithCurrentAnchors((Axis)0, 64f);
				component.SetSizeWithCurrentAnchors((Axis)1, 64f);
				resizeCursorUIBase.Enabled = false;
			}
			catch (Exception ex)
			{
				Universe.LogWarning("Exception creating Resize Cursor UI!\r\n" + ex.ToString());
			}
		}

		public PanelManager(UIBase owner)
		{
			//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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			Owner = owner;
			PanelHolder = UIFactory.CreateUIObject("PanelHolder", owner.RootObject);
			RectTransform component = PanelHolder.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
		}

		protected internal virtual void AddPanel(PanelBase panel)
		{
			allDraggers.Add(panel.Dragger);
			draggerInstances.Add(panel.Dragger);
			panelInstances.Add(panel);
			transformIDToUIPanel.Add(((Object)panel.UIRoot.transform).GetInstanceID(), panel);
		}

		protected internal virtual void RemovePanel(PanelBase panel)
		{
			allDraggers.Remove(panel.Dragger);
			draggerInstances.Remove(panel.Dragger);
			panelInstances.Remove(panel);
			transformIDToUIPanel.Remove(((Object)panel.UIRoot.transform).GetInstanceID());
		}

		protected internal virtual void InvokeOnPanelsReordered()
		{
			Owner.SetOnTop();
			SortDraggerHeirarchy();
			this.OnPanelsReordered?.Invoke();
		}

		protected internal virtual void Update()
		{
			if (!ResizePrompting && ShouldUpdateFocus)
			{
				UpdateFocus();
			}
			if (!draggerHandledThisFrame)
			{
				UpdateDraggers();
			}
		}

		protected virtual void UpdateFocus()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: 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)
			bool flag = false;
			if (!focusHandledThisFrame)
			{
				Vector3 mousePosition = MousePosition;
				int childCount = PanelHolder.transform.childCount;
				for (int num = childCount - 1; num >= 0; num--)
				{
					Transform child = PanelHolder.transform.GetChild(num);
					if (transformIDToUIPanel.TryGetValue(((Object)child).GetInstanceID(), out var value))
					{
						Vector3 val = ((Transform)value.Rect).InverseTransformPoint(mousePosition);
						if (value.Enabled)
						{
							Rect rect = value.Rect.rect;
							if (((Rect)(ref rect)).Contains(val))
							{
								focusHandledThisFrame = true;
								flag = true;
								Owner.SetOnTop();
								if (child.GetSiblingIndex() != childCount - 1)
								{
									child.SetAsLastSibling();
									InvokeOnPanelsReordered();
								}
								break;
							}
						}
					}
				}
			}
			if (!flag)
			{
				this.OnClickedOutsidePanels?.Invoke();
			}
		}

		protected virtual void SortDraggerHeirarchy()
		{
			draggerInstances.Sort((PanelDragger a, PanelDragger b) => ((Transform)b.Rect).GetSiblingIndex().CompareTo(((Transform)a.Rect).GetSiblingIndex()));
		}

		protected internal virtual void UpdateDraggers()
		{
			//IL_004d: 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_008c: Unknown result type (might be due to invalid IL or missing references)
			if (!MouseInTargetDisplay)
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)resizeCursor))
			{
				CreateResizeCursorUI();
			}
			MouseState mouseState = ((!InputManager.GetMouseButtonDown(0)) ? (InputManager.GetMouseButton(0) ? MouseState.Held : MouseState.NotPressed) : MouseState.Down);
			Vector3 mousePosition = MousePosition;
			foreach (PanelDragger draggerInstance in draggerInstances)
			{
				if (((Component)draggerInstance.Rect).gameObject.activeSelf)
				{
					draggerInstance.Update(mouseState, mousePosition);
					if (draggerHandledThisFrame)
					{
						break;
					}
				}
			}
			if (!wasAnyDragging || mouseState != MouseState.NotPressed)
			{
				return;
			}
			foreach (PanelDragger draggerInstance2 in draggerInstances)
			{
				draggerInstance2.WasDragging = false;
			}
			wasAnyDragging = false;
		}
	}
	internal class PanelDragger
	{
		[Flags]
		public enum ResizeTypes : ulong
		{
			NONE = 0uL,
			Top = 1uL,
			Left = 2uL,
			Right = 4uL,
			Bottom = 8uL,
			TopLeft = 3uL,
			TopRight = 5uL,
			BottomLeft = 0xAuL,
			BottomRight = 0xCuL
		}

		private const int RESIZE_THICKNESS = 10;

		private Vector2 lastDragPosition;

		private ResizeTypes currentResizeType = ResizeTypes.NONE;

		private Vector2 lastResizePos;

		private ResizeTypes lastResizeHoverType;

		private Rect totalResizeRect;

		private readonly Dictionary<ResizeTypes, Rect> m_resizeMask = new Dictionary<ResizeTypes, Rect>
		{
			{
				ResizeTypes.Top,
				default(Rect)
			},
			{
				ResizeTypes.Left,
				default(Rect)
			},
			{
				ResizeTypes.Right,
				default(Rect)
			},
			{
				ResizeTypes.Bottom,
				default(Rect)
			}
		};

		private const int DBL_THICKESS = 20;

		public PanelBase UIPanel { get; private set; }

		public bool AllowDragAndResize => UIPanel.CanDragAndResize;

		public RectTransform Rect { get; set; }

		public RectTransform DragableArea { get; set; }

		public bool WasDragging { get; set; }

		public bool WasResizing { get; internal set; }

		private bool WasHoveringResize => PanelManager.resizeCursor.activeInHierarchy;

		public event Action OnFinishResize;

		public event Action OnFinishDrag;

		public PanelDragger(PanelBase uiPanel)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_0037: 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_0049: 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)
			UIPanel = uiPanel;
			DragableArea = uiPanel.TitleBar.GetComponent<RectTransform>();
			Rect = uiPanel.Rect;
			UpdateResizeCache();
		}

		protected internal virtual void Update(MouseState state, Vector3 rawMousePos)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0027: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: 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_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Transform)Rect).InverseTransformPoint(rawMousePos);
			bool flag = MouseInResizeArea(Vector2.op_Implicit(val));
			Vector3 val2 = ((Transform)DragableArea).InverseTransformPoint(rawMousePos);
			Rect rect = DragableArea.rect;
			bool flag2 = ((Rect)(ref rect)).Contains(val2);
			if (WasHoveringResize && Object.op_Implicit((Object)(object)PanelManager.resizeCursor))
			{
				UpdateHoverImagePos();
			}
			switch (state)
			{
			case MouseState.Down:
				if (flag2 || flag)
				{
					UIPanel.SetActive(active: true);
				}
				if (flag2)
				{
					if (AllowDragAndResize)
					{
						OnBeginDrag();
					}
					PanelManager.draggerHandledThisFrame = true;
				}
				else if (flag)
				{
					ResizeTypes resizeType = GetResizeType(Vector2.op_Implicit(val));
					if (resizeType != ResizeTypes.NONE)
					{
						OnBeginResize(resizeType);
					}
					PanelManager.draggerHandledThisFrame = true;
				}
				break;
			case MouseState.Held:
				if (WasDragging)
				{
					OnDrag();
					PanelManager.draggerHandledThisFrame = true;
				}
				else if (WasResizing)
				{
					OnResize();
					PanelManager.draggerHandledThisFrame = true;
				}
				break;
			case MouseState.NotPressed:
				if (AllowDragAndResize && flag2)
				{
					if (WasDragging)
					{
						OnEndDrag();
					}
					if (WasHoveringResize)
					{
						OnHoverResizeEnd();
					}
					PanelManager.draggerHandledThisFrame = true;
				}
				else if (flag || WasResizing)
				{
					if (WasResizing)
					{
						OnEndResize();
					}
					ResizeTypes resizeType = GetResizeType(Vector2.op_Implicit(val));
					if (resizeType != ResizeTypes.NONE)
					{
						OnHoverResize(resizeType);
					}
					else if (WasHoveringResize)
					{
						OnHoverResizeEnd();
					}
					PanelManager.draggerHandledThisFrame = true;
				}
				else if (WasHoveringResize)
				{
					OnHoverResizeEnd();
				}
				break;
			}
		}

		public virtual void OnBeginDrag()
		{
			//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_002a: Unknown result type (might be due to invalid IL or missing references)
			PanelManager.wasAnyDragging = true;
			WasDragging = true;
			lastDragPosition = Vector2.op_Implicit(UIPanel.Owner.Panels.MousePosition);
		}

		public virtual void OnDrag()
		{
			//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_0017: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 mousePosition = UIPanel.Owner.Panels.MousePosition;
			Vector2 val = Vector2.op_Implicit(mousePosition) - lastDragPosition;
			lastDragPosition = Vector2.op_Implicit(mousePosition);
			((Transform)Rect).localPosition = ((Transform)Rect).localPosition + Vector2.op_Implicit(val);
			UIPanel.EnsureValidPosition();
		}

		public virtual void OnEndDrag()
		{
			WasDragging = false;
			this.OnFinishDrag?.Invoke();
		}

		private void UpdateResizeCache()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0046: 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_0065: 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_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_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: 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_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: 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)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = Rect.rect;
			float num = ((Rect)(ref rect)).x - 10f + 1f;
			rect = Rect.rect;
			float num2 = ((Rect)(ref rect)).y - 10f + 1f;
			rect = Rect.rect;
			float num3 = ((Rect)(ref rect)).width + 20f - 2f;
			rect = Rect.rect;
			totalResizeRect = new Rect(num, num2, num3, ((Rect)(ref rect)).height + 20f - 2f);
			if (AllowDragAndResize)
			{
				m_resizeMask[ResizeTypes.Bottom] = new Rect(((Rect)(ref totalResizeRect)).x, ((Rect)(ref totalResizeRect)).y, ((Rect)(ref totalResizeRect)).width, 10f);
				m_resizeMask[ResizeTypes.Left] = new Rect(((Rect)(ref totalResizeRect)).x, ((Rect)(ref totalResizeRect)).y, 10f, ((Rect)(ref totalResizeRect)).height);
				Dictionary<ResizeTypes, Rect> resizeMask = m_resizeMask;
				long key = 1L;
				float x = ((Rect)(ref totalResizeRect)).x;
				rect = Rect.rect;
				float y = ((Rect)(ref rect)).y;
				rect = Rect.rect;
				resizeMask[(ResizeTypes)key] = new Rect(x, y + ((Rect)(ref rect)).height - 2f, ((Rect)(ref totalResizeRect)).width, 10f);
				Dictionary<ResizeTypes, Rect> resizeMask2 = m_resizeMask;
				long key2 = 4L;
				float x2 = ((Rect)(ref totalResizeRect)).x;
				rect = Rect.rect;
				resizeMask2[(ResizeTypes)key2] = new Rect(x2 + ((Rect)(ref rect)).width + 10f - 2f, ((Rect)(ref totalResizeRect)).y, 10f, ((Rect)(ref totalResizeRect)).height);
			}
		}

		protected virtual bool MouseInResizeArea(Vector2 mousePos)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return ((Rect)(ref totalResizeRect)).Contains(mousePos);
		}

		private ResizeTypes GetResizeType(Vector2 mousePos)
		{
			//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_002d: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: 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_006f: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			ResizeTypes resizeTypes = ResizeTypes.NONE;
			Rect val = m_resizeMask[ResizeTypes.Top];
			if (((Rect)(ref val)).Contains(mousePos))
			{
				resizeTypes |= ResizeTypes.Top;
			}
			else
			{
				val = m_resizeMask[ResizeTypes.Bottom];
				if (((Rect)(ref val)).Contains(mousePos))
				{
					resizeTypes |= ResizeTypes.Bottom;
				}
			}
			val = m_resizeMask[ResizeTypes.Left];
			if (((Rect)(ref val)).Contains(mousePos))
			{
				resizeTypes |= ResizeTypes.Left;
			}
			else
			{
				val = m_resizeMask[ResizeTypes.Right];
				if (((Rect)(ref val)).Contains(mousePos))
				{
					resizeTypes |= ResizeTypes.Right;
				}
			}
			return resizeTypes;
		}

		public virtual void OnHoverResize(ResizeTypes resizeType)
		{
			//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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			if (WasHoveringResize && lastResizeHoverType == resizeType)
			{
				return;
			}
			lastResizeHoverType = resizeType;
			PanelManager.resizeCursorUIBase.Enabled = true;
			PanelManager.resizeCursor.SetActive(true);
			float num = 0f;
			ResizeTypes num2 = resizeType - 1;
			if (num2 <= ResizeTypes.Right)
			{
				switch (num2)
				{
				case ResizeTypes.Right:
					goto IL_0099;
				case ResizeTypes.NONE:
					goto IL_00a1;
				case ResizeTypes.Left:
					goto IL_00a9;
				case ResizeTypes.Top:
				case ResizeTypes.TopLeft:
					goto IL_00b1;
				}
			}
			ResizeTypes num3 = resizeType - 8;
			if (num3 > ResizeTypes.Right)
			{
				goto IL_00b1;
			}
			switch (num3)
			{
			case ResizeTypes.Left:
				break;
			case ResizeTypes.NONE:
				goto IL_00a1;
			case ResizeTypes.Right:
				goto IL_00a9;
			default:
				goto IL_00b1;
			}
			goto IL_0099;
			IL_00a9:
			num = 135f;
			goto IL_00b1;
			IL_00b1:
			Quaternion rotation = PanelManager.resizeCursor.transform.rotation;
			((Quaternion)(ref rotation)).eulerAngles = new Vector3(0f, 0f, num);
			PanelManager.resizeCursor.transform.rotation = rotation;
			UpdateHoverImagePos();
			return;
			IL_0099:
			num = 45f;
			goto IL_00b1;
			IL_00a1:
			num = 90f;
			goto IL_00b1;
		}

		private void UpdateHoverImagePos()
		{
			//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_003e: 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)
			Vector3 mousePosition = UIPanel.Owner.Panels.MousePosition;
			RectTransform rootRect = UIPanel.Owner.RootRect;
			PanelManager.resizeCursorUIBase.SetOnTop();
			PanelManager.resizeCursor.transform.localPosition = ((Transform)rootRect).InverseTransformPoint(mousePosition);
		}

		public virtual void OnHoverResizeEnd()
		{
			PanelManager.resizeCursorUIBase.Enabled = false;
			PanelManager.resizeCursor.SetActive(false);
		}

		public virtual void OnBeginResize(ResizeTypes resizeType)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			currentResizeType = resizeType;
			lastResizePos = Vector2.op_Implicit(UIPanel.Owner.Panels.MousePosition);
			WasResizing = true;
			PanelManager.Resizing = true;
		}

		public virtual void OnResize()
		{
			//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_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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_005b: 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_0075: 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_00a0: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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_00d8: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: 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_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: 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_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: 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_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
			Vector3 mousePosition = UIPanel.Owner.Panels.MousePosition;
			Vector2 val = lastResizePos - Vector2.op_Implicit(mousePosition);
			if (Vector2.op_Implicit(mousePosition) == lastResizePos)
			{
				return;
			}
			Vector2 screenDimensions = UIPanel.Owner.Panels.ScreenDimensions;
			if (!(mousePosition.x < 0f) && !(mousePosition.y < 0f) && !(mousePosition.x > screenDimensions.x) && !(mousePosition.y > screenDimensions.y))
			{
				lastResizePos = Vector2.op_Implicit(mousePosition);
				float num = (float)((decimal)val.x / (decimal)screenDimensions.x);
				float num2 = (float)((decimal)val.y / (decimal)screenDimensions.y);
				Vector2 anchorMin = Rect.anchorMin;
				Vector2 anchorMax = Rect.anchorMax;
				if (currentResizeType.HasFlag(ResizeTypes.Left))
				{
					anchorMin.x -= num;
				}
				else if (currentResizeType.HasFlag(ResizeTypes.Right))
				{
					anchorMax.x -= num;
				}
				if (currentResizeType.HasFlag(ResizeTypes.Top))
				{
					anchorMax.y -= num2;
				}
				else if (currentResizeType.HasFlag(ResizeTypes.Bottom))
				{
					anchorMin.y -= num2;
				}
				Vector2 anchorMin2 = Rect.anchorMin;
				Vector2 anchorMax2 = Rect.anchorMax;
				Rect.anchorMin = new Vector2(anchorMin.x, anchorMin.y);
				Rect.anchorMax = new Vector2(anchorMax.x, anchorMax.y);
				Rect rect = Rect.rect;
				if (((Rect)(ref rect)).width < (float)UIPanel.MinWidth)
				{
					Rect.anchorMin = new Vector2(anchorMin2.x, Rect.anchorMin.y);
					Rect.anchorMax = new Vector2(anchorMax2.x, Rect.anchorMax.y);
				}
				rect = Rect.rect;
				if (((Rect)(ref rect)).height < (float)UIPanel.MinHeight)
				{
					Rect.anchorMin = new Vector2(Rect.anchorMin.x, anchorMin2.y);
					Rect.anchorMax = new Vector2(Rect.anchorMax.x, anchorMax2.y);
				}
			}
		}

		public virtual void OnEndResize()
		{
			WasResizing = false;
			PanelManager.Resizing = false;
			try
			{
				OnHoverResizeEnd();
			}
			catch
			{
			}
			UpdateResizeCache();
			this.OnFinishResize?.Invoke();
		}
	}
}
namespace ChatLineColorMod_UniverseLib.UI.Models
{
	internal abstract class UIModel
	{
		public abstract GameObject UIRoot { get; }

		public bool Enabled
		{
			get
			{
				return Object.op_Implicit((Object)(object)UIRoot) && UIRoot.activeInHierarchy;
			}
			set
			{
				if (Object.op_Implicit((Object)(object)UIRoot) && Enabled != value)
				{
					UIRoot.SetActive(value);
					this.OnToggleEnabled?.Invoke(value);
				}
			}
		}

		public event Action<bool> OnToggleEnabled;

		public abstract void ConstructUI(GameObject parent);

		public virtual void Toggle()
		{
			SetActive(!Enabled);
		}

		public virtual void SetActive(bool active)
		{
			GameObject uIRoot = UIRoot;
			if (uIRoot != null)
			{
				uIRoot.SetActive(active);
			}
		}

		public virtual void Destroy()
		{
			if (Object.op_Implicit((Object)(object)UIRoot))
			{
				Object.Destroy((Object)(object)UIRoot);
			}
		}
	}
	internal abstract class UIBehaviourModel : UIModel
	{
		private static readonly List<UIBehaviourModel> Instances = new List<UIBehaviourModel>();

		internal static void UpdateInstances()
		{
			if (!Instances.Any())
			{
				return;
			}
			try
			{
				for (int num = Instances.Count - 1; num >= 0; num--)
				{
					UIBehaviourModel uIBehaviourModel = Instances[num];
					if (uIBehaviourModel == null || !Object.op_Implicit((Object)(object)uIBehaviourModel.UIRoot))
					{
						Instances.RemoveAt(num);
					}
					else if (uIBehaviourModel.Enabled)
					{
						uIBehaviourModel.Update();
					}
				}
			}
			catch (Exception message)
			{
				Universe.Log(message);
			}
		}

		public UIBehaviourModel()
		{
			Instances.Add(this);
		}

		public virtual void Update()
		{
		}

		public override void Destroy()
		{
			if (Instances.Contains(this))
			{
				Instances.Remove(this);
			}
			base.Destroy();
		}
	}
}
namespace ChatLineColorMod_UniverseLib.UI.Panels
{
	internal abstract class PanelBase : UIBehaviourModel
	{
		protected GameObject uiRoot;

		public UIBase Owner { get; }

		public abstract string Name { get; }

		public abstract int MinWidth { get; }

		public abstract int MinHeight { get; }

		public abstract Vector2 DefaultAnchorMin { get; }

		public abstract Vector2 DefaultAnchorMax { get; }

		public virtual Vector2 DefaultPosition { get; }

		public virtual bool CanDragAndResize => true;

		public PanelDragger Dragger { get; internal set; }

		public override GameObject UIRoot => uiRoot;

		public RectTransform Rect { get; private set; }

		public GameObject ContentRoot { get; protected set; }

		public GameObject TitleBar { get; private set; }

		public PanelBase(UIBase owner)
		{
			Owner = owner;
			ConstructUI();
			Owner.Panels.AddPanel(this);
		}

		public override void Destroy()
		{
			Owner.Panels.RemovePanel(this);
			base.Destroy();
		}

		public virtual void OnFinishResize()
		{
		}

		public virtual void OnFinishDrag()
		{
		}

		public override void SetActive(bool active)
		{
			if (base.Enabled != active)
			{
				base.SetActive(active);
			}
			if (!active)
			{
				Dragger.WasDragging = false;
				return;
			}
			UIRoot.transform.SetAsLastSibling();
			Owner.Panels.InvokeOnPanelsReordered();
		}

		protected virtual void OnClosePanelClicked()
		{
			SetActive(active: false);
		}

		public virtual void SetDefaultSizeAndPosition()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			((Transform)Rect).localPosition = Vector2.op_Implicit(DefaultPosition);
			Rect.pivot = new Vector2(0f, 1f);
			Rect.anchorMin = DefaultAnchorMin;
			Rect.anchorMax = DefaultAnchorMax;
			LayoutRebuilder.ForceRebuildLayoutImmediate(Rect);
			EnsureValidPosition();
			EnsureValidSize();
			Dragger.OnEndResize();
		}

		public virtual void EnsureValidSize()
		{
			//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_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)
			Rect rect = Rect.rect;
			if (((Rect)(ref rect)).width < (float)MinWidth)
			{
				Rect.SetSizeWithCurrentAnchors((Axis)0, (float)MinWidth);
			}
			rect = Rect.rect;
			if (((Rect)(ref rect)).height < (float)MinHeight)
			{
				Rect.SetSizeWithCurrentAnchors((Axis)1, (float)MinHeight);
			}
			Dragger.OnEndResize();
		}

		public virtual void EnsureValidPosition()
		{
			//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_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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			Vector3 localPosition = ((Transform)Rect).localPosition;
			Vector2 screenDimensions = Owner.Panels.ScreenDimensions;
			float num = screenDimensions.x * 0.5f;
			float num2 = screenDimensions.y * 0.5f;
			float num3 = 0f - num;
			Rect rect = Rect.rect;
			localPosition.x = Math.Max(num3 - ((Rect)(ref rect)).width + 50f, Math.Min(localPosition.x, num - 50f));
			localPosition.y = Math.Max(0f - num2 + 50f, Math.Min(localPosition.y, num2));
			((Transform)Rect).localPosition = localPosition;
		}

		protected abstract void ConstructPanelContent();

		protected virtual PanelDragger CreatePanelDragger()
		{
			return new PanelDragger(this);
		}

		public virtual void ConstructUI()
		{
			//IL_00ff: 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_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			uiRoot = UIFactory.CreatePanel(Name, Owner.Panels.PanelHolder, out var contentHolder);
			ContentRoot = contentHolder;
			Rect = uiRoot.GetComponent<RectTransform>();
			UIFactory.SetLayoutGroup<VerticalLayoutGroup>(ContentRoot, (bool?)false, (bool?)false, (bool?)true, (bool?)true, (int?)2, (int?)2, (int?)2, (int?)2, (int?)2, (TextAnchor?)(TextAnchor)0);
			UIFactory.SetLayoutElement(ContentRoot, 0, 0, 9999, 9999);
			TitleBar = UIFactory.CreateHorizontalGroup(ContentRoot, "TitleBar", forceExpandWidth: false, forceExpandHeight: true, childControlWidth: true, childControlHeight: true, 2, new Vector4(2f, 2f, 2f, 2f), new Color(0.06f, 0.06f, 0.06f));
			GameObject titleBar = TitleBar;
			int? minHeight = 25;
			int? flexibleHeight = 0;
			UIFactory.SetLayoutElement(titleBar, null, minHeight, null, flexibleHeight);
			Text val = UIFactory.CreateLabel(TitleBar, "TitleBar", Name, (TextAnchor)3);
			UIFactory.SetLayoutElement(((Component)val).gameObject, 50, 25, 9999, 0);
			GameObject val2 = UIFactory.CreateUIObject("CloseHolder", TitleBar);
			UIFactory.SetLayoutElement(val2, minHeight: 25, flexibleHeight: 0, minWidth: 30, flexibleWidth: 9999);
			bool? forceWidth = false;
			bool? forceHeight = false;
			bool? childControlWidth = true;
			bool? childControlHeight = true;
			int? spacing = 3;
			TextAnchor? childAlignment = (TextAnchor)5;
			UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(val2, forceWidth, forceHeight, childControlWidth, childControlHeight, spacing, (int?)null, (int?)null, (int?)null, (int?)null, childAlignment);
			ButtonRef buttonRef = UIFactory.CreateButton(val2, "CloseButton", "—");
			UIFactory.SetLayoutElement(((Component)buttonRef.Component).gameObject, minHeight: 25, minWidth: 25, flexibleWidth: 0);
			RuntimeHelper.SetColorBlock((Selectable)(object)buttonRef.Component, (Color?)new Color(0.33f, 0.32f, 0.31f), (Color?)null, (Color?)null, (Color?)null);
			buttonRef.OnClick = (Action)Delegate.Combine(buttonRef.OnClick, (Action)delegate
			{
				OnClosePanelClicked();
			});
			if (!CanDragAndResize)
			{
				TitleBar.SetActive(false);
			}
			Dragger = CreatePanelDragger();
			Dragger.OnFinishResize += OnFinishResize;
			Dragger.OnFinishDrag += OnFinishDrag;
			ConstructPanelContent();
			SetDefaultSizeAndPosition();
			RuntimeHelper.StartCoroutine(LateSetupCoroutine());
		}

		private IEnumerator LateSetupCoroutine()
		{
			yield return null;
			LateConstructUI();
		}

		protected virtual void LateConstructUI()
		{
			SetDefaultSizeAndPosition();
		}

		[Obsolete("Not used. Use ConstructUI() instead.")]
		public override void ConstructUI(GameObject parent)
		{
			ConstructUI();
		}
	}
}
namespace ChatLineColorMod_UniverseLib.UI.Models
{
	internal class ButtonRef
	{
		public Action OnClick;

		public Button Component { get; }

		public Text ButtonText { get; }

		public GameObject GameObject => ((Component)Component).gameObject;

		public RectTransform Transform => ((Il2CppObjectBase)((Component)Component).transform).TryCast<RectTransform>();

		public bool Enabled
		{
			get
			{
				return ((Behaviour)Component).enabled;
			}
			set
			{
				((Behaviour)Component).enabled = value;
			}
		}

		public ButtonRef(Button button)
		{
			Component = button;
			ButtonText = ((Component)button).GetComponentInChildren<Text>();
			((UnityEvent)(object)button.onClick).AddListener(delegate
			{
				OnClick?.Invoke();
			});
		}
	}
}
namespace ChatLineColorMod_UniverseLib.UI.Panels
{
	internal enum MouseState
	{
		Down,
		Held,
		NotPressed
	}
}
namespace ChatLineColorMod_UniverseLib
{
	internal class Universe
	{
		public enum GlobalState
		{
			WaitingToSetup,
			SettingUp,
			SetupCompleted
		}

		public const string NAME = "UniverseLib";

		public const string VERSION = "1.5.1";

		public const string AUTHOR = "Sinai";

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

		private static float startupDelay;

		private static Action<string, LogType> logHandler;

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


		public static GlobalState CurrentGlobalState { get; private set; }

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


		private static event Action OnInitialized;

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

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

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

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

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

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

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

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

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

		internal static bool Patch(Type type, string methodName, MethodType methodType, Type[] arguments = null, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			try
			{
				string text = (((int)methodType == 1) ? "get_" : (((int)methodType != 2) ? string.Empty : "set_"));
				string text2 = text;
				MethodInfo methodInfo = ((arguments == null) ? type.GetMethod(text2 + methodName, AccessTools.all) : type.GetMethod(text2 + methodName, AccessTools.all, null, arguments, null));
				if (methodInfo == null)
				{
					return false;
				}
				if (Il2CppType.From(type, false) != (Type)null && Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod((MethodBase)methodInfo) == null)
				{
					Log("\t IL2CPP method has no corresponding pointer, aborting patch of " + type.FullName + "." + methodName);
					return false;
				}
				PatchProcessor val = Harmony.CreateProcessor((MethodBase)methodInfo);
				if (prefix != null)
				{
					val.AddPrefix(new HarmonyMethod(prefix));
				}
				if (postfix != null)
				{
					val.AddPostfix(new HarmonyMethod(postfix));
				}
				if (finalizer != null)
				{
					val.AddFinalizer(new HarmonyMethod(finalizer));
				}
				val.Patch();
				return true;
			}
			catch (Exception value)
			{
				LogWarning($"\t Exception patching {type.FullName}.{methodName}: {value}");
				return false;
			}
		}

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

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

		internal static bool Patch(Type type, string methodName, MethodType methodType, Type[][] possibleArguments, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			foreach (Type[] arguments in possibleArguments)
			{
				if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer))
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace ChatLineColorMod_UniverseLib.Runtime
{
	internal enum RuntimeContext
	{
		Mono,
		IL2CPP
	}
}
namespace ChatLineColorMod_UniverseLib.Config
{
	internal struct UniverseLibConfig
	{
		public bool? Disable_EventSystem_Override;

		public bool? Force_Unlock_Mouse;

		public string Unhollowed_Modules_Folder;

		public bool? Disable_Fallback_EventSystem_Search;

		public bool? Allow_UI_Selection_Outside_UIBase;
	}
}
namespace ChatLineColorMod_UniverseLib.Input
{
	internal static class InputManager
	{
		internal static IHandleInput inputHandler;

		private static bool isRebinding;

		internal static IEnumerable<KeyCode> allKeycodes;

		internal static Action<KeyCode> onRebindPressed;

		internal static Action<KeyCode?> onRebindFinished;

		public static InputType CurrentType { get; private set; }

		public static Vector3 MousePosition
		{
			get
			{
				//IL_0022: 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_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: 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)
				if (Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
				{
					return Vector2.op_Implicit(Vector2.zero);
				}
				return Vector2.op_Implicit(inputHandler.MousePosition);
			}
		}

		public static Vector2 MouseScrollDelta
		{
			get
			{
				//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_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				if (Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
				{
					return Vector2.zero;
				}
				return inputHandler.MouseScrollDelta;
			}
		}

		public static bool Rebinding
		{
			get
			{
				return isRebinding && UniversalUI.AnyUIShowing;
			}
			set
			{
				isRebinding = value;
			}
		}

		public static KeyCode? LastRebindKey { get; set; }

		internal static void Init()
		{
			InitHandler();
			InitKeycodes();
			CursorUnlocker.Init();
			EventSystemHelper.Init();
		}

		private static void InitHandler()
		{
			if (ReflectionUtility.GetTypeByName("UnityEngine.Input") == null)
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					if (assembly.FullName.Contains("UnityEngine.InputLegacyModule"))
					{
						ReflectionUtility.CacheTypes(assembly);
						break;
					}
				}
			}
			if (LegacyInput.TInput != null)
			{
				try
				{
					inputHandler = new LegacyInput();
					CurrentType = InputType.Legacy;
					inputHandler.GetKeyDown((KeyCode)286);
					Universe.Log("Initialized Legacy Input support");
					return;
				}
				catch
				{
				}
			}
			if (InputSystem.TKeyboard != null)
			{
				try
				{
					inputHandler = new InputSystem();
					CurrentType = InputType.InputSystem;
					Universe.Log("Initialized new InputSystem support.");
					return;
				}
				catch (Exception message)
				{
					Universe.Log(message);
				}
			}
			Universe.LogWarning("Could not find any Input Module Type!");
			inputHandler = new NoInput();
			CurrentType = InputType.None;
		}

		private static void InitKeycodes()
		{
			//IL_0027: 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_0064: Unknown result type (might be due to invalid IL or missing references)
			Array values = Enum.GetValues(typeof(KeyCode));
			List<KeyCode> list = new List<KeyCode>();
			foreach (KeyCode item2 in values)
			{
				KeyCode item = item2;
				string text = ((object)(KeyCode)(ref item)).ToString();
				if (!text.Contains("Mouse") && !text.Contains("Joystick"))
				{
					list.Add(item);
				}
			}
			allKeycodes = list.ToArray();
		}

		public static bool GetKeyDown(KeyCode key)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (Rebinding || Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
			{
				return false;
			}
			if ((int)key == 0)
			{
				return false;
			}
			return inputHandler.GetKeyDown(key);
		}

		public static bool GetKey(KeyCode key)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (Rebinding || Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
			{
				return false;
			}
			if ((int)key == 0)
			{
				return false;
			}
			return inputHandler.GetKey(key);
		}

		public static bool GetKeyUp(KeyCode key)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (Rebinding || Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
			{
				return false;
			}
			if ((int)key == 0)
			{
				return false;
			}
			return inputHandler.GetKeyUp(key);
		}

		public static bool GetMouseButtonDown(int btn)
		{
			if (Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
			{
				return false;
			}
			return inputHandler.GetMouseButtonDown(btn);
		}

		public static bool GetMouseButton(int btn)
		{
			if (Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
			{
				return false;
			}
			return inputHandler.GetMouseButton(btn);
		}

		public static bool GetMouseButtonUp(int btn)
		{
			if (Universe.CurrentGlobalState != Universe.GlobalState.SetupCompleted)
			{
				return false;
			}
			return inputHandler.GetMouseButtonUp(btn);
		}

		public static void ResetInputAxes()
		{
			if (Universe.CurrentGlobalState == Universe.GlobalState.SetupCompleted)
			{
				inputHandler.ResetInputAxes();
			}
		}

		internal static void Update()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (Rebinding)
			{
				KeyCode? currentKeyDown = GetCurrentKeyDown();
				if (currentKeyDown.HasValue)
				{
					LastRebindKey = currentKeyDown;
					onRebindPressed?.Invoke(currentKeyDown.Value);
				}
			}
		}

		internal static KeyCode? GetCurrentKeyDown()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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)
			foreach (KeyCode allKeycode in allKeycodes)
			{
				if (inputHandler.GetKeyDown(allKeycode))
				{
					return allKeycode;
				}
			}
			return null;
		}

		public static void BeginRebind(Action<KeyCode> onSelection, Action<KeyCode?> onFinished)
		{
			if (!Rebinding)
			{
				onRebindPressed = onSelection;
				onRebindFinished = onFinished;
				Rebinding = true;
				LastRebindKey = null;
			}
		}

		public static void EndRebind()
		{
			if (Rebinding)
			{
				Rebinding = false;
				onRebindFinished?.Invoke(LastRebindKey);
				onRebindFinished = null;
				onRebindPressed = null;
			}
		}
	}
	internal enum InputType
	{
		InputSystem,
		Legacy,
		None
	}
	internal interface IHandleInput
	{
		Vector2 MousePosition { get; }

		Vector2 MouseScrollDelta { get; }

		BaseInputModule UIInputModule { get; }

		bool GetKeyDown(KeyCode key);

		bool GetKey(KeyCode key);

		bool GetKeyUp(KeyCode key);

		bool GetMouseButtonDown(int btn);

		bool GetMouseButton(int btn);

		bool GetMouseButtonUp(int btn);

		void ResetInputAxes();

		void AddUIInputModule();

		void ActivateModule();
	}
}
namespace ChatLineColorMod_UniverseLib.UI
{
	internal static class UniversalUI
	{
		internal static readonly Dictionary<string, UIBase> registeredUIs = new Dictionary<string, UIBase>();

		internal static readonly List<UIBase> uiBases = new List<UIBase>();

		public const int MAX_INPUTFIELD_CHARS = 16000;

		public const int MAX_TEXT_VERTS = 65000;

		internal static AssetBundle UIBundle;

		public static bool Initializing { get; internal set; } = true;


		public static bool AnyUIShowing => registeredUIs.Any((KeyValuePair<string, UIBase> it) => it.Value.Enabled);

		public static GameObject CanvasRoot { get; private set; }

		public static EventSystem EventSys { get; private set; }

		public static GameObject PoolHolder { get; private set; }

		public static Font ConsoleFont { get; private set; }

		public static Font DefaultFont { get; private set; }

		public static Shader BackupShader { get; private set; }

		public static Color EnabledButtonColor { get; } = new Color(0.2f, 0.4f, 0.28f);


		public static Color DisabledButtonColor { get; } = new Color(0.25f, 0.25f, 0.25f);


		public static UIBase RegisterUI(string id, Action updateMethod)
		{
			return new UIBase(id, updateMethod);
		}

		public static T RegisterUI<T>(string id, Action updateMethod) where T : UIBase
		{
			return (T)Activator.CreateInstance(typeof(T), id, updateMethod);
		}

		public static void SetUIActive(string id, bool active)
		{
			if (registeredUIs.TryGetValue(id, out var value))
			{
				value.RootObject.SetActive(active);
				if (active)
				{
					value.SetOnTop();
				}
				else if (value != PanelManager.resizeCursorUIBase)
				{
					PanelManager.ForceEndResize();
				}
				CursorUnlocker.UpdateCursorControl();
				return;
			}
			throw new ArgumentException("There is no UI registered with the id '" + id + "'");
		}

		internal static void Init()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			LoadBundle();
			CreateRootCanvas();
			PoolHolder = new GameObject("PoolHolder");
			PoolHolder.transform.parent = CanvasRoot.transform;
			PoolHolder.SetActive(false);
			Initializing = false;
		}

		internal static void Update()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)CanvasRoot) || Initializing || !AnyUIShowing)
			{
				return;
			}
			if (EventSys.IsPointerOverGameObject() && (InputManager.MouseScrollDelta.y != 0f || InputManager.GetMouseButtonUp(0) || InputManager.GetMouseButtonUp(1)))
			{
				InputManager.ResetInputAxes();
			}
			InputManager.Update();
			InputFieldRef.UpdateInstances();
			UIBehaviourModel.UpdateInstances();
			PanelManager.focusHandledThisFrame = false;
			PanelManager.draggerHandledThisFrame = false;
			for (int i = 0; i < uiBases.Count; i++)
			{
				UIBase uIBase = uiBases[i];
				if (uIBase.Enabled)
				{
					uIBase.Update();
				}
			}
		}

		private static void CreateRootCanvas()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0022: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			CanvasRoot = new GameObject("UniverseLibCanvas");
			Object.DontDestroyOnLoad((Object)(object)CanvasRoot);
			GameObject canvasRoot = CanvasRoot;
			((Object)canvasRoot).hideFlags = (HideFlags)(((Object)canvasRoot).hideFlags | 0x3D);
			CanvasRoot.layer = 5;
			CanvasRoot.transform.position = new Vector3(0f, 0f, 1f);
			CanvasRoot.SetActive(false);
			EventSys = CanvasRoot.AddComponent<EventSystem>();
			EventSystemHelper.AddUIModule();
			((Behaviour)EventSys).enabled = false;
			CanvasRoot.SetActive(true);
		}

		private static void LoadBundle()
		{
			SetupAssetBundlePatches();
			try
			{
				string[] array = Application.unityVersion.Split('.');
				int num = int.Parse(array[0]);
				int num2 = int.Parse(array[1]);
				int num3 = int.Parse(array[2][0].ToString());
				if (num > 5)
				{
					UIBundle = LoadBundle("modern");
				}
				else if (num == 5 && num2 >= 6)
				{
					UIBundle = LoadBundle("legacy.5.6");
				}
				else if (num == 5 && ((num2 == 3 && num3 >= 4) || num2 > 3))
				{
					UIBundle = LoadBundle("legacy.5.3.4");
				}
				else
				{
					UIBundle = LoadBundle("legacy");
				}
			}
			catch
			{
				Universe.LogWarning("Exception parsing Unity version, falling back to old AssetBundle load method...");
				UIBundle = LoadBundle("modern") ?? LoadBundle("legacy.5.6") ?? LoadBundle("legacy.5.3.4") ?? LoadBundle("legacy");
			}
			if ((Object)(object)UIBundle == (Object)null)
			{
				Universe.LogWarning("Could not load the UniverseLib UI Bundle!");
				DefaultFont = (ConsoleFont = Resources.GetBuiltinResource<Font>("Arial.ttf"));
				return;
			}
			ConsoleFont = UIBundle.LoadAsset<Font>("CONSOLA");
			((Object)ConsoleFont).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)ConsoleFont);
			DefaultFont = UIBundle.LoadAsset<Font>("arial");
			((Object)DefaultFont).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)DefaultFont);
			BackupShader = UIBundle.LoadAsset<Shader>("DefaultUI");
			((Object)BackupShader).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)BackupShader);
			Shader shader = Graphic.defaultGraphicMaterial.shader;
			if (((shader != null) ? ((Object)shader).name : null) != "UI/Default")
			{
				Universe.Log("This game does not ship with the 'UI/Default' shader, using manual Default Shader...");
				Graphic.defaultGraphicMaterial.shader = BackupShader;
			}
			else
			{
				BackupShader = Graphic.defaultGraphicMaterial.shader;
			}
		}

		private static AssetBundle LoadBundle(string id)
		{
			AssetBundle assetBundle = AssetBundle.LoadFromMemory(Il2CppStructArray<byte>.op_Implicit(ReadFully(typeof(Universe).Assembly.GetManifestResourceStream("UniverseLib.Resources." + id + ".bundle"))));
			if (Object.op_Implicit((Object)(object)assetBundle))
			{
				Universe.Log("Loaded " + id + " bundle for Unity " + Application.unityVersion);
			}
			return assetBundle;
		}

		private static byte[] ReadFully(Stream input)
		{
			using MemoryStream memoryStream = new MemoryStream();
			byte[] array = new byte[81920];
			int count;
			while ((count = input.Read(array, 0, array.Length)) != 0)
			{
				memoryStream.Write(array, 0, count);
			}
			return memoryStream.ToArray();
		}

		private static void SetupAssetBundlePatches()
		{
			Universe.Patch(ReflectionUtility.GetTypeByName("UnityEngine.AssetBundle"), "UnloadAllAssetBundles", (MethodType)0, (Type[])null, AccessTools.Method(typeof(UniversalUI), "Prefix_UnloadAllAssetBundles", (Type[])null, (Type[])null), (MethodInfo)null, (MethodInfo)null);
		}

		private static bool Prefix_UnloadAllAssetBundles(bool unloadAllObjects)
		{
			try
			{
				MethodInfo method = typeof(AssetBundle).GetMethod("GetAllLoadedAssetBundles", AccessTools.all);
				if (method == null)
				{
					return true;
				}
				AssetBundle[] array = method.Invoke(null, ArgumentUtility.EmptyArgs) as AssetBundle[];
				AssetBundle[] array2 = array;
				foreach (AssetBundle assetBundle in array2)
				{
					if (!(((Object)assetBundle).m_CachedPtr == ((Object)UIBundle).m_CachedPtr))
					{
						assetBundle.Unload(unloadAllObjects);
					}
				}
			}
			catch (Exception value)
			{
				Universe.LogWarning($"Exception unloading AssetBundles: {value}");
			}
			return false;
		}
	}
}
namespace ChatLineColorMod_UniverseLib
{
	internal class AssetBundle : Object
	{
		internal delegate void d_Unload(IntPtr _this, bool unloadAllLoadedObjects);

		internal delegate IntPtr d_LoadAsset_Internal(IntPtr _this, IntPtr name, IntPtr type);

		internal delegate IntPtr d_LoadAssetWithSubAssets_Internal(IntPtr _this, IntPtr name, IntPtr type);

		public delegate IntPtr d_GetAllLoadedAssetBundles_Native();

		private delegate IntPtr d_LoadFromMemory(IntPtr binary, uint crc);

		internal delegate IntPtr d_LoadFromFile(IntPtr path, uint crc, ulong offset);

		public readonly IntPtr m_bundlePtr = IntPtr.Zero;

		static AssetBundle()
		{
			ClassInjector.RegisterTypeInIl2Cpp<AssetBundle>();
		}

		[HideFromIl2Cpp]
		public static AssetBundle LoadFromFile(string path)
		{
			IntPtr intPtr = ICallManager.GetICallUnreliable<d_LoadFromFile>(new string[2] { "UnityEngine.AssetBundle::LoadFromFile_Internal", "UnityEngine.AssetBundle::LoadFromFile" })(IL2CPP.ManagedStringToIl2Cpp(path), 0u, 0uL);
			return (intPtr != IntPtr.Zero) ? new AssetBundle(intPtr) : null;
		}

		[HideFromIl2Cpp]
		public static AssetBundle LoadFromMemory(Il2CppStructArray<byte> binary, uint crc = 0u)
		{
			IntPtr intPtr = ICallManager.GetICallUnreliable<d_LoadFromMemory>(new string[2] { "UnityEngine.AssetBundle::LoadFromMemory_Internal", "UnityEngine.AssetBundle::LoadFromMemory" })(((Il2CppObjectBase)binary).Pointer, crc);
			return (intPtr != IntPtr.Zero) ? new AssetBundle(intPtr) : null;
		}

		[HideFromIl2Cpp]
		public static AssetBundle[] GetAllLoadedAssetBundles()
		{
			IntPtr intPtr = ICallManager.GetICall<d_GetAllLoadedAssetBundles_Native>("UnityEngine.AssetBundle::GetAllLoadedAssetBundles_Native")();
			return (intPtr != IntPtr.Zero) ? Il2CppArrayBase<AssetBundle>.op_Implicit((Il2CppArrayBase<AssetBundle>)(object)new Il2CppReferenceArray<AssetBundle>(intPtr)) : null;
		}

		public AssetBundle(IntPtr ptr)
			: base(ptr)
		{
			m_bundlePtr = ptr;
		}

		[HideFromIl2Cpp]
		public Object[] LoadAllAssets()
		{
			IntPtr intPtr = ICallManager.GetICall<d_LoadAssetWithSubAssets_Internal>("UnityEngine.AssetBundle::LoadAssetWithSubAssets_Internal")(m_bundlePtr, IL2CPP.ManagedStringToIl2Cpp(""), ((Il2CppObjectBase)Il2CppType.Of<Object>()).Pointer);
			return (Object[])((intPtr != IntPtr.Zero) ? ((Array)Il2CppArrayBase<Object>.op_Implicit((Il2CppArrayBase<Object>)(object)new Il2CppReferenceArray<Object>(intPtr))) : ((Array)new Object[0]));
		}

		[HideFromIl2Cpp]
		public T LoadAsset<T>(string name) where T : Object
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			IntPtr intPtr = ICallManager.GetICall<d_LoadAsset_Internal>("UnityEngine.AssetBundle::LoadAsset_Internal")(m_bundlePtr, IL2CPP.ManagedStringToIl2Cpp(name), ((Il2CppObjectBase)Il2CppType.Of<T>()).Pointer);
			return (intPtr != IntPtr.Zero) ? ((Il2CppObjectBase)new Object(intPtr)).TryCast<T>() : default(T);
		}

		[HideFromIl2Cpp]
		public void Unload(bool unloadAllLoadedObjects)
		{
			ICallManager.GetICall<d_Unload>("UnityEngine.AssetBundle::Unload")(m_bundlePtr, unloadAllLoadedObjects);
		}
	}
	internal class ReflectionUtility
	{
		public static bool Initializing;

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

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

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

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

		private static string[] allTypeNamesArray;

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

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

		internal static ReflectionUtility Instance { get; private set; }

		public static event Action<Type> OnTypeLoaded;

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

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

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

		private static void SetupTypeCache()
		{
			if (Universe.Context == RuntimeContext.Mono)
			{
				ForceLoadManagedAssemblies();
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly asm in assemblies)
			{
				CacheTypes(asm);
			}
			AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded;
		}

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

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

		internal static void CacheTypes(Assembly asm)
		{
			Type[] types = asm.GetTypes();
			foreach (Type type in types)
			{
				if (!string.IsNullOrEmpty(type.Namespace) && !uniqueNamespaces.Contains(type.Namespace))
				{
					uniqueNamespaces.Add(type.Namespace);
					int j;
					for (j = 0; j < AllNamespaces.Count && type.Namespace.CompareTo(AllNamespaces[j]) >= 0; j++)
					{
					}
					AllNamespaces.Insert(j, type.Namespace);
				}
				AllTypes[type.FullName] = type;
				ReflectionUtility.OnTypeLoaded?.Invoke(type);
			}
		}

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

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

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

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

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

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

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

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

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

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

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

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

		private static IEnumerator DoGetImplementations(Action<HashSet<Type>> onResultsFetched, Type baseType, bool allowAbstract, bool allowGeneric, bool allowEnum)
		{
			List<Type> resolvedTypes = new List<Type>();
			OnTypeLoaded += o

ModernCamera.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using HarmonyLib;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using ModernCamera.Behaviours;
using ModernCamera.Enums;
using ModernCamera.Hooks;
using ModernCamera.Structs;
using ModernCamera.Utils;
using ProjectM;
using ProjectM.Sequencer;
using ProjectM.UI;
using Silkworm.API;
using Silkworm.Core.KeyBinding;
using Silkworm.Core.Options;
using Silkworm.Utils;
using Stunlock.Core;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Entities;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("VRising")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Makes the camera more like a mmo camera and removes the limits")]
[assembly: AssemblyFileVersion("1.5.6.0")]
[assembly: AssemblyInformationalVersion("1.5.6")]
[assembly: AssemblyProduct("ModernCamera")]
[assembly: AssemblyTitle("ModernCamera")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.6.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ModernCamera
{
	public class ModernCamera : MonoBehaviour
	{
		private static GameObject CrosshairPrefab;

		private static GameObject Crosshair;

		private static CanvasScaler CanvasScaler;

		private static bool ShouldGatherSystems = true;

		private static ZoomModifierSystem ZoomModifierSystem;

		private static PrefabCollectionSystem PrefabCollectionSystem;

		private static UIDataSystem UIDataSystem;

		private static Camera GameCamera;

		private static bool GameFocused;

		public static void Enabled(bool enabled)
		{
			Settings.Enabled = enabled;
			UpdateEnabled(enabled);
		}

		public static void ActionMode(bool enabled)
		{
			ModernCameraState.IsMouseLocked = enabled;
			ModernCameraState.IsActionMode = enabled;
		}

		private static void UpdateEnabled(bool enabled)
		{
			if (ZoomModifierSystem != null)
			{
				((ComponentSystemBase)ZoomModifierSystem).Enabled = !enabled;
			}
			if ((Object)(object)Crosshair != (Object)null)
			{
				Crosshair.active = enabled && Settings.AlwaysShowCrosshair && !ModernCameraState.InBuildMode;
			}
			if (!enabled)
			{
				Cursor.visible = true;
				ActionMode(enabled: false);
			}
		}

		private static void UpdateFieldOfView(float fov)
		{
			if ((Object)(object)GameCamera != (Object)null)
			{
				GameCamera.fieldOfView = fov;
			}
		}

		private static void ToggleUI()
		{
			ModernCameraState.IsUIHidden = !ModernCameraState.IsUIHidden;
			DisableUISettings.SetHideHUD(ModernCameraState.IsUIHidden, WorldUtils.ClientWorld);
		}

		private void Awake()
		{
			ModernCameraState.RegisterCameraBehaviour(new FirstPersonCameraBehaviour());
			ModernCameraState.RegisterCameraBehaviour(new ThirdPersonCameraBehaviour());
			Settings.AddEnabledListener(UpdateEnabled);
			Settings.AddFieldOfViewListener(UpdateFieldOfView);
			Settings.AddHideUIListener(ToggleUI);
		}

		private void Update()
		{
			if (!GameFocused || !Settings.Enabled)
			{
				return;
			}
			if ((Object)(object)CrosshairPrefab == (Object)null)
			{
				BuildCrosshair();
			}
			if (WorldUtils.ClientWorldExists)
			{
				if ((Object)(object)GameCamera == (Object)null)
				{
					GameObject val = GameObject.Find("Main_GameToolCamera(Clone)");
					if ((Object)(object)val != (Object)null)
					{
						GameCamera = val.GetComponent<Camera>();
						UpdateFieldOfView(Settings.FieldOfView);
					}
				}
				if (ShouldGatherSystems)
				{
					GatherSystems();
				}
				UpdateSystems();
				UpdateCrosshair();
			}
			else
			{
				ShouldGatherSystems = true;
				Cursor.visible = true;
			}
		}

		private void OnApplicationFocus(bool hasFocus)
		{
			GameFocused = hasFocus;
		}

		private void BuildCrosshair()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (CursorController._CursorDatas != null)
				{
					CursorData val = ((IEnumerable<CursorData>)CursorController._CursorDatas).First((CursorData x) => (int)x.CursorType == 0);
					if (val != null)
					{
						CrosshairPrefab = new GameObject("Crosshair");
						CrosshairPrefab.active = false;
						CrosshairPrefab.AddComponent<CanvasRenderer>();
						RectTransform obj = CrosshairPrefab.AddComponent<RectTransform>();
						((Component)obj).transform.SetSiblingIndex(1);
						obj.pivot = new Vector2(0.5f, 0.5f);
						obj.anchorMin = new Vector2(0.5f, 0.5f);
						obj.anchorMax = new Vector2(0.5f, 0.5f);
						obj.sizeDelta = new Vector2(32f, 32f);
						((Transform)obj).localScale = new Vector3(1.2f, 1.2f, 1.2f);
						((Transform)obj).localPosition = new Vector3(0f, 0f, 0f);
						CrosshairPrefab.AddComponent<Image>().sprite = Sprite.Create(val.Texture, new Rect(0f, 0f, (float)((Texture)val.Texture).width, (float)((Texture)val.Texture).height), new Vector2(0.5f, 0.5f), 100f);
						CrosshairPrefab.active = false;
					}
				}
			}
			catch (Exception ex)
			{
				LogUtils.LogDebugError((object)ex);
			}
		}

		private void GatherSystems()
		{
			ZoomModifierSystem = WorldUtils.ClientWorld.GetExistingSystem<ZoomModifierSystem>();
			if (ZoomModifierSystem != null)
			{
				((ComponentSystemBase)ZoomModifierSystem).Enabled = false;
			}
			PrefabCollectionSystem = WorldUtils.ClientWorld.GetExistingSystem<PrefabCollectionSystem>();
			UIDataSystem = WorldUtils.ClientWorld.GetExistingSystem<UIDataSystem>();
			ShouldGatherSystems = false;
		}

		private void UpdateSystems()
		{
			//IL_006d: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			if (UIDataSystem == null || PrefabCollectionSystem == null)
			{
				return;
			}
			try
			{
				if ((Object)(object)UIDataSystem.UI.BuffBarParent != (Object)null)
				{
					ModernCameraState.IsShapeshifted = false;
					ModernCameraState.ShapeshiftName = "";
					Enumerator<Data> enumerator = UIDataSystem.UI.BuffBarParent.BuffsSelectionGroup.Entries.GetEnumerator();
					while (enumerator.MoveNext())
					{
						Data current = enumerator.Current;
						if (!((PrefabCollectionSystem_Base)PrefabCollectionSystem).PrefabGuidToNameDictionary.ContainsKey(current.PrefabGUID))
						{
							continue;
						}
						string text = ((PrefabCollectionSystem_Base)PrefabCollectionSystem).PrefabGuidToNameDictionary[current.PrefabGUID];
						if (text != null)
						{
							ModernCameraState.IsShapeshifted = text.Contains("shapeshift", StringComparison.OrdinalIgnoreCase);
							if (ModernCameraState.IsShapeshifted)
							{
								ModernCameraState.ShapeshiftName = text.Trim();
								break;
							}
						}
					}
				}
				if (!((Object)(object)UIDataSystem.UI.AbilityBar != (Object)null))
				{
					return;
				}
				ModernCameraState.IsMounted = false;
				Enumerator<AbilityBarEntry> enumerator2 = UIDataSystem.UI.AbilityBar.Entries.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					AbilityBarEntry current2 = enumerator2.Current;
					if (!((PrefabCollectionSystem_Base)PrefabCollectionSystem).PrefabGuidToNameDictionary.ContainsKey(current2.AbilityId))
					{
						continue;
					}
					string text2 = ((PrefabCollectionSystem_Base)PrefabCollectionSystem).PrefabGuidToNameDictionary[current2.AbilityId];
					if (text2 != null)
					{
						ModernCameraState.IsMounted = text2.Contains("mounted", StringComparison.OrdinalIgnoreCase);
						if (ModernCameraState.IsMounted)
						{
							break;
						}
					}
				}
			}
			catch (Exception ex)
			{
				LogUtils.LogDebugError((object)ex);
			}
		}

		private void UpdateCrosshair()
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				bool visible = true;
				bool flag = false;
				if ((Object)(object)Crosshair == (Object)null && (Object)(object)CrosshairPrefab != (Object)null)
				{
					GameObject val = GameObject.Find("HUDCanvas(Clone)/Canvas");
					if ((Object)(object)val == (Object)null)
					{
						return;
					}
					CanvasScaler = val.GetComponent<CanvasScaler>();
					Crosshair = Object.Instantiate<GameObject>(CrosshairPrefab, val.transform);
					Crosshair.active = true;
				}
				if (ModernCameraState.ValidGameplayInputState && (ModernCameraState.IsMouseLocked || ((InputState)(ref ModernCameraState.GameplayInputState)).IsInputPressed((InputFlag)45)) && !ModernCameraState.IsMenuOpen)
				{
					if (ModernCameraState.IsActionMode || ModernCameraState.IsFirstPerson || Settings.CameraAimMode == CameraAimMode.Forward)
					{
						Mouse.SetCursorPosition(Screen.width / 2 + Settings.AimOffsetX, Screen.height / 2 - Settings.AimOffsetY);
					}
					flag = ModernCameraState.IsFirstPerson || (ModernCameraState.IsActionMode && Settings.ActionModeCrosshair);
					visible = false;
				}
				if ((Object)(object)Crosshair != (Object)null)
				{
					Crosshair.active = (flag || Settings.AlwaysShowCrosshair) && !ModernCameraState.InBuildMode;
					if (ModernCameraState.IsFirstPerson)
					{
						Crosshair.transform.localPosition = Vector3.zero;
					}
					else if ((Object)(object)CanvasScaler != (Object)null)
					{
						Crosshair.transform.localPosition = new Vector3((float)Settings.AimOffsetX * (CanvasScaler.referenceResolution.x / (float)Screen.width), (float)Settings.AimOffsetY * (CanvasScaler.referenceResolution.y / (float)Screen.height), 0f);
					}
				}
				Cursor.visible = visible;
			}
			catch (Exception ex)
			{
				LogUtils.LogDebugError((object)ex);
			}
		}
	}
	internal static class ModernCameraState
	{
		internal static bool IsUIHidden;

		internal static bool IsFirstPerson;

		internal static bool IsActionMode;

		internal static bool IsMouseLocked;

		internal static bool IsShapeshifted;

		internal static bool IsMounted;

		internal static bool InBuildMode;

		internal static string ShapeshiftName;

		internal static BehaviourType CurrentBehaviourType = BehaviourType.Default;

		internal static Dictionary<BehaviourType, CameraBehaviour> CameraBehaviours = new Dictionary<BehaviourType, CameraBehaviour>();

		internal static bool ValidGameplayInputState;

		internal static InputState GameplayInputState;

		private static int _menusOpen;

		internal static bool IsMenuOpen
		{
			get
			{
				return _menusOpen > 0;
			}
			set
			{
				_menusOpen = (value ? (_menusOpen + 1) : Mathf.Max(0, _menusOpen - 1));
			}
		}

		internal static CameraBehaviour CurrentCameraBehaviour
		{
			get
			{
				if (CameraBehaviours.ContainsKey(CurrentBehaviourType))
				{
					return CameraBehaviours[CurrentBehaviourType];
				}
				return null;
			}
		}

		internal static void RegisterCameraBehaviour(CameraBehaviour behaviour)
		{
			CameraBehaviours.Add(behaviour.BehaviourType, behaviour);
		}

		internal static void Reset()
		{
			IsUIHidden = false;
			IsFirstPerson = false;
			IsActionMode = false;
			IsMouseLocked = false;
			IsShapeshifted = false;
			IsMounted = false;
			InBuildMode = false;
			ShapeshiftName = "";
			ValidGameplayInputState = false;
			CurrentCameraBehaviour?.Deactivate();
			CurrentBehaviourType = BehaviourType.Default;
		}
	}
	[BepInProcess("VRising.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("VRising.ModernCamera", "ModernCamera", "1.5.6")]
	public class Plugin : BasePlugin
	{
		private static Harmony Harmony;

		public override void Load()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			LogUtils.Init(((BasePlugin)this).Log);
			Settings.Init();
			((BasePlugin)this).AddComponent<ModernCamera>();
			TopdownCameraSystem_Hook.CreateAndApply();
			Harmony = new Harmony("VRising.ModernCamera");
			Harmony.PatchAll();
			LogUtils.LogInfo((object)"Plugin VRising.ModernCamera v1.5.6 is loaded!");
		}

		public override bool Unload()
		{
			Harmony.UnpatchSelf();
			TopdownCameraSystem_Hook.Dispose();
			return true;
		}
	}
	internal static class Settings
	{
		internal static float FirstPersonForwardOffset = 1.65f;

		internal static float MountedOffset = 1.6f;

		internal static float HeadHeightOffset = 1.05f;

		internal static float ShoulderRightOffset = 0.8f;

		internal static Dictionary<string, Vector2> FirstPersonShapeshiftOffsets = new Dictionary<string, Vector2>
		{
			{
				"AB_Shapeshift_Bat_Buff",
				new Vector2(0f, 2.5f)
			},
			{
				"AB_Shapeshift_Bear_Buff",
				new Vector2(0.25f, 5f)
			},
			{
				"AB_Shapeshift_Bear_Skin01_Buff",
				new Vector2(0.25f, 5f)
			},
			{
				"AB_Shapeshift_Human_Grandma_Skin01_Buff",
				new Vector2(-0.1f, 1.55f)
			},
			{
				"AB_Shapeshift_Human_Buff",
				new Vector2(0.5f, 1.4f)
			},
			{
				"AB_Shapeshift_Rat_Buff",
				new Vector2(-1.85f, 2f)
			},
			{
				"AB_Shapeshift_Toad_Buff",
				new Vector2(-0.6f, 4.2f)
			},
			{
				"AB_Shapeshift_Wolf_Buff",
				new Vector2(-0.25f, 4.3f)
			},
			{
				"AB_Shapeshift_Wolf_Skin01_Buff",
				new Vector2(-0.25f, 4.3f)
			}
		};

		private static float ZoomOffset = 2f;

		private static ToggleOption EnabledOption;

		private static SliderOption FieldOfViewOption;

		private static ToggleOption AlwaysShowCrosshairOption;

		private static ToggleOption ActionModeCrosshairOption;

		private static ToggleOption FirstPersonEnabledOption;

		private static ToggleOption DefaultBuildModeOption;

		private static DropdownOption CameraAimModeOption;

		private static SliderOption AimOffsetXOption;

		private static SliderOption AimOffsetYOption;

		private static ToggleOption LockCameraZoomOption;

		private static SliderOption LockCameraZoomDistanceOption;

		private static SliderOption MinZoomOption;

		private static SliderOption MaxZoomOption;

		private static ToggleOption LockCameraPitchOption;

		private static SliderOption LockCameraPitchAngleOption;

		private static SliderOption MinPitchOption;

		private static SliderOption MaxPitchOption;

		private static ToggleOption OverTheShoulderOption;

		private static SliderOption OverTheShoulderXOption;

		private static SliderOption OverTheShoulderYOption;

		private static Keybinding EnabledKeybind;

		private static Keybinding ActionModeKeybind;

		private static Keybinding HideUIKeybind;

		internal static bool Enabled
		{
			get
			{
				return ((Option<bool>)(object)EnabledOption).Value;
			}
			set
			{
				((Option<bool>)(object)EnabledOption).SetValue(value);
			}
		}

		internal static bool FirstPersonEnabled
		{
			get
			{
				return ((Option<bool>)(object)FirstPersonEnabledOption).Value;
			}
			set
			{
				((Option<bool>)(object)FirstPersonEnabledOption).SetValue(value);
			}
		}

		internal static bool DefaultBuildMode
		{
			get
			{
				return ((Option<bool>)(object)DefaultBuildModeOption).Value;
			}
			set
			{
				((Option<bool>)(object)DefaultBuildModeOption).SetValue(value);
			}
		}

		internal static bool AlwaysShowCrosshair
		{
			get
			{
				return ((Option<bool>)(object)AlwaysShowCrosshairOption).Value;
			}
			set
			{
				((Option<bool>)(object)AlwaysShowCrosshairOption).SetValue(value);
			}
		}

		internal static bool ActionModeCrosshair
		{
			get
			{
				return ((Option<bool>)(object)ActionModeCrosshairOption).Value;
			}
			set
			{
				((Option<bool>)(object)ActionModeCrosshairOption).SetValue(value);
			}
		}

		internal static float FieldOfView
		{
			get
			{
				return ((Option<float>)(object)FieldOfViewOption).Value;
			}
			set
			{
				((Option<float>)(object)FieldOfViewOption).SetValue(value);
			}
		}

		internal static int AimOffsetX
		{
			get
			{
				return (int)((float)Screen.width * (((Option<float>)(object)AimOffsetXOption).Value / 100f));
			}
			set
			{
				((Option<float>)(object)AimOffsetXOption).SetValue((float)Mathf.Clamp(value / Screen.width, -25, 25));
			}
		}

		internal static int AimOffsetY
		{
			get
			{
				return (int)((float)Screen.height * (((Option<float>)(object)AimOffsetYOption).Value / 100f));
			}
			set
			{
				((Option<float>)(object)AimOffsetYOption).SetValue((float)Mathf.Clamp(value / Screen.width, -25, 25));
			}
		}

		internal static CameraAimMode CameraAimMode
		{
			get
			{
				return CameraAimModeOption.GetEnumValue<CameraAimMode>();
			}
			set
			{
				((Option<int>)(object)CameraAimModeOption).SetValue((int)value);
			}
		}

		internal static bool LockZoom
		{
			get
			{
				return ((Option<bool>)(object)LockCameraZoomOption).Value;
			}
			set
			{
				((Option<bool>)(object)LockCameraZoomOption).SetValue(value);
			}
		}

		internal static float LockZoomDistance
		{
			get
			{
				return ((Option<float>)(object)LockCameraZoomDistanceOption).Value;
			}
			set
			{
				((Option<float>)(object)LockCameraZoomDistanceOption).SetValue(value);
			}
		}

		internal static float MinZoom
		{
			get
			{
				return ((Option<float>)(object)MinZoomOption).Value;
			}
			set
			{
				((Option<float>)(object)MinZoomOption).SetValue(value);
			}
		}

		internal static float MaxZoom
		{
			get
			{
				return ((Option<float>)(object)MaxZoomOption).Value;
			}
			set
			{
				((Option<float>)(object)MaxZoomOption).SetValue(value);
			}
		}

		internal static bool LockPitch
		{
			get
			{
				return ((Option<bool>)(object)LockCameraPitchOption).Value;
			}
			set
			{
				((Option<bool>)(object)LockCameraPitchOption).SetValue(value);
			}
		}

		internal static float LockPitchAngle
		{
			get
			{
				return ((Option<float>)(object)LockCameraPitchAngleOption).Value * ((float)Math.PI / 180f);
			}
			set
			{
				((Option<float>)(object)LockCameraPitchAngleOption).SetValue(Mathf.Clamp(value * 57.29578f, 0f, 90f));
			}
		}

		internal static float MinPitch
		{
			get
			{
				return ((Option<float>)(object)MinPitchOption).Value * ((float)Math.PI / 180f);
			}
			set
			{
				((Option<float>)(object)MinPitchOption).SetValue(Mathf.Clamp(value * 57.29578f, 0f, 90f));
			}
		}

		internal static float MaxPitch
		{
			get
			{
				return ((Option<float>)(object)MaxPitchOption).Value * ((float)Math.PI / 180f);
			}
			set
			{
				((Option<float>)(object)MaxPitchOption).SetValue(Mathf.Clamp(value * 57.29578f, 0f, 90f));
			}
		}

		internal static bool OverTheShoulder
		{
			get
			{
				return ((Option<bool>)(object)OverTheShoulderOption).Value;
			}
			set
			{
				((Option<bool>)(object)OverTheShoulderOption).SetValue(value);
			}
		}

		internal static float OverTheShoulderX
		{
			get
			{
				return ((Option<float>)(object)OverTheShoulderXOption).Value;
			}
			set
			{
				((Option<float>)(object)OverTheShoulderXOption).SetValue(value);
			}
		}

		internal static float OverTheShoulderY
		{
			get
			{
				return ((Option<float>)(object)OverTheShoulderYOption).Value;
			}
			set
			{
				((Option<float>)(object)OverTheShoulderYOption).SetValue(value);
			}
		}

		internal static void Init()
		{
			SetupOptions();
			SetupKeybinds();
		}

		internal static void AddEnabledListener(Action<bool> action)
		{
			((Option<bool>)(object)EnabledOption).AddListener(action);
		}

		internal static void AddFieldOfViewListener(Action<float> action)
		{
			((Option<float>)(object)FieldOfViewOption).AddListener(action);
		}

		internal static void AddHideUIListener(Action action)
		{
			HideUIKeybind.AddKeyDownListener(action);
		}

		private static void SetupOptions()
		{
			OptionCategory obj = OptionsManager.AddCategory("Modern Camera");
			EnabledOption = obj.AddToggle("moderncamera.enabled", "Enabled", true);
			FirstPersonEnabledOption = obj.AddToggle("moderncamera.firstperson", "Enable First Person", true);
			DefaultBuildModeOption = obj.AddToggle("moderncamera.defaultbuildmode", "Use Default Build Mode Camera", true);
			AlwaysShowCrosshairOption = obj.AddToggle("moderncamera.alwaysshowcrosshair", "Always show Crosshair", false);
			ActionModeCrosshairOption = obj.AddToggle("moderncamera.actionmodecrosshair", "Show Crosshair in Action Mode", false);
			FieldOfViewOption = obj.AddSlider("moderncamera.fieldofview", "Field of View", 50f, 90f, 60f);
			obj.AddDivider("Third Person Aiming");
			CameraAimModeOption = obj.AddDropdown("moderncamera.aimmode", "Aim Mode", 0, Enum.GetNames(typeof(CameraAimMode)));
			AimOffsetXOption = obj.AddSlider("moderncamera.aimoffsetx", "Screen X% Offset ", -25f, 25f, 0f);
			AimOffsetYOption = obj.AddSlider("moderncamera.aimoffsety", "Screen Y% Offset", -25f, 25f, 0f);
			obj.AddDivider("Third Person Zoom");
			MinZoomOption = obj.AddSlider("moderncamera.minzoom", "Min Zoom", 1f, 18f, 2f);
			MaxZoomOption = obj.AddSlider("moderncamera.maxzoom", "Max Zoom", 3f, 20f, 18f);
			LockCameraZoomOption = obj.AddToggle("moderncamera.lockzoom", "Lock Camera Zoom", false);
			LockCameraZoomDistanceOption = obj.AddSlider("moderncamera.lockzoomdistance", "Locked Camera Zoom Distance", 6f, 20f, 15f);
			obj.AddDivider("Third Person Pitch");
			MinPitchOption = obj.AddSlider("moderncamera.minpitch", "Min Pitch", 0f, 90f, 9f);
			MaxPitchOption = obj.AddSlider("moderncamera.maxpitch", "Max Pitch", 0f, 90f, 90f);
			LockCameraPitchOption = obj.AddToggle("moderncamera.lockpitch", "Lock Camera Pitch", false);
			LockCameraPitchAngleOption = obj.AddSlider("moderncamera.lockpitchangle", "Locked Camera Pitch Angle", 0f, 90f, 60f);
			obj.AddDivider("Over the Shoulder");
			OverTheShoulderOption = obj.AddToggle("moderncamera.overtheshoulder", "Use Over the Shoulder Offset", false);
			OverTheShoulderXOption = obj.AddSlider("moderncamera.overtheshoulderx", "X Offset", 0.5f, 4f, 1f);
			OverTheShoulderYOption = obj.AddSlider("moderncamera.overtheshouldery", "Y Offset", 1f, 8f, 1f);
			((Option<float>)(object)MinZoomOption).AddListener((Action<float>)delegate(float value)
			{
				if (value + ZoomOffset > MaxZoom && value + ZoomOffset < MaxZoomOption.MaxValue)
				{
					((Option<float>)(object)MaxZoomOption).SetValue(value + ZoomOffset);
				}
				else if (value + ZoomOffset > MaxZoomOption.MaxValue)
				{
					((Option<float>)(object)MinZoomOption).SetValue(MaxZoomOption.MaxValue - ZoomOffset);
				}
			});
			((Option<float>)(object)MaxZoomOption).AddListener((Action<float>)delegate(float value)
			{
				if (value - ZoomOffset < MinZoom && value - ZoomOffset > MinZoomOption.MinValue)
				{
					((Option<float>)(object)MinZoomOption).SetValue(value - ZoomOffset);
				}
				else if (value - ZoomOffset < MinZoomOption.MinValue)
				{
					((Option<float>)(object)MaxZoomOption).SetValue(MinZoomOption.MinValue + ZoomOffset);
				}
			});
			((Option<float>)(object)MinPitchOption).AddListener((Action<float>)delegate(float value)
			{
				if (value > ((Option<float>)(object)MaxPitchOption).Value && value < MaxPitchOption.MaxValue)
				{
					((Option<float>)(object)MaxPitchOption).SetValue(value);
				}
				else if (value > MaxPitchOption.MaxValue)
				{
					((Option<float>)(object)MinPitchOption).SetValue(MaxPitchOption.MaxValue);
				}
			});
			((Option<float>)(object)MaxPitchOption).AddListener((Action<float>)delegate(float value)
			{
				if (value < ((Option<float>)(object)MinPitchOption).Value && value > MinPitchOption.MinValue)
				{
					((Option<float>)(object)MinPitchOption).SetValue(value);
				}
				else if (value < MinPitchOption.MinValue)
				{
					((Option<float>)(object)MaxPitchOption).SetValue(MinPitchOption.MinValue);
				}
			});
		}

		private static void SetupKeybinds()
		{
			KeybindingCategory obj = KeybindingsManager.AddCategory("Modern Camera");
			EnabledKeybind = obj.AddKeyBinding("moderncamera.enabled", "Enabled");
			EnabledKeybind.AddKeyDownListener((Action)delegate
			{
				((Option<bool>)(object)EnabledOption).SetValue(!Enabled);
			});
			ActionModeKeybind = obj.AddKeyBinding("moderncamera.actionmode", "Action Mode");
			ActionModeKeybind.AddKeyDownListener((Action)delegate
			{
				if (Enabled && !ModernCameraState.IsFirstPerson)
				{
					ModernCameraState.IsMouseLocked = !ModernCameraState.IsMouseLocked;
					ModernCameraState.IsActionMode = !ModernCameraState.IsActionMode;
				}
			});
			HideUIKeybind = obj.AddKeyBinding("moderncamera.hideui", "Hide UI");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "VRising.ModernCamera";

		public const string PLUGIN_NAME = "ModernCamera";

		public const string PLUGIN_VERSION = "1.5.6";
	}
}
namespace ModernCamera.Utils
{
	internal static class Mouse
	{
		[DllImport("user32.dll")]
		private static extern bool SetCursorPos(int X, int Y);

		[DllImport("user32.dll")]
		private static extern bool GetCursorPos(out POINT point);

		[DllImport("user32.dll")]
		private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

		internal static bool SetCursorPosition(POINT point)
		{
			return SetCursorPos(point.X, point.Y);
		}

		internal static bool SetCursorPosition(int x, int y)
		{
			POINT pOINT = Window.ClientToScreen(x, y);
			return SetCursorPos(pOINT.X, pOINT.Y);
		}

		internal static void CenterCursorPosition()
		{
			RECT clientRect = Window.GetClientRect();
			SetCursorPosition((clientRect.Right - clientRect.Left) / 2, (clientRect.Bottom - clientRect.Top) / 2);
		}

		internal static POINT GetCursorPosition()
		{
			GetCursorPos(out var point);
			return point;
		}

		internal static void Click(MouseEvent mouseEvent)
		{
			Click(mouseEvent, GetCursorPosition());
		}

		internal static void Click(MouseEvent mouseEvent, POINT point)
		{
			mouse_event((int)mouseEvent, point.X, point.Y, 0, 0);
		}

		internal static void Click(MouseEvent mouseEvent, int x, int y)
		{
			mouse_event((int)mouseEvent, x, y, 0, 0);
		}
	}
	internal static class Window
	{
		internal static IntPtr Handle;

		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		private static extern IntPtr FindWindow(string strClassName, string strWindowName);

		[DllImport("user32.dll")]
		private static extern bool GetWindowRect(IntPtr hwnd, ref RECT rectangle);

		[DllImport("user32.dll")]
		private static extern bool GetClientRect(IntPtr hwnd, ref RECT rectangle);

		[DllImport("user32.dll")]
		private static extern bool ClientToScreen(IntPtr hwnd, ref POINT point);

		[DllImport("user32.dll")]
		private static extern bool ScreenToClient(IntPtr hwnd, ref POINT point);

		static Window()
		{
			Handle = GetWindow("VRising");
		}

		public static IntPtr GetWindow(string title)
		{
			return FindWindow(null, title);
		}

		public static RECT GetWindowRect()
		{
			RECT rectangle = default(RECT);
			GetWindowRect(Handle, ref rectangle);
			return rectangle;
		}

		public static RECT GetClientRect()
		{
			RECT rectangle = default(RECT);
			GetClientRect(Handle, ref rectangle);
			return rectangle;
		}

		public static POINT ClientToScreen(int x, int y)
		{
			POINT point = new POINT(x, y);
			ClientToScreen(Handle, ref point);
			return point;
		}

		public static POINT ClientToScreen(POINT point)
		{
			return ClientToScreen(point.X, point.Y);
		}

		public static POINT ScreenToClient(int x, int y)
		{
			POINT point = new POINT(x, y);
			ClientToScreen(Handle, ref point);
			return point;
		}

		public static POINT ScreenToClient(POINT point)
		{
			return ScreenToClient(point.X, point.Y);
		}
	}
}
namespace ModernCamera.Structs
{
	internal struct POINT
	{
		internal int X;

		internal int Y;

		internal POINT(int X, int Y)
		{
			this.X = X;
			this.Y = Y;
		}
	}
	internal struct RECT
	{
		internal int Left;

		internal int Top;

		internal int Right;

		internal int Bottom;

		internal RECT(int Left, int Top, int Right, int Bottom)
		{
			this.Left = Left;
			this.Top = Top;
			this.Right = Right;
			this.Bottom = Bottom;
		}
	}
}
namespace ModernCamera.Patches
{
	[HarmonyPatch]
	internal static class ActionWheelSystem_Patch
	{
		private static bool WheelVisible;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ActionWheelSystem), "OnUpdate")]
		private static void OnUpdate(ActionWheelSystem __instance)
		{
			if (!WheelVisible && (__instance._ActionWheel.IsVisible() || __instance._EmoteWheel.IsVisible()))
			{
				ModernCameraState.IsMenuOpen = true;
				WheelVisible = true;
			}
			else if (WheelVisible && !__instance._ActionWheel.IsVisible() && !__instance._EmoteWheel.IsVisible())
			{
				ModernCameraState.IsMenuOpen = false;
				WheelVisible = false;
			}
		}
	}
	[HarmonyPatch]
	internal class EscapeMenuView_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(EscapeMenuView), "OnEnable")]
		private static void OnEnable()
		{
			ModernCameraState.IsMenuOpen = true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EscapeMenuView), "OnDestroy")]
		private static void OnDestroy()
		{
			ModernCameraState.IsMenuOpen = false;
		}
	}
	[HarmonyPatch]
	internal static class GameplayInputSystem_Patch
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameplayInputSystem), "HandleInput")]
		private unsafe static void HandleInputPrefix(ref InputState inputState)
		{
			//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)
			ModernCameraState.ValidGameplayInputState = true;
			ModernCameraState.GameplayInputState = inputState;
			if (Settings.Enabled && ModernCameraState.IsMouseLocked && !ModernCameraState.IsMenuOpen && !((InputState)(ref inputState)).IsInputPressed((InputFlag)45))
			{
				((UnsafeList)inputState.InputsPressed.m_ListData).Add<InputFlag>((InputFlag)45);
			}
		}
	}
	[HarmonyPatch]
	internal static class HUDElementComponent_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDElementComponent), "UpdateVisibility")]
		private static void UpdateVisibility(HUDElementComponent __instance)
		{
			if (!((Object)((Component)__instance).gameObject).name.Equals("InteractorEntry(Clone)"))
			{
				return;
			}
			foreach (CanvasGroup componentsInChild in ((Component)__instance).GetComponentsInChildren<CanvasGroup>())
			{
				componentsInChild.alpha = 1f;
			}
		}
	}
	[HarmonyPatch]
	internal static class HUDMenu_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDMenu), "OnEnable")]
		private static void OnEnable()
		{
			ModernCameraState.IsMenuOpen = true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDMenu), "OnDisable")]
		private static void OnDisable()
		{
			ModernCameraState.IsMenuOpen = false;
		}
	}
	[HarmonyPatch]
	internal static class OptionsMenu_Base_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(OptionsMenu_Base), "Start")]
		private static void Start()
		{
			ModernCameraState.IsMenuOpen = true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(OptionsMenu_Base), "OnDestroy")]
		private static void OnDestroy()
		{
			ModernCameraState.IsMenuOpen = false;
		}
	}
	[HarmonyPatch]
	internal static class TopdownCameraSystem_Patch
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(TopdownCameraSystem), "OnUpdate")]
		private static void OnUpdatePrefix(TopdownCameraSystem __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (Settings.Enabled)
			{
				__instance._ZoomModifierSystem._ZoomModifiers.Clear();
			}
		}
	}
	[HarmonyPatch]
	internal class UIEntryPoint_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIEntryPoint), "Awake")]
		private static void AwakePostfix()
		{
			ModernCameraState.Reset();
		}
	}
}
namespace ModernCamera.Hooks
{
	internal static class TopdownCameraSystem_Hook
	{
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate void HandleInput(IntPtr _this, ref InputState inputState);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate void UpdateCameraInputs(IntPtr _this, ref TopdownCameraState cameraState, ref TopdownCamera cameraData);

		private static HandleInput? HandleInputOriginal;

		private static INativeDetour? HandleInputDetour;

		private static UpdateCameraInputs? UpdateCameraInputsOriginal;

		private static INativeDetour? UpdateCameraInputsDetour;

		private static bool DefaultZoomSettingsSaved;

		private static bool UsingDefaultZoomSettings;

		private static ZoomSettings DefaultZoomSettings;

		private static ZoomSettings DefaultStandardZoomSettings;

		private static ZoomSettings DefaultBuildModeZoomSettings;

		internal static void CreateAndApply()
		{
			if (HandleInputDetour == null)
			{
				HandleInputDetour = DetourUtils.Create<HandleInput>(typeof(TopdownCameraSystem), "HandleInput", (HandleInput)HandleInputHook, ref HandleInputOriginal);
			}
			if (UpdateCameraInputsDetour == null)
			{
				UpdateCameraInputsDetour = DetourUtils.Create<UpdateCameraInputs>(typeof(TopdownCameraSystem), "UpdateCameraInputs", "OriginalLambdaBody", (UpdateCameraInputs)UpdateCameraInputsHook, ref UpdateCameraInputsOriginal);
			}
		}

		internal static void Dispose()
		{
			((IDisposable)UpdateCameraInputsDetour)?.Dispose();
			((IDisposable)HandleInputDetour)?.Dispose();
		}

		private static void HandleInputHook(IntPtr _this, ref InputState inputState)
		{
			if (Settings.Enabled)
			{
				ModernCameraState.CurrentCameraBehaviour?.HandleInput(ref inputState);
			}
			HandleInputOriginal(_this, ref inputState);
		}

		private static void UpdateCameraInputsHook(IntPtr _this, ref TopdownCameraState cameraState, ref TopdownCamera cameraData)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: 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)
			if (Settings.Enabled)
			{
				if (!DefaultZoomSettingsSaved)
				{
					DefaultZoomSettings = cameraState.ZoomSettings;
					DefaultStandardZoomSettings = cameraData.StandardZoomSettings;
					DefaultBuildModeZoomSettings = cameraData.BuildModeZoomSettings;
					DefaultZoomSettingsSaved = true;
				}
				UsingDefaultZoomSettings = false;
				cameraState.ZoomSettings.MaxZoom = Settings.MaxZoom;
				cameraState.ZoomSettings.MinZoom = 0f;
				foreach (CameraBehaviour value in ModernCameraState.CameraBehaviours.Values)
				{
					if (value.ShouldActivate(ref cameraState))
					{
						ModernCameraState.CurrentCameraBehaviour?.Deactivate();
						value.Activate(ref cameraState);
						break;
					}
				}
				if (!ModernCameraState.CurrentCameraBehaviour.Active)
				{
					ModernCameraState.CurrentCameraBehaviour.Activate(ref cameraState);
				}
				ModernCameraState.CurrentCameraBehaviour.UpdateCameraInputs(ref cameraState, ref cameraData);
				cameraData.StandardZoomSettings = cameraState.ZoomSettings;
			}
			else if (DefaultZoomSettingsSaved && !UsingDefaultZoomSettings)
			{
				cameraState.ZoomSettings = DefaultZoomSettings;
				cameraData.StandardZoomSettings = DefaultStandardZoomSettings;
				cameraData.BuildModeZoomSettings = DefaultBuildModeZoomSettings;
				UsingDefaultZoomSettings = true;
			}
			UpdateCameraInputsOriginal(_this, ref cameraState, ref cameraData);
		}
	}
}
namespace ModernCamera.Enums
{
	internal enum BehaviourType
	{
		Default,
		FirstPerson,
		ThirdPerson
	}
	internal enum CameraAimMode
	{
		Default,
		Forward
	}
	[Flags]
	internal enum MouseEvent
	{
		Absolute = 0x8000,
		LeftDown = 2,
		LeftUp = 4,
		MiddleDown = 0x20,
		MiddleUp = 0x40,
		Move = 1,
		RightDown = 8,
		RightUp = 0x10
	}
}
namespace ModernCamera.Behaviours
{
	internal abstract class CameraBehaviour
	{
		internal BehaviourType BehaviourType;

		internal float DefaultMaxPitch;

		internal float DefaultMinPitch;

		internal bool Active;

		protected static float TargetZoom = Settings.MaxZoom / 2f;

		protected static ZoomSettings BuildModeZoomSettings;

		protected static bool IsBuildSettingsSet;

		internal virtual void Activate(ref TopdownCameraState state)
		{
			Active = true;
		}

		internal virtual void Deactivate()
		{
			TargetZoom = Settings.MaxZoom / 2f;
			Active = false;
		}

		internal virtual bool ShouldActivate(ref TopdownCameraState state)
		{
			return false;
		}

		internal unsafe virtual void HandleInput(ref InputState inputState)
		{
			if (inputState.InputsPressed.IsCreated && ModernCameraState.IsMouseLocked && !ModernCameraState.IsMenuOpen && !((InputState)(ref inputState)).IsInputPressed((InputFlag)45))
			{
				((UnsafeList)inputState.InputsPressed.m_ListData).Add<InputFlag>((InputFlag)45);
			}
			if (((InputState)(ref inputState)).GetAnalogValue((AnalogInput)16) != 0f && (!ModernCameraState.InBuildMode || !Settings.DefaultBuildMode))
			{
				float num = Mathf.Lerp(0.25f, 1.5f, Mathf.Max(0f, TargetZoom - Settings.MinZoom) / Settings.MaxZoom);
				float num2 = ((((InputState)(ref inputState)).GetAnalogValue((AnalogInput)16) > 0f) ? num : (0f - num));
				if ((TargetZoom > Settings.MinZoom && TargetZoom + num2 < Settings.MinZoom) || (ModernCameraState.IsFirstPerson && num2 > 0f))
				{
					TargetZoom = Settings.MinZoom;
				}
				else
				{
					TargetZoom = Mathf.Clamp(TargetZoom + num2, Settings.FirstPersonEnabled ? 0f : Settings.MinZoom, Settings.MaxZoom);
				}
				((InputState)(ref inputState)).SetAnalogValue((AnalogInput)16, 0f);
			}
			if (TargetZoom > Settings.MaxZoom)
			{
				TargetZoom = Settings.MaxZoom;
			}
		}

		internal virtual void UpdateCameraInputs(ref TopdownCameraState state, ref TopdownCamera data)
		{
			//IL_0013: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			ModernCameraState.InBuildMode = state.InBuildMode;
			if (!IsBuildSettingsSet)
			{
				BuildModeZoomSettings = data.BuildModeZoomSettings;
				IsBuildSettingsSet = true;
			}
			state.ZoomSettings.MaxPitch = DefaultMaxPitch;
			state.ZoomSettings.MinPitch = DefaultMinPitch;
			if (!state.InBuildMode || !Settings.DefaultBuildMode)
			{
				data.BuildModeZoomSettings.MaxPitch = DefaultMaxPitch;
				data.BuildModeZoomSettings.MinPitch = DefaultMinPitch;
				state.LastTarget.Zoom = TargetZoom;
				state.Target.Zoom = TargetZoom;
			}
			if (state.InBuildMode && Settings.DefaultBuildMode)
			{
				data.BuildModeZoomSettings = BuildModeZoomSettings;
				state.LastTarget.Zoom = data.BuildModeZoomDistance;
				state.Target.Zoom = data.BuildModeZoomDistance;
			}
		}
	}
	internal class FirstPersonCameraBehaviour : CameraBehaviour
	{
		internal FirstPersonCameraBehaviour()
		{
			BehaviourType = BehaviourType.FirstPerson;
			DefaultMaxPitch = 1.57f;
			DefaultMinPitch = -1.57f;
		}

		internal override void Activate(ref TopdownCameraState state)
		{
			base.Activate(ref state);
			ModernCameraState.IsMouseLocked = true;
			ModernCameraState.IsFirstPerson = true;
			ModernCameraState.CurrentBehaviourType = BehaviourType;
			state.PitchPercent = 0.51f;
			CameraBehaviour.TargetZoom = 0f;
		}

		internal override void Deactivate()
		{
			base.Deactivate();
			if (!ModernCameraState.IsActionMode)
			{
				ModernCameraState.IsMouseLocked = false;
			}
			ModernCameraState.IsFirstPerson = false;
		}

		internal override bool ShouldActivate(ref TopdownCameraState state)
		{
			if (Settings.FirstPersonEnabled && ModernCameraState.CurrentBehaviourType != BehaviourType)
			{
				return CameraBehaviour.TargetZoom < Settings.MinZoom;
			}
			return false;
		}

		internal override void UpdateCameraInputs(ref TopdownCameraState state, ref TopdownCamera data)
		{
			//IL_002f: 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)
			base.UpdateCameraInputs(ref state, ref data);
			float z = Settings.FirstPersonForwardOffset;
			float num = Settings.HeadHeightOffset;
			if (Settings.FirstPersonShapeshiftOffsets.ContainsKey(ModernCameraState.ShapeshiftName))
			{
				z = Settings.FirstPersonShapeshiftOffsets[ModernCameraState.ShapeshiftName].y;
				num = Settings.FirstPersonShapeshiftOffsets[ModernCameraState.ShapeshiftName].x;
			}
			state.LastTarget.NormalizedLookAtOffset.z = z;
			state.LastTarget.NormalizedLookAtOffset.y = (ModernCameraState.IsMounted ? (num + Settings.MountedOffset) : num);
		}
	}
	internal class ThirdPersonCameraBehaviour : CameraBehaviour
	{
		private float LastPitchPercent = float.PositiveInfinity;

		internal ThirdPersonCameraBehaviour()
		{
			BehaviourType = BehaviourType.ThirdPerson;
		}

		internal override void Activate(ref TopdownCameraState state)
		{
			base.Activate(ref state);
			if (ModernCameraState.CurrentBehaviourType == BehaviourType)
			{
				CameraBehaviour.TargetZoom = Settings.MaxZoom / 2f;
			}
			else
			{
				CameraBehaviour.TargetZoom = Settings.MinZoom;
			}
			ModernCameraState.CurrentBehaviourType = BehaviourType;
			state.PitchPercent = ((LastPitchPercent == float.PositiveInfinity) ? 0.5f : LastPitchPercent);
		}

		internal override bool ShouldActivate(ref TopdownCameraState state)
		{
			if (ModernCameraState.CurrentBehaviourType != BehaviourType)
			{
				return CameraBehaviour.TargetZoom > 0f;
			}
			return false;
		}

		internal override void HandleInput(ref InputState inputState)
		{
			base.HandleInput(ref inputState);
			if (Settings.LockZoom)
			{
				CameraBehaviour.TargetZoom = Settings.LockZoomDistance;
			}
		}

		internal override void UpdateCameraInputs(ref TopdownCameraState state, ref TopdownCamera data)
		{
			DefaultMaxPitch = Settings.MaxPitch;
			DefaultMinPitch = Settings.MinPitch;
			base.UpdateCameraInputs(ref state, ref data);
			state.LastTarget.NormalizedLookAtOffset.y = (ModernCameraState.IsMounted ? (Settings.HeadHeightOffset + Settings.MountedOffset) : Settings.HeadHeightOffset);
			if (Settings.OverTheShoulder && !ModernCameraState.IsShapeshifted && !ModernCameraState.IsMounted)
			{
				float num = Mathf.Max(0f, state.Current.Zoom - state.ZoomSettings.MinZoom) / state.ZoomSettings.MaxZoom;
				state.LastTarget.NormalizedLookAtOffset.x = Mathf.Lerp(Settings.OverTheShoulderX, 0f, num);
				state.LastTarget.NormalizedLookAtOffset.y = Mathf.Lerp(Settings.OverTheShoulderY, 0f, num);
			}
			if (Settings.LockPitch && (!state.InBuildMode || !Settings.DefaultBuildMode))
			{
				state.ZoomSettings.MaxPitch = Settings.LockPitchAngle;
				state.ZoomSettings.MinPitch = Settings.LockPitchAngle;
				data.BuildModeZoomSettings.MaxPitch = Settings.LockPitchAngle;
				data.BuildModeZoomSettings.MinPitch = Settings.LockPitchAngle;
			}
			LastPitchPercent = state.PitchPercent;
		}
	}
}

PopupTotals.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.UI;
using StunShared.UI;
using Stunlock.Core;
using Stunlock.Localization;
using TMPro;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Entities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("PopupTotals")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod to show the total amount of an item in your inventory while collecting resources")]
[assembly: AssemblyFileVersion("1.0.7")]
[assembly: AssemblyInformationalVersion("1.0.7+ca15a8ebb31171caf57f1493d056f4d805af7168")]
[assembly: AssemblyProduct("PopupTotals")]
[assembly: AssemblyTitle("PopupTotals")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.7.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class PluginInfo
{
	public const string PLUGIN_GUID = "PopupTotals";

	public const string PLUGIN_NAME = "PopupTotals";

	public const string PLUGIN_VERSION = "1.0.7";
}
namespace PopupTotals
{
	[HarmonyPatch]
	public class ItemUtils
	{
		private static readonly Dictionary<string, PrefabGUID> ItemNameToPrefabLookup = new Dictionary<string, PrefabGUID>();

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

		private static readonly List<string> SubStringsToMatch = new List<string> { "_Ingredient_", "Item_Consumable", "Item_Building_Plants" };

		private static GameDataSystem System { get; set; }

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameDataSystem), "RegisterItems")]
		private static void GameDataSystem_RegisterItems_Postfix(ref GameDataSystem __instance)
		{
			//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)
			System = __instance;
			if (__instance.ItemHashLookupMap.Count() != 0)
			{
				Plugin.Logger.LogInfo((object)"Creating lookup tables...");
				RebuildLut();
			}
		}

		private static void RebuildLut()
		{
			//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_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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: 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_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			ItemNameToPrefabLookup.Clear();
			Errored.Clear();
			ManagedDataRegistry managedDataRegistry = System.ManagedDataRegistry;
			Enumerator<PrefabGUID, ItemData> enumerator = System.ItemHashLookupMap.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValue<PrefabGUID, ItemData> current = enumerator.Current;
				try
				{
					PrefabGUID key = current.Key;
					ManagedItemData orDefault = managedDataRegistry.GetOrDefault<ManagedItemData>(key, (ManagedItemData)null);
					if (orDefault == null || !SubStringsToMatch.Any(orDefault.PrefabName.Contains))
					{
						continue;
					}
					string prefabName = orDefault.PrefabName;
					bool flag = ((prefabName == "Item_Ingredient_Kit_Base" || prefabName == "Item_Ingredient_Gem_Base") ? true : false);
					if (!flag)
					{
						string text = Localization.Get(orDefault.Name, false);
						ManualLogSource logger = Plugin.Logger;
						BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(34, 3, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Item: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", PrefabName: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(orDefault.PrefabName);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", PrefabGUID: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((object)(PrefabGUID)(ref key)).ToString());
						}
						logger.LogDebug(val);
						ItemNameToPrefabLookup.TryAdd(text, key);
					}
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogError((object)ex);
				}
			}
		}

		public static PrefabGUID GetOrRebuild(string itemName)
		{
			//IL_000f: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0034: 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)
			if (ItemNameToPrefabLookup.TryGetValue(itemName, out var value))
			{
				return value;
			}
			RebuildLut();
			if (ItemNameToPrefabLookup.TryGetValue(itemName, out var value2))
			{
				return value2;
			}
			if (Errored.Contains(itemName))
			{
				return PrefabGUID.Empty;
			}
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error rebuilding LUT no item name found: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(itemName);
			}
			logger.LogError(val);
			Errored.Add(itemName);
			return PrefabGUID.Empty;
		}
	}
	[BepInPlugin("PopupTotals", "PopupTotals", "1.0.7")]
	public class Plugin : BasePlugin
	{
		private Harmony _harmony;

		internal static ManualLogSource Logger { get; private set; }

		public override void Load()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			_harmony = new Harmony("PopupTotals");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(18, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("PopupTotals");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
			}
			log.LogInfo(val);
		}
	}
	[HarmonyPatch]
	public class ScrollingCombatTextParentMapperPatch
	{
		private static Action<SCTText, EntryData> _handler;

		private static bool _hooked;

		private static PrefabGUID? _sctTypeResourceGain;

		private static World _world;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ScrollingCombatTextParentMapper), "OnUpdate")]
		private static void OnUpdate_Prefix(ref ScrollingCombatTextParentMapper __instance)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (_hooked)
			{
				return;
			}
			PrefabCollectionSystem existingSystem = ((ComponentSystemBase)__instance).World.GetExistingSystem<PrefabCollectionSystem>();
			if (existingSystem == null || __instance._Elements == null)
			{
				_hooked = false;
				return;
			}
			PrefabGUID value = default(PrefabGUID);
			if (((PrefabCollectionSystem_Base)existingSystem).NameToPrefabGuidDictionary.TryGetValue("(SCTType) SCT_Type_ResouceGain", ref value))
			{
				_sctTypeResourceGain = value;
			}
			if (!_sctTypeResourceGain.HasValue)
			{
				_hooked = false;
				return;
			}
			_world = ((ComponentSystemBase)__instance).World;
			_handler = OnEntryUpdate;
			EntryGroup<SCTText, EntryData> elements = __instance._Elements;
			((EntryGroupBase<SCTText, EntryData>)(object)elements).OnEntryUpdate = ((EntryGroupBase<SCTText, EntryData>)(object)elements).OnEntryUpdate + Action<SCTText, EntryData>.op_Implicit(_handler);
			_hooked = true;
		}

		private static void OnEntryUpdate(SCTText text, EntryData entry)
		{
			//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_001c: 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_0057: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			if (!_sctTypeResourceGain.HasValue || entry.Type.GuidHash == _sctTypeResourceGain.Value.GuidHash)
			{
				string text2 = ((object)(FixedString128)(ref entry.SourceTypeText)).ToString();
				if (!text2.Contains('(') || !text2.Contains(')'))
				{
					PrefabGUID orRebuild = ItemUtils.GetOrRebuild(text2);
					Entity val = default(Entity);
					ConsoleShared.TryGetLocalCharacter(ref val, _world);
					int itemAmount = InventoryUtilities.GetItemAmount(_world.EntityManager, val, orRebuild, default(Nullable_Unboxed<int>));
					string text3 = $"{text2} ({itemAmount})";
					entry.SourceTypeText = new FixedString128(text3);
					((TMP_Text)text.Text).m_text = ((TMP_Text)text.Text).m_text.Replace(text2, text3);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ScrollingCombatTextParentMapper), "OnDestroy")]
		private static void OnDestroy_Postfix(ref ScrollingCombatTextParentMapper __instance)
		{
			if (_handler != null)
			{
				EntryGroup<SCTText, EntryData> elements = __instance._Elements;
				((EntryGroupBase<SCTText, EntryData>)(object)elements).OnEntryUpdate = ((EntryGroupBase<SCTText, EntryData>)(object)elements).OnEntryUpdate - Action<SCTText, EntryData>.op_Implicit(_handler);
				_hooked = false;
			}
		}
	}
}

QuickStash.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Bloodstone.API;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.CastleBuilding;
using ProjectM.Network;
using ProjectM.Scripting;
using Unity.Collections;
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
using VampireCommandFramework;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("QuickStash")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Allows you to use Compulsively Count on all nearby stashes with 1 click")]
[assembly: AssemblyFileVersion("1.3.3.0")]
[assembly: AssemblyInformationalVersion("1.3.3")]
[assembly: AssemblyProduct("QuickStash")]
[assembly: AssemblyTitle("QuickStash")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace QuickStash
{
	[HarmonyPatch]
	public class GameplayInputSystem_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameplayInputSystem), "HandleInput")]
		private static void HandleInput(GameplayInputSystem __instance)
		{
			QuickStashClient.HandleInput(__instance);
		}
	}
	[BepInPlugin("QuickStash", "QuickStash", "1.3.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[Reloadable]
	public class Plugin : BasePlugin
	{
		public static ManualLogSource Logger;

		public static bool VCF;

		public static Keybinding configKeybinding;

		public static ConfigEntry<float> configMaxDistance;

		private Harmony _hooks;

		private void InitConfig()
		{
			//IL_0026: 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)
			configMaxDistance = ((BasePlugin)this).Config.Bind<float>("Server", "MaxDistance", 50f, "The max distance for transfering items. 5 'distance' is about 1 tile.");
			KeybindingDescription val = default(KeybindingDescription);
			val.Id = "elmegaard.quickstash.deposit";
			val.Category = "QuickStash";
			val.Name = "Deposit";
			val.DefaultKeybinding = (KeyCode)103;
			configKeybinding = KeybindManager.Register(val);
		}

		private void RegisterMessages()
		{
			VNetworkRegistry.RegisterServerboundStruct<MergeInventoriesMessage>((Action<FromCharacter, MergeInventoriesMessage>)delegate(FromCharacter fromCharacter, MergeInventoriesMessage msg)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				QuickStashServer.OnMergeInventoriesMessage(fromCharacter, msg);
			});
		}

		private void ClearMessages()
		{
			VNetworkRegistry.UnregisterStruct<MergeInventoriesMessage>();
		}

		public override void Load()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			VCF = ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("gg.deca.VampireCommandFramework");
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(12, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("***** VCF : ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(VCF);
			}
			logger.LogInfo(val);
			InitConfig();
			if (VCFWrapper.Enabled)
			{
				VCFWrapper.RegisterAll();
			}
			QuickStashClient.Reset();
			_hooks = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			RegisterMessages();
			ManualLogSource log = ((BasePlugin)this).Log;
			val = new BepInExInfoLogInterpolatedStringHandler(18, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("QuickStash");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
			}
			log.LogInfo(val);
		}

		public override bool Unload()
		{
			((BasePlugin)this).Config.Clear();
			KeybindManager.Unregister(configKeybinding);
			_hooks.UnpatchSelf();
			ClearMessages();
			return true;
		}
	}
	public class QuickStashClient
	{
		private static DateTime _lastInventoryTransfer = DateTime.Now;

		public static void Reset()
		{
			_lastInventoryTransfer = DateTime.Now;
		}

		public static void HandleInput(GameplayInputSystem __instance)
		{
			//IL_000d: 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)
			if (VWorld.IsClient && (Input.GetKeyInt(Plugin.configKeybinding.Primary) || Input.GetKeyInt(Plugin.configKeybinding.Secondary)) && DateTime.Now - _lastInventoryTransfer > TimeSpan.FromSeconds(0.5))
			{
				_lastInventoryTransfer = DateTime.Now;
				TransferItems();
			}
		}

		private static void TransferItems()
		{
			VNetwork.SendToServerStruct<MergeInventoriesMessage>(default(MergeInventoriesMessage));
		}
	}
	public class QuickStashServer
	{
		private static readonly List<PrefabGUID> _itemRefreshGuids = new List<PrefabGUID>
		{
			new PrefabGUID(1686577386),
			new PrefabGUID(-949672483)
		};

		private static readonly Dictionary<Entity, DateTime> _lastMerge = new Dictionary<Entity, DateTime>();

		public static void OnMergeInventoriesMessage(FromCharacter fromCharacter, MergeInventoriesMessage msg)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			MergeInventories(fromCharacter);
		}

		internal static bool MergeInventories(FromCharacter fromCharacter)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: 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_00c5: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: 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_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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_00fb: 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_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: 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_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			if (!VWorld.IsServer || fromCharacter.Character == Entity.Null)
			{
				return false;
			}
			if (_lastMerge.ContainsKey(fromCharacter.Character) && DateTime.Now - _lastMerge[fromCharacter.Character] < TimeSpan.FromSeconds(0.5))
			{
				return false;
			}
			_lastMerge[fromCharacter.Character] = DateTime.Now;
			NativeList<Entity> val = default(NativeList<Entity>);
			val..ctor((Allocator)2);
			InventoryUtilities.TryGetInventoryEntities(VWorld.Server.EntityManager, fromCharacter.Character, ref val);
			if (val.Length == 0)
			{
				val.Dispose();
				return false;
			}
			ServerGameManager serverGameManager = VWorld.Server.GetExistingSystem<ServerScriptMapper>()._ServerGameManager;
			GameDataSystem existingSystem = VWorld.Server.GetExistingSystem<GameDataSystem>();
			Enumerator<Entity> enumerator = QuickStashShared.GetStashEntities(VWorld.Server.EntityManager).GetEnumerator();
			bool flag = default(bool);
			while (enumerator.MoveNext())
			{
				Entity current = enumerator.Current;
				if (((ServerGameManager)(ref serverGameManager)).IsAllies(fromCharacter.Character, current) && IsWithinDistance(fromCharacter.Character, current, VWorld.Server.EntityManager))
				{
					Enumerator<Entity> enumerator2 = val.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						Entity current2 = enumerator2.Current;
						InventoryUtilitiesServer.TrySmartMergeInventories(VWorld.Server.EntityManager, existingSystem.ItemHashLookupMap, current2, current, ref flag, default(Nullable_Unboxed<int>));
					}
				}
			}
			val.Dispose();
			foreach (PrefabGUID itemRefreshGuid in _itemRefreshGuids)
			{
				InventoryUtilitiesServer.CreateInventoryChangedEvent(VWorld.Server.EntityManager, fromCharacter.Character, itemRefreshGuid, 0, (InventoryChangedEventType)2);
			}
			return true;
		}

		private static bool IsWithinDistance(Entity interactor, Entity inventory, EntityManager entityManager)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: 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_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_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_0022: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			LocalToWorld componentData = ((EntityManager)(ref entityManager)).GetComponentData<LocalToWorld>(interactor);
			LocalToWorld componentData2 = ((EntityManager)(ref entityManager)).GetComponentData<LocalToWorld>(inventory);
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(((LocalToWorld)(ref componentData)).Position.x - ((LocalToWorld)(ref componentData2)).Position.x, ((LocalToWorld)(ref componentData)).Position.y - ((LocalToWorld)(ref componentData2)).Position.y, ((LocalToWorld)(ref componentData)).Position.z - ((LocalToWorld)(ref componentData2)).Position.z);
			if (Math.Sqrt(Math.Pow(val.x, 2.0) + Math.Pow(val.y, 2.0) + Math.Pow(val.z, 2.0)) > (double)Plugin.configMaxDistance.Value)
			{
				return false;
			}
			return true;
		}
	}
	public class QuickStashShared
	{
		private static ComponentType[] _containerComponents;

		private static ComponentType[] ContainerComponents
		{
			get
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_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_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				if (_containerComponents == null)
				{
					_containerComponents = (ComponentType[])(object)new ComponentType[4]
					{
						ComponentType.ReadOnly(Il2CppType.Of<Team>()),
						ComponentType.ReadOnly(Il2CppType.Of<CastleHeartConnection>()),
						ComponentType.ReadOnly(Il2CppType.Of<InventoryBuffer>()),
						ComponentType.ReadOnly(Il2CppType.Of<NameableInteractable>())
					};
				}
				return _containerComponents;
			}
		}

		public static NativeArray<Entity> GetStashEntities(EntityManager entityManager)
		{
			//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_0010: Unknown result type (might be due to invalid IL or missing references)
			EntityQuery val = ((EntityManager)(ref entityManager)).CreateEntityQuery(ContainerComponents);
			return ((EntityQuery)(ref val)).ToEntityArray((Allocator)2);
		}

		public static bool IsEntityStash(EntityManager entityManager, Entity entity)
		{
			//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)
			return !ContainerComponents.Any((ComponentType x) => !((EntityManager)(ref entityManager)).HasComponent(entity, x));
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct MergeInventoriesMessage
	{
	}
	public static class VCFWrapper
	{
		public static bool Enabled => ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("gg.deca.VampireCommandFramework");

		public static void RegisterAll()
		{
			CommandRegistry.RegisterAll();
		}

		[Command("stash", "cc", null, "Compulsively Count on all nearby allied chests.", null, false)]
		public static void VCFCompulsivelyCount(ChatCommandContext ctx)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			FromCharacter fromCharacter = default(FromCharacter);
			fromCharacter.User = ctx.Event.SenderUserEntity;
			fromCharacter.Character = ctx.Event.SenderCharacterEntity;
			if (QuickStashServer.MergeInventories(fromCharacter))
			{
				ctx.Reply("Stashed all items");
			}
			else
			{
				ctx.Reply("Failed to stash items. Contact admin or moderator for support.");
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "QuickStash";

		public const string PLUGIN_NAME = "QuickStash";

		public const string PLUGIN_VERSION = "1.3.3";
	}
}

ShutTheFortUp.dll

Decompiled 5 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.IL2CPP;
using BepInEx.Logging;
using ProjectM;
using ProjectM.CastleBuilding;
using ProjectM.Scripting;
using UnhollowerBaseLib;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using VampireCommandFramework;
using Wetstone.API;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("ShutTheFortUp")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Opens or closes all your doors and/or windows with a single command")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1+1.Branch.main.Sha.ab46d441e6dac63b6f5e101ceb35bf4bc2b581b4")]
[assembly: AssemblyProduct("ShutTheFortUp")]
[assembly: AssemblyTitle("ShutTheFortUp")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.1.0")]
[module: UnverifiableCode]
namespace ShutTheFortUp;

[BepInPlugin("ShutTheFortUp", "ShutTheFortUp", "0.1.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BasePlugin
{
	public enum DoorWindow
	{
		Doors,
		Windows
	}

	private const float MAX_CASTLE_DISTANCE = 60f;

	private static readonly HashSet<int> WINDOW_PREFABS = new HashSet<int> { -1771014048 };

	private static EntityManager _em => VWorld.Server.EntityManager;

	public override void Load()
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		ManualLogSource log = ((BasePlugin)this).Log;
		bool flag = default(bool);
		BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(27, 2, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("ShutTheFortUp");
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" version ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("0.1.1");
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
		}
		log.LogInfo(val);
		CommandRegistry.RegisterAll();
	}

	[Command("close-all", null, null, null, null, false)]
	public static void CloseAll(ChatCommandContext ctx, DoorWindow? target = null)
	{
		ChangeDoorWindows(ctx, open: false, target);
	}

	[Command("open-all", null, null, null, null, false)]
	public static void OpenAll(ChatCommandContext ctx, DoorWindow? target = null)
	{
		ChangeDoorWindows(ctx, open: true, target);
	}

	private static void ChangeDoorWindows(ChatCommandContext ctx, bool open, DoorWindow? target)
	{
		//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_0011: 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_0029: 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_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: 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_0062: 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_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: 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_0077: 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_0097: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: 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_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_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: 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_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Expected O, but got Unknown
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: 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_0169: 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_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: 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_0199: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: 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_01a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0235: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		Entity senderCharacterEntity = ctx.Event.SenderCharacterEntity;
		EntityManager em = _em;
		EntityQuery val = ((EntityManager)(ref em)).CreateEntityQuery((ComponentType[])(object)new ComponentType[2]
		{
			ComponentType.ReadOnly<CastleHeart>(),
			ComponentType.ReadOnly<LocalToWorld>()
		});
		NativeArray<Entity> obj = ((EntityQuery)(ref val)).ToEntityArray((Allocator)2);
		ServerScriptMapper existingSystem = VWorld.Server.GetExistingSystem<ServerScriptMapper>();
		ServerGameManager val2 = ((existingSystem != null) ? existingSystem._ServerGameManager : null);
		em = _em;
		LocalToWorld componentData = ((EntityManager)(ref em)).GetComponentData<LocalToWorld>(senderCharacterEntity);
		float3 position = ((LocalToWorld)(ref componentData)).Position;
		Entity val3 = Entity.Null;
		float num = float.MaxValue;
		Enumerator<Entity> enumerator = obj.GetEnumerator();
		while (enumerator.MoveNext())
		{
			Entity current = enumerator.Current;
			if (val2._TeamChecker.IsAllies(senderCharacterEntity, current))
			{
				em = _em;
				componentData = ((EntityManager)(ref em)).GetComponentData<LocalToWorld>(current);
				float num2 = Vector3.Distance(float3.op_Implicit(((LocalToWorld)(ref componentData)).Position), float3.op_Implicit(position));
				if (num2 < num && num2 < 60f)
				{
					num = num2;
					val3 = current;
				}
			}
		}
		if (val3 == Entity.Null)
		{
			throw ctx.Error("Could not find nearby castle you own");
		}
		em = _em;
		EntityQueryDesc[] array = new EntityQueryDesc[1];
		EntityQueryDesc val4 = new EntityQueryDesc();
		val4.All = Il2CppStructArray<ComponentType>.op_Implicit((ComponentType[])(object)new ComponentType[4]
		{
			ComponentType.ReadWrite<Door>(),
			ComponentType.ReadOnly<CastleHeartConnection>(),
			ComponentType.ReadOnly<PrefabGUID>(),
			ComponentType.ReadOnly<Team>()
		});
		val4.Options = (EntityQueryOptions)2;
		array[0] = val4;
		val = ((EntityManager)(ref em)).CreateEntityQuery((EntityQueryDesc[])(object)array);
		NativeArray<Entity> obj2 = ((EntityQuery)(ref val)).ToEntityArray((Allocator)2);
		int num3 = 0;
		enumerator = obj2.GetEnumerator();
		while (enumerator.MoveNext())
		{
			Entity current2 = enumerator.Current;
			em = _em;
			if (((EntityManager)(ref em)).GetComponentData<CastleHeartConnection>(current2).CastleHeartEntity._Entity != val3)
			{
				continue;
			}
			if (target.HasValue)
			{
				em = _em;
				PrefabGUID componentData2 = ((EntityManager)(ref em)).GetComponentData<PrefabGUID>(current2);
				if ((target == DoorWindow.Doors && WINDOW_PREFABS.Contains(componentData2.GuidHash)) || (target == DoorWindow.Windows && !WINDOW_PREFABS.Contains(componentData2.GuidHash)))
				{
					continue;
				}
			}
			em = _em;
			Door componentData3 = ((EntityManager)(ref em)).GetComponentData<Door>(current2);
			componentData3.OpenState = open;
			em = _em;
			((EntityManager)(ref em)).SetComponentData<Door>(current2, componentData3);
			num3++;
		}
		ctx.Reply(string.Format("Changed {0} {1}", num3, target?.ToString() ?? "Windows and Doors"));
	}
}
public static class MyPluginInfo
{
	public const string PLUGIN_GUID = "ShutTheFortUp";

	public const string PLUGIN_NAME = "ShutTheFortUp";

	public const string PLUGIN_VERSION = "0.1.1";
}

Silkworm.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using HarmonyLib;
using Iced.Intel;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using ProjectM;
using ProjectM.UI;
using Silkworm.API;
using Silkworm.Core.KeyBinding;
using Silkworm.Core.Options;
using Silkworm.Utils;
using StunShared.UI;
using Stunlock.Localization;
using TMPro;
using Unity.Entities;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("iZastic")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Custom VRising library inspired by Wetstone")]
[assembly: AssemblyFileVersion("1.2.2.0")]
[assembly: AssemblyInformationalVersion("1.2.2")]
[assembly: AssemblyProduct("Silkworm")]
[assembly: AssemblyTitle("Silkworm")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Silkworm
{
	[BepInPlugin("iZastic.Silkworm", "Silkworm", "1.2.2")]
	public class Plugin : BasePlugin
	{
		internal static ManualLogSource Logger;

		private static Harmony harmony;

		public override void Load()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			harmony = new Harmony("iZastic.Silkworm");
			harmony.PatchAll();
			OptionsManager.Load();
			KeybindingsManager.Load();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(20, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("iZastic.Silkworm");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" v");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.2.2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
			}
			logger.LogInfo(val);
		}

		public override bool Unload()
		{
			OptionsManager.FullSave();
			KeybindingsManager.FullSave();
			return true;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "iZastic.Silkworm";

		public const string PLUGIN_NAME = "Silkworm";

		public const string PLUGIN_VERSION = "1.2.2";
	}
}
namespace Silkworm.Utils
{
	public static class DetourUtils
	{
		public static INativeDetour Create<T>(Type type, string innerTypeName, string methodName, T to, out T original) where T : Delegate
		{
			return Create(GetInnerType(type, innerTypeName), methodName, to, out original);
		}

		public static INativeDetour Create<T>(Type type, string methodName, T to, out T original) where T : Delegate
		{
			return Create(type.GetMethod(methodName, AccessTools.all), to, out original);
		}

		private static INativeDetour Create<T>(MethodInfo method, T to, out T original) where T : Delegate
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			IntPtr intPtr = Il2CppMethodResolver.ResolveFromMethodInfo(method);
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(15, 3, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Detouring ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method.DeclaringType.FullName);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method.Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" at ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(intPtr.ToString("X"));
			}
			logger.LogDebug(val);
			return INativeDetour.CreateAndApply<T>(intPtr, to, ref original);
		}

		private static Type GetInnerType(Type type, string innerTypeName)
		{
			return type.GetNestedTypes().First((Type x) => x.Name.Contains(innerTypeName));
		}
	}
	public static class FileUtils
	{
		private static readonly JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
		{
			WriteIndented = true,
			IncludeFields = true
		};

		public static bool Exists(string filename)
		{
			return File.Exists(Path.Join(Paths.ConfigPath, "Silkworm", filename));
		}

		public static void WriteJson(string filename, object? data)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			try
			{
				string contents = JsonSerializer.Serialize(data, jsonSerializerOptions);
				Directory.CreateDirectory(Path.Join(Paths.ConfigPath, "Silkworm"));
				File.WriteAllText(Path.Join(Paths.ConfigPath, "Silkworm", filename), contents);
			}
			catch
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(13, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error saving ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(filename);
				}
				logger.LogWarning(val);
			}
		}

		public static T? ReadJson<T>(string filename)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			try
			{
				return JsonSerializer.Deserialize<T>(File.ReadAllText(Path.Join(Paths.ConfigPath, "Silkworm", filename)), jsonSerializerOptions);
			}
			catch
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(14, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error reading ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(filename);
				}
				logger.LogWarning(val);
				return default(T);
			}
		}
	}
	public static class HashUtils
	{
		private const uint FNVOffset32 = 2166136261u;

		private const uint FNVPrime32 = 16777619u;

		private static ulong FNVPrime64 = 1099511628211uL;

		private static ulong FNVOffset64 = 14695981039346656037uL;

		public static uint Hash32(string value)
		{
			uint num = 2166136261u;
			foreach (char c in value)
			{
				num = 16777619 * (num ^ c);
			}
			return num;
		}

		public static ulong Hash64(string value)
		{
			ulong num = FNVOffset64;
			foreach (char c in value)
			{
				num = FNVPrime64 * (num ^ c);
			}
			return num;
		}
	}
	public static class Il2CppMethodResolver
	{
		private static ulong ExtractTargetAddress(in Instruction instruction)
		{
			//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_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			OpKind op0Kind = ((Instruction)(ref instruction)).Op0Kind;
			if ((int)op0Kind != 4)
			{
				if ((int)op0Kind == 5)
				{
					return ((Instruction)(ref instruction)).FarBranch32;
				}
				return ((Instruction)(ref instruction)).NearBranchTarget;
			}
			return ((Instruction)(ref instruction)).FarBranch16;
		}

		private unsafe static IntPtr ResolveMethodPointer(IntPtr methodPointer)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0043: 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_0128: Invalid comparison between Unknown and I4
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Invalid comparison between Unknown and I4
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Invalid comparison between Unknown and I4
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Invalid comparison between Unknown and I4
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			StreamCodeReader val = new StreamCodeReader((Stream)new UnmanagedMemoryStream((byte*)(void*)methodPointer, 1024L, 1024L, FileAccess.Read));
			Decoder val2 = Decoder.Create((IntPtr.Size == 8) ? 64 : 32, (CodeReader)(object)val, (DecoderOptions)0);
			val2.IP = (ulong)methodPointer.ToInt64();
			Instruction instruction = default(Instruction);
			bool flag = default(bool);
			while ((int)((Instruction)(ref instruction)).Mnemonic != 1620)
			{
				val2.Decode(ref instruction);
				if ((int)((Instruction)(ref instruction)).Mnemonic != 308 && (int)((Instruction)(ref instruction)).Mnemonic != 7)
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExDebugLogInterpolatedStringHandler val3 = new BepInExDebugLogInterpolatedStringHandler(48, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Encountered mnemonic ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Mnemonic>(((Instruction)(ref instruction)).Mnemonic);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(". Treating as normal method");
					}
					logger.LogDebug(val3);
					return methodPointer;
				}
				if ((int)((Instruction)(ref instruction)).Mnemonic == 7 && ((Instruction)(ref instruction)).Immediate32 != 16)
				{
					ManualLogSource logger2 = Plugin.Logger;
					BepInExDebugLogInterpolatedStringHandler val3 = new BepInExDebugLogInterpolatedStringHandler(56, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Encountered non-unboxing add ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<uint>(((Instruction)(ref instruction)).Immediate32);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(". Treating as normal method");
					}
					logger2.LogDebug(val3);
					return methodPointer;
				}
				if ((int)((Instruction)(ref instruction)).Mnemonic == 308)
				{
					return new IntPtr((long)ExtractTargetAddress(in instruction));
				}
			}
			return methodPointer;
		}

		public static IntPtr ResolveFromMethodInfo(INativeMethodInfoStruct methodInfo)
		{
			return ResolveMethodPointer(methodInfo.MethodPointer);
		}

		public unsafe static IntPtr ResolveFromMethodInfo(MethodInfo method)
		{
			FieldInfo il2CppMethodInfoPointerFieldForGeneratedMethod = Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod((MethodBase)method);
			if (il2CppMethodInfoPointerFieldForGeneratedMethod == null)
			{
				throw new Exception($"Couldn't obtain method info for {method}");
			}
			return ResolveFromMethodInfo(UnityVersionHandler.Wrap((Il2CppMethodInfo*)(void*)(IntPtr)(il2CppMethodInfoPointerFieldForGeneratedMethod.GetValue(null) ?? ((object)IntPtr.Zero))) ?? throw new Exception($"Method info for {method} is invalid"));
		}
	}
	public static class LogUtils
	{
		private static ManualLogSource Log;

		static LogUtils()
		{
			Log = Logger.CreateLogSource("Silkworm");
		}

		public static void Init(ManualLogSource log)
		{
			Log = log;
		}

		public static bool IsLogLevel(LogLevel level)
		{
			//IL_0000: 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)
			return ((Enum)Logger.ListenedLogLevels).HasFlag((Enum)(object)level);
		}

		public static void LogFatal(object data)
		{
			Log.LogFatal(data);
		}

		public static void LogError(object data)
		{
			Log.LogError(data);
		}

		public static void LogWarning(object data)
		{
			Log.LogWarning(data);
		}

		public static void LogMessage(object data)
		{
			Log.LogMessage(data);
		}

		public static void LogInfo(object data)
		{
			Log.LogInfo(data);
		}

		public static void LogDebug(object data)
		{
			Log.LogDebug(data);
		}

		public static void LogDebugFatal(object data)
		{
			if (IsLogLevel((LogLevel)32))
			{
				LogFatal(data);
			}
		}

		public static void LogDebugError(object data)
		{
			if (IsLogLevel((LogLevel)32))
			{
				LogDebug(data);
			}
		}

		public static void LogDebugWarning(object data)
		{
			if (IsLogLevel((LogLevel)32))
			{
				LogWarning(data);
			}
		}
	}
	public static class WorldUtils
	{
		private static readonly string _ClientWorldName = "Client_0";

		private static readonly string _ServerWorldName = "Server";

		private static World? _ClientWorld;

		private static World? _ServerWorld;

		public static bool ClientWorldExists => WorldExists(_ClientWorldName);

		public static bool ServerWorldExists => WorldExists(_ServerWorldName);

		public static World DefaultWorld => World.DefaultGameObjectInjectionWorld;

		public static World ClientWorld
		{
			get
			{
				if (_ClientWorld == null || !_ClientWorld.IsCreated)
				{
					_ClientWorld = FindWorld(_ClientWorldName) ?? throw new Exception("Client world does not exist yet");
				}
				return _ClientWorld;
			}
		}

		public static World ServerWorld
		{
			get
			{
				if (_ServerWorld == null || !_ServerWorld.IsCreated)
				{
					_ServerWorld = FindWorld(_ServerWorldName) ?? throw new Exception("Server world does not exist yet");
				}
				return _ServerWorld;
			}
		}

		public static bool WorldExists(string name)
		{
			Enumerator<World> enumerator = World.All.GetEnumerator();
			while (enumerator.MoveNext())
			{
				if (enumerator.Current.Name == name)
				{
					return true;
				}
			}
			return false;
		}

		public static World? FindWorld(string name)
		{
			Enumerator<World> enumerator = World.All.GetEnumerator();
			while (enumerator.MoveNext())
			{
				World current = enumerator.Current;
				if (current.Name == name)
				{
					return current;
				}
			}
			return null;
		}
	}
}
namespace Silkworm.Hooks
{
	[HarmonyPatch]
	internal static class InputSystem_Hook
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(InputSystem), "GetKeyInputMap")]
		private static bool GetKeyInputMap(InputSystem __instance, InputFlag input, ref string inputText, ref Sprite inputIcon, bool primary)
		{
			//IL_0006: 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_0018: 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_002b: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			Keybinding keybinding = KeybindingsManager.GetKeybinding(input);
			if (keybinding == null)
			{
				return true;
			}
			KeyCode keyCode = (primary ? keybinding.Primary : keybinding.Secondary);
			if ((int)keyCode == 0)
			{
				return false;
			}
			KeycodeMapping val = ((IEnumerable<KeycodeMapping>)__instance._ControlsVisualMapping.KeysData).FirstOrDefault((Func<KeycodeMapping, bool>)((KeycodeMapping x) => x.KeyCode == keyCode));
			inputText = ((val == null) ? __instance.GetKeyCodeString(keyCode) : Localization.Get(val.TextKey, true));
			if (val != null)
			{
				inputIcon = val.KeySprite;
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InputSystem), "ModifyKeyInputSetting")]
		private static bool ModifyKeyInputSetting(InputFlag inputFlag, KeyCode newKey, bool primary)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Keybinding keybinding = KeybindingsManager.GetKeybinding(inputFlag);
			if (keybinding == null)
			{
				return true;
			}
			if (primary)
			{
				keybinding.Primary = newKey;
			}
			else
			{
				keybinding.Secondary = newKey;
			}
			KeybindingsManager.FullSave();
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InputSystem), "OnUpdate")]
		private static void OnUpdate()
		{
			foreach (KeybindingCategory value in KeybindingsManager.Categories.Values)
			{
				foreach (Keybinding value2 in value.KeybindingMap.Values)
				{
					if (value2.IsDown)
					{
						UnityEvent onKeyDown = value2.OnKeyDown;
						if (onKeyDown != null)
						{
							onKeyDown.Invoke();
						}
					}
					if (value2.IsPressed)
					{
						UnityEvent onKeyPressed = value2.OnKeyPressed;
						if (onKeyPressed != null)
						{
							onKeyPressed.Invoke();
						}
					}
					if (value2.IsUp)
					{
						UnityEvent onKeyUp = value2.OnKeyUp;
						if (onKeyUp != null)
						{
							onKeyUp.Invoke();
						}
					}
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class Localization_Hook
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(Localization), "Get", new Type[]
		{
			typeof(AssetGuid),
			typeof(bool)
		})]
		private static bool Get(AssetGuid guid, ref string __result)
		{
			//IL_0000: 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)
			if (!LocalizationManager.HasKey(guid))
			{
				return true;
			}
			__result = LocalizationManager.GetKey(guid);
			return false;
		}
	}
	[HarmonyPatch]
	internal static class OptionsPanel_Interface_Hook
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(OptionsPanel_Interface), "Start")]
		private static void Start(OptionsPanel_Interface __instance)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: 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_01d8: Unknown result type (might be due to invalid IL or missing references)
			foreach (OptionCategory value in OptionsManager.Categories.Values)
			{
				UIHelper.InstantiatePrefabUnderAnchor<OptionsCategoryHeader>(__instance.CategoryHeaderPrefab, __instance.ContentNode).SetText(value.LocalizationKey);
				foreach (string option3 in value.Options)
				{
					SliderOption sliderOption;
					DropdownOption option2;
					string text;
					if (value.TryGetToggle(option3, out var option))
					{
						Options_Control_Checkbox checkbox = UIHelper.InstantiatePrefabUnderAnchor<Options_Control_Checkbox>(__instance.CheckboxPrefab, __instance.ContentNode);
						checkbox.Initialize(option.NameKey, option.Value, OnChange(option));
						option.AddListener(delegate(bool value)
						{
							checkbox.Toggle.isOn = value;
						});
					}
					else if (value.TryGetSlider(option3, out sliderOption))
					{
						Options_Control_Slider slider = UIHelper.InstantiatePrefabUnderAnchor<Options_Control_Slider>(__instance.SliderPrefab, __instance.ContentNode);
						slider.Initialize(sliderOption.NameKey, LocalizationManager.GetFormatKey(sliderOption.ValueFormat), sliderOption.MinValue, sliderOption.MaxValue, sliderOption.Value, OnChange(sliderOption), Func<float, float>.op_Implicit((Func<float, float>)delegate
						{
							if (sliderOption.Value < 10f)
							{
								return Mathf.Round(sliderOption.Value * 10f) / 10f;
							}
							return (sliderOption.Value < 0f) ? (Mathf.Round(sliderOption.Value * 100f) / 100f) : Mathf.Round(sliderOption.Value);
						}));
						sliderOption.AddListener(delegate(float value)
						{
							slider.Slider.value = value;
						});
					}
					else if (value.TryGetDropdown(option3, out option2))
					{
						Options_Control_Dropdown dropdown = UIHelper.InstantiatePrefabUnderAnchor<Options_Control_Dropdown>(__instance.DropdownPrefab, __instance.ContentNode);
						List<string> values = new List<string>();
						option2.Values.ToList().ForEach(delegate(string x)
						{
							values.Add(x);
						});
						dropdown.Initialize(option2.NameKey, values, option2.Value, OnChange(option2));
						option2.AddListener(delegate(int value)
						{
							dropdown.Dropdown.value = value;
						});
					}
					else if (value.TryGetDivider(option3, out text))
					{
						CreateDivider((Transform)(object)__instance.ContentNode, text);
					}
				}
			}
		}

		private static GameObject CreateDivider(Transform parent, string text)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0020: 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_0058: 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_007c: 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)
			Il2CppArrayBase<TextMeshProUGUI> componentsInChildren = ((Component)parent).GetComponentsInChildren<TextMeshProUGUI>();
			GameObject val = new GameObject("Divider");
			RectTransform obj = val.AddComponent<RectTransform>();
			((Transform)obj).SetParent(parent);
			((Transform)obj).localScale = Vector3.one;
			obj.sizeDelta = new Vector2(0f, 28f);
			((Graphic)val.AddComponent<Image>()).color = new Color(0.12f, 0.152f, 0.2f, 0.15f);
			val.AddComponent<LayoutElement>().preferredHeight = 28f;
			GameObject val2 = new GameObject("Text");
			RectTransform obj2 = val2.AddComponent<RectTransform>();
			((Transform)obj2).SetParent(val.transform);
			((Transform)obj2).localScale = Vector3.one;
			TextMeshProUGUI val3 = val2.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val3).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val3).fontStyle = (FontStyles)32;
			((TMP_Text)val3).font = ((TMP_Text)componentsInChildren[0]).font;
			((TMP_Text)val3).fontSize = 20f;
			if (text != null)
			{
				((TMP_Text)val3).SetText(text, true);
			}
			return val;
		}

		private static UnityAction<T> OnChange<T>(Option<T> option)
		{
			return UnityAction<T>.op_Implicit((Action<T>)delegate(T value)
			{
				option.SetValue(value);
				OptionsManager.FullSave();
			});
		}
	}
	[HarmonyPatch]
	internal class Options_ControlsPanel_Hook
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(Options_ControlsPanel), "Start")]
		private static void Start(Options_ControlsPanel __instance)
		{
			//IL_002c: 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)
			foreach (KeybindingCategory value in KeybindingsManager.Categories.Values)
			{
				UIHelper.InstantiatePrefabUnderAnchor<OptionsCategoryHeader>(__instance.CategoryHeaderPrefab, __instance.ContentNode).SetText(value.NameKey);
				foreach (Keybinding value2 in value.KeybindingMap.Values)
				{
					__instance.AddEntry(value2.InputFlag);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Options_ControlsPanel), "Update")]
		private static void Update(Options_ControlsPanel __instance)
		{
			//IL_0016: 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)
			Enumerator<ControlsInputEntry> enumerator = __instance._Entries.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ControlsInputEntry current = enumerator.Current;
				Keybinding keybinding = KeybindingsManager.GetKeybinding(current._InputFlag);
				if (keybinding != null)
				{
					current.SetInputName(keybinding.NameKey);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Options_ControlsPanel), "OnResetButtonClicked")]
		private static void OnResetButtonClicked()
		{
			//IL_0034: 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)
			foreach (KeybindingCategory value in KeybindingsManager.Categories.Values)
			{
				foreach (Keybinding value2 in value.KeybindingMap.Values)
				{
					value2.Primary = value2.DefaultPrimary;
					value2.Secondary = value2.DefaultSecondary;
				}
			}
			KeybindingsManager.FullSave();
		}
	}
}
namespace Silkworm.Core.Options
{
	public class DropdownOption : Option<int>
	{
		internal string[] Values;

		public DropdownOption(string id, string name, int defaultValue, string[] values)
			: base(id, name, defaultValue)
		{
			Values = values;
		}

		public T GetEnumValue<T>()
		{
			return (T)Enum.Parse(typeof(T), Values[Value]);
		}
	}
	public class Option<T>
	{
		internal readonly LocalizationKey NameKey;

		public string Id { get; internal set; }

		public string Name { get; internal set; }

		public virtual T Value { get; internal set; }

		public T DefaultValue { get; internal set; }

		public UnityEvent<T> OnChange { get; internal set; } = new UnityEvent<T>();


		public Option(string id, string name, T defaultValue)
		{
			//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)
			Id = id;
			Name = name;
			Value = defaultValue;
			DefaultValue = defaultValue;
			NameKey = LocalizationManager.CreateKey(name);
		}

		public virtual void SetValue(T value)
		{
			Value = value;
			OnChange?.Invoke(Value);
		}

		public void AddListener(Action<T> action)
		{
			OnChange.AddListener(UnityAction<T>.op_Implicit(action));
		}
	}
	public class OptionCategory
	{
		public Dictionary<string, bool> Toggles = new Dictionary<string, bool>();

		public Dictionary<string, float> Sliders = new Dictionary<string, float>();

		public Dictionary<string, string> Dropdowns = new Dictionary<string, string>();

		internal readonly LocalizationKey LocalizationKey;

		internal List<string> Options = new List<string>();

		internal Dictionary<string, ToggleOption> ToggleOptions = new Dictionary<string, ToggleOption>();

		internal Dictionary<string, SliderOption> SliderOptions = new Dictionary<string, SliderOption>();

		internal Dictionary<string, DropdownOption> DropdownOptions = new Dictionary<string, DropdownOption>();

		internal Dictionary<string, string> Dividers = new Dictionary<string, string>();

		public string Name { get; internal set; }

		public OptionCategory(string name)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			Name = name;
			LocalizationKey = LocalizationManager.CreateKey(name);
		}

		public ToggleOption AddToggle(string id, string name, bool defaultValue)
		{
			ToggleOption toggleOption = new ToggleOption(id, name, defaultValue);
			if (Toggles.ContainsKey(id))
			{
				toggleOption.Value = Toggles[id];
			}
			ToggleOptions.Add(id, toggleOption);
			Options.Add(toggleOption.Id);
			return toggleOption;
		}

		public SliderOption AddSlider(string id, string name, float minValue, float maxValue, float defaultValue)
		{
			return AddSlider(id, name, minValue, maxValue, defaultValue, "default");
		}

		public SliderOption AddSlider(string id, string name, float minValue, float maxValue, float defaultValue, string format)
		{
			SliderOption sliderOption = new SliderOption(id, name, minValue, maxValue, defaultValue, format);
			if (Sliders.ContainsKey(id))
			{
				sliderOption.Value = Mathf.Clamp(Sliders[id], minValue, maxValue);
			}
			SliderOptions.Add(id, sliderOption);
			Options.Add(sliderOption.Id);
			return sliderOption;
		}

		public DropdownOption AddDropdown(string id, string name, int defaultValue, string[] values)
		{
			DropdownOption dropdownOption = new DropdownOption(id, name, defaultValue, values);
			if (Dropdowns.ContainsKey(id))
			{
				dropdownOption.Value = Mathf.Max(0, Array.IndexOf(values, Dropdowns[id]));
			}
			DropdownOptions.Add(id, dropdownOption);
			Options.Add(dropdownOption.Id);
			return dropdownOption;
		}

		public void AddDivider()
		{
			AddDivider(null);
		}

		public void AddDivider(string name)
		{
			string text = Guid.NewGuid().ToString();
			Dividers.Add(text, name);
			Options.Add(text);
		}

		public ToggleOption GetToggle(string id)
		{
			return ToggleOptions.GetValueOrDefault(id);
		}

		public SliderOption GetSlider(string id)
		{
			return SliderOptions.GetValueOrDefault(id);
		}

		public DropdownOption GetDropdown(string id)
		{
			return DropdownOptions.GetValueOrDefault(id);
		}

		public bool HasToggle(string id)
		{
			return ToggleOptions.ContainsKey(id);
		}

		public bool HasSlider(string id)
		{
			return SliderOptions.ContainsKey(id);
		}

		public bool HasDropdown(string id)
		{
			return DropdownOptions.ContainsKey(id);
		}

		public bool TryGetToggle(string id, out ToggleOption option)
		{
			if (!ToggleOptions.ContainsKey(id))
			{
				option = null;
				return false;
			}
			option = ToggleOptions[id];
			return true;
		}

		public bool TryGetSlider(string id, out SliderOption option)
		{
			if (!SliderOptions.ContainsKey(id))
			{
				option = null;
				return false;
			}
			option = SliderOptions[id];
			return true;
		}

		public bool TryGetDropdown(string id, out DropdownOption option)
		{
			if (!DropdownOptions.ContainsKey(id))
			{
				option = null;
				return false;
			}
			option = DropdownOptions[id];
			return true;
		}

		public bool TryGetDivider(string id, out string text)
		{
			if (!Dividers.ContainsKey(id))
			{
				text = null;
				return false;
			}
			text = Dividers[id];
			return true;
		}
	}
	public class SliderOption : Option<float>
	{
		public float MinValue { get; internal set; }

		public float MaxValue { get; internal set; }

		public override float Value
		{
			get
			{
				return Mathf.Clamp(base.Value, MinValue, MaxValue);
			}
			internal set
			{
				base.Value = value;
			}
		}

		public string ValueFormat { get; internal set; }

		public SliderOption(string id, string text, float minValue, float maxValue, float defaultvalue, string valueFormat)
			: base(id, text, defaultvalue)
		{
			MinValue = minValue;
			MaxValue = maxValue;
			Value = Mathf.Clamp(Value, MinValue, MaxValue);
			ValueFormat = valueFormat;
		}

		public override void SetValue(float value)
		{
			base.SetValue(value);
			Value = Mathf.Clamp(Value, MinValue, MaxValue);
		}
	}
	public class ToggleOption : Option<bool>
	{
		public ToggleOption(string id, string name, bool defaultvalue)
			: base(id, name, defaultvalue)
		{
		}
	}
}
namespace Silkworm.Core.KeyBinding
{
	public class Keybinding
	{
		internal KeybindingData Data;

		internal LocalizationKey NameKey;

		internal InputFlag InputFlag;

		public string Id
		{
			get
			{
				return Data.Id;
			}
			internal set
			{
				Data.Id = value;
			}
		}

		public string Name
		{
			get
			{
				return Data.Name;
			}
			internal set
			{
				Data.Name = value;
			}
		}

		public KeyCode Primary
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return Data.Primary;
			}
			internal set
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				Data.Primary = value;
			}
		}

		public KeyCode Secondary
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return Data.Secondary;
			}
			internal set
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				Data.Secondary = value;
			}
		}

		public bool IsPressed
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				if (!Input.GetKey(Primary))
				{
					return Input.GetKey(Secondary);
				}
				return true;
			}
		}

		public bool IsDown
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				if (!Input.GetKeyDown(Primary))
				{
					return Input.GetKeyDown(Secondary);
				}
				return true;
			}
		}

		public bool IsUp
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				if (!Input.GetKeyUp(Primary))
				{
					return Input.GetKeyUp(Secondary);
				}
				return true;
			}
		}

		public UnityEvent OnKeyPressed { get; internal set; } = new UnityEvent();


		public UnityEvent OnKeyDown { get; internal set; } = new UnityEvent();


		public UnityEvent OnKeyUp { get; internal set; } = new UnityEvent();


		internal KeyCode DefaultPrimary { get; set; }

		internal KeyCode DefaultSecondary { get; set; }

		public Keybinding(string id, string name, KeyCode defaultPrimary, KeyCode defaultSecondary)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_002a: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			Data = new KeybindingData(id, name, defaultPrimary, defaultSecondary);
			NameKey = LocalizationManager.CreateKey(name);
			DefaultPrimary = defaultPrimary;
			DefaultSecondary = defaultSecondary;
			ulong num = HashUtils.Hash64(id);
			do
			{
				InputFlag = (InputFlag)num;
			}
			while (Enum.IsDefined(typeof(InputFlag), (object)(InputFlag)(num--)));
		}

		public Keybinding(string id, string name, KeyCode defaultPrimary)
			: this(id, name, defaultPrimary, (KeyCode)0)
		{
		}//IL_0003: Unknown result type (might be due to invalid IL or missing references)


		public Keybinding(string id, string name)
			: this(id, name, (KeyCode)0)
		{
		}

		public void AddKeyPressedListener(Action action)
		{
			OnKeyPressed.AddListener(UnityAction.op_Implicit(action));
		}

		public void AddKeyDownListener(Action action)
		{
			OnKeyDown.AddListener(UnityAction.op_Implicit(action));
		}

		public void AddKeyUpListener(Action action)
		{
			OnKeyUp.AddListener(UnityAction.op_Implicit(action));
		}
	}
	public class KeybindingCategory
	{
		public Dictionary<string, KeybindingData> Keybindings = new Dictionary<string, KeybindingData>();

		internal LocalizationKey NameKey;

		internal Dictionary<string, Keybinding> KeybindingMap = new Dictionary<string, Keybinding>();

		internal Dictionary<InputFlag, string> KeybindingFlags = new Dictionary<InputFlag, string>();

		public string Name { get; internal set; }

		public KeybindingCategory(string name)
		{
			//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)
			Name = name;
			NameKey = LocalizationManager.CreateKey(name);
		}

		public Keybinding AddKeyBinding(string id, string name, KeyCode defaultPrimary, KeyCode defaultSecondary)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: 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_0026: 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)
			Keybinding keybinding = new Keybinding(id, name, defaultPrimary, defaultSecondary);
			if (Keybindings.ContainsKey(id))
			{
				keybinding.Primary = Keybindings[id].Primary;
				keybinding.Secondary = Keybindings[id].Secondary;
			}
			KeybindingMap.Add(id, keybinding);
			KeybindingFlags.Add(keybinding.InputFlag, id);
			return keybinding;
		}

		public Keybinding AddKeyBinding(string id, string name, KeyCode defaultPrimary)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return AddKeyBinding(id, name, defaultPrimary, (KeyCode)0);
		}

		public Keybinding AddKeyBinding(string id, string name)
		{
			return AddKeyBinding(id, name, (KeyCode)0);
		}

		public Keybinding GetKeybinding(string id)
		{
			return KeybindingMap.GetValueOrDefault(id);
		}

		public Keybinding GetKeybinding(InputFlag flag)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			string valueOrDefault = KeybindingFlags.GetValueOrDefault(flag);
			if (valueOrDefault != null)
			{
				return GetKeybinding(valueOrDefault);
			}
			return null;
		}

		public bool HasKeybinding(string id)
		{
			return KeybindingMap.ContainsKey(id);
		}

		public bool HasKeybinding(InputFlag flag)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			string valueOrDefault = KeybindingFlags.GetValueOrDefault(flag);
			if (valueOrDefault != null)
			{
				return HasKeybinding(valueOrDefault);
			}
			return false;
		}
	}
	public class KeybindingData
	{
		public string Id { get; internal set; }

		public string Name { get; internal set; }

		public KeyCode Primary { get; internal set; }

		public KeyCode Secondary { get; internal set; }

		public KeybindingData(string id, string name, KeyCode primary, KeyCode secondary)
		{
			//IL_0015: 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)
			Id = id;
			Name = name;
			Primary = primary;
			Secondary = secondary;
		}
	}
}
namespace Silkworm.API
{
	public static class KeybindingsManager
	{
		internal static Dictionary<string, KeybindingCategory> Categories = new Dictionary<string, KeybindingCategory>();

		internal static string KeybindingFilename = "keybindings.json";

		public static KeybindingCategory AddCategory(string name)
		{
			if (!Categories.ContainsKey(name))
			{
				Categories.Add(name, new KeybindingCategory(name));
			}
			return Categories[name];
		}

		public static Keybinding AddKeybinding(string category, string id, string name, KeyCode defaultPrimary, KeyCode defaultSecondary)
		{
			//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)
			return AddCategory(category).AddKeyBinding(id, name, defaultPrimary, defaultSecondary);
		}

		public static Keybinding AddKeybinding(string category, string id, string name, KeyCode defaultPrimary)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return AddKeybinding(category, id, name, defaultPrimary, (KeyCode)0);
		}

		public static Keybinding AddKeybinding(string category, string id, string name)
		{
			return AddKeybinding(category, id, name, (KeyCode)0);
		}

		public static Keybinding GetKeybinding(string id)
		{
			foreach (KeybindingCategory value in Categories.Values)
			{
				if (value.HasKeybinding(id))
				{
					return value.GetKeybinding(id);
				}
			}
			return null;
		}

		public static Keybinding GetKeybinding(InputFlag flag)
		{
			//IL_001b: 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)
			foreach (KeybindingCategory value in Categories.Values)
			{
				if (value.HasKeybinding(flag))
				{
					return value.GetKeybinding(flag);
				}
			}
			return null;
		}

		public static void Save()
		{
			FileUtils.WriteJson(KeybindingFilename, Categories);
		}

		internal static void FullSave()
		{
			List<string> list = new List<string>();
			foreach (KeybindingCategory value in Categories.Values)
			{
				value.Keybindings.Clear();
				foreach (Keybinding value2 in value.KeybindingMap.Values)
				{
					value.Keybindings.Add(value2.Id, value2.Data);
				}
				if (value.Keybindings.Count == 0)
				{
					list.Add(value.Name);
				}
			}
			foreach (string item in list)
			{
				Categories.Remove(item);
			}
			Save();
		}

		internal static void Load()
		{
			if (!FileUtils.Exists(KeybindingFilename))
			{
				Save();
			}
			Dictionary<string, KeybindingCategory> dictionary = FileUtils.ReadJson<Dictionary<string, KeybindingCategory>>(KeybindingFilename);
			if (dictionary != null)
			{
				Categories = dictionary;
			}
		}
	}
	public static class LocalizationManager
	{
		public static class Format
		{
			public const string Default = "default";

			public const string Percent = "percent";
		}

		public static readonly LocalizationKey DefaultValue;

		public static readonly LocalizationKey PercentValue;

		private static readonly Dictionary<AssetGuid, string> guids;

		static LocalizationManager()
		{
			//IL_000f: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			guids = new Dictionary<AssetGuid, string>();
			DefaultValue = CreateKey("{value}");
			PercentValue = CreateKey("{value}%");
		}

		public static LocalizationKey GetFormatKey(string format)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (format == "percent")
			{
				return PercentValue;
			}
			return DefaultValue;
		}

		public static LocalizationKey CreateKey(string value)
		{
			//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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			LocalizationKey result = default(LocalizationKey);
			((LocalizationKey)(ref result))..ctor(AssetGuid.FromGuid(Guid.NewGuid()));
			guids.Add(((LocalizationKey)(ref result)).GetGuid(), value);
			return result;
		}

		internal static string GetKey(AssetGuid guid)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return guids[guid];
		}

		internal static string GetKey(LocalizationKey key)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return GetKey(((LocalizationKey)(ref key)).GetGuid());
		}

		internal static bool HasKey(AssetGuid guid)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return guids.ContainsKey(guid);
		}
	}
	public static class OptionsManager
	{
		internal static Dictionary<string, OptionCategory> Categories = new Dictionary<string, OptionCategory>();

		internal static string OptionsFilename = "options.json";

		public static OptionCategory AddCategory(string name)
		{
			if (!Categories.ContainsKey(name))
			{
				Categories.Add(name, new OptionCategory(name));
			}
			return Categories[name];
		}

		public static ToggleOption AddToggle(string category, string id, string text, bool defaultValue)
		{
			return AddCategory(category).AddToggle(id, text, defaultValue);
		}

		public static SliderOption AddSlider(string category, string id, string text, float minValue, float maxValue, float defaultValue)
		{
			return AddSlider(category, id, text, minValue, maxValue, defaultValue, "default");
		}

		public static SliderOption AddSlider(string category, string id, string text, float minValue, float maxValue, float defaultValue, string format)
		{
			return AddCategory(category).AddSlider(id, text, minValue, maxValue, defaultValue, format);
		}

		public static DropdownOption AddDropdown(string category, string id, string name, int defaultValue, string[] values)
		{
			return AddCategory(category).AddDropdown(id, name, defaultValue, values);
		}

		public static ToggleOption GetToggle(string id)
		{
			foreach (OptionCategory value in Categories.Values)
			{
				if (value.HasToggle(id))
				{
					return value.GetToggle(id);
				}
			}
			return null;
		}

		public static SliderOption GetSlider(string id)
		{
			foreach (OptionCategory value in Categories.Values)
			{
				if (value.HasSlider(id))
				{
					return value.GetSlider(id);
				}
			}
			return null;
		}

		public static DropdownOption GetDropdown(string id)
		{
			foreach (OptionCategory value in Categories.Values)
			{
				if (value.HasDropdown(id))
				{
					return value.GetDropdown(id);
				}
			}
			return null;
		}

		public static void Save()
		{
			FileUtils.WriteJson(OptionsFilename, Categories);
		}

		internal static void FullSave()
		{
			List<string> list = new List<string>();
			foreach (OptionCategory value in Categories.Values)
			{
				value.Toggles.Clear();
				value.Sliders.Clear();
				value.Dropdowns.Clear();
				foreach (ToggleOption value2 in value.ToggleOptions.Values)
				{
					value.Toggles.Add(value2.Id, value2.Value);
				}
				foreach (SliderOption value3 in value.SliderOptions.Values)
				{
					value.Sliders.Add(value3.Id, value3.Value);
				}
				foreach (DropdownOption value4 in value.DropdownOptions.Values)
				{
					value.Dropdowns.Add(value4.Id, value4.Values[value4.Value]);
				}
				if (value.Toggles.Count + value.Sliders.Count + value.Dropdowns.Count == 0)
				{
					list.Add(value.Name);
				}
			}
			foreach (string item in list)
			{
				Categories.Remove(item);
			}
			Save();
		}

		internal static void Load()
		{
			if (!FileUtils.Exists(OptionsFilename))
			{
				Save();
			}
			Dictionary<string, OptionCategory> dictionary = FileUtils.ReadJson<Dictionary<string, OptionCategory>>(OptionsFilename);
			if (dictionary != null)
			{
				Categories = dictionary;
			}
		}
	}
}

UniverseLib.IL2CPP.Interop.dll

Decompiled 5 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Common.Attributes;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Il2CppSystem.Threading;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UniverseLib.Config;
using UniverseLib.Input;
using UniverseLib.Reflection;
using UniverseLib.Runtime;
using UniverseLib.Runtime.Il2Cpp;
using UniverseLib.UI;
using UniverseLib.UI.Models;
using UniverseLib.UI.ObjectPool;
using UniverseLib.UI.Panels;
using UniverseLib.UI.Widgets;
using UniverseLib.UI.Widgets.ScrollView;
using UniverseLib.Utility;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("UniverseLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sinai")]
[assembly: AssemblyProduct("UniverseLib")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b21dbde3-5d6f-4726-93ab-cc3cc68bae7d")]
[assembly: AssemblyFileVersion("1.5.1")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.1.0")]
[module: UnverifiableCode]
namespace UniverseLib
{
	public static class ReflectionExtensions
	{
		public static Type GetActualType(this object obj)
		{
			return ReflectionUtility.Instance.Internal_GetActualType(obj);
		}

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

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

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

		[Obsolete("This method is no longer necessary, just use Assembly.GetTypes().", false)]
		public static IEnumerable<Type> TryGetTypes(this Assembly asm)
		{
			return asm.GetTypes();
		}

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

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

		public static Exception GetInnerMostException(this Exception e)
		{
			while (e != null && e.InnerException != null && !(e.InnerException is RuntimeWrappedException))
			{
				e = e.InnerException;
			}
			return e;
		}
	}
	internal class Il2CppDictionary : IEnumerator<DictionaryEntry>, IEnumerator, IDisposable
	{
		private readonly Il2CppEnumerator keysEnumerator;

		private readonly Il2CppEnumerator valuesEnumerator;

		public object Current => new DictionaryEntry(keysEnumerator.Current, valuesEnumerator.Current);

		DictionaryEntry IEnumerator<DictionaryEntry>.Current => new DictionaryEntry(keysEnumerator.Current, valuesEnumerator.Current);

		public Il2CppDictionary(Il2CppEnumerator keysEnumerator, Il2CppEnumerator valuesEnumerator)
		{
			this.keysEnumerator = keysEnumerator;
			this.valuesEnumerator = valuesEnumerator;
		}

		public bool MoveNext()
		{
			return keysEnumerator.MoveNext() && valuesEnumerator.MoveNext();
		}

		public void Dispose()
		{
			throw new NotImplementedException();
		}

		public void Reset()
		{
			throw new NotImplementedException();
		}
	}
	internal class Il2CppEnumerator : IEnumerator
	{
		private readonly object enumerator;

		private readonly MethodInfo m_GetEnumerator;

		private readonly object instanceForMoveNext;

		private readonly MethodInfo m_MoveNext;

		private readonly object instanceForCurrent;

		private readonly MethodInfo p_Current;

		public object Current => p_Current.Invoke(instanceForCurrent, null);

		public bool MoveNext()
		{
			return (bool)m_MoveNext.Invoke(instanceForMoveNext, null);
		}

		public void Reset()
		{
			throw new NotImplementedException();
		}

		public Il2CppEnumerator(object instance, Type type)
		{
			m_GetEnumerator = type.GetMethod("GetEnumerator") ?? type.GetMethod("System_Collections_IEnumerable_GetEnumerator", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			enumerator = m_GetEnumerator.Invoke(instance.TryCast(m_GetEnumerator.DeclaringType), ArgumentUtility.EmptyArgs);
			if (enumerator == null)
			{
				throw new Exception("GetEnumerator returned null");
			}
			Type actualType = enumerator.GetActualType();
			m_MoveNext = actualType.GetMethod("MoveNext") ?? actualType.GetMethod("System_Collections_IEnumerator_MoveNext", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			instanceForMoveNext = enumerator.TryCast(m_MoveNext.DeclaringType);
			p_Current = actualType.GetProperty("Current")?.GetGetMethod() ?? actualType.GetMethod("System_Collections_IEnumerator_get_Current", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			instanceForCurrent = enumerator.TryCast(p_Current.DeclaringType);
		}
	}
	public class Il2CppReflection : ReflectionUtility
	{
		internal Stopwatch initStopwatch = new Stopwatch();

		internal static readonly Dictionary<string, MethodInfo> unboxMethods = new Dictionary<string, MethodInfo>();

		internal static readonly Dictionary<string, Type> il2cppPrimitivesToMono = new Dictionary<string, Type>
		{
			{
				"Il2CppSystem.Boolean",
				typeof(bool)
			},
			{
				"Il2CppSystem.Byte",
				typeof(byte)
			},
			{
				"Il2CppSystem.SByte",
				typeof(sbyte)
			},
			{
				"Il2CppSystem.Char",
				typeof(char)
			},
			{
				"Il2CppSystem.Double",
				typeof(double)
			},
			{
				"Il2CppSystem.Single",
				typeof(float)
			},
			{
				"Il2CppSystem.Int32",
				typeof(int)
			},
			{
				"Il2CppSystem.UInt32",
				typeof(uint)
			},
			{
				"Il2CppSystem.Int64",
				typeof(long)
			},
			{
				"Il2CppSystem.UInt64",
				typeof(ulong)
			},
			{
				"Il2CppSystem.Int16",
				typeof(short)
			},
			{
				"Il2CppSystem.UInt16",
				typeof(ushort)
			},
			{
				"Il2CppSystem.IntPtr",
				typeof(IntPtr)
			},
			{
				"Il2CppSystem.UIntPtr",
				typeof(UIntPtr)
			}
		};

		private const string IL2CPP_STRING_FULLNAME = "Il2CppSystem.String";

		private const string STRING_FULLNAME = "System.String";

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

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

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

		internal static IntPtr cppIEnumerablePointer;

		internal static IntPtr cppIDictionaryPointer;

		protected override void Initialize()
		{
			base.Initialize();
			ReflectionUtility.Initializing = true;
			((MonoBehaviour)UniversalBehaviour.Instance).StartCoroutine(InitCoroutine().WrapToIl2Cpp());
		}

		private IEnumerator InitCoroutine()
		{
			initStopwatch.Start();
			Stopwatch sw = new Stopwatch();
			sw.Start();
			IEnumerator coro = TryLoadGameModules();
			while (coro.MoveNext())
			{
				yield return null;
			}
			Universe.Log($"Loaded Unhollowed modules in {(float)sw.ElapsedMilliseconds * 0.001f} seconds.");
			sw.Reset();
			sw.Start();
			BuildDeobfuscationCache();
			Universe.Log($"Setup deobfuscation cache in {(float)sw.ElapsedMilliseconds * 0.001f} seconds.");
			ReflectionUtility.OnTypeLoaded += TryCacheDeobfuscatedType;
			ReflectionUtility.Initializing = false;
		}

		internal override Type Internal_GetTypeByName(string fullName)
		{
			if (obfuscatedToDeobfuscatedTypes.TryGetValue(fullName, out var value))
			{
				return value;
			}
			return base.Internal_GetTypeByName(fullName);
		}

		internal override Type Internal_GetActualType(object obj)
		{
			if (obj == null)
			{
				return null;
			}
			Type type = obj.GetType();
			try
			{
				if (il2cppPrimitivesToMono.TryGetValue(type.FullName, out var value))
				{
					return value;
				}
				Il2CppObjectBase val = (Il2CppObjectBase)((obj is Il2CppObjectBase) ? obj : null);
				if (val != null)
				{
					if (type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(Il2CppArrayBase<>))
					{
						return type;
					}
					IntPtr intPtr = IL2CPP.il2cpp_object_get_class(val.Pointer);
					Object val2 = (Object)((obj is Object) ? obj : null);
					Type cppType = ((val2 == null) ? Il2CppType.TypeFromPointer(intPtr, "<unknown type>") : val2.GetIl2CppType());
					return GetUnhollowedType(cppType) ?? type;
				}
			}
			catch (Exception ex)
			{
				Universe.LogWarning("Exception in IL2CPP GetActualType: " + ex);
			}
			return type;
		}

		public static Type GetUnhollowedType(Type cppType)
		{
			if (cppType.IsArray)
			{
				return GetArrayBaseForArray(cppType);
			}
			if (ReflectionUtility.AllTypes.TryGetValue(cppType.FullName, out var value) && value.IsPrimitive)
			{
				return value;
			}
			if (IsString(cppType))
			{
				return typeof(string);
			}
			string text = cppType.FullName;
			if (obfuscatedToDeobfuscatedTypes.TryGetValue(text, out var value2))
			{
				return value2;
			}
			if (text.StartsWith("System."))
			{
				text = "Il2Cpp" + text;
			}
			if (!ReflectionUtility.AllTypes.TryGetValue(text, out var value3))
			{
				string text2;
				try
				{
					text2 = Il2CppTypeRedirector.GetAssemblyQualifiedName(cppType);
				}
				catch
				{
					text2 = cppType.AssemblyQualifiedName;
				}
				for (int i = 0; i < text2.Length; i++)
				{
					char c = text2[i];
					if (c == '<' || c == '>')
					{
						text2 = text2.Remove(i, 1);
						text2 = text2.Insert(i, "_");
					}
				}
				value3 = Type.GetType(text2);
				if (value3 == null)
				{
					Universe.LogWarning($"Failed to get Unhollowed type from '{text2}' (originally '{cppType.AssemblyQualifiedName}')!");
				}
			}
			return value3;
		}

		internal static Type GetArrayBaseForArray(Type cppType)
		{
			Type unhollowedType = GetUnhollowedType(cppType.GetElementType());
			if (unhollowedType == null)
			{
				throw new Exception("Could not get unhollowed Element type for Array: " + cppType.FullName);
			}
			if (unhollowedType.IsValueType)
			{
				return typeof(Il2CppStructArray<>).MakeGenericType(unhollowedType);
			}
			if (unhollowedType == typeof(string))
			{
				return typeof(Il2CppStringArray);
			}
			return typeof(Il2CppReferenceArray<>).MakeGenericType(unhollowedType);
		}

		internal override object Internal_TryCast(object obj, Type toType)
		{
			if (obj == null)
			{
				return null;
			}
			Type type = obj.GetType();
			if (type == toType)
			{
				return obj;
			}
			if (type.IsValueType)
			{
				if (IsIl2CppPrimitive(type) && toType.IsPrimitive)
				{
					return MakeMonoPrimitive(obj);
				}
				if (IsIl2CppPrimitive(toType))
				{
					return MakeIl2CppPrimitive(toType, obj);
				}
				if (typeof(Object).IsAssignableFrom(toType))
				{
					return BoxIl2CppObject(obj).TryCast(toType);
				}
				return obj;
			}
			if (obj is string && typeof(Object).IsAssignableFrom(toType))
			{
				return BoxStringToType(obj, toType);
			}
			Il2CppObjectBase val = (Il2CppObjectBase)((obj is Il2CppObjectBase) ? obj : null);
			if (val == null)
			{
				return obj;
			}
			if (toType.IsValueType)
			{
				return UnboxCppObject(val, toType);
			}
			if (toType == typeof(string))
			{
				return UnboxString(obj);
			}
			if (toType.IsSubclassOf(typeof(Il2CppObjectBase)))
			{
				if (!Il2CppTypeNotNull(toType, out var il2cppPtr))
				{
					return obj;
				}
				IntPtr intPtr = IL2CPP.il2cpp_object_get_class(val.Pointer);
				if (!IL2CPP.il2cpp_class_is_assignable_from(il2cppPtr, intPtr))
				{
					return obj;
				}
				if (RuntimeSpecificsStore.IsInjected(il2cppPtr))
				{
					object monoObjectFromIl2CppPointer = ClassInjectorBase.GetMonoObjectFromIl2CppPointer(val.Pointer);
					if (monoObjectFromIl2CppPointer != null)
					{
						return monoObjectFromIl2CppPointer;
					}
				}
				try
				{
					return Activator.CreateInstance(toType, val.Pointer);
				}
				catch
				{
					return obj;
				}
			}
			return obj;
		}

		public static object UnboxCppObject(Il2CppObjectBase cppObj, Type toType)
		{
			if (!toType.IsValueType)
			{
				return null;
			}
			try
			{
				if (toType.IsEnum)
				{
					Type type = ((object)cppObj).GetType();
					if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						object obj = cppObj.TryCast(type);
						PropertyInfo property = type.GetProperty("HasValue");
						if ((bool)property.GetValue(obj, null))
						{
							PropertyInfo property2 = type.GetProperty("Value");
							return Enum.Parse(toType, property2.GetValue(obj, null).ToString());
						}
						return cppObj;
					}
					return Enum.Parse(toType, ((Object)cppObj.TryCast<Enum>()).ToString());
				}
				string assemblyQualifiedName = toType.AssemblyQualifiedName;
				if (!unboxMethods.ContainsKey(assemblyQualifiedName))
				{
					unboxMethods.Add(assemblyQualifiedName, typeof(Il2CppObjectBase).GetMethod("Unbox").MakeGenericMethod(toType));
				}
				return unboxMethods[assemblyQualifiedName].Invoke(cppObj, ArgumentUtility.EmptyArgs);
			}
			catch (Exception ex)
			{
				Universe.LogWarning("Exception Unboxing Il2Cpp object to struct: " + ex);
				return null;
			}
		}

		public static Object BoxIl2CppObject(object value)
		{
			if (value == null)
			{
				return null;
			}
			try
			{
				Type type = value.GetType();
				if (!type.IsValueType)
				{
					return null;
				}
				if (type.IsEnum)
				{
					return Enum.Parse(Il2CppType.From(type), value.ToString());
				}
				if (type.IsPrimitive && ReflectionUtility.AllTypes.TryGetValue("Il2Cpp" + type.FullName, out var value2))
				{
					return BoxIl2CppObject(MakeIl2CppPrimitive(value2, value), value2);
				}
				return BoxIl2CppObject(value, type);
			}
			catch (Exception ex)
			{
				Universe.LogWarning("Exception in BoxIl2CppObject: " + ex);
				return null;
			}
		}

		private static Object BoxIl2CppObject(object cppStruct, Type structType)
		{
			object? obj = AccessTools.Method(structType, "BoxIl2CppObject", ArgumentUtility.EmptyTypes, (Type[])null).Invoke(cppStruct, ArgumentUtility.EmptyArgs);
			return (Object)((obj is Object) ? obj : null);
		}

		public static bool IsIl2CppPrimitive(object obj)
		{
			return IsIl2CppPrimitive(obj.GetType());
		}

		public static bool IsIl2CppPrimitive(Type type)
		{
			return il2cppPrimitivesToMono.ContainsKey(type.FullName);
		}

		public static object MakeMonoPrimitive(object cppPrimitive)
		{
			return AccessTools.Field(cppPrimitive.GetType(), "m_value").GetValue(cppPrimitive);
		}

		public static object MakeIl2CppPrimitive(Type cppType, object monoValue)
		{
			object obj = Activator.CreateInstance(cppType);
			AccessTools.Field(cppType, "m_value").SetValue(obj, monoValue);
			return obj;
		}

		public static bool IsString(object obj)
		{
			if (obj is string || obj is String)
			{
				return true;
			}
			Object val = (Object)((obj is Object) ? obj : null);
			if (val != null)
			{
				Type il2CppType = val.GetIl2CppType();
				return il2CppType.FullName == "Il2CppSystem.String" || il2CppType.FullName == "System.String";
			}
			return false;
		}

		public static bool IsString(Type type)
		{
			return type == typeof(string) || type == typeof(String);
		}

		public static bool IsString(Type cppType)
		{
			return cppType.FullName == "System.String" || cppType.FullName == "Il2CppSystem.String";
		}

		public static object BoxStringToType(object value, Type castTo)
		{
			if (castTo == typeof(String))
			{
				return String.op_Implicit(value as string);
			}
			return Object.op_Implicit(value as string);
		}

		public static string UnboxString(object value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (value is string result)
			{
				return result;
			}
			Object val = (Object)((value is Object) ? value : null);
			if (val == null)
			{
				throw new NotSupportedException("Unable to unbox string from type " + value.GetActualType().FullName + ".");
			}
			string text = String.op_Implicit((String)(object)((val is String) ? val : null));
			if (string.IsNullOrEmpty(text))
			{
				text = val.ToString();
			}
			return text;
		}

		public static bool Il2CppTypeNotNull(Type type)
		{
			IntPtr il2cppPtr;
			return Il2CppTypeNotNull(type, out il2cppPtr);
		}

		public static bool Il2CppTypeNotNull(Type type, out IntPtr il2cppPtr)
		{
			if (!cppClassPointers.TryGetValue(type.AssemblyQualifiedName, out il2cppPtr))
			{
				il2cppPtr = (IntPtr)typeof(Il2CppClassPointerStore<>).MakeGenericType(type).GetField("NativeClassPtr", BindingFlags.Static | BindingFlags.Public).GetValue(null);
				cppClassPointers.Add(type.AssemblyQualifiedName, il2cppPtr);
			}
			return il2cppPtr != IntPtr.Zero;
		}

		private static void BuildDeobfuscationCache()
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				Type[] types = assembly.GetTypes();
				foreach (Type type in types)
				{
					TryCacheDeobfuscatedType(type);
				}
			}
		}

		private static void TryCacheDeobfuscatedType(Type type)
		{
			try
			{
				if (!type.CustomAttributes.Any())
				{
					return;
				}
				foreach (CustomAttributeData customAttribute in type.CustomAttributes)
				{
					if (customAttribute.AttributeType == typeof(ObfuscatedNameAttribute))
					{
						string text = customAttribute.ConstructorArguments[0].Value.ToString();
						obfuscatedToDeobfuscatedTypes.Add(text, type);
						deobfuscatedToObfuscatedNames.Add(type.FullName, text);
						break;
					}
				}
			}
			catch
			{
			}
		}

		internal override string Internal_ProcessTypeInString(string theString, Type type)
		{
			if (deobfuscatedToObfuscatedNames.TryGetValue(type.FullName, out var value))
			{
				return theString.Replace(value, type.FullName);
			}
			return theString;
		}

		internal override void Internal_FindSingleton(string[] possibleNames, Type type, BindingFlags flags, List<object> instances)
		{
			foreach (string name in possibleNames)
			{
				PropertyInfo property = type.GetProperty(name, flags);
				if (property != null)
				{
					object value = property.GetValue(null, null);
					if (value != null)
					{
						instances.Add(value);
						return;
					}
				}
			}
			base.Internal_FindSingleton(possibleNames, type, flags, instances);
		}

		internal IEnumerator TryLoadGameModules()
		{
			string dir = ConfigManager.Unhollowed_Modules_Folder;
			if (Directory.Exists(dir))
			{
				string[] files = Directory.GetFiles(dir, "*.dll");
				foreach (string filePath in files)
				{
					if (initStopwatch.ElapsedMilliseconds > 10)
					{
						yield return null;
						initStopwatch.Reset();
						initStopwatch.Start();
					}
					DoLoadModule(filePath);
				}
			}
			else
			{
				Universe.LogWarning("Expected Unhollowed folder path does not exist: '" + dir + "'. If you are using the standalone release, you can specify the Unhollowed modules path when you call CreateInstance().");
			}
		}

		internal bool DoLoadModule(string fullPath)
		{
			if (string.IsNullOrEmpty(fullPath) || !File.Exists(fullPath))
			{
				return false;
			}
			try
			{
				Assembly.LoadFrom(fullPath);
				return true;
			}
			catch
			{
				return false;
			}
		}

		protected override bool Internal_IsEnumerable(Type type)
		{
			if (base.Internal_IsEnumerable(type))
			{
				return true;
			}
			try
			{
				if (cppIEnumerablePointer == IntPtr.Zero)
				{
					Il2CppTypeNotNull(typeof(IEnumerable), out cppIEnumerablePointer);
				}
				if (cppIEnumerablePointer != IntPtr.Zero && Il2CppTypeNotNull(type, out var il2cppPtr) && IL2CPP.il2cpp_class_is_assignable_from(cppIEnumerablePointer, il2cppPtr))
				{
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		protected override bool Internal_TryGetEntryType(Type enumerableType, out Type type)
		{
			if (base.Internal_TryGetEntryType(enumerableType, out type))
			{
				return true;
			}
			if (type.IsGenericType)
			{
				type = type.GetGenericArguments()[0];
				return true;
			}
			type = typeof(object);
			return false;
		}

		protected override bool Internal_TryGetEnumerator(object instance, out IEnumerator enumerator)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if (instance is IEnumerable)
			{
				return base.Internal_TryGetEnumerator(instance, out enumerator);
			}
			enumerator = null;
			Type actualType = instance.GetActualType();
			try
			{
				enumerator = new Il2CppEnumerator(instance, actualType);
				return true;
			}
			catch (Exception value)
			{
				Universe.LogWarning($"IEnumerable of type {actualType.FullName} failed to get enumerator: {value}");
				return false;
			}
		}

		protected override bool Internal_IsDictionary(Type type)
		{
			if (base.Internal_IsDictionary(type))
			{
				return true;
			}
			try
			{
				if (cppIDictionaryPointer == IntPtr.Zero && !Il2CppTypeNotNull(typeof(IDictionary), out cppIDictionaryPointer))
				{
					return false;
				}
				if (Il2CppTypeNotNull(type, out var il2cppPtr) && IL2CPP.il2cpp_class_is_assignable_from(cppIDictionaryPointer, il2cppPtr))
				{
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		protected override bool Internal_TryGetEntryTypes(Type type, out Type keys, out Type values)
		{
			if (base.Internal_TryGetEntryTypes(type, out keys, out values))
			{
				return true;
			}
			if (type.IsGenericType)
			{
				Type[] genericArguments = type.GetGenericArguments();
				if (genericArguments.Length == 2)
				{
					keys = genericArguments[0];
					values = genericArguments[1];
					return true;
				}
			}
			keys = typeof(object);
			values = typeof(object);
			return false;
		}

		protected override bool Internal_TryGetDictEnumerator(object dictionary, out IEnumerator<DictionaryEntry> dictEnumerator)
		{
			if (dictionary is IDictionary)
			{
				return base.Internal_TryGetDictEnumerator(dictionary, out dictEnumerator);
			}
			try
			{
				Type actualType = dictionary.GetActualType();
				if (typeof(Hashtable).IsAssignableFrom(actualType))
				{
					dictEnumerator = EnumerateCppHashTable(dictionary.TryCast<Hashtable>());
					return true;
				}
				PropertyInfo property = actualType.GetProperty("Keys");
				object value = property.GetValue(dictionary.TryCast(property.DeclaringType), null);
				PropertyInfo property2 = actualType.GetProperty("Values");
				object value2 = property2.GetValue(dictionary.TryCast(property2.DeclaringType), null);
				Il2CppEnumerator keysEnumerator = new Il2CppEnumerator(value, value.GetActualType());
				Il2CppEnumerator valuesEnumerator = new Il2CppEnumerator(value2, value2.GetActualType());
				dictEnumerator = new Il2CppDictionary(keysEnumerator, valuesEnumerator);
				return true;
			}
			catch (Exception value3)
			{
				Universe.Log($"IDictionary failed to enumerate: {value3}");
				dictEnumerator = null;
				return false;
			}
		}

		private static IEnumerator<DictionaryEntry> EnumerateCppHashTable(Hashtable hashtable)
		{
			for (int i = 0; i < ((Il2CppArrayBase<bucket>)(object)hashtable.buckets).Count; i++)
			{
				bucket bucket = ((Il2CppArrayBase<bucket>)(object)hashtable.buckets)[i];
				if (bucket != null && bucket.key != null)
				{
					yield return new DictionaryEntry(bucket.key, bucket.val);
				}
			}
		}
	}
	internal static class ReflectionPatches
	{
		internal static void Init()
		{
			Universe.Patch(typeof(Assembly), "GetTypes", (MethodType)0, new Type[0], null, null, AccessTools.Method(typeof(ReflectionPatches), "Finalizer_Assembly_GetTypes", (Type[])null, (Type[])null));
		}

		public static Exception Finalizer_Assembly_GetTypes(Assembly __instance, Exception __exception, ref Type[] __result)
		{
			if (__exception != null)
			{
				if (__exception is ReflectionTypeLoadException e)
				{
					__result = ReflectionUtility.TryExtractTypesFromException(e);
				}
				else
				{
					try
					{
						__result = __instance.GetExportedTypes();
					}
					catch (ReflectionTypeLoadException e2)
					{
						__result = ReflectionUtility.TryExtractTypesFromException(e2);
					}
					catch
					{
						__result = ArgumentUtility.EmptyTypes;
					}
				}
			}
			return null;
		}
	}
	public class ReflectionUtility
	{
		public static bool Initializing;

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

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

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

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

		private static string[] allTypeNamesArray;

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

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

		internal static ReflectionUtility Instance { get; private set; }

		public static event Action<Type> OnTypeLoaded;

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

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

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

		private static void SetupTypeCache()
		{
			if (Universe.Context == RuntimeContext.Mono)
			{
				ForceLoadManagedAssemblies();
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly asm in assemblies)
			{
				CacheTypes(asm);
			}
			AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded;
		}

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

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

		internal static void CacheTypes(Assembly asm)
		{
			Type[] types = asm.GetTypes();
			foreach (Type type in types)
			{
				if (!string.IsNullOrEmpty(type.Namespace) && !uniqueNamespaces.Contains(type.Namespace))
				{
					uniqueNamespaces.Add(type.Namespace);
					int j;
					for (j = 0; j < AllNamespaces.Count && type.Namespace.CompareTo(AllNamespaces[j]) >= 0; j++)
					{
					}
					AllNamespaces.Insert(j, type.Namespace);
				}
				AllTypes[type.FullName] = type;
				ReflectionUtility.OnTypeLoaded?.Invoke(type);
			}
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		protected internal abstract void OnInitialize();

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

		protected internal abstract Coroutine Internal_StartCoroutine(IEnumerator routine);

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

		protected internal abstract void Internal_StopCoroutine(Coroutine coroutine);

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

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

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

		protected internal abstract ScriptableObject Internal_CreateScriptable(Type type);

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

		protected internal abstract string Internal_LayerToName(int layer);

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

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

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

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

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

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

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

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

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

		protected internal abstract int Internal_GetRootCount(Scene scene);

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

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

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

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

		protected internal abstract void Internal_SetColorBlock(Selectable selectable, Color? normal = null, Color? highlighted = null, Color? pressed = null, Color? disabled = null);
	}
	public class AssetBundle : Object
	{
		internal delegate IntPtr d_LoadFromFile(IntPtr path, uint crc, ulong offset);

		private delegate IntPtr d_LoadFromMemory(IntPtr binary, uint crc);

		public delegate IntPtr d_GetAllLoadedAssetBundles_Native();

		internal delegate IntPtr d_LoadAssetWithSubAssets_Internal(IntPtr _this, IntPtr name, IntPtr type);

		internal delegate IntPtr d_LoadAsset_Internal(IntPtr _this, IntPtr name, IntPtr type);

		internal delegate void d_Unload(IntPtr _this, bool unloadAllLoadedObjects);

		public readonly IntPtr m_bundlePtr = IntPtr.Zero;

		static AssetBundle()
		{
			ClassInjector.RegisterTypeInIl2Cpp<AssetBundle>();
		}

		[HideFromIl2Cpp]
		public static AssetBundle LoadFromFile(string path)
		{
			IntPtr intPtr = ICallManager.GetICallUnreliable<d_LoadFromFile>(new string[2] { "UnityEngine.AssetBundle::LoadFromFile_Internal", "UnityEngine.AssetBundle::LoadFromFile" })(IL2CPP.ManagedStringToIl2Cpp(path), 0u, 0uL);
			return (intPtr != IntPtr.Zero) ? new AssetBundle(intPtr) : null;
		}

		[HideFromIl2Cpp]
		public static AssetBundle LoadFromMemory(Il2CppStructArray<byte> binary, uint crc = 0u)
		{
			IntPtr intPtr = ICallManager.GetICallUnreliable<d_LoadFromMemory>(new string[2] { "UnityEngine.AssetBundle::LoadFromMemory_Internal", "UnityEngine.AssetBundle::LoadFromMemory" })(((Il2CppObjectBase)binary).Pointer, crc);
			return (intPtr != IntPtr.Zero) ? new AssetBundle(intPtr) : null;
		}

		[HideFromIl2Cpp]
		public static AssetBundle[] GetAllLoadedAssetBundles()
		{
			IntPtr intPtr = ICallManager.GetICall<d_GetAllLoadedAssetBundles_Native>("UnityEngine.AssetBundle::GetAllLoadedAssetBundles_Native")();
			return (intPtr != IntPtr.Zero) ? Il2CppArrayBase<AssetBundle>.op_Implicit((Il2CppArrayBase<AssetBundle>)(object)new Il2CppReferenceArray<AssetBundle>(intPtr)) : null;
		}

		public AssetBundle(IntPtr ptr)
			: base(ptr)
		{
			m_bundlePtr = ptr;
		}

		[HideFromIl2Cpp]
		public Object[] LoadAllAssets()
		{
			IntPtr intPtr = ICallManager.GetICall<d_LoadAssetWithSubAssets_Internal>("UnityEngine.AssetBundle::LoadAssetWithSubAssets_Internal")(m_bundlePtr, IL2CPP.ManagedStringToIl2Cpp(""), ((Il2CppObjectBase)Il2CppType.Of<Object>()).Pointer);
			return (Object[])((intPtr != IntPtr.Zero) ? ((Array)Il2CppArrayBase<Object>.op_Implicit((Il2CppArrayBase<Object>)(object)new Il2CppReferenceArray<Object>(intPtr))) : ((Array)new Object[0]));
		}

		[HideFromIl2Cpp]
		public T LoadAsset<T>(string name) where T : Object
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			IntPtr intPtr = ICallManager.GetICall<d_LoadAsset_Internal>("UnityEngine.AssetBundle::LoadAsset_Internal")(m_bundlePtr, IL2CPP.ManagedStringToIl2Cpp(name), ((Il2CppObjectBase)Il2CppType.Of<T>()).Pointer);
			return (intPtr != IntPtr.Zero) ? ((Il2CppObjectBase)new Object(intPtr)).TryCast<T>() : default(T);
		}

		[HideFromIl2Cpp]
		public void Unload(bool unloadAllLoadedObjects)
		{
			ICallManager.GetICall<d_Unload>("UnityEngine.AssetBundle::Unload")(m_bundlePtr, unloadAllLoadedObjects);
		}
	}
	public static class Il2CppExtensions
	{
		public static void AddListener(this UnityEvent action, Action listener)
		{
			action.AddListener(UnityAction.op_Implicit(listener));
		}

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

		public static void RemoveListener(this UnityEvent action, Action listener)
		{
			action.RemoveListener(UnityAction.op_Implicit(listener));
		}

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

		public static void SetChildControlHeight(this HorizontalOrVerticalLayoutGroup group, bool value)
		{
			group.childControlHeight = value;
		}

		public static void SetChildControlWidth(this HorizontalOrVerticalLayoutGroup group, bool value)
		{
			group.childControlWidth = value;
		}
	}
	internal class UniversalBehaviour : MonoBehaviour
	{
		private static Delegate queuedDelegate;

		internal static UniversalBehaviour Instance { get; private set; }

		internal static void Setup()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_001b: 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)
			ClassInjector.RegisterTypeInIl2Cpp<UniversalBehaviour>();
			GameObject val = new GameObject("UniverseLibBehaviour");
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).hideFlags = (HideFlags)(((Object)val).hideFlags | 0x3D);
			Instance = val.AddComponent<UniversalBehaviour>();
		}

		internal void Update()
		{
			Universe.Update();
		}

		public UniversalBehaviour(IntPtr ptr)
			: base(ptr)
		{
		}

		internal static void InvokeDelegate(Delegate method)
		{
			queuedDelegate = method;
			((MonoBehaviour)Instance).Invoke("InvokeQueuedAction", 0f);
		}

		private void InvokeQueuedAction()
		{
			try
			{
				Delegate @delegate = queuedDelegate;
				queuedDelegate = null;
				@delegate?.DynamicInvoke();
			}
			catch (Exception value)
			{
				Universe.LogWarning($"Exception invoking action from IL2CPP thread: {value}");
			}
		}
	}
	public class Universe
	{
		public enum GlobalState
		{
			WaitingToSetup,
			SettingUp,
			SetupCompleted
		}

		public const string NAME = "UniverseLib";

		public const string VERSION = "1.5.1";

		public const string AUTHOR = "Sinai";

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

		private static float startupDelay;

		private static Action<string, LogType> logHandler;

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


		public static GlobalState CurrentGlobalState { get; private set; }

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


		private static event Action OnInitialized;

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

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

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

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

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

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

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

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

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

		internal static bool Patch(Type type, string methodName, MethodType methodType, Type[] arguments = null, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			try
			{
				string text = (((int)methodType == 1) ? "get_" : (((int)methodType != 2) ? string.Empty : "set_"));
				string text2 = text;
				MethodInfo methodInfo = ((arguments == null) ? type.GetMethod(text2 + methodName, AccessTools.all) : type.GetMethod(text2 + methodName, AccessTools.all, null, arguments, null));
				if (methodInfo == null)
				{
					return false;
				}
				if (Il2CppType.From(type, false) != (Type)null && Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod((MethodBase)methodInfo) == null)
				{
					Log("\t IL2CPP method has no corresponding pointer, aborting patch of " + type.FullName + "." + methodName);
					return false;
				}
				PatchProcessor val = Harmony.CreateProcessor((MethodBase)methodInfo);
				if (prefix != null)
				{
					val.AddPrefix(new HarmonyMethod(prefix));
				}
				if (postfix != null)
				{
					val.AddPostfix(new HarmonyMethod(postfix));
				}
				if (finalizer != null)
				{
					val.AddFinalizer(new HarmonyMethod(finalizer));
				}
				val.Patch();
				return true;
			}
			catch (Exception value)
			{
				LogWarning($"\t Exception patching {type.FullName}.{methodName}: {value}");
				return false;
			}
		}

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

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

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

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

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

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

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

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

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

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

		internal delegate string ToStringMethod(object obj);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		internal static string Vector2ToString(object obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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)
			if (!(obj is Vector2 val) || 1 == 0)
			{
				return null;
			}
			return FormatDecimalSequence(val.x, val.y);
		}

		internal static object TryParseVector3(string input)
		{
			//IL_0003: 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)
			Vector3 val = default(Vector3);
			string[] array = input.Split(' ');
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

		internal static string Vector3ToString(object obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Vector3 val) || 1 == 0)
			{
				return null;
			}
			return FormatDecimalSequence(val.x, val.y, val.z);
		}

		internal static object TryParseVector4(string input)
		{
			//IL_0003: 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)
			Vector4 val = default(Vector4);
			string[] array = input.Split(' ');
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			val.w = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

		internal static string Vector4ToString(object obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Vector4 val) || 1 == 0)
			{
				return null;
			}
			return FormatDecimalSequence(val.x, val.y, val.z, val.w);
		}

		internal static object TryParseQuaternion(string input)
		{
			//IL_0003: 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_00e1: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			string[] array = input.Split(' ');
			if (array.Length == 4)
			{
				Quaternion val2 = default(Quaternion);
				val2.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
				val2.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
				val2.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
				val2.w = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
				return val2;
			}
			val.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			return Quaternion.Euler(val);
		}

		internal static string QuaternionToString(object obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_002f: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Quaternion val) || 1 == 0)
			{
				return null;
			}
			Vector3 eulerAngles = ((Quaternion)(ref val)).eulerAngles;
			return FormatDecimalSequence(eulerAngles.x, eulerAngles.y, eulerAngles.z);
		}

		internal static object TryParseRect(string input)
		{
			//IL_0003: 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)
			Rect val = default(Rect);
			string[] array = input.Split(' ');
			((Rect)(ref val)).x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			((Rect)(ref val)).y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			((Rect)(ref val)).width = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			((Rect)(ref val)).height = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			return val;
		}

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

		internal static object TryParseColor(string input)
		{
			//IL_0003: 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)
			Color val = default(Color);
			string[] array = input.Split(' ');
			val.r = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.g = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.b = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			if (array.Length > 3)
			{
				val.a = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			}
			else
			{
				val.a = 1f;
			}
			return val;
		}

		internal static string ColorToString(object obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (!(obj is Color val) || 1 == 0)
			{
				return null;
			}
			return FormatDecimalSequence(val.r, val.g, val.b, val.a);
		}

		internal static object TryParseColor32(string input)
		{
			//IL_0003: 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)
			Color32 val = default(Color32);
			string[] array = input.Split(' ');
			val.r = byte.Parse(array[0].Trim(), CultureInfo.CurrentCulture);
			val.g = byte.Parse(array[1].Trim(), CultureInfo.CurrentCulture);
			val.b = byte.Parse(array[2].Trim(), CultureInfo.CurrentCulture);
			if (array.Length > 3)
			{
				val.a = byte.Parse(array[3].Trim(), CultureInfo.CurrentCulture);
			}
			else
			{
				val.a = byte.MaxValue;
			}
			return val;
		}

		internal static string Color32ToString(object obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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)
			if (!(obj is Color32 val))
			{
				return null;
			}
			return $"{val.r} {val.g} {val.b} {val.a}";
		}

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

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

		public const string CONST = "#92c470";

		public const string CLASS_STATIC = "#3a8d71";

		public const string CLASS_INSTANCE = "#2df7b2";

		public const string STRUCT = "#0fba3a";

		public const string INTERFACE = "#9b9b82";

		public const string FIELD_STATIC = "#8d8dc6";

		public const string FIELD_INSTANCE = "#c266ff";

		public const string METHOD_STATIC = "#b55b02";

		public const string METHOD_INSTANCE = "#ff8000";

		public const string PROP_STATIC = "#588075";

		public const string PROP_INSTANCE = "#55a38e";

		public const string LOCAL_ARG = "#a6e9e9";

		public const string OPEN_COLOR = "<color=";

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

		public const string OPEN_ITALIC = "<i>";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private const string eventSystemNamespace = "UnityEngine.EventSystem";

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

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

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

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

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

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

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

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

		public static string ToHex(this Color color)
		{
			//IL_0001: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			byte value = (byte)Mathf.Clamp(Mathf.RoundToInt(color.r * 255f), 0, 255);
			byte value2 = (byte)Mathf.Clamp(Mathf.RoundToInt(color.g * 255f), 0, 255);
			byte value3 = (byte)Mathf.Clamp(Mathf.RoundToInt(color.b * 255f), 0, 255);
			return $"{value:X2}{value2:X2}{value3:X2}";
		}

		public static Color ToColor(this string _string)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: 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_00e8: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			_string = _string.Replace("#", "");
			if (_string.Length != 6)
			{
				return Color.magenta;
			}
			byte b = byte.Parse(_string.Substring(0, 2), NumberStyles.HexNumber);
			byte b2 = byte.Parse(_string.Substring(2, 2), NumberStyles.HexNumber);
			byte b3 = byte.Parse(_string.Substring(4, 2), NumberStyles.HexNumber);
			Color result = default(Color);
			result.r = (float)((decimal)b / 255m);
			result.g = (float)((decimal)b2 / 255m);
			result.b = (float)((decimal)b3 / 255m);
			result.a = 1f;
			return result;
		}

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

		public string ID { get; }

		public GameObject RootObject { get; }

		public RectTransform RootRect { get; }

		public Canvas Canvas { get; }

		public Action UpdateMethod { get; }

		public PanelManager Panels { get; }

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

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

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

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

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

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

		internal static Color defaultTextColor = Color.white;

		public static GameObject CreateUIObject(string name, GameObject parent, Vector2 sizeDelta = default(Vector2))
		{
			//IL_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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name)
			{
				layer = 5,
				hideFlags = (HideFlags)61
			};
			if (Object.op_Implicit((Object)(object)parent))
			{
				val.transform.SetParent(parent.transform, false);
			}
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.sizeDelta = sizeDelta;
			return val;
		}

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

		internal static void SetDefaultSelectableValues(Selectable selectable)
		{
			//IL_002d: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			Navigation navigation = selectable.navigation;
			navigation.mode = (Mode)4;
			selectable.navigation = navigation;
			RuntimeHelper.Instance.Internal_SetColorBlock(selectable, (Color?)new Color(0.2f, 0.2f, 0.2f), (Color?)new Color(0.3f, 0.3f, 0.3f), (Color?)new Color(0.15f, 0.15f, 0.15f), (Color?)null);
		}

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

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

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

		public static GameObject CreatePanel(string name, GameObject parent, out GameObject contentHolder, Color? bgColor = null)
		{
			//IL_0005: 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_0061: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_00b7: 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_00da: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateUIObject(name, parent);
			UIFactory.SetLayoutGroup<VerticalLayoutGroup>(val, (bool?)true, (bool?)true, (bool?)true, (bool?)true, (int?)0, (int?)1, (int?)1, (int?)1, (int?)1, (TextAnchor?)null);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.anchoredPosition = Vector2.zero;
			component.sizeDelta = Vector2.zero;
			((Graphic)val.AddComponent<Image>()).color = Color.black;
			val.AddComponent<RectMask2D>();
			contentHolder = CreateUIObject("Content", val);
			Image val2 = contentHolder.AddComponent<Image>();
			val2.type = (Type)3;
			((Graphic)val2).color = (Color)((!bgColor.HasValue) ? new Color(0.07f, 0.07f, 0.07f) : bgColor.Value);
			UIFactory.SetLayoutGroup<VerticalLayoutGroup>(contentHolder, (bool?)true, (bool?)true, (bool?)true, (bool?)true, (int?)3, (int?)3, (int?)3, (int?)3, (int?)3, (TextAnchor?)null);
			return val;
		}

		public static GameObject CreateVerticalGroup(GameObject parent, string name, bool forceWidth, bool forceHeight, bool childControlWidth, bool childControlHeight, int spacing = 0, Vector4 padding = default(Vector4), Color bgColor = default(Color), TextAnchor? childAlignment = null)
		{
			//IL_0005: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown r

VampireCommandFramework.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using ProjectM;
using ProjectM.Network;
using SemanticVersioning;
using Unity.Collections;
using Unity.Entities;
using UnityEngine;
using VCF.Core.Basics;
using VampireCommandFramework;
using VampireCommandFramework.Basics;
using VampireCommandFramework.Breadstone;
using VampireCommandFramework.Common;
using VampireCommandFramework.Registry;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("deca")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Framework for commands in V Rising")]
[assembly: AssemblyFileVersion("0.8.2.0")]
[assembly: AssemblyInformationalVersion("0.8.2+8.Branch.main.Sha.ecad29a030816a5126da969b02fd31d7031b0d0c")]
[assembly: AssemblyProduct("VampireCommandFramework")]
[assembly: AssemblyTitle("VampireCommandFramework")]
[assembly: InternalsVisibleTo("VCF.Tests")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.8.2.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace VampireCommandFramework
{
	public class ChatCommandContext : ICommandContext
	{
		public VChatEvent Event { get; }

		public User User => Event.User;

		public IServiceProvider Services { get; }

		public string Name
		{
			get
			{
				//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)
				User user = User;
				return ((object)(FixedString64)(ref user.CharacterName)).ToString();
			}
		}

		public bool IsAdmin => User.IsAdmin;

		public ChatCommandContext(VChatEvent e)
		{
			Event = e;
		}

		public void Reply(string v)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			ServerChatUtils.SendSystemMessageToClient(VWorld.Server.EntityManager, User, v);
		}

		public CommandException Error(string LogMessage)
		{
			return new CommandException(LogMessage);
		}
	}
	public static class Color
	{
		public static string Red = "red";

		public static string Primary = "#b0b";

		public static string White = "#eee";

		public static string LightGrey = "#ccc";

		public static string Yellow = "#dd0";

		public static string DarkGreen = "#0c0";
	}
	public abstract class CommandArgumentConverter<T> : CommandArgumentConverter<T, ICommandContext>
	{
	}
	public abstract class CommandArgumentConverter<T, C> where C : ICommandContext
	{
		public abstract T Parse(C ctx, string input);
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class CommandAttribute : Attribute
	{
		public string Name { get; }

		public string ShortHand { get; }

		public string Usage { get; }

		public string Description { get; }

		public string Id { get; }

		public bool AdminOnly { get; }

		public CommandAttribute(string name, string shortHand = null, string usage = null, string description = null, string id = null, bool adminOnly = false)
		{
			Name = name;
			ShortHand = shortHand;
			Usage = usage;
			Description = description;
			Id = id ?? Name.Replace(" ", "-");
			AdminOnly = adminOnly;
		}
	}
	[Serializable]
	public class CommandException : Exception
	{
		public CommandException()
		{
		}

		public CommandException(string message)
			: base(message)
		{
		}

		public CommandException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected CommandException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class CommandGroupAttribute : Attribute
	{
		public string Name { get; }

		public string ShortHand { get; }

		public CommandGroupAttribute(string name, string shortHand = null)
		{
			Name = name;
			ShortHand = shortHand;
		}
	}
	public abstract class CommandMiddleware
	{
		public virtual bool CanExecute(ICommandContext ctx, CommandAttribute attribute, MethodInfo method)
		{
			return true;
		}

		public virtual void BeforeExecute(ICommandContext ctx, CommandAttribute attribute, MethodInfo method)
		{
		}

		public virtual void AfterExecute(ICommandContext ctx, CommandAttribute attribute, MethodInfo method)
		{
		}
	}
	public enum CommandResult
	{
		Unmatched,
		UsageError,
		CommandError,
		InternalError,
		Denied,
		Success
	}
	public static class Format
	{
		public enum FormatMode
		{
			GameChat,
			None
		}

		public static FormatMode Mode { get; set; }

		public static string B(string input)
		{
			return input.Bold();
		}

		public static string Bold(this string input)
		{
			return (Mode == FormatMode.GameChat) ? ("<b>" + input + "</b>") : input;
		}

		public static string I(string input)
		{
			return input.Italic();
		}

		public static string Italic(this string input)
		{
			return (Mode == FormatMode.GameChat) ? ("<i>" + input + "</i>") : input;
		}

		public static string Underline(this string input)
		{
			return (Mode == FormatMode.GameChat) ? ("<u>" + input + "</u>") : input;
		}

		public static string Color(this string input, string color)
		{
			return (Mode == FormatMode.GameChat) ? $"<color={color}>{input}</color>" : input;
		}

		public static string Size(this string input, int size)
		{
			return (Mode == FormatMode.GameChat) ? $"<size={size}>{input}</size>" : input;
		}

		public static string Small(this string input)
		{
			return input.Size(10);
		}

		public static string Normal(this string input)
		{
			return input.Size(16);
		}

		public static string Medium(this string input)
		{
			return input.Size(20);
		}

		public static string Large(this string input)
		{
			return input.Size(24);
		}
	}
	public interface ICommandContext
	{
		IServiceProvider Services { get; }

		string Name { get; }

		bool IsAdmin { get; }

		CommandException Error(string LogMessage);

		void Reply(string v);
	}
	public interface IConverterUsage
	{
		string Usage { get; }
	}
	[BepInPlugin("gg.deca.VampireCommandFramework", "VampireCommandFramework", "0.8.2")]
	internal class Plugin : BasePlugin
	{
		private Harmony _harmony;

		public override void Load()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			Log.Instance = ((BasePlugin)this).Log;
			if (!VWorld.IsServer)
			{
				((BasePlugin)this).Log.LogMessage((object)"Note: Vampire Command Framework is loading on the client but only adds functionality on the server at this time, seeing this message is not a problem or bug.");
				return;
			}
			_harmony = new Harmony("gg.deca.VampireCommandFramework");
			_harmony.PatchAll();
			CommandRegistry.RegisterCommandType(typeof(HelpCommands));
			CommandRegistry.RegisterCommandType(typeof(BepInExConfigCommands));
			((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("gg.deca.VampireCommandFramework", out var value);
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExMessageLogInterpolatedStringHandler val = new BepInExMessageLogInterpolatedStringHandler(12, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("VCF Loaded: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Version>((value != null) ? value.Metadata.Version : null);
			}
			log.LogMessage(val);
		}

		public override bool Unload()
		{
			_harmony.UnpatchSelf();
			return true;
		}
	}
	public static class CommandRegistry
	{
		internal const string DEFAULT_PREFIX = ".";

		private static CommandCache _cache = new CommandCache();

		internal static Dictionary<Type, (object instance, MethodInfo tryParse, Type contextType)> _converters = new Dictionary<Type, (object, MethodInfo, Type)>();

		private static List<CommandMiddleware> DEFAULT_MIDDLEWARES = new List<CommandMiddleware>
		{
			new BasicAdminCheck()
		};

		public static List<CommandMiddleware> Middlewares { get; } = new List<CommandMiddleware>
		{
			new BasicAdminCheck()
		};


		internal static Dictionary<Assembly, Dictionary<CommandMetadata, List<string>>> AssemblyCommandMap { get; } = new Dictionary<Assembly, Dictionary<CommandMetadata, List<string>>>();


		internal static void Reset()
		{
			Middlewares.Clear();
			Middlewares.AddRange(DEFAULT_MIDDLEWARES);
			AssemblyCommandMap.Clear();
			_converters.Clear();
			_cache = new CommandCache();
		}

		internal static bool CanCommandExecute(ICommandContext ctx, CommandMetadata command)
		{
			foreach (CommandMiddleware middleware in Middlewares)
			{
				try
				{
					if (!middleware.CanExecute(ctx, command.Attribute, command.Method))
					{
						return false;
					}
				}
				catch (Exception value)
				{
					Log.Error($"Error executing {middleware.GetType().Name} {value}");
					return false;
				}
			}
			return true;
		}

		public static CommandResult Handle(ICommandContext ctx, string input)
		{
			CacheResult command2 = _cache.GetCommand(input);
			CommandMetadata command3 = command2.Command;
			string[] args = command2.Args;
			CommandMetadata commandMetadata = command3;
			string[] array = args;
			if (!command2.IsMatched)
			{
				if (!command2.HasPartial)
				{
					return CommandResult.Unmatched;
				}
				foreach (CommandMetadata partialMatch in command2.PartialMatches)
				{
					ctx.SysReply(HelpCommands.PrintShortHelp(partialMatch));
				}
				return CommandResult.UsageError;
			}
			if (!commandMetadata.ContextType.IsAssignableFrom(ctx?.GetType()))
			{
				Log.Warning($"Matched [{commandMetadata.Attribute.Id}] but can not assign {commandMetadata.ContextType.Name} from {ctx?.GetType().Name}");
				return CommandResult.InternalError;
			}
			if (commandMetadata.Constructor != null && !commandMetadata.ConstructorType.IsAssignableFrom(ctx?.GetType()))
			{
				Log.Warning($"Matched [{commandMetadata.Attribute.Id}] but can not assign {commandMetadata.ConstructorType.Name} from {ctx?.GetType().Name}");
				ctx.InternalError();
				return CommandResult.InternalError;
			}
			int num = array.Length;
			int num2 = commandMetadata.Parameters.Length;
			object[] array2 = new object[num2 + 1];
			array2[0] = ctx;
			if (num != num2)
			{
				if (!commandMetadata.Parameters.Skip(num).All((ParameterInfo p) => p.HasDefaultValue))
				{
					return CommandResult.UsageError;
				}
				for (int i = num; i < num2; i++)
				{
					array2[i + 1] = commandMetadata.Parameters[i].DefaultValue;
				}
			}
			for (int j = 0; j < num; j++)
			{
				ParameterInfo parameterInfo = commandMetadata.Parameters[j];
				string text = array[j];
				if (_converters.TryGetValue(parameterInfo.ParameterType, out (object, MethodInfo, Type) value))
				{
					var (obj, methodInfo, type) = value;
					if (!type.IsAssignableFrom(ctx.GetType()))
					{
						Log.Error("Converter type " + type.Name + " is not assignable from " + ctx.GetType().Name);
						ctx.InternalError();
						return CommandResult.InternalError;
					}
					object[] parameters = new object[2] { ctx, text };
					try
					{
						object obj2 = methodInfo.Invoke(obj, parameters);
						array2[j + 1] = obj2;
					}
					catch (TargetInvocationException ex)
					{
						if (ex.InnerException is CommandException ex2)
						{
							ctx.Reply("<color=red>[error]</color> Failed converted parameter: " + ex2.Message);
							return CommandResult.UsageError;
						}
						Log.Warning($"Hit unexpected exception {ex}");
						ctx.InternalError();
						return CommandResult.InternalError;
					}
					catch (Exception value2)
					{
						Log.Warning($"Hit unexpected exception {value2}");
						ctx.InternalError();
						return CommandResult.InternalError;
					}
					continue;
				}
				TypeConverter converter = TypeDescriptor.GetConverter(parameterInfo.ParameterType);
				try
				{
					object obj3 = converter.ConvertFromInvariantString(text);
					if (converter is EnumConverter && !Enum.IsDefined(parameterInfo.ParameterType, obj3))
					{
						ctx.Reply($"<color=red>[error]</color> Invalid value {obj3} for {parameterInfo.ParameterType.Name}");
						return CommandResult.UsageError;
					}
					array2[j + 1] = obj3;
				}
				catch (Exception ex3)
				{
					ctx.Reply("<color=red>[error]</color> Failed converted parameter: " + ex3.Message);
					return CommandResult.UsageError;
				}
			}
			object obj4 = null;
			if (!commandMetadata.Method.IsStatic && (!commandMetadata.Method.DeclaringType.IsAbstract || !commandMetadata.Method.DeclaringType.IsSealed))
			{
				try
				{
					object? obj5;
					if (!(commandMetadata.Constructor == null))
					{
						ConstructorInfo constructor = commandMetadata.Constructor;
						object[] parameters2 = new ICommandContext[1] { ctx };
						obj5 = constructor.Invoke(parameters2);
					}
					else
					{
						obj5 = Activator.CreateInstance(commandMetadata.Method.DeclaringType);
					}
					obj4 = obj5;
				}
				catch (TargetInvocationException ex4)
				{
					if (ex4.InnerException is CommandException ex5)
					{
						ctx.SysReply(ex5.Message);
					}
					else
					{
						ctx.InternalError();
					}
					return CommandResult.InternalError;
				}
			}
			if (!CanCommandExecute(ctx, commandMetadata))
			{
				ctx.Reply("<color=red>[denied]</color> " + commandMetadata.Attribute.Id);
				return CommandResult.Denied;
			}
			HandleBeforeExecute(ctx, commandMetadata);
			CommandException ex7 = default(CommandException);
			try
			{
				commandMetadata.Method.Invoke(obj4, array2);
			}
			catch (TargetInvocationException ex6) when (((Func<bool>)delegate
			{
				// Could not convert BlockContainer to single expression
				ex7 = ex6.InnerException as CommandException;
				return ex7 != null;
			}).Invoke())
			{
				ctx.Reply("<color=red>[error]</color> " + ex7.Message);
				return CommandResult.CommandError;
			}
			catch (Exception value3)
			{
				Log.Warning($"Hit unexpected exception executing command {commandMetadata.Attribute.Id}\n: {value3}");
				ctx.InternalError();
				return CommandResult.InternalError;
			}
			HandleAfterExecute(ctx, commandMetadata);
			return CommandResult.Success;
			static void HandleAfterExecute(ICommandContext ctx, CommandMetadata command)
			{
				Middlewares.ForEach(delegate(CommandMiddleware m)
				{
					m.AfterExecute(ctx, command.Attribute, command.Method);
				});
			}
			static void HandleBeforeExecute(ICommandContext ctx, CommandMetadata command)
			{
				Middlewares.ForEach(delegate(CommandMiddleware m)
				{
					m.BeforeExecute(ctx, command.Attribute, command.Method);
				});
			}
		}

		public static void UnregisterConverter(Type converter)
		{
			if (IsGenericConverterContext(converter) || IsSpecificConverterContext(converter))
			{
				Type[] genericTypeArguments = converter.BaseType.GenericTypeArguments;
				Type type = genericTypeArguments.FirstOrDefault();
				if (type == null)
				{
					Log.Warning("Could not resolve converter type " + converter.Name);
				}
				else if (_converters.ContainsKey(type))
				{
					_converters.Remove(type);
					Log.Info("Unregistered converter " + converter.Name);
				}
				else
				{
					Log.Warning("Call to UnregisterConverter for a converter that was not registered. Type: " + converter.Name);
				}
			}
		}

		internal static bool IsGenericConverterContext(Type rootType)
		{
			return rootType.BaseType.Name == typeof(CommandArgumentConverter<>).Name;
		}

		internal static bool IsSpecificConverterContext(Type rootType)
		{
			return rootType.BaseType.Name == typeof(CommandArgumentConverter<, >).Name;
		}

		public static void RegisterConverter(Type converter)
		{
			bool flag = IsGenericConverterContext(converter);
			bool flag2 = IsSpecificConverterContext(converter);
			if (!flag && !flag2)
			{
				return;
			}
			Log.Debug($"Trying to process {converter} as specifc={flag2} generic={flag}");
			object item = Activator.CreateInstance(converter);
			MethodInfo method = converter.GetMethod("Parse", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod);
			if (method == null)
			{
				Log.Error("Can't find TryParse that matches");
				return;
			}
			Type[] genericTypeArguments = converter.BaseType.GenericTypeArguments;
			Type type = genericTypeArguments.FirstOrDefault();
			if (type == null)
			{
				Log.Error("Can't determine generic base type to convert from. ");
				return;
			}
			Type item2 = typeof(ICommandContext);
			if (flag2)
			{
				if (genericTypeArguments.Length != 2 || !typeof(ICommandContext).IsAssignableFrom(genericTypeArguments[1]))
				{
					Log.Error("Can't determine generic base type to convert from.");
					return;
				}
				item2 = genericTypeArguments[1];
			}
			_converters.Add(type, (item, method, item2));
		}

		public static void RegisterAll()
		{
			RegisterAll(Assembly.GetCallingAssembly());
		}

		public static void RegisterAll(Assembly assembly)
		{
			Type[] types = assembly.GetTypes();
			Type[] array = types;
			foreach (Type converter in array)
			{
				RegisterConverter(converter);
			}
			Type[] array2 = types;
			foreach (Type type in array2)
			{
				RegisterCommandType(type);
			}
		}

		public static void RegisterCommandType(Type type)
		{
			CommandGroupAttribute customAttribute = type.GetCustomAttribute<CommandGroupAttribute>();
			Assembly assembly = type.Assembly;
			if (customAttribute != null)
			{
			}
			MethodInfo[] methods = type.GetMethods();
			ConstructorInfo customConstructor = (from c in type.GetConstructors()
				where c.GetParameters().Length == 1 && typeof(ICommandContext).IsAssignableFrom(c.GetParameters().SingleOrDefault()?.ParameterType)
				select c).FirstOrDefault();
			MethodInfo[] array = methods;
			foreach (MethodInfo method in array)
			{
				RegisterMethod(assembly, customAttribute, customConstructor, method);
			}
		}

		private static void RegisterMethod(Assembly assembly, CommandGroupAttribute groupAttr, ConstructorInfo customConstructor, MethodInfo method)
		{
			CommandAttribute customAttribute = method.GetCustomAttribute<CommandAttribute>();
			if (customAttribute == null)
			{
				return;
			}
			ParameterInfo[] parameters = method.GetParameters();
			ParameterInfo parameterInfo = parameters.FirstOrDefault();
			if (parameterInfo == null || parameterInfo.ParameterType is ICommandContext)
			{
				Log.Error("Method " + method.Name + " has no CommandContext as first argument");
				return;
			}
			ParameterInfo[] array = parameters.Skip(1).ToArray();
			if (!array.All(delegate(ParameterInfo param)
			{
				if (_converters.ContainsKey(param.ParameterType))
				{
					Log.Debug($"Method {method.Name} has a parameter of type {param.ParameterType.Name} which is registered as a converter");
					return true;
				}
				TypeConverter converter = TypeDescriptor.GetConverter(param.ParameterType);
				if (converter == null || !converter.CanConvertFrom(typeof(string)))
				{
					Log.Warning($"Parameter {param.Name} could not be converted, so {method.Name} will be ignored.");
					return false;
				}
				return true;
			}))
			{
				return;
			}
			Type constructorType = customConstructor?.GetParameters().Single().ParameterType;
			CommandMetadata commandMetadata = new CommandMetadata(customAttribute, method, customConstructor, array, parameterInfo.ParameterType, constructorType, groupAttr);
			string[] array2 = ((groupAttr != null) ? ((groupAttr.ShortHand != null) ? new string[2]
			{
				groupAttr.Name + " ",
				groupAttr.ShortHand + " "
			} : new string[1] { groupAttr.Name + " " }) : new string[1] { "" });
			string[] array3 = ((customAttribute.ShortHand != null) ? new string[2] { customAttribute.Name, customAttribute.ShortHand } : new string[1] { customAttribute.Name });
			string text = ".";
			List<string> list = new List<string>();
			string[] array4 = array2;
			foreach (string text2 in array4)
			{
				string[] array5 = array3;
				foreach (string text3 in array5)
				{
					string text4 = text + text2 + text3;
					_cache.AddCommand(text4, array, commandMetadata);
					list.Add(text4);
				}
			}
			AssemblyCommandMap.TryGetValue(assembly, out var value);
			if (value == null)
			{
				value = new Dictionary<CommandMetadata, List<string>>();
			}
			value[commandMetadata] = list;
			AssemblyCommandMap[assembly] = value;
		}

		public static void UnregisterAssembly()
		{
			UnregisterAssembly(Assembly.GetCallingAssembly());
		}

		public static void UnregisterAssembly(Assembly assembly)
		{
			foreach (TypeInfo definedType in assembly.DefinedTypes)
			{
				_cache.RemoveCommandsFromType(definedType);
				UnregisterConverter(definedType);
			}
			AssemblyCommandMap.Remove(assembly);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "gg.deca.VampireCommandFramework";

		public const string PLUGIN_NAME = "VampireCommandFramework";

		public const string PLUGIN_VERSION = "0.8.2";
	}
}
namespace VampireCommandFramework.Registry
{
	internal record CacheResult(CommandMetadata Command, string[] Args, IEnumerable<CommandMetadata> PartialMatches)
	{
		internal bool IsMatched => Command != null;

		internal bool HasPartial => PartialMatches?.Any() ?? false;

		[CompilerGenerated]
		protected virtual bool PrintMembers(StringBuilder builder)
		{
			RuntimeHelpers.EnsureSufficientExecutionStack();
			builder.Append("Command = ");
			builder.Append(Command);
			builder.Append(", Args = ");
			builder.Append(Args);
			builder.Append(", PartialMatches = ");
			builder.Append(PartialMatches);
			return true;
		}
	}
	internal class CommandCache
	{
		private static Dictionary<Type, HashSet<(string, int)>> _commandAssemblyMap = new Dictionary<Type, HashSet<(string, int)>>();

		private Dictionary<string, Dictionary<int, CommandMetadata>> _newCache = new Dictionary<string, Dictionary<int, CommandMetadata>>();

		internal void AddCommand(string key, ParameterInfo[] parameters, CommandMetadata command)
		{
			int num = parameters.Length;
			int num2 = parameters.Where((ParameterInfo p) => p.HasDefaultValue).Count();
			if (!_newCache.ContainsKey(key))
			{
				_newCache.Add(key, new Dictionary<int, CommandMetadata>());
			}
			for (int i = num - num2; i <= num; i++)
			{
				_newCache[key] = _newCache.GetValueOrDefault(key, new Dictionary<int, CommandMetadata>()) ?? new Dictionary<int, CommandMetadata>();
				if (_newCache[key].ContainsKey(i))
				{
					Log.Warning($"Command {key} has multiple commands with {i} parameters");
				}
				else
				{
					_newCache[key][i] = command;
					Type declaringType = command.Method.DeclaringType;
					HashSet<(string, int)> value;
					HashSet<(string, int)> hashSet = (_commandAssemblyMap.TryGetValue(declaringType, out value) ? value : new HashSet<(string, int)>());
					hashSet.Add((key, i));
					_commandAssemblyMap[declaringType] = hashSet;
				}
			}
		}

		internal CacheResult GetCommand(string rawInput)
		{
			List<CommandMetadata> list = new List<CommandMetadata>();
			foreach (var (text2, dictionary2) in _newCache)
			{
				if (rawInput.StartsWith(text2) && (rawInput.Length <= text2.Length || rawInput[text2.Length] == ' '))
				{
					string input = rawInput.Substring(text2.Length).Trim();
					string[] array = Utility.GetParts(input).ToArray();
					if (dictionary2.TryGetValue(array.Length, out var value))
					{
						return new CacheResult(value, array, null);
					}
					list.AddRange(dictionary2.Values);
				}
			}
			return new CacheResult(null, null, list.Distinct());
		}

		internal void RemoveCommandsFromType(Type t)
		{
			if (!_commandAssemblyMap.TryGetValue(t, out var value))
			{
				return;
			}
			foreach (var (key, key2) in value)
			{
				if (_newCache.TryGetValue(key, out var value2))
				{
					value2.Remove(key2);
				}
			}
			_commandAssemblyMap.Remove(t);
		}

		internal void Clear()
		{
			_newCache.Clear();
		}

		internal void Reset()
		{
			throw new NotImplementedException();
		}
	}
	internal record CommandMetadata(CommandAttribute Attribute, MethodInfo Method, ConstructorInfo Constructor, ParameterInfo[] Parameters, Type ContextType, Type ConstructorType, CommandGroupAttribute GroupAttribute);
}
namespace VampireCommandFramework.Common
{
	internal static class Log
	{
		internal static ManualLogSource Instance { get; set; }

		public static void Warning(string s)
		{
			LogOrConsole(s, delegate(string s)
			{
				Instance.LogWarning((object)s);
			});
		}

		public static void Error(string s)
		{
			LogOrConsole(s, delegate(string s)
			{
				Instance.LogError((object)s);
			});
		}

		public static void Debug(string s)
		{
			LogOrConsole(s, delegate(string s)
			{
				Instance.LogDebug((object)s);
			});
		}

		public static void Info(string s)
		{
			LogOrConsole(s, delegate(string s)
			{
				Instance.LogInfo((object)s);
			});
		}

		private static void LogOrConsole(string message, Action<string> instanceLog)
		{
			if (Instance == null)
			{
				Console.WriteLine(message);
			}
			else
			{
				instanceLog(message);
			}
		}
	}
	internal static class Utility
	{
		private const int MAX_MESSAGE_SIZE = 460;

		internal static IEnumerable<string> GetParts(string input)
		{
			string[] parts = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < parts.Length; i++)
			{
				if (parts[i].StartsWith('"'))
				{
					parts[i] = parts[i].TrimStart('"');
					int start = i++;
					for (; i < parts.Length; i++)
					{
						if (parts[i].EndsWith('"'))
						{
							parts[i] = parts[i].TrimEnd('"');
							yield return string.Join(" ", parts[start..(i + 1)]);
							break;
						}
					}
				}
				else
				{
					yield return parts[i];
				}
			}
		}

		internal static void InternalError(this ICommandContext ctx)
		{
			ctx.SysReply("An internal error has occurred.");
		}

		internal static void SysReply(this ICommandContext ctx, string input)
		{
			ctx.Reply("[vcf] ".Color(Color.Primary) + input.Color(Color.White));
		}

		internal static void SysPaginatedReply(this ICommandContext ctx, StringBuilder input)
		{
			ctx.SysPaginatedReply(input.ToString());
		}

		internal static void SysPaginatedReply(this ICommandContext ctx, string input)
		{
			if (input.Length <= 460)
			{
				ctx.SysReply(input);
				return;
			}
			string[] array = SplitIntoPages(input);
			string[] array2 = array;
			foreach (string text in array2)
			{
				string text2 = text.TrimEnd('\n', '\r', ' ');
				text2 = Environment.NewLine + text2;
				ctx.SysReply(text2);
			}
		}

		internal static string[] SplitIntoPages(string rawText, int pageSize = 460)
		{
			List<string> list = new List<string>();
			StringBuilder stringBuilder = new StringBuilder();
			string[] array = rawText.Split(Environment.NewLine);
			List<string> list2 = new List<string>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text.Length > pageSize)
				{
					string text2 = text;
					while (!string.IsNullOrWhiteSpace(text2) && text2.Length > pageSize)
					{
						int num = text2.LastIndexOf(' ', pageSize - (int)((double)pageSize * 0.05));
						if (num < 0)
						{
							num = Math.Min(pageSize - 1, text2.Length);
						}
						list2.Add(text2.Substring(0, num));
						text2 = text2.Substring(num);
					}
					list2.Add(text2);
				}
				else
				{
					list2.Add(text);
				}
			}
			foreach (string item in list2)
			{
				if (stringBuilder.Length + item.Length > pageSize)
				{
					list.Add(stringBuilder.ToString());
					stringBuilder.Clear();
				}
				stringBuilder.AppendLine(item);
			}
			if (stringBuilder.Length > 0)
			{
				list.Add(stringBuilder.ToString());
			}
			return list.ToArray();
		}
	}
}
namespace VampireCommandFramework.Breadstone
{
	[HarmonyPriority(200)]
	[HarmonyBefore(new string[] { "gg.deca.Bloodstone" })]
	[HarmonyPatch(typeof(ChatMessageSystem), "OnUpdate")]
	public static class ChatMessageSystem_Patch
	{
		public static bool Prefix(ChatMessageSystem __instance)
		{
			//IL_0002: 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_0017: 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_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_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_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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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_0062: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: 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_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_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: 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_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			_ = __instance.__ChatMessageJob_entityQuery;
			if (true)
			{
				EntityQuery _ChatMessageJob_entityQuery = __instance.__ChatMessageJob_entityQuery;
				Enumerator<Entity> enumerator = ((EntityQuery)(ref _ChatMessageJob_entityQuery)).ToEntityArray((Allocator)2).GetEnumerator();
				while (enumerator.MoveNext())
				{
					Entity current = enumerator.Current;
					EntityManager entityManager = ((ComponentSystemBase)__instance).EntityManager;
					FromCharacter componentData = ((EntityManager)(ref entityManager)).GetComponentData<FromCharacter>(current);
					entityManager = ((ComponentSystemBase)__instance).EntityManager;
					User componentData2 = ((EntityManager)(ref entityManager)).GetComponentData<User>(componentData.User);
					entityManager = ((ComponentSystemBase)__instance).EntityManager;
					ChatMessageEvent componentData3 = ((EntityManager)(ref entityManager)).GetComponentData<ChatMessageEvent>(current);
					string text = ((object)(FixedString512)(ref componentData3.MessageText)).ToString();
					VChatEvent e = new VChatEvent(componentData.User, componentData.Character, text, componentData3.MessageType, componentData2);
					ChatCommandContext ctx = new ChatCommandContext(e);
					CommandResult commandResult;
					try
					{
						commandResult = CommandRegistry.Handle(ctx, text);
					}
					catch (Exception value)
					{
						Log.Error($"Error while handling chat message {value}");
						continue;
					}
					if (commandResult == CommandResult.Success && text.StartsWith(".help-legacy", StringComparison.InvariantCulture))
					{
						componentData3.MessageText = FixedString512.op_Implicit(text.Replace("-legacy", string.Empty));
						entityManager = ((ComponentSystemBase)__instance).EntityManager;
						((EntityManager)(ref entityManager)).SetComponentData<ChatMessageEvent>(current, componentData3);
						return true;
					}
					if (commandResult != 0)
					{
						entityManager = VWorld.Server.EntityManager;
						((EntityManager)(ref entityManager)).DestroyEntity(current);
						return true;
					}
				}
			}
			return true;
		}
	}
	public class VChatEvent
	{
		public Entity SenderUserEntity { get; }

		public Entity SenderCharacterEntity { get; }

		public string Message { get; }

		public ChatMessageType Type { get; }

		public bool Cancelled { get; private set; } = false;


		public User User { get; }

		internal VChatEvent(Entity userEntity, Entity characterEntity, string message, ChatMessageType type, User user)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			SenderUserEntity = userEntity;
			SenderCharacterEntity = characterEntity;
			Message = message;
			Type = type;
			User = user;
		}

		public void Cancel()
		{
			Cancelled = true;
		}
	}
	internal static class VWorld
	{
		private static World _serverWorld;

		public static World Server
		{
			get
			{
				if (_serverWorld != null)
				{
					return _serverWorld;
				}
				_serverWorld = GetWorld("Server") ?? throw new Exception("There is no Server world (yet). Did you install a server mod on the client?");
				return _serverWorld;
			}
		}

		public static bool IsServer => Application.productName == "VRisingServer";

		public static void SendSystemMessage(this User user, string message)
		{
			//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)
			ServerChatUtils.SendSystemMessageToClient(Server.EntityManager, user, message);
		}

		private static World GetWorld(string name)
		{
			Enumerator<World> enumerator = World.s_AllWorlds.GetEnumerator();
			while (enumerator.MoveNext())
			{
				World current = enumerator.Current;
				if (current.Name == name)
				{
					_serverWorld = current;
					return current;
				}
			}
			return null;
		}
	}
}
namespace VampireCommandFramework.Basics
{
	[CommandGroup("config", null)]
	public class BepInExConfigCommands
	{
		[Command("dump", null, null, null, null, true)]
		public void DumpConfig(ICommandContext ctx, string pluginGuid)
		{
			var (guid, val2) = (KeyValuePair<string, PluginInfo>)(ref ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.FirstOrDefault((KeyValuePair<string, PluginInfo> x) => x.Value.Metadata.GUID.Contains(pluginGuid, StringComparison.InvariantCultureIgnoreCase)));
			if (val2 != null)
			{
				object instance = val2.Instance;
				BasePlugin val3 = (BasePlugin)((instance is BasePlugin) ? instance : null);
				if (val3 != null)
				{
					DumpConfig(ctx, guid, val3);
					return;
				}
			}
			foreach (KeyValuePair<string, PluginInfo> plugin in ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins)
			{
				ctx.SysReply("Found: " + plugin.Value.Metadata.GUID);
			}
			throw ctx.Error("Can not find that plugin");
		}

		[Command("set", null, null, null, null, true)]
		public void DumpConfig(ICommandContext ctx, string pluginGuid, string section, string key, string value)
		{
			var (text2, val2) = (KeyValuePair<string, PluginInfo>)(ref ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.FirstOrDefault((KeyValuePair<string, PluginInfo> x) => x.Value.Metadata.GUID.Contains(pluginGuid, StringComparison.InvariantCultureIgnoreCase)));
			if (val2 != null)
			{
				object instance = val2.Instance;
				BasePlugin val3 = (BasePlugin)((instance is BasePlugin) ? instance : null);
				if (val3 != null)
				{
					var (val6, val7) = (KeyValuePair<ConfigDefinition, ConfigEntryBase>)(ref ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)val3.Config).FirstOrDefault((KeyValuePair<ConfigDefinition, ConfigEntryBase> k) => k.Key.Section.Equals(section, StringComparison.InvariantCultureIgnoreCase) && k.Key.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)));
					if (val6 == (ConfigDefinition)null)
					{
						throw ctx.Error("Could not find property");
					}
					try
					{
						object value2 = TomlTypeConverter.ConvertToValue(value, val7.SettingType);
						val7.SetSerializedValue(value);
						if (!val3.Config.SaveOnConfigSet)
						{
							val3.Config.Save();
						}
						ctx.SysReply($"Set {val6.Key} = {value2}");
						return;
					}
					catch (Exception)
					{
						throw ctx.Error($"Can not convert {value} to {val7.SettingType}");
					}
				}
			}
			foreach (KeyValuePair<string, PluginInfo> plugin in ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins)
			{
				ctx.SysReply("Found: " + plugin.Value.Metadata.GUID);
			}
			throw ctx.Error("Can not find that plugin");
		}

		private static void DumpConfig(ICommandContext ctx, string guid, BasePlugin plugin)
		{
			ConfigFile config = plugin.Config;
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("Path: " + config.ConfigFilePath);
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(33, 2, stringBuilder2);
			handler.AppendLiteral("Dumping config for ");
			handler.AppendFormatted(guid.Color("#f0f"));
			handler.AppendLiteral(" with ");
			handler.AppendFormatted(((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config).Count());
			handler.AppendLiteral(" entries");
			stringBuilder3.AppendLine(ref handler);
			foreach (IGrouping<string, KeyValuePair<ConfigDefinition, ConfigEntryBase>> item in from k in (IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config
				group k by k.Key.Section into k
				orderby k.Key
				select k)
			{
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder4 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 1, stringBuilder2);
				handler.AppendLiteral("[");
				handler.AppendFormatted(item.Key);
				handler.AppendLiteral("]");
				stringBuilder4.AppendLine(ref handler);
				foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item2 in item)
				{
					item2.Deconstruct(out var key, out var value);
					ConfigDefinition val = key;
					ConfigEntryBase val2 = value;
					stringBuilder2 = stringBuilder;
					StringBuilder stringBuilder5 = stringBuilder2;
					handler = new StringBuilder.AppendInterpolatedStringHandler(3, 2, stringBuilder2);
					handler.AppendFormatted(val.Key.Color(Color.White));
					handler.AppendLiteral(" = ");
					handler.AppendFormatted(val2.BoxedValue.ToString().Color(Color.LightGrey));
					stringBuilder5.AppendLine(ref handler);
				}
			}
			ctx.SysPaginatedReply(stringBuilder);
		}
	}
	internal static class HelpCommands
	{
		private static readonly Regex _trailingLongDashRegex = new Regex("-\\d+$");

		[Command("help-legacy", null, null, "Passes through a .help command that is compatible with other mods that don't use VCF.", null, false)]
		public static void HelpLegacy(ICommandContext ctx, string search = null)
		{
			ctx.SysReply("Attempting compatible .help " + search + " for non-VCF mods.");
		}

		[Command("help", null, null, null, null, false)]
		public static void HelpCommand(ICommandContext ctx, string search = null)
		{
			if (!string.IsNullOrEmpty(search))
			{
				KeyValuePair<Assembly, Dictionary<CommandMetadata, List<string>>> assembly2 = CommandRegistry.AssemblyCommandMap.FirstOrDefault((KeyValuePair<Assembly, Dictionary<CommandMetadata, List<string>>> x) => x.Key.GetName().Name.StartsWith(search, StringComparison.OrdinalIgnoreCase));
				if (assembly2.Value != null)
				{
					StringBuilder stringBuilder = new StringBuilder();
					PrintAssemblyHelp(ctx, assembly2, stringBuilder);
					ctx.SysPaginatedReply(stringBuilder);
					return;
				}
				IEnumerable<KeyValuePair<CommandMetadata, List<string>>> source = CommandRegistry.AssemblyCommandMap.SelectMany((KeyValuePair<Assembly, Dictionary<CommandMetadata, List<string>>> x) => x.Value);
				IEnumerable<KeyValuePair<CommandMetadata, List<string>>> source2 = source.Where((KeyValuePair<CommandMetadata, List<string>> x) => string.Equals(x.Key.Attribute.Id, search, StringComparison.InvariantCultureIgnoreCase) || string.Equals(x.Key.Attribute.Name, search, StringComparison.InvariantCultureIgnoreCase) || x.Value.Contains<string>(search, StringComparer.InvariantCultureIgnoreCase));
				source2 = source2.Where((KeyValuePair<CommandMetadata, List<string>> kvp) => CommandRegistry.CanCommandExecute(ctx, kvp.Key));
				if (!source2.Any())
				{
					throw ctx.Error("Could not find any commands for \"" + search + "\"");
				}
				StringBuilder stringBuilder2 = new StringBuilder();
				foreach (KeyValuePair<CommandMetadata, List<string>> item2 in source2)
				{
					GenerateFullHelp(item2.Key, item2.Value, stringBuilder2);
				}
				ctx.SysPaginatedReply(stringBuilder2);
				return;
			}
			StringBuilder stringBuilder3 = new StringBuilder();
			StringBuilder stringBuilder4 = stringBuilder3;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(17, 1, stringBuilder4);
			handler.AppendLiteral("Listing ");
			handler.AppendFormatted(Format.B("all"));
			handler.AppendLiteral(" commands");
			stringBuilder4.AppendLine(ref handler);
			foreach (KeyValuePair<Assembly, Dictionary<CommandMetadata, List<string>>> item3 in CommandRegistry.AssemblyCommandMap)
			{
				PrintAssemblyHelp(ctx, item3, stringBuilder3);
			}
			ctx.SysPaginatedReply(stringBuilder3);
			static void GenerateFullHelp(CommandMetadata command, List<string> aliases, StringBuilder sb)
			{
				StringBuilder stringBuilder5 = sb;
				StringBuilder stringBuilder6 = stringBuilder5;
				StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(4, 3, stringBuilder5);
				handler2.AppendFormatted(Format.B(command.Attribute.Name));
				handler2.AppendLiteral(" (");
				handler2.AppendFormatted(command.Attribute.Id);
				handler2.AppendLiteral(") ");
				handler2.AppendFormatted(command.Attribute.Description);
				stringBuilder6.AppendLine(ref handler2);
				sb.AppendLine(PrintShortHelp(command));
				stringBuilder5 = sb;
				StringBuilder stringBuilder7 = stringBuilder5;
				handler2 = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder5);
				handler2.AppendFormatted(Format.B("Aliases").Underline());
				handler2.AppendLiteral(": ");
				handler2.AppendFormatted(string.Join(", ", aliases).Italic());
				stringBuilder7.AppendLine(ref handler2);
				IEnumerable<Type> enumerable = from t in command.Parameters.Select((ParameterInfo p) => p.ParameterType).Distinct()
					where t.IsEnum
					select t;
				foreach (Type item4 in enumerable)
				{
					stringBuilder5 = sb;
					StringBuilder stringBuilder8 = stringBuilder5;
					handler2 = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder5);
					handler2.AppendFormatted((item4.Name + " Values").Bold().Underline());
					handler2.AppendLiteral(": ");
					handler2.AppendFormatted(string.Join(", ", Enum.GetNames(item4)));
					stringBuilder8.AppendLine(ref handler2);
				}
				IEnumerable<Type> enumerable2 = from p in command.Parameters.Select((ParameterInfo p) => p.ParameterType).Distinct()
					where CommandRegistry._converters.ContainsKey(p)
					select p;
				foreach (Type item5 in enumerable2)
				{
					object item = CommandRegistry._converters[item5].instance;
					if (item is IConverterUsage)
					{
						IConverterUsage converterUsage = item as IConverterUsage;
						stringBuilder5 = sb;
						StringBuilder stringBuilder9 = stringBuilder5;
						handler2 = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder5);
						handler2.AppendFormatted((item5.Name ?? "").Bold());
						handler2.AppendLiteral(": ");
						handler2.AppendFormatted(converterUsage.Usage);
						stringBuilder9.AppendLine(ref handler2);
					}
				}
			}
			static void PrintAssemblyHelp(ICommandContext ctx, KeyValuePair<Assembly, Dictionary<CommandMetadata, List<string>>> assembly, StringBuilder sb)
			{
				string name = assembly.Key.GetName().Name;
				name = _trailingLongDashRegex.Replace(name, "");
				sb.AppendLine(("Commands from " + name.Medium().Color(Color.Primary) + ":").Underline());
				IEnumerable<CommandMetadata> enumerable3 = assembly.Value.Keys.Where((CommandMetadata c) => CommandRegistry.CanCommandExecute(ctx, c));
				foreach (CommandMetadata item6 in enumerable3)
				{
					sb.AppendLine(PrintShortHelp(item6));
				}
			}
		}

		internal static string PrintShortHelp(CommandMetadata command)
		{
			CommandAttribute attribute = command.Attribute;
			string text = (string.IsNullOrEmpty(command.GroupAttribute?.Name) ? string.Empty : (command.GroupAttribute.Name + " "));
			string input = text + attribute.Name;
			string orGenerateUsage = GetOrGenerateUsage(command);
			string text2 = ".".Color(Color.Yellow);
			string text3 = input.Color(Color.White);
			return text2 + text3 + orGenerateUsage;
		}

		internal static string GetOrGenerateUsage(CommandMetadata command)
		{
			string text = command.Attribute.Usage;
			if (string.IsNullOrWhiteSpace(text))
			{
				IEnumerable<string> values = command.Parameters.Select((ParameterInfo p) => (!p.HasDefaultValue) ? ("(" + p.Name + ")").Color(Color.LightGrey) : $"[{p.Name}={p.DefaultValue}]".Color(Color.DarkGreen));
				text = string.Join(" ", values);
			}
			return (!string.IsNullOrWhiteSpace(text)) ? (" " + text) : string.Empty;
		}
	}
}
namespace VCF.Core.Basics
{
	public class BasicAdminCheck : CommandMiddleware
	{
		public override bool CanExecute(ICommandContext ctx, CommandAttribute cmd, MethodInfo m)
		{
			return !cmd.AdminOnly || ctx.IsAdmin;
		}
	}
	public class RolePermissionMiddleware : CommandMiddleware
	{
		public override bool CanExecute(ICommandContext ctx, CommandAttribute command, MethodInfo method)
		{
			if (ctx.IsAdmin)
			{
				return true;
			}
			RoleRepository service = ctx.Services.GetService<RoleRepository>();
			return service.CanUserExecuteCommand(ctx.Name, command.Id);
		}
	}
	public interface IRoleStorage
	{
		HashSet<string> Roles { get; }

		void SetCommandPermission(string command, HashSet<string> roleIds);

		void SetUserRoles(string userId, HashSet<string> roleIds);

		HashSet<string> GetCommandPermission(string command);

		HashSet<string> GetUserRoles(string userId);
	}
	public class RoleRepository
	{
		private IRoleStorage _storage;

		public HashSet<string> Roles => _storage.Roles;

		public RoleRepository(IRoleStorage storage)
		{
			_storage = storage;
		}

		public void AddUserToRole(string user, string role)
		{
			HashSet<string> hashSet = _storage.GetUserRoles(user) ?? new HashSet<string>();
			hashSet.Add(role);
			_storage.SetUserRoles(user, hashSet);
		}

		public void RemoveUserFromRole(string user, string role)
		{
			HashSet<string> hashSet = _storage.GetUserRoles(user) ?? new HashSet<string>();
			hashSet.Remove(role);
			_storage.SetUserRoles(user, hashSet);
		}

		public void AddRoleToCommand(string command, string role)
		{
			HashSet<string> hashSet = _storage.GetCommandPermission(command) ?? new HashSet<string>();
			hashSet.Add(role);
			_storage.SetCommandPermission(command, hashSet);
		}

		public void RemoveRoleFromCommand(string command, string role)
		{
			HashSet<string> hashSet = _storage.GetCommandPermission(command) ?? new HashSet<string>();
			hashSet.Remove(role);
			_storage.SetCommandPermission(command, hashSet);
		}

		public HashSet<string> ListUserRoles(string user)
		{
			return _storage.GetUserRoles(user);
		}

		public HashSet<string> ListCommandRoles(string command)
		{
			return _storage.GetCommandPermission(command);
		}

		public bool CanUserExecuteCommand(string user, string command)
		{
			HashSet<string> commandPermission = _storage.GetCommandPermission(command);
			if (commandPermission == null)
			{
				return false;
			}
			HashSet<string> userRoles = _storage.GetUserRoles(user);
			if (userRoles == null)
			{
				return false;
			}
			return commandPermission.Any(userRoles.Contains);
		}
	}
	public class MemoryRoleStorage : IRoleStorage
	{
		private Dictionary<string, HashSet<string>> _userRoles = new Dictionary<string, HashSet<string>>();

		private Dictionary<string, HashSet<string>> _commandPermissions = new Dictionary<string, HashSet<string>>();

		public HashSet<string> Roles => new HashSet<string>();

		public void SetCommandPermission(string command, HashSet<string> roleIds)
		{
			foreach (string roleId in roleIds)
			{
				Roles.Add(roleId);
			}
			_commandPermissions[command] = roleIds;
		}

		public void SetUserRoles(string userId, HashSet<string> roleIds)
		{
			_userRoles[userId] = roleIds;
		}

		public HashSet<string> GetCommandPermission(string command)
		{
			return _commandPermissions.GetValueOrDefault(command);
		}

		public HashSet<string> GetUserRoles(string userId)
		{
			HashSet<string> value;
			return _userRoles.TryGetValue(userId, out value) ? value : new HashSet<string>();
		}
	}
	public class RoleCommands
	{
		public record struct Role(string Name);

		public record struct User(string Id);

		public record struct Command(string Id);

		public class RoleConverter : CommandArgumentConverter<Role>
		{
			public override Role Parse(ICommandContext ctx, string input)
			{
				RoleRepository requiredService = ctx.Services.GetRequiredService<RoleRepository>();
				if (requiredService.Roles.Contains(input))
				{
					return new Role(input);
				}
				throw ctx.Error("Invalid role");
			}
		}

		public class UserConverter : CommandArgumentConverter<User>
		{
			public override User Parse(ICommandContext ctx, string input)
			{
				return new User(input);
			}
		}

		private RoleRepository _roleRepository = new RoleRepository(new MemoryRoleStorage());

		[Command("create", null, null, null, null, false)]
		public void CreateRole(ICommandContext ctx, string name)
		{
			_roleRepository.Roles.Add(name);
		}

		[Command("allow", null, null, null, null, false)]
		public void AllowCommand(ICommandContext ctx, Role role, Command command)
		{
			_roleRepository.AddRoleToCommand(command.Id, role.Name);
		}

		[Command("deny", null, null, null, null, false)]
		public void DenyCommand(ICommandContext ctx, Role role, Command command)
		{
			_roleRepository.RemoveRoleFromCommand(command.Id, role.Name);
		}

		[Command("assign", null, null, null, null, false)]
		public void AssignUserToRole(ICommandContext ctx, User user, Role role)
		{
			_roleRepository.AddUserToRole(user.Id, role.Name);
		}

		[Command("unassign", null, null, null, null, false)]
		public void UnassignUserFromRole(ICommandContext ctx, User user, Role role)
		{
			_roleRepository.RemoveUserFromRole(user.Id, role.Name);
		}

		[Command("list", null, null, null, null, false)]
		public void ListRoles(ICommandContext ctx)
		{
			ctx.Reply("Roles: " + string.Join(", ", _roleRepository.Roles));
		}

		[Command("list user", null, null, null, null, false)]
		public void ListRoles(ICommandContext ctx, User user)
		{
			ctx.Reply("Roles: " + string.Join(", ", _roleRepository.ListUserRoles(user.Id)));
		}

		[Command("list command", null, null, null, null, false)]
		public void ListCommands(ICommandContext ctx, Command command)
		{
			ctx.Reply("Roles: " + string.Join(", ", _roleRepository.ListCommandRoles(command.Id)));
		}
	}
}