Decompiled source of WolfPack v1.1.0

WolfPack.dll

Decompiled 4 months ago
using System;
using System.Collections;
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.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("WolfPack")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WolfPack")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("498fed1f-d0d5-49ca-9e3f-19cf52d7d13a")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
internal sealed class ConfigurationManagerAttributes
{
	public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput);

	public bool? ShowRangeAsPercent;

	public Action<ConfigEntryBase> CustomDrawer;

	public CustomHotkeyDrawerFunc CustomHotkeyDrawer;

	public bool? Browsable;

	public string Category;

	public object DefaultValue;

	public bool? HideDefaultButton;

	public bool? HideSettingName;

	public string Description;

	public string DispName;

	public int? Order;

	public bool? ReadOnly;

	public bool? IsAdvanced;

	public Func<object, string> ObjToStr;

	public Func<string, object> StrToObj;
}
namespace neobotics.ValheimMods;

public class DelegatedConfigEntry<T> : DelegatedConfigEntryBase
{
	private ConfigEntry<T> _entry;

	private EventHandler rootHandler = null;

	private Action<object, EventArgs> clientDelegate;

	private Logging Log;

	public ConfigEntry<T> ConfigEntry
	{
		get
		{
			return _entry;
		}
		set
		{
			_entry = value;
			if (_entry != null && rootHandler != null)
			{
				_entry.SettingChanged += rootHandler;
			}
			Name = ((ConfigEntryBase)_entry).Definition.Key;
			Section = ((ConfigEntryBase)_entry).Definition.Section;
			ServerValue = ((ConfigEntryBase)_entry).GetSerializedValue();
			Log.Trace("Set " + Section + " " + Name + " to serialized value " + ServerValue);
		}
	}

	public T Value
	{
		get
		{
			return _entry.Value;
		}
		set
		{
			_entry.Value = value;
		}
	}

	public DelegatedConfigEntry(bool useServerDelegate = false)
		: this((Action<object, EventArgs>)null, useServerDelegate)
	{
	}

	public DelegatedConfigEntry(Action<object, EventArgs> delegateHandler, bool useServerDelegate = false)
	{
		Log = Logging.GetLogger();
		Log.Trace("DelegatedConfigEntry");
		if (delegateHandler != null)
		{
			clientDelegate = delegateHandler;
		}
		if (useServerDelegate)
		{
			Log.Trace("Configuring server delegate");
			rootHandler = delegate(object s, EventArgs e)
			{
				ServerDelegate(s, e);
			};
			ServerConfiguration.ServerDelegatedEntries.Add(this);
		}
		else if (clientDelegate != null)
		{
			rootHandler = delegate(object s, EventArgs e)
			{
				clientDelegate(s, e);
			};
		}
	}

	private void ServerDelegate(object sender, EventArgs args)
	{
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Expected O, but got Unknown
		Logging.GetLogger().Trace("ServerDelegate");
		_entry.SettingChanged -= rootHandler;
		ZNet instance = ZNet.instance;
		bool? flag = ((instance != null) ? new bool?(instance.IsServer()) : null);
		if (flag.HasValue)
		{
			if (flag == false && ServerConfiguration.Instance.ReceivedServerValues)
			{
				if (ServerValue != null)
				{
					((ConfigEntryBase)_entry).SetSerializedValue(ServerValue);
					Log.Debug("Setting " + Name + " to server value " + ServerValue);
				}
			}
			else if (flag == true)
			{
				ServerValue = ((ConfigEntryBase)_entry).GetSerializedValue();
				ServerConfiguration.Instance.SendConfigToAllClients(sender, (SettingChangedEventArgs)args);
			}
		}
		if (clientDelegate != null)
		{
			clientDelegate(sender, args);
		}
		_entry.SettingChanged += rootHandler;
	}

	public void EnableHandler(bool setActive)
	{
		if (setActive)
		{
			_entry.SettingChanged += rootHandler;
		}
		else
		{
			_entry.SettingChanged -= rootHandler;
		}
	}

	public bool IsKeyPressed()
	{
		//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_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: 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)
		if (ConfigEntry is ConfigEntry<KeyboardShortcut> val)
		{
			KeyboardShortcut value = val.Value;
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers)
			{
				if (!Input.GetKey(modifier))
				{
					return false;
				}
			}
			if (!Input.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey))
			{
				return false;
			}
			return true;
		}
		Log.Error("Keyboard read attempted on non-KeyboardShortcut config.");
		return false;
	}

	public bool IsKeyDown()
	{
		//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_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: 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)
		if (ConfigEntry is ConfigEntry<KeyboardShortcut> val)
		{
			KeyboardShortcut value = val.Value;
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers)
			{
				if (!Input.GetKey(modifier))
				{
					return false;
				}
			}
			if (!Input.GetKey(((KeyboardShortcut)(ref value)).MainKey))
			{
				return false;
			}
			return true;
		}
		Log.Error("Keyboard read attempted on non-KeyboardShortcut config.");
		return false;
	}

	public bool IsKeyReleased()
	{
		//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_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: 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)
		if (ConfigEntry is ConfigEntry<KeyboardShortcut> val)
		{
			KeyboardShortcut value = val.Value;
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers)
			{
				if (!Input.GetKeyUp(modifier))
				{
					return false;
				}
			}
			if (!Input.GetKeyUp(((KeyboardShortcut)(ref value)).MainKey))
			{
				return false;
			}
			return true;
		}
		Log.Error("Keyboard read attempted on non-KeyboardShortcut config.");
		return false;
	}
}
public class DelegatedConfigEntryBase
{
	public string Name = null;

	public string Section = null;

	public string ServerValue = null;
}
public class Logging
{
	public enum LogLevels
	{
		Critical,
		Error,
		Warning,
		Info,
		Debug,
		Trace
	}

	private static Logging _logger;

	public LogLevels LogLevel { get; set; }

	public string ModName { get; set; }

	private Logging(LogLevels level, string name)
	{
		LogLevel = level;
		ModName = name;
	}

	public static Logging GetLogger(LogLevels level, string name)
	{
		if (_logger == null)
		{
			_logger = new Logging(level, name);
		}
		return _logger;
	}

	public static Logging GetLogger()
	{
		if (_logger == null)
		{
			throw new NullReferenceException("Logger not initialized");
		}
		return _logger;
	}

	public void Trace(string msg)
	{
		if (LogLevel >= LogLevels.Trace)
		{
			Debug.Log((object)Message(msg));
		}
	}

	public void Debug(string msg)
	{
		if (LogLevel >= LogLevels.Debug)
		{
			Debug.Log((object)Message(msg));
		}
	}

	public void Info(string msg)
	{
		if (LogLevel >= LogLevels.Info)
		{
			Debug.Log((object)Message(msg));
		}
	}

	public void Warning(string msg)
	{
		if (LogLevel >= LogLevels.Warning)
		{
			Debug.LogWarning((object)Message(msg));
		}
	}

	public void Error(string msg)
	{
		if (LogLevel >= LogLevels.Error)
		{
			Debug.LogWarning((object)Message(msg));
		}
	}

	public void Error(Exception e)
	{
		Error(e, stackTrace: false);
	}

	public void Error(Exception e, bool stackTrace)
	{
		if (LogLevel >= LogLevels.Error)
		{
			Warning(Message(e.Message));
			if (stackTrace)
			{
				Warning(e.StackTrace);
			}
		}
	}

	public void Critical(Exception e)
	{
		if (LogLevel >= LogLevels.Critical)
		{
			Debug(Message(e.Message));
			Error(e.StackTrace);
		}
	}

	private string Message(string msg)
	{
		return ModName + ": " + msg;
	}

	public static void ChangeLogging(object s, EventArgs e)
	{
		SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null);
		GetLogger().Debug($"ChangeLog {val.ChangedSetting.Definition.Key} to {val.ChangedSetting.BoxedValue}");
		GetLogger().LogLevel = Cfg.debugLevel.Value;
	}
}
public class ServerConfiguration
{
	[HarmonyPatch(typeof(ZNet), "StopAll")]
	private static class ZNet_Shutdown_Patch
	{
		[HarmonyPrefix]
		private static void ZNet_StopAll_Prefix(ZNet __instance)
		{
			Log.Debug("ZNet_StopAll_Patch_Prefix");
			if (Instance != null)
			{
				Instance.ReceivedServerValues = false;
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	private static class ZNet_OnNewConnection_Patch
	{
		private static void Postfix(ZNet __instance, ZNetPeer peer)
		{
			Log.Debug("ZNet OnNewConnection postfix");
			if (!__instance.IsServer())
			{
				try
				{
					peer.m_rpc.Register<ZPackage>("ClientConfigReceiver." + GetPluginGuid(), (Action<ZRpc, ZPackage>)Instance.RPC_ClientConfigReceiver);
					Log.Debug("Player registered RPC_ClientConfigReceiver");
					return;
				}
				catch (Exception)
				{
					Log.Warning("Failed to register RPC");
					return;
				}
			}
			try
			{
				Instance.SendConfigToClient(peer);
			}
			catch (Exception)
			{
				Log.Warning("Error sending server configuration to client");
			}
		}
	}

	public static List<DelegatedConfigEntryBase> ServerDelegatedEntries = new List<DelegatedConfigEntryBase>();

	private static ConfigFile LocalConfig;

	private static BaseUnityPlugin Mod;

	private static string ConfigFileName;

	private static ServerConfiguration _instance;

	private static Logging Log;

	public bool IsSetup = false;

	public bool ReceivedServerValues = false;

	public FileSystemWatcher ConfigWatcher;

	private const string NOT_CONFIGURED = "ServerConfiguration not initialized. Setup first.";

	public static ServerConfiguration Instance
	{
		get
		{
			if (_instance == null)
			{
				_instance = new ServerConfiguration();
			}
			return _instance;
		}
	}

	private ServerConfiguration()
	{
	}

	public void Setup(ConfigFile config, BaseUnityPlugin modInstance)
	{
		LocalConfig = config;
		Log = Logging.GetLogger();
		Log.Trace("ServerConfiguration Setup");
		Mod = modInstance;
		ConfigFileName = Path.GetFileName(LocalConfig.ConfigFilePath);
		IsSetup = true;
	}

	public void CreateConfigWatcher()
	{
		ConfigWatcher = Utils.CreateFileWatcher(LocalConfig.ConfigFilePath, LoadConfig);
	}

	private void LoadConfig(object sender, FileSystemEventArgs e)
	{
		if (!File.Exists(LocalConfig.ConfigFilePath))
		{
			return;
		}
		try
		{
			Log.Debug($"Loading configuration {e.ChangeType}");
			LocalConfig.Reload();
		}
		catch
		{
			Log.Error("Error loading configuration file " + ConfigFileName);
		}
	}

	public static string GetPluginGuid()
	{
		return Mod.Info.Metadata.GUID;
	}

	public void RPC_ClientConfigReceiver(ZRpc zrpc, ZPackage package)
	{
		if (!Instance.IsSetup)
		{
			Log.Error("ServerConfiguration not initialized. Setup first.");
			return;
		}
		Log.Debug("ClientConfigReceiver");
		string section;
		string name;
		while (package.GetPos() < package.Size())
		{
			section = package.ReadString();
			name = package.ReadString();
			string text = package.ReadString();
			Log.Trace("Reading " + section + " " + name + " value " + text + " from ZPackage");
			DelegatedConfigEntryBase delegatedConfigEntryBase = ServerDelegatedEntries.Find((DelegatedConfigEntryBase e) => e.Name == name && e.Section == section);
			if (delegatedConfigEntryBase != null)
			{
				Log.Trace("Found DCEB on client and setting to server value " + text);
				delegatedConfigEntryBase.ServerValue = text;
			}
			ConfigEntryBase val = LocalConfig[section, name];
			if (val != null)
			{
				Log.Trace("Found local CEB and setting underlying config value " + text);
				val.SetSerializedValue(text);
			}
		}
		ReceivedServerValues = true;
	}

	internal void WriteConfigEntries(ZPackage zpkg)
	{
		foreach (DelegatedConfigEntryBase serverDelegatedEntry in ServerDelegatedEntries)
		{
			Log.Trace("Writing " + serverDelegatedEntry.Section + " " + serverDelegatedEntry.Name + " value " + serverDelegatedEntry.ServerValue + " to ZPackage");
			zpkg.Write(serverDelegatedEntry.Section);
			zpkg.Write(serverDelegatedEntry.Name);
			zpkg.Write(serverDelegatedEntry.ServerValue);
		}
	}

	internal void SendConfigToClient(ZNetPeer peer)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Expected O, but got Unknown
		if (!Instance.IsSetup)
		{
			Log.Error("ServerConfiguration not initialized. Setup first.");
			return;
		}
		Log.Debug("SendConfigToClient");
		ZPackage val = new ZPackage();
		WriteConfigEntries(val);
		peer.m_rpc.Invoke("ClientConfigReceiver." + GetPluginGuid(), new object[1] { val });
		Log.Trace("Invoked ClientConfigReceiver on peer");
	}

	public void SendConfigToAllClients(object o, SettingChangedEventArgs e)
	{
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Expected O, but got Unknown
		if (!IsSetup)
		{
			Log.Error("ServerConfiguration not initialized. Setup first.");
		}
		else if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && ZNet.instance.GetPeerConnections() > 0)
		{
			Log.Debug("SendConfigToAllClients");
			ZPackage zpkg = new ZPackage();
			WriteConfigEntries(zpkg);
			((MonoBehaviour)Mod).StartCoroutine(_instance.Co_BroadcastConfig(zpkg));
		}
	}

	private IEnumerator Co_BroadcastConfig(ZPackage zpkg)
	{
		Log.Debug("Co_BroadcastConfig");
		List<ZNetPeer> connectedPeers = ZNet.instance.GetConnectedPeers();
		foreach (ZNetPeer peer in connectedPeers)
		{
			if (peer != ZNet.instance.GetServerPeer())
			{
				peer.m_rpc.Invoke("ClientConfigReceiver." + GetPluginGuid(), new object[1] { zpkg });
				Log.Trace("Invoked ClientConfigReceiver on peer");
			}
			yield return null;
		}
	}
}
internal class Utils
{
	public static TEnum Guardrails<TEnum>(string value, TEnum enumDefault) where TEnum : struct
	{
		if (Enum.TryParse<TEnum>(value, ignoreCase: true, out var result))
		{
			return result;
		}
		return enumDefault;
	}

	public static int Guardrails(int value, int lbound, int ubound)
	{
		if (value < lbound)
		{
			return lbound;
		}
		if (value > ubound)
		{
			return ubound;
		}
		return value;
	}

	public static string truncate(string value, int maxChars)
	{
		if (value == null)
		{
			return null;
		}
		return (value.Length > maxChars) ? value.Substring(0, maxChars) : value;
	}

	public static void GetCharactersInRangeXZ(Vector3 point, float radius, List<Character> characters)
	{
		//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)
		float num = radius * radius;
		foreach (Character s_character in Character.s_characters)
		{
			if (DistanceSqrXZ(((Component)s_character).transform.position, point) < num)
			{
				characters.Add(s_character);
			}
		}
	}

	public static float DistanceSqr(Vector3 v0, Vector3 v1)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: 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)
		float num = v1.x - v0.x;
		float num2 = v1.y - v0.y;
		float num3 = v1.z - v0.z;
		return num * num + num2 * num2 + num3 * num3;
	}

	public static float DistanceSqrXZ(Vector3 v0, Vector3 v1)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		float num = v1.x - v0.x;
		float num2 = v1.z - v0.z;
		return num * num + num2 * num2;
	}

	public static float DistanceXZ(Vector3 v0, Vector3 v1)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		float num = v1.x - v0.x;
		float num2 = v1.z - v0.z;
		return Mathf.Sqrt(num * num + num2 * num2);
	}

	public static float Guardrails(float value, float lbound, float ubound)
	{
		if (value < lbound)
		{
			return lbound;
		}
		if (value > ubound)
		{
			return ubound;
		}
		return value;
	}

	public static string UnClonifiedName(string name)
	{
		if (name == null)
		{
			return null;
		}
		int num = name.IndexOf("(Clone)");
		if (num < 1)
		{
			return name;
		}
		return name.Substring(0, num);
	}

	public static void SetTranslator(int id, string idText)
	{
		MethodInfo method = typeof(Localization).GetMethod("AddWord", BindingFlags.Instance | BindingFlags.NonPublic);
		method.Invoke(Localization.instance, new object[2]
		{
			"skill_" + id,
			idText
		});
	}

	public static string GetTranslated(int id)
	{
		Logging.GetLogger().Debug(string.Format("Got translation for id {0} to {1}", id, Localization.instance.Localize("skill_" + id)));
		return Localization.instance.Localize("$skill_" + id);
	}

	public static string GetAssemblyPathedFile(string fileName)
	{
		Assembly executingAssembly = Assembly.GetExecutingAssembly();
		FileInfo fileInfo = new FileInfo(executingAssembly.Location);
		string text = fileInfo.DirectoryName.Replace('\\', '/');
		return text + "/" + fileName;
	}

	public static Sprite GetPrefabIcon(string prefabName)
	{
		Sprite result = null;
		GameObject prefab = GetPrefab(prefabName);
		ItemDrop val = default(ItemDrop);
		if ((Object)(object)prefab != (Object)null && prefab.TryGetComponent<ItemDrop>(ref val))
		{
			result = val.m_itemData.GetIcon();
		}
		return result;
	}

	public static Player GetPlayerByZDOID(ZDOID zid)
	{
		//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_0021: Unknown result type (might be due to invalid IL or missing references)
		foreach (Player allPlayer in Player.GetAllPlayers())
		{
			ZDOID zDOID = ((Character)allPlayer).GetZDOID();
			if (((ZDOID)(ref zDOID)).Equals(zid))
			{
				return allPlayer;
			}
		}
		return null;
	}

	public static Character GetCharacterByZDOID(string cid)
	{
		//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)
		foreach (Character allCharacter in Character.GetAllCharacters())
		{
			ZDOID zDOID = allCharacter.GetZDOID();
			if (((object)(ZDOID)(ref zDOID)).ToString().Equals(cid))
			{
				return allCharacter;
			}
		}
		return null;
	}

	public static Character GetCharacterByZDOID(ZDOID cid)
	{
		//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_0021: Unknown result type (might be due to invalid IL or missing references)
		foreach (Character allCharacter in Character.GetAllCharacters())
		{
			ZDOID zDOID = allCharacter.GetZDOID();
			if (((ZDOID)(ref zDOID)).Equals(cid))
			{
				return allCharacter;
			}
		}
		return null;
	}

	public static ZNetPeer GetPeerByRPC(ZRpc rpc)
	{
		foreach (ZNetPeer peer in ZNet.instance.GetPeers())
		{
			if (peer.m_rpc == rpc)
			{
				return peer;
			}
		}
		return null;
	}

	public static List<GameObject> GetGameObjectsOfType(Type t)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		List<GameObject> list = new List<GameObject>();
		Object[] array = Object.FindObjectsOfType(t);
		Object[] array2 = array;
		foreach (Object val in array2)
		{
			list.Add(((Component)val).gameObject);
		}
		return list;
	}

	public static GameObject GetClosestGameObjectOfType(Type t, Vector3 point, float radius)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		return GetGameObjectsOfTypeInRangeByDistance(t, point, radius)?[0];
	}

	public static List<GameObject> GetGameObjectsOfTypeInRangeByDistance(Type t, Vector3 point, float radius)
	{
		//IL_0008: 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)
		List<KeyValuePair<GameObject, float>> list = new List<KeyValuePair<GameObject, float>>();
		List<GameObject> gameObjectsOfTypeInRange = GetGameObjectsOfTypeInRange(t, point, radius);
		if (gameObjectsOfTypeInRange.Count > 0)
		{
			foreach (GameObject item in gameObjectsOfTypeInRange)
			{
				list.Add(new KeyValuePair<GameObject, float>(item, Vector3.Distance(item.transform.position, point)));
			}
			list.Sort((KeyValuePair<GameObject, float> pair1, KeyValuePair<GameObject, float> pair2) => pair1.Value.CompareTo(pair2.Value));
			return list.ConvertAll((KeyValuePair<GameObject, float> x) => x.Key);
		}
		return null;
	}

	public static List<GameObject> GetGameObjectsOfTypeInRange(Type t, Vector3 point, float radius)
	{
		//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)
		return (from x in GetGameObjectsOfType(t)
			where Vector3.Distance(x.transform.position, point) < radius
			select x).ToList();
	}

	public static float GetPointDepth(Vector3 p)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		return ZoneSystem.instance.m_waterLevel - GetSolidHeight(p);
	}

	public static List<string> GetDelimitedStringAsList(string delimitedString, char delimiter)
	{
		List<string> list = new List<string>();
		string[] array = delimitedString.Split(new char[1] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
		foreach (string text in array)
		{
			list.Add(text.Trim());
		}
		return list;
	}

	public static float GetSolidHeight(Vector3 p)
	{
		//IL_0022: 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_0055: Unknown result type (might be due to invalid IL or missing references)
		int solidRayMask = ZoneSystem.instance.m_solidRayMask;
		float result = 0f;
		p.y += 1000f;
		RaycastHit val = default(RaycastHit);
		if (Physics.Raycast(p, Vector3.down, ref val, 2000f, solidRayMask) && !Object.op_Implicit((Object)(object)((RaycastHit)(ref val)).collider.attachedRigidbody))
		{
			result = ((RaycastHit)(ref val)).point.y;
		}
		return result;
	}

	public static Transform FindChild(Transform aParent, string aName)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Expected O, but got Unknown
		foreach (Transform item in aParent)
		{
			Transform val = item;
			if (((Object)val).name == aName)
			{
				return val;
			}
			Transform val2 = FindChild(val, aName);
			if ((Object)(object)val2 != (Object)null)
			{
				return val2;
			}
		}
		return null;
	}

	public static Transform FindParent(Transform go)
	{
		while ((Object)(object)go.parent != (Object)null)
		{
			go = go.parent;
		}
		return go;
	}

	public static GameObject GetPrefab(int prefabHash)
	{
		return GetPrefabByHash(prefabHash);
	}

	public static GameObject GetPrefabByHash(int prefabHash)
	{
		GameObject val = ObjectDB.instance.GetItemPrefab(prefabHash);
		Logging logger = Logging.GetLogger();
		if ((Object)(object)val != (Object)null)
		{
			logger.Debug("Found prefab in ObjectDB");
		}
		else
		{
			ZNetScene instance = ZNetScene.instance;
			val = ((instance != null) ? instance.GetPrefab(prefabHash) : null);
			if ((Object)(object)val != (Object)null)
			{
				logger.Debug("Found prefab in Scene");
			}
		}
		return val;
	}

	public static GameObject GetPrefab(string prefabName)
	{
		GameObject val = ObjectDB.instance.GetItemPrefab(prefabName);
		Logging logger = Logging.GetLogger();
		if ((Object)(object)val != (Object)null)
		{
			logger.Debug("Found " + prefabName + " in ObjectDB");
		}
		else
		{
			ZNetScene instance = ZNetScene.instance;
			val = ((instance != null) ? instance.GetPrefab(prefabName) : null);
			if ((Object)(object)val != (Object)null)
			{
				logger.Debug("Found " + prefabName + " in Scene");
			}
		}
		return val;
	}

	public static string SerializeFromDictionary<K, V>(string delimp, string delimc, IDictionary<K, V> dict)
	{
		if (dict == null)
		{
			return null;
		}
		IEnumerable<string> values = dict.Select(delegate(KeyValuePair<K, V> kvp)
		{
			KeyValuePair<K, V> keyValuePair = kvp;
			string? obj = keyValuePair.Key?.ToString();
			string text = delimc;
			keyValuePair = kvp;
			return obj + text + keyValuePair.Value;
		});
		return string.Join(delimp, values);
	}

	public static void DeserializeToDictionary<K, V>(string serializedString, string delimp, string delimc, ref IDictionary<K, V> dict)
	{
		if (dict == null)
		{
			return;
		}
		dict.Clear();
		string[] separator = new string[1] { delimp };
		string[] separator2 = new string[1] { delimc };
		string[] array = serializedString.Split(separator, StringSplitOptions.RemoveEmptyEntries);
		string[] array2 = array;
		foreach (string text in array2)
		{
			string[] array3 = text.Split(separator2, StringSplitOptions.RemoveEmptyEntries);
			if (array3.Length == 2)
			{
				dict.Add(TypedValue<K>(array3[0]), TypedValue<V>(array3[1]));
			}
		}
	}

	public static FileSystemWatcher CreateFileWatcher(string fullPath, FileSystemEventHandler handler)
	{
		string fileName = Path.GetFileName(fullPath);
		string path = fullPath.Substring(0, fullPath.Length - fileName.Length);
		FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path, fileName);
		fileSystemWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime;
		fileSystemWatcher.Changed += handler;
		fileSystemWatcher.Created += handler;
		fileSystemWatcher.IncludeSubdirectories = false;
		fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
		fileSystemWatcher.EnableRaisingEvents = true;
		return fileSystemWatcher;
	}

	public static T TypedValue<T>(object a)
	{
		return (T)Convert.ChangeType(a, typeof(T));
	}

	public static float TimeAdjustedRamp(float maxValue, float duration, float elapsedTime, float pctFromStartRise, float pctFromEndFall)
	{
		float num = elapsedTime / duration;
		if (num <= pctFromStartRise)
		{
			return maxValue * (num / pctFromStartRise);
		}
		if (num >= 1f - pctFromEndFall)
		{
			return maxValue * ((1f - num) / pctFromEndFall);
		}
		return maxValue;
	}

	public static bool CopyComponentToGameObject(Component original, ref GameObject destination)
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Expected O, but got Unknown
		Logging logger = Logging.GetLogger();
		Type type = ((object)original).GetType();
		logger.Debug($"Original Type is {type}");
		GameObject obj = destination;
		logger.Debug("Destination GameObject " + ((obj != null) ? ((Object)obj).name : null));
		Component val = destination.GetComponent(type);
		if ((Object)(object)val == (Object)null)
		{
			val = destination.AddComponent(type);
		}
		if ((Object)(object)val == (Object)null)
		{
			logger.Debug("Destination component is null");
			return false;
		}
		Component val2 = (Component)Activator.CreateInstance(type);
		if ((Object)(object)val2 == (Object)null)
		{
			logger.Debug("Destination component is null");
			return false;
		}
		if ((Object)(object)val2 == (Object)null)
		{
			logger.Debug("Boxed component is null");
			return false;
		}
		FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		FieldInfo[] array = fields;
		foreach (FieldInfo fieldInfo in array)
		{
			fieldInfo.SetValue(val2, fieldInfo.GetValue(original));
		}
		val = val2;
		return true;
	}

	public static bool CopyObject(object original, object target)
	{
		Logging logger = Logging.GetLogger();
		Type type = original.GetType();
		Type type2 = target.GetType();
		object obj = null;
		if (type == null)
		{
			logger.Warning("Copy Object: Source object is null");
			obj = Activator.CreateInstance(type);
			return false;
		}
		if (type2 == null)
		{
			logger.Warning("Copy Object: Destination object is null");
			return false;
		}
		if (type2 != type)
		{
			logger.Warning("Copy Object: Source and destination components are different types");
			return false;
		}
		FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		FieldInfo[] array = fields;
		foreach (FieldInfo fieldInfo in array)
		{
			fieldInfo.SetValue(target, fieldInfo.GetValue(original));
		}
		return true;
	}
}
internal class Cfg
{
	public static DelegatedConfigEntry<Logging.LogLevels> debugLevel = null;

	public static DelegatedConfigEntry<KeyboardShortcut> packBehaviorKey = null;

	public static DelegatedConfigEntry<KeyboardShortcut> characterSelectorKey = null;

	public static DelegatedConfigEntry<KeyboardShortcut> packStayKey = null;

	public static DelegatedConfigEntry<string> trainableCreatures = null;

	public static DelegatedConfigEntry<int> detectionRange = null;

	public static ConfigEntry<bool> twoKeyAction = null;

	public static ConfigEntry<string> wolfCallSound = null;

	public static ConfigEntry<bool> useSound = null;

	public static ConfigEntry<int> minimumCreatureLevel = null;

	public static ConfigEntry<int> scrollDelay = null;

	public static ConfigEntry<bool> useMouseWheel = null;

	public static ConfigEntry<bool> logCreatures = null;

	public static ConfigEntry<string> notifications = null;

	public static ConfigEntry<int> strictObedience = null;

	public static ConfigEntry<string> lastCalledCreature = null;

	public static ConfigEntry<int> followRadius = null;

	private static KeyCode[] keyModifiers = (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 };

	private static KeyboardShortcut packBehaviorKeyDefault = new KeyboardShortcut((KeyCode)116, keyModifiers);

	private static KeyboardShortcut characterSelectorKeyDefault = new KeyboardShortcut((KeyCode)117, keyModifiers);

	private static KeyboardShortcut packStayKeyDefault = new KeyboardShortcut((KeyCode)121, keyModifiers);

	public static void BepInExConfig(BaseUnityPlugin _instance)
	{
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: 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
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Expected O, but got Unknown
		//IL_0184: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Expected O, but got Unknown
		//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b8: Expected O, but got Unknown
		//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02eb: Expected O, but got Unknown
		//IL_0313: Unknown result type (might be due to invalid IL or missing references)
		//IL_031d: Expected O, but got Unknown
		ServerConfiguration.Instance.Setup(_instance.Config, _instance);
		debugLevel = new DelegatedConfigEntry<Logging.LogLevels>(Logging.ChangeLogging);
		debugLevel.ConfigEntry = _instance.Config.Bind<Logging.LogLevels>("Utility", "LogLevel", Logging.LogLevels.Info, "Controls the level of information contained in the log");
		WolfPack.Log.LogLevel = debugLevel.Value;
		detectionRange = new DelegatedConfigEntry<int>(useServerDelegate: true);
		detectionRange.ConfigEntry = _instance.Config.Bind<int>("General", "DetectionRange", 50, new ConfigDescription("Tame creatures beyond this distance will not be affected. Min 1; Max 150", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 150), Array.Empty<object>()));
		trainableCreatures = new DelegatedConfigEntry<string>(WolfPack.ChangeTrainables, useServerDelegate: true);
		trainableCreatures.ConfigEntry = _instance.Config.Bind<string>("General", "TrainableCreatures", "wolf", "List of creatures that will be called to Follow or Stay, separated by commas, e.g., wolf,boar,lox. Accepts an asterisk (*) as the first and/or last character in a parital name to match every creature who's name starts* with, *ends with or *contains* that text.");
		followRadius = _instance.Config.Bind<int>("General", "FollowRadius", 10, new ConfigDescription("The radius in which following creatures will randomly distribute around the player to prevent 'bunching'", (AcceptableValueBase)(object)new AcceptableValueRange<int>(3, 30), Array.Empty<object>()));
		lastCalledCreature = _instance.Config.Bind<string>("Hidden", "LastCalledCreature", "", new ConfigDescription("The last creature type selected from the TrainableCreatures list", (AcceptableValueBase)null, new object[1]
		{
			new ConfigurationManagerAttributes
			{
				Browsable = false
			}
		}));
		packBehaviorKey = new DelegatedConfigEntry<KeyboardShortcut>();
		packBehaviorKey.ConfigEntry = _instance.Config.Bind<KeyboardShortcut>("General", "PackBehaviorShortcut", packBehaviorKeyDefault, "Keyboard shortcut toggles pack to Follow or Stay. If UseTwoKeys is set to true, only calls creatures to Follow.");
		packStayKey = new DelegatedConfigEntry<KeyboardShortcut>();
		packStayKey.ConfigEntry = _instance.Config.Bind<KeyboardShortcut>("General", "AlternateStayShortcut", packStayKeyDefault, "Keyboard shortcut to cause pack to Stay. Only used if UseTwoKeys is set to True");
		characterSelectorKey = new DelegatedConfigEntry<KeyboardShortcut>();
		characterSelectorKey.ConfigEntry = _instance.Config.Bind<KeyboardShortcut>("General", "CreatureSelectorShortcut", characterSelectorKeyDefault, "Keyboard shortcut to rotate through TrainableCreatures list. If UseMouseWheel is set to True, hold this key down and use the mouse wheel to change creatures. If UseMouseWheel is set to False, press this key to cycle between creatures");
		twoKeyAction = _instance.Config.Bind<bool>("General", "UseTwoKeys", false, "True or False to use separate keys for Follow and Stay. If set to True, will use the shortcut defined in AlternateStayShortcut to cause pack to Stay");
		minimumCreatureLevel = _instance.Config.Bind<int>("General", "MinimumCreatureLevel", 0, new ConfigDescription("Lowest level (in 'stars') of creature affected, e.g., 0 = no stars, 1 = 1 star, 2 = 2 stars. NOTE: applied to all creatures. Min 0; Max 2", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 2), Array.Empty<object>()));
		useMouseWheel = _instance.Config.Bind<bool>("General", "UseMouseWheel", true, "Set to True or False to use mouse wheel to switch between called creatures. When set to True, hold the CreatureSelectorShortcut while spinning the mouse wheel.");
		notifications = _instance.Config.Bind<string>("General", "Notifications", "Center", new ConfigDescription("Area where creature selection notifications appear. Can be 'TopLeft' or 'Center'. Default is Center", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "Center", "TopLeft" }), Array.Empty<object>()));
		strictObedience = _instance.Config.Bind<int>("General", "StrictObedience", 10, new ConfigDescription("Max distance 'Stayed' creatures will stray. Set to 0 for NO wandering. Default is 10. Min 0; Max 20", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
		scrollDelay = _instance.Config.Bind<int>("Utility", "MouseWheelLatency", 3, new ConfigDescription("Controls how sensitive the mouse wheel is when selecting creatures. Increase if too sensitive, decrease if too sluggish. Min 0; Max 10", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
		logCreatures = _instance.Config.Bind<bool>("Utility", "LogCreatureNames", false, "If set to True, will write all located creature names to the logger. Intended for temporary use to identify creature names to add to the TrainableCreatureList.");
		useSound = _instance.Config.Bind<bool>("Audio", "UseSound", true, "True or False to enable wolf follow sound effect");
		wolfCallSound = _instance.Config.Bind<string>("Audio", "PackCallSound", "Whistle.wav", "Audio file played when creatures are called to Follow. [Choose Whistle.wav, Horn1.wav, or Horn2.wav]");
		ServerConfiguration.Instance.CreateConfigWatcher();
	}
}
internal class CreatureMatcher
{
	private string mPrefix = "$enemy_";

	private string pSuffix = "(clone)";

	private static CreatureMatcher _instance;

	public int MatchType { get; private set; }

	public string Matching { get; private set; }

	public string Name { get; private set; }

	public string HoverName { get; private set; }

	public string PrefixName { get; private set; }

	public static CreatureMatcher Instance
	{
		get
		{
			if (_instance == null)
			{
				_instance = new CreatureMatcher();
			}
			return _instance;
		}
	}

	private CreatureMatcher()
	{
	}

	public void Config(string matchName)
	{
		MatchType = 1;
		Matching = matchName;
		if (matchName.Equals("*"))
		{
			MatchType = 3;
		}
		else if (matchName.StartsWith("*") && matchName.EndsWith("*") && matchName.Length > 2)
		{
			Matching = matchName.Substring(1).Substring(0, matchName.Length - 2);
			MatchType = 5;
		}
		else if (matchName.StartsWith("*") && matchName.Length > 1)
		{
			Matching = matchName.Substring(1);
			MatchType = 2;
		}
		else if (matchName.EndsWith("*") && matchName.Length > 1)
		{
			Matching = matchName.Substring(0, matchName.Length - 1);
			MatchType = 4;
		}
	}

	public bool Match(Character aCharacter)
	{
		Name = aCharacter.m_name.ToLower();
		HoverName = aCharacter.GetHoverName().ToLower();
		PrefixName = ((Object)((Component)aCharacter).gameObject).name.ToLower();
		if (Name.StartsWith(mPrefix))
		{
			Name = Name.Substring(mPrefix.Length);
		}
		if (PrefixName.EndsWith(pSuffix))
		{
			PrefixName = PrefixName.Substring(0, PrefixName.Length - pSuffix.Length);
		}
		List<string> list = new List<string> { Name, HoverName, PrefixName };
		bool flag = false;
		return MatchType switch
		{
			1 => list.Exists((string n) => n.Equals(Matching)), 
			2 => list.Exists((string n) => n.EndsWith(Matching)), 
			3 => true, 
			4 => list.Exists((string n) => n.StartsWith(Matching)), 
			5 => list.Exists((string n) => n.Contains(Matching)), 
			_ => false, 
		};
	}
}
internal class DebugUtils
{
	public static void ObjectInspector(object o)
	{
		if (o == null)
		{
			Debug.Log((object)"Object is null");
			return;
		}
		BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
		Type type = o.GetType();
		Debug.Log((object)(o.ToString() + " Type " + type.Name));
		PropertyInfo[] properties = type.GetProperties(bindingAttr);
		PropertyInfo[] array = properties;
		foreach (PropertyInfo propertyInfo in array)
		{
			Debug.Log((object)$"{type.Name}.{propertyInfo.Name} = {propertyInfo.GetValue(o)}");
		}
		FieldInfo[] fields = type.GetFields(bindingAttr);
		FieldInfo[] array2 = fields;
		foreach (FieldInfo field in array2)
		{
			FieldPrinter(o, type, field);
		}
	}

	public static void MethodInspector(object o)
	{
		if (o == null)
		{
			Debug.Log((object)"Object is null");
			return;
		}
		BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
		Type type = o.GetType();
		Debug.Log((object)(o.ToString() + " Type " + type.Name));
		MethodInfo[] methods = type.GetMethods(bindingAttr);
		foreach (MethodInfo methodInfo in methods)
		{
			ParameterInfo[] parameters = methodInfo.GetParameters();
			string arg = string.Join(", ", (from x in methodInfo.GetParameters()
				select x.ParameterType?.ToString() + " " + x.Name).ToArray());
			Debug.Log((object)$"{methodInfo.ReturnType} {methodInfo.Name} ({arg})");
		}
	}

	private static void ItemDataInspector(ItemData item)
	{
		ObjectInspector(item);
		ObjectInspector(item.m_shared);
	}

	private static void FieldPrinter(object o, Type t, FieldInfo field)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Expected O, but got Unknown
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Expected O, but got Unknown
		try
		{
			if (field.FieldType == typeof(ItemData))
			{
				ItemData val = (ItemData)field.GetValue(o);
				if (val != null)
				{
					ItemDataInspector(val);
				}
				else
				{
					Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]");
				}
			}
			else if (field.FieldType == typeof(Transform))
			{
				Transform val2 = (Transform)field.GetValue(o);
				if ((Object)(object)val2 != (Object)null)
				{
					Debug.Log((object)("\tTransform.parent = " + ((Object)val2.parent).name));
				}
				else
				{
					Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]");
				}
			}
			else if (field.FieldType == typeof(EffectList))
			{
				EffectList val3 = (EffectList)field.GetValue(o);
				if (val3 != null)
				{
					Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)}:");
					EffectData[] effectPrefabs = val3.m_effectPrefabs;
					foreach (EffectData val4 in effectPrefabs)
					{
						Debug.Log((object)("\tEffectData.m_prefab = " + ((Object)val4.m_prefab).name));
					}
				}
				else
				{
					Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]");
				}
			}
			else
			{
				Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)}");
			}
		}
		catch (Exception)
		{
			Debug.Log((object)("Exception accessing " + t?.Name + "." + field?.Name));
		}
	}

	public static void GameObjectInspector(GameObject go)
	{
		Debug.Log((object)("\n\nInspecting GameObject " + ((Object)go).name));
		ObjectInspector(go);
		Component[] componentsInChildren = go.GetComponentsInChildren<Component>();
		Component[] array = componentsInChildren;
		foreach (Component val in array)
		{
			string obj = ((val != null) ? ((Object)val).name : null);
			object obj2;
			if (val == null)
			{
				obj2 = null;
			}
			else
			{
				Transform transform = val.transform;
				if (transform == null)
				{
					obj2 = null;
				}
				else
				{
					Transform parent = transform.parent;
					obj2 = ((parent != null) ? ((Object)parent).name : null);
				}
			}
			Debug.Log((object)("\n\nInspecting Component " + obj + " with parent " + (string?)obj2));
			ObjectInspector(val);
		}
	}

	public static void ComponentInspector(Component c)
	{
		Debug.Log((object)("\n\nInspecting Component " + ((Object)c).name));
		ObjectInspector(c);
	}

	public static void EffectsInspector(EffectList e)
	{
		EffectData[] effectPrefabs = e.m_effectPrefabs;
		Debug.Log((object)$"Effect list has effects {e.HasEffects()} count {effectPrefabs.Length}");
		EffectData[] array = effectPrefabs;
		foreach (EffectData val in array)
		{
			Debug.Log((object)$"Effect Data {val} prefab name {((Object)val.m_prefab).name} prefab GameObject name {((Object)val.m_prefab.gameObject).name}");
		}
	}

	public static void PrintInventory()
	{
		Player localPlayer = Player.m_localPlayer;
		Inventory inventory = ((Humanoid)localPlayer).GetInventory();
		foreach (ItemData allItem in inventory.GetAllItems())
		{
			Debug.Log((object)allItem.m_shared.m_name);
		}
	}

	public static void PrintAllObjects()
	{
		ZNetScene.instance.m_prefabs.ForEach(delegate(GameObject x)
		{
			Debug.Log((object)("GameObject " + ((Object)x).name));
		});
	}

	public static void PrintAllCharacters()
	{
		Character.GetAllCharacters().ForEach(delegate(Character x)
		{
			Debug.Log((object)("Character " + ((Object)x).name));
		});
	}
}
[BepInPlugin("neobotics.valheim_mod.wolfpack", "Wolfpack", "1.1.0")]
[BepInProcess("valheim.exe")]
[BepInProcess("valheim_server.exe")]
public class WolfPack : BaseUnityPlugin
{
	[HarmonyPatch(typeof(BaseAI), "Follow")]
	private static class BaseAI_Follow_Patch
	{
		[HarmonyPrefix]
		private static bool BaseAI_Follow_Prefix(BaseAI __instance, GameObject go, float dt)
		{
			//IL_0037: 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_0075: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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_00b6: 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_00d5: Unknown result type (might be due to invalid IL or missing references)
			Log.Debug("BaseAI_Follow_Patch_Prefix");
			Player val = default(Player);
			if (__instance.m_character.m_tamed && go.TryGetComponent<Player>(ref val))
			{
				float num = Vector3.Distance(go.transform.position, ((Component)__instance.m_character).transform.position);
				bool flag = num > 10f;
				if (num < 3f)
				{
					__instance.StopMoving();
				}
				else
				{
					Vector2 val2 = Random.insideUnitCircle * (float)Cfg.followRadius.Value;
					Vector3 val3 = default(Vector3);
					((Vector3)(ref val3))..ctor(val2.x + go.transform.position.x, go.transform.position.y, val2.y + go.transform.position.z);
					__instance.MoveTo(dt, val3, 0f, flag);
				}
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
	private static class Camera_Update_Patch
	{
		private static bool keyWasDown;

		private static float zoomSensitivity;

		private static void Prefix(GameCamera __instance, float dt, ref float ___m_zoomSens)
		{
			//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)
			if (Cfg.useMouseWheel.Value)
			{
				KeyboardShortcut value = Cfg.characterSelectorKey.Value;
				if (((KeyboardShortcut)(ref value)).IsPressed())
				{
					if (!keyWasDown)
					{
						zoomSensitivity = ___m_zoomSens;
						___m_zoomSens = 0f;
						keyWasDown = true;
					}
					return;
				}
			}
			if (keyWasDown)
			{
				___m_zoomSens = zoomSensitivity;
				keyWasDown = false;
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	private class PatchOnNewConnection_Patch
	{
		private static void Postfix(ZNetPeer peer, ZNet __instance)
		{
			if (Log.LogLevel >= Logging.LogLevels.Debug)
			{
				Log.Debug("OnNewConnection_Patch");
			}
			if (__instance.IsServer() && serverIsRegistered)
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.Register<ZDOID, string>("WolfCall", (Action<long, ZDOID, string>)RPC_WolfCall);
				if (__instance.IsServer())
				{
					serverIsRegistered = true;
				}
			}
			catch (Exception)
			{
				Log.Warning("Attempt to re-register RPCs");
			}
		}
	}

	[HarmonyPatch(typeof(Player), "Update")]
	public class Player_Update_Patch
	{
		private static void Prefix(Player __instance)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance == (Object)(object)Player.m_localPlayer))
			{
				return;
			}
			if (!Cfg.useMouseWheel.Value)
			{
				if (Cfg.characterSelectorKey.IsKeyPressed() && trainables.Count > 0)
				{
					currentCreatureIndex = ++currentCreatureIndex % trainables.Count;
					NotifyCreatureChange(__instance);
				}
			}
			else if (Cfg.characterSelectorKey.IsKeyDown())
			{
				float y = Input.mouseScrollDelta.y;
				Log.Debug($"Character selector key pressed with mouse wheel enabled: mouse scroll delta:{y}");
				if (y != 0f)
				{
					if (y > 0f && lastMouseWheelDelta <= 0f)
					{
						currentCreatureIndex = ((currentCreatureIndex < trainables.Count - 1) ? (++currentCreatureIndex) : 0);
					}
					if (y < 0f && lastMouseWheelDelta >= 0f)
					{
						currentCreatureIndex = ((currentCreatureIndex <= 0) ? (trainables.Count - 1) : (--currentCreatureIndex));
					}
					lastMouseWheelDelta = y;
					frameDelay = Cfg.scrollDelay.Value;
					NotifyCreatureChange(__instance);
				}
				else if (frameDelay > 0)
				{
					frameDelay--;
				}
				else
				{
					lastMouseWheelDelta = 0f;
				}
			}
			bool flag = false;
			if (Cfg.twoKeyAction.Value)
			{
				bool flag2 = Cfg.packBehaviorKey.IsKeyPressed();
				bool flag3 = Cfg.packStayKey.IsKeyPressed();
				if (flag2)
				{
					packFollow = true;
				}
				else if (flag3)
				{
					packFollow = false;
				}
				flag = flag2 || flag3;
			}
			else
			{
				flag = Cfg.packBehaviorKey.IsKeyPressed();
			}
			if (!flag)
			{
				return;
			}
			try
			{
				if (Log.LogLevel >= Logging.LogLevels.Debug)
				{
					Log.Debug("Player_Update_Patch.Prefix");
					Log.Trace($"Keypress Player ID {__instance.GetPlayerID()} Name {__instance.GetPlayerName()} ZDOID {((Character)__instance).GetZDOID()}");
				}
				Local_CommandWolves(__instance, trainables[currentCreatureIndex], packFollow);
				((Character)__instance).Message((MessageType)2, packFollow ? (creatureMessage + " follow you") : (creatureMessage + " stay"), 0, (Sprite)null);
			}
			catch (Exception e)
			{
				Log.Error(e, stackTrace: false);
			}
			if (!Cfg.twoKeyAction.Value)
			{
				packFollow = !packFollow;
			}
		}
	}

	public static string Mod = "WolfPack";

	public static Logging Log;

	public static string followZDOstring = "follow";

	private readonly Harmony harmony = new Harmony("neobotics.valheim_mod.wolfpack");

	private static WolfPack _modinstance;

	private static volatile bool packFollow = true;

	private static string creatureMessage = null;

	private static int currentCreatureIndex = 0;

	private static List<string> trainables = new List<string>();

	private static float lastMouseWheelDelta = 0f;

	private static int frameDelay = 0;

	private static Random rand = new Random();

	private static List<string> RPCs = new List<string>();

	private static bool serverIsRegistered = false;

	public static Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>();

	private static Dictionary<string, MessageType> notifyLocation = new Dictionary<string, MessageType>
	{
		{
			"topleft",
			(MessageType)1
		},
		{
			"center",
			(MessageType)2
		}
	};

	public static WolfPack Instance => _modinstance;

	private void Awake()
	{
		_modinstance = this;
		harmony.PatchAll(Assembly.GetExecutingAssembly());
		ConfigureMod();
		Log.Debug("awake");
	}

	private void OnDestroy()
	{
		harmony.UnpatchSelf();
	}

	private void ConfigureMod()
	{
		Log = Logging.GetLogger(Logging.LogLevels.Info, Mod);
		Cfg.BepInExConfig((BaseUnityPlugin)(object)_modinstance);
		LoadTrainableCreatureList(Cfg.trainableCreatures.Value);
		if (Cfg.useSound.Value)
		{
			LoadAudioResources();
		}
	}

	internal static void ChangeTrainables(object s, EventArgs e)
	{
		SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null);
		Log.Debug($"ChangeInt {val.ChangedSetting.Definition.Key} to {val.ChangedSetting.BoxedValue}");
		_modinstance.LoadTrainableCreatureList(Cfg.trainableCreatures.Value);
	}

	private static bool OkToKey(Player player)
	{
		return !((Character)player).InPlaceMode() && !Chat.instance.HasFocus() && !Console.IsVisible() && (Object)(object)TextViewer.instance != (Object)null && !TextViewer.instance.IsVisible() && !((Character)player).InCutscene() && !GameCamera.InFreeFly() && !Minimap.IsOpen() && !Menu.IsVisible() && !TextInput.IsVisible() && !InventoryGui.IsVisible() && !StoreGui.IsVisible();
	}

	private static void KeypressEntryPoint()
	{
		Player localPlayer = Player.m_localPlayer;
		Log.Debug("KeypressEntryPoint");
	}

	private void LoadAudioResources()
	{
		Assembly executingAssembly = Assembly.GetExecutingAssembly();
		FileInfo fileInfo = new FileInfo(executingAssembly.Location);
		string[] array = new string[0];
		List<string> list = new List<string> { "*.wav", "*.mp3", "*.wma" };
		string directoryName = fileInfo.DirectoryName;
		audioClips.Clear();
		foreach (string item in list)
		{
			array = CollectionExtensions.AddRangeToArray<string>(array, Directory.GetFiles(fileInfo.DirectoryName, item, SearchOption.TopDirectoryOnly));
		}
		((MonoBehaviour)this).StartCoroutine(Co_LoadAudio(directoryName, array));
	}

	private IEnumerator Co_LoadAudio(string filePath, string[] audioFiles)
	{
		WWW URL = null;
		for (int f = 0; f < audioFiles.Length; f++)
		{
			string clipUri = new Uri(audioFiles[f]).AbsoluteUri;
			string clipName = audioFiles[f].Substring(filePath.Length + 1);
			Log.Debug("Loading audio clip " + clipName);
			try
			{
				URL = new WWW(clipUri);
			}
			catch (Exception e2)
			{
				Log.Warning("Can't find audio resource: " + e2.Message);
			}
			yield return URL;
			if (URL != null)
			{
				try
				{
					AudioClip anAudioClip = URL.GetAudioClip(true, false);
					audioClips.Add(clipName.ToLower(), anAudioClip);
				}
				catch (Exception ex)
				{
					Exception e = ex;
					Log.Warning("Failed to load clip " + clipUri + ": " + e.Message);
				}
			}
			else
			{
				Log.Warning("Failed to get URL for " + clipUri);
			}
		}
	}

	private void LoadTrainableCreatureList(string trainable)
	{
		trainables.Clear();
		string[] array = trainable.ToLower().Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
		string empty = string.Empty;
		string[] array2 = array;
		foreach (string text in array2)
		{
			string item = text.Trim();
			trainables.Add(item);
		}
		if (!Utility.IsNullOrWhiteSpace(Cfg.lastCalledCreature.Value) && trainables.Contains(Cfg.lastCalledCreature.Value))
		{
			empty = Cfg.lastCalledCreature.Value;
			currentCreatureIndex = trainables.IndexOf(empty);
		}
		else
		{
			empty = trainables[0];
		}
		creatureMessage = WolfUtils.Pluralizer(empty);
	}

	private static void Local_CommandWolves(Player aPlayer, string matchName, bool commandIsFollow)
	{
		//IL_002d: 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_0085: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		Log.Debug("Local_CommandWolves");
		Log.Trace($"Command by {aPlayer.GetPlayerName()} ZDOID {((Character)aPlayer).GetZDOID()} on {matchName} toFollow {commandIsFollow}");
		int nrOfPlayers = ZNet.instance.GetNrOfPlayers();
		if (commandIsFollow)
		{
			if (nrOfPlayers == 1)
			{
				WolfAudio.CallOfTheWild(aPlayer, Cfg.wolfCallSound.Value);
			}
			else
			{
				ZDOID zDOID = ((Character)aPlayer).GetZDOID();
				bool flag = true;
				Log.Debug($"Player {aPlayer.GetPlayerName()} {zDOID} invoking remote WolfCall {Cfg.wolfCallSound.Value}");
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "WolfCall", new object[2]
				{
					zDOID,
					Cfg.wolfCallSound.Value
				});
			}
		}
		List<Character> list = new List<Character>();
		List<Character> list2 = new List<Character>();
		Character.GetCharactersInRange(((Component)aPlayer).transform.position, (float)Cfg.detectionRange.Value, list);
		CreatureMatcher instance = CreatureMatcher.Instance;
		instance.Config(matchName);
		foreach (Character item in list)
		{
			if (!item.IsPlayer())
			{
				bool flag2 = instance.Match(item);
				if (Cfg.logCreatures.Value)
				{
					Log.Info($"Found {instance.Name} Named {instance.HoverName} Prefab {instance.PrefixName}. Matching {instance.Matching} (match type {instance.MatchType}): {flag2}");
				}
				if (flag2 && item.GetLevel() >= Cfg.minimumCreatureLevel.Value + 1 && item.IsTamed())
				{
					list2.Add(item);
				}
			}
		}
		((MonoBehaviour)_modinstance).StartCoroutine(_modinstance.Co_CommandWolves(aPlayer, commandIsFollow, list2));
	}

	private IEnumerator Co_CommandWolves(Player aPlayer, bool commandIsFollow, List<Character> selectedCreatures)
	{
		Log.Debug("Co_CommandWolves");
		foreach (Character aCreature in selectedCreatures)
		{
			UpdateWolfAI(aPlayer, aCreature, commandIsFollow);
			yield return null;
		}
	}

	private static void UpdateWolfAI(Player aPlayer, Character aCharacter, bool commandIsFollow)
	{
		GameObject gameObject = ((Component)aPlayer).gameObject;
		Log.Debug("UpdateWolfAI");
		try
		{
			MonsterAI val = default(MonsterAI);
			if (!((Component)aCharacter).gameObject.TryGetComponent<MonsterAI>(ref val))
			{
				Log.Warning("Can't get pet AI");
				return;
			}
			Tameable val2 = default(Tameable);
			if (!((Component)aCharacter).gameObject.TryGetComponent<Tameable>(ref val2))
			{
				Log.Warning("Can't get tameable pet");
				return;
			}
			ZNetView val3 = default(ZNetView);
			if (!((Component)aCharacter).gameObject.TryGetComponent<ZNetView>(ref val3))
			{
				Log.Warning("Can't get view for pet");
				return;
			}
			ZDO zDO = val3.GetZDO();
			string @string = zDO.GetString(followZDOstring, "");
			Log.Debug($"Current player: {aPlayer.GetPlayerID()} wolf owned by: {zDO.GetOwner()} wolf following {@string}");
			if (commandIsFollow)
			{
				Log.Trace("Follow");
				if (Utility.IsNullOrWhiteSpace(@string))
				{
					Log.Debug("Commanding creature to follow " + aPlayer.GetPlayerName());
					val2.Command((Humanoid)(object)aPlayer, false);
					((BaseAI)val).m_randomMoveRange = Cfg.strictObedience.Value;
				}
				else
				{
					Log.Debug("Creature already following " + @string + ". Follow cancelled.");
				}
				return;
			}
			Log.Trace("Stay");
			if (@string == aPlayer.GetPlayerName())
			{
				Log.Debug("Commanding creature following " + aPlayer.GetPlayerName() + " to stay");
				float randomMoveInterval = ((BaseAI)val).m_randomMoveInterval;
				((BaseAI)val).m_randomMoveInterval = (float)rand.NextDouble() * randomMoveInterval + 3f;
				((BaseAI)val).ResetRandomMovement();
				((BaseAI)val).m_randomMoveInterval = randomMoveInterval;
				val2.Command((Humanoid)(object)aPlayer, false);
			}
			else
			{
				Log.Debug("Creature already following " + @string + ". Stay cancelled.");
			}
		}
		catch (Exception ex)
		{
			Log.Warning("Error updating pet AI: " + ex.Message);
		}
	}

	private static void NotifyCreatureChange(Player aPlayer)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		creatureMessage = WolfUtils.Pluralizer(trainables[currentCreatureIndex]);
		((Character)aPlayer).Message(notifyLocation[Cfg.notifications.Value.ToLower()], Mod + " is calling " + creatureMessage, 0, (Sprite)null);
		Cfg.lastCalledCreature.Value = trainables[currentCreatureIndex];
	}

	public static void RPC_WolfCall(long sender, ZDOID zPlayer, string clipName)
	{
		//IL_005e: 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 (ZNet.instance.IsDedicated())
		{
			return;
		}
		try
		{
			if (Log.LogLevel >= Logging.LogLevels.Debug)
			{
				Log.Debug("RPC_WolfCall");
				Log.Trace($"Peer {sender} sent WolfCall from ZDOID {zPlayer}");
			}
			Player playerByZDOID = Utils.GetPlayerByZDOID(zPlayer);
			if ((Object)(object)playerByZDOID != (Object)null)
			{
				WolfAudio.CallOfTheWild(playerByZDOID, Player.m_localPlayer, clipName);
			}
			else
			{
				Log.Warning("WolfCall player is null");
			}
		}
		catch (Exception e)
		{
			Log.Error(e, stackTrace: false);
		}
	}
}
internal class WolfAudio
{
	public static void CallOfTheWild(Player sourcePlayer, string clipName)
	{
		//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_0012: 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)
		Vector3 position = ((Component)sourcePlayer).gameObject.transform.position;
		CallOfTheWild(position, position, clipName);
	}

	public static void CallOfTheWild(Player sourcePlayer, Player targetPlayer, string clipName)
	{
		//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_0023: 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)
		Vector3 position = ((Component)sourcePlayer).gameObject.transform.position;
		Vector3 position2 = ((Component)targetPlayer).gameObject.transform.position;
		CallOfTheWild(position, position2, clipName);
	}

	public static void CallOfTheWild(Vector3 sourcePoint, Vector3 targetPoint, string clipName)
	{
		//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_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_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_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_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_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)
		if (Cfg.useSound.Value)
		{
			Logging.GetLogger().Debug("CallOfTheWild\n");
			Vector3 val = sourcePoint - targetPoint;
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			float num = Vector3.Distance(sourcePoint, targetPoint);
			float num2 = (num + 1f) / 10f;
			if (WolfPack.audioClips.TryGetValue(clipName.ToLower(), out var value))
			{
				AudioSource.PlayClipAtPoint(value, targetPoint + normalized * num2, 1f);
			}
		}
	}
}
internal class WolfUtils
{
	public static string Pluralizer(string singular)
	{
		string text = "";
		if (singular.Equals("*"))
		{
			return "Creatures";
		}
		if (singular.EndsWith("*") && singular.Length > 1)
		{
			singular = singular.Substring(0, singular.Length - 1);
		}
		if (singular.StartsWith("*") && singular.Length > 1)
		{
			singular = singular.Substring(1);
		}
		string text2 = singular;
		string text3 = text2;
		text = ((!(text3 == "wolf")) ? ((!singular.EndsWith("x") && !singular.EndsWith("ch") && !singular.EndsWith("sh") && !singular.EndsWith("s")) ? (singular + "s") : (singular + "es")) : "wolves");
		return text.Substring(0, 1).ToUpper() + text.Substring(1);
	}
}