Decompiled source of TozoDestructo v1.0.3

plugins/TozoDestructo/TozoDestructo.dll

Decompiled a day 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 AGD.ModAPI;
using AGD.Modding;
using BepInEx;
using Character;
using Core;
using DisputeLib;
using FMOD;
using FishNet;
using FishNet.Object;
using Game;
using HarmonyLib;
using Items;
using Microsoft.CodeAnalysis;
using Player;
using ThrownItems;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TozoDestructo")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyProduct("TozoDestructo")]
[assembly: AssemblyTitle("TozoDestructo")]
[assembly: AssemblyVersion("1.0.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TozoDestructo
{
	internal static class Network
	{
		public struct State
		{
			public int Id;

			public Vector3 Position;

			public float Yaw;
		}

		private const string MsgSpawn = "spawn";

		private const string MsgState = "state";

		private const string MsgRemove = "remove";

		public static void Register(IModContext context)
		{
			IModNetwork network = context.Network;
			network.RegisterClientHandler("spawn", (Action<ModReader>)delegate(ModReader r)
			{
				//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)
				int id = r.ReadInt();
				Vector3 pos = r.ReadVector3();
				float yaw = r.ReadFloat();
				TozoClient.Instance?.OnSpawn(id, pos, yaw);
			});
			network.RegisterClientHandler("state", (Action<ModReader>)delegate(ModReader r)
			{
				//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_002d: Unknown result type (might be due to invalid IL or missing references)
				int num = r.ReadInt();
				for (int i = 0; i < num; i++)
				{
					int id = r.ReadInt();
					Vector3 pos = r.ReadVector3();
					float yaw = r.ReadFloat();
					TozoClient.Instance?.OnState(id, pos, yaw);
				}
			});
			network.RegisterClientHandler("remove", (Action<ModReader>)delegate(ModReader r)
			{
				int id = r.ReadInt();
				TozoClient.Instance?.OnRemove(id);
			});
		}

		public static void SendSpawn(int id, Vector3 pos, float yaw)
		{
			//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)
			IModContext context = TozoMod.Context;
			if (context != null)
			{
				context.Network.SendToClients("spawn", (Action<ModWriter>)delegate(ModWriter w)
				{
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					w.WriteInt(id);
					w.WriteVector3(pos);
					w.WriteFloat(yaw);
				}, true, true);
			}
		}

		public static void SendStates(List<State> states)
		{
			if (states.Count == 0)
			{
				return;
			}
			IModContext context = TozoMod.Context;
			if (context == null)
			{
				return;
			}
			context.Network.SendToClients("state", (Action<ModWriter>)delegate(ModWriter w)
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				w.WriteInt(states.Count);
				foreach (State state in states)
				{
					w.WriteInt(state.Id);
					w.WriteVector3(state.Position);
					w.WriteFloat(state.Yaw);
				}
			}, false, true);
		}

		public static void SendRemove(int id)
		{
			IModContext context = TozoMod.Context;
			if (context != null)
			{
				context.Network.SendToClients("remove", (Action<ModWriter>)delegate(ModWriter w)
				{
					w.WriteInt(id);
				}, true, true);
			}
		}
	}
	[BepInPlugin("tozodestructo.loader", "TozoDestructo Loader", "1.0.1")]
	public class ThunderstoreLoader : BaseUnityPlugin
	{
		internal static class ScanRootPatch
		{
			internal static MethodInfo ScanRoot;

			internal static void Postfix(string root, Dictionary<string, DiscoveredMod> byId)
			{
				if (ModRoot != null && !(ScanRoot == null) && string.Equals(Path.GetFullPath(root).TrimEnd('\\', '/'), Path.GetFullPath(ModPaths.InstallModsPath).TrimEnd('\\', '/'), StringComparison.OrdinalIgnoreCase))
				{
					ScanRoot.Invoke(null, new object[4] { ModRoot, byId, false, true });
				}
			}
		}

		public const string DllName = "TozoDestructo.dll";

		public static readonly string[] ModFiles = new string[3] { "mod.json", "tozo.png", "item_icon.png" };

		internal static string ModRoot;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Expected O, but got Unknown
			string location = ((BaseUnityPlugin)this).Info.Location;
			string text = FindSourceFolder(Path.GetDirectoryName(location));
			if (text == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not find TozoDestructo's mod.json near " + location + ". Reinstall the mod from its zip."));
				return;
			}
			if (IsInsideGameModsFolder(text))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Mod is already in the game's Mods folder; nothing to do.");
				return;
			}
			try
			{
				ModRoot = Path.Combine(Paths.CachePath, "TozoDestructo");
				Directory.CreateDirectory(ModRoot);
				string[] files = Directory.GetFiles(ModRoot, "*", SearchOption.AllDirectories);
				foreach (string path in files)
				{
					string fileName = Path.GetFileName(path);
					if (!ModFiles.Contains<string>(fileName, StringComparer.OrdinalIgnoreCase) && !fileName.Equals("TozoDestructo.dll", StringComparison.OrdinalIgnoreCase))
					{
						File.Delete(path);
					}
				}
				files = ModFiles;
				foreach (string text2 in files)
				{
					string text3 = Path.Combine(text, text2);
					if (File.Exists(text3))
					{
						CopyIfChanged(text3, Path.Combine(ModRoot, text2));
					}
					else
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Missing " + text2 + " in " + text));
					}
				}
				CopyIfChanged(location, Path.Combine(ModRoot, "TozoDestructo.dll"));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not prepare the mod folder: " + ex));
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(LocalModProvider), "ScanRoot", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"LocalModProvider.ScanRoot not found (game update?). Install the mod manually into the game's Mods folder instead.");
				return;
			}
			ScanRootPatch.ScanRoot = methodInfo;
			_harmony = new Harmony("tozodestructo.loader");
			_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ScanRootPatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Registered mod folder with the game's mod loader: " + ModRoot));
		}

		private static string FindSourceFolder(string dllDir)
		{
			if (string.IsNullOrEmpty(dllDir))
			{
				return null;
			}
			List<string> list = new List<string> { dllDir };
			try
			{
				list.AddRange(Directory.GetDirectories(dllDir, "*", SearchOption.AllDirectories));
			}
			catch
			{
			}
			string directoryName = Path.GetDirectoryName(dllDir);
			if (directoryName != null)
			{
				list.Add(directoryName);
			}
			foreach (string item in list)
			{
				string path = Path.Combine(item, "mod.json");
				try
				{
					if (File.Exists(path) && File.ReadAllText(path).IndexOf("\"tozodestructo\"", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return item;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static void CopyIfChanged(string from, string to)
		{
			if (File.Exists(to))
			{
				FileInfo fileInfo = new FileInfo(from);
				FileInfo fileInfo2 = new FileInfo(to);
				if (fileInfo.Length == fileInfo2.Length && ((ReadOnlySpan<byte>)File.ReadAllBytes(from)).SequenceEqual((ReadOnlySpan<byte>)File.ReadAllBytes(to)))
				{
					return;
				}
			}
			File.Copy(from, to, overwrite: true);
		}

		private static bool IsInsideGameModsFolder(string path)
		{
			try
			{
				string text = Path.GetFullPath(path).TrimEnd('\\', '/');
				string[] array = new string[2]
				{
					ModPaths.InstallModsPath,
					ModPaths.PersistentModsPath
				};
				for (int i = 0; i < array.Length; i++)
				{
					string text2 = Path.GetFullPath(array[i]).TrimEnd('\\', '/');
					if (text.StartsWith(text2 + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}
	}
	internal class TozoClient : MonoBehaviour
	{
		private class View
		{
			public GameObject Root;

			public Transform Body;

			public Vector3 NetPosition;

			public float NetYaw;

			public float LastHeard;

			public float BobPhase;
		}

		private const float FollowSharpness = 12f;

		private const float BobHeight = 0.12f;

		private const float BobSpeed = 2.5f;

		private const float StaleTimeout = 3f;

		private readonly Dictionary<int, View> _views = new Dictionary<int, View>();

		private readonly List<int> _toRemove = new List<int>();

		public static TozoClient Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		private void OnDestroy()
		{
			ClearAll();
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		public void OnSpawn(int id, Vector3 pos, float yaw)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0035: 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_0050: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (_views.ContainsKey(id))
			{
				OnState(id, pos, yaw);
				return;
			}
			GameObject val = new GameObject("Tozo_" + id);
			val.transform.SetPositionAndRotation(pos, Quaternion.Euler(0f, yaw, 0f));
			Transform transform = new GameObject("Body").transform;
			transform.SetParent(val.transform, false);
			Visuals.CreateQuad(transform, 1.9f, "Image").transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
			_views[id] = new View
			{
				Root = val,
				Body = transform,
				NetPosition = pos,
				NetYaw = yaw,
				LastHeard = Time.time,
				BobPhase = Random.value * MathF.PI * 2f
			};
		}

		public void OnState(int id, Vector3 pos, float yaw)
		{
			//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)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!_views.TryGetValue(id, out var value))
			{
				OnSpawn(id, pos, yaw);
				return;
			}
			value.NetPosition = pos;
			value.NetYaw = yaw;
			value.LastHeard = Time.time;
		}

		public void OnRemove(int id)
		{
			if (_views.TryGetValue(id, out var value))
			{
				if (Object.op_Implicit((Object)(object)value.Root))
				{
					Object.Destroy((Object)(object)value.Root);
				}
				_views.Remove(id);
			}
		}

		public void ClearAll()
		{
			foreach (View value in _views.Values)
			{
				if (Object.op_Implicit((Object)(object)value.Root))
				{
					Object.Destroy((Object)(object)value.Root);
				}
			}
			_views.Clear();
		}

		private void Update()
		{
			//IL_0088: 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_0094: 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_00b4: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
			float num = 1f - Mathf.Exp(-12f * Time.deltaTime);
			_toRemove.Clear();
			foreach (KeyValuePair<int, View> view in _views)
			{
				View value = view.Value;
				if ((Object)(object)value.Root == (Object)null || Time.time - value.LastHeard > 3f)
				{
					_toRemove.Add(view.Key);
					continue;
				}
				Transform transform = value.Root.transform;
				transform.position = Vector3.Lerp(transform.position, value.NetPosition, num);
				transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0f, value.NetYaw, 0f), num);
				value.Body.localPosition = new Vector3(0f, Mathf.Sin(Time.time * 2.5f + value.BobPhase) * 0.12f, 0f);
			}
			foreach (int item in _toRemove)
			{
				OnRemove(item);
			}
		}
	}
	public class TozoMod : IModPlugin
	{
		public const string ItemId = "tozo_destructo";

		internal static IModContext Context;

		internal static Item TozoItem;

		internal static Texture2D Texture;

		internal static Material Material;

		private GameObject _templateHolder;

		private GameObject _driver;

		public void OnLoad(IModContext context)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			Context = context;
			try
			{
				Texture = LoadTexture(Path.Combine(context.InstallPath, "tozo.png"));
				Material = Visuals.CreateMaterial(Texture);
				_templateHolder = new GameObject("TozoDestructo_Templates");
				_templateHolder.SetActive(false);
				((Object)_templateHolder).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)(object)_templateHolder);
				RegisterItem(context);
				Network.Register(context);
				_driver = new GameObject("TozoDestructo_Driver");
				((Object)_driver).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)(object)_driver);
				_driver.AddComponent<TozoServer>();
				_driver.AddComponent<TozoClient>();
				context.Events.OnRoundStart += OnRoundChanged;
				context.Events.OnRoundEnd += OnRoundChanged;
				Debug.Log((object)"[TozoDestructo] Loaded.");
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("[TozoDestructo] Failed to load: " + ex));
			}
		}

		public void OnUnload()
		{
			if (Context != null)
			{
				Context.Events.OnRoundStart -= OnRoundChanged;
				Context.Events.OnRoundEnd -= OnRoundChanged;
			}
			if (Object.op_Implicit((Object)(object)_driver))
			{
				Object.Destroy((Object)(object)_driver);
			}
			if (Object.op_Implicit((Object)(object)_templateHolder))
			{
				Object.Destroy((Object)(object)_templateHolder);
			}
			if (Object.op_Implicit((Object)(object)Material))
			{
				Object.Destroy((Object)(object)Material);
			}
			if (Object.op_Implicit((Object)(object)Texture))
			{
				Object.Destroy((Object)(object)Texture);
			}
			TozoItem = null;
			Context = null;
		}

		private static void OnRoundChanged(RoundEvent e)
		{
			TozoServer.Instance?.ClearAll();
			TozoClient.Instance?.ClearAll();
		}

		private void RegisterItem(IModContext context)
		{
			//IL_0087: 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_0097: 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_00ad: 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_00c0: Expected O, but got Unknown
			string text = FindTeaTableItemName();
			if (text == null)
			{
				Debug.LogError((object)"[TozoDestructo] Could not find the vanilla Tea Table item to base the item on.");
				return;
			}
			GameObject val = Visuals.CreatePedestalTemplate(_templateHolder.transform);
			GameObject val2 = Visuals.CreateHeldTemplate(_templateHolder.transform);
			Item val3 = context.CreateItemFromVanilla(text, val2, val);
			if ((Object)(object)val3 == (Object)null)
			{
				Debug.LogError((object)("[TozoDestructo] CreateItemFromVanilla failed for " + text));
				return;
			}
			((Object)val3).name = "TozoDestructo";
			ThrowableConfig val4 = (ThrowableConfig)(object)((val3 is ThrowableConfig) ? val3 : null);
			if (val4 != null)
			{
				val4.deployablePrefab = null;
			}
			val3.dropPrefab = null;
			context.RegisterItem("tozo_destructo", (ScriptableObject)(object)val3, new ModItemMetadata
			{
				Title = "Tozo Destructo",
				Description = "Throw to summon Tozo somewhere on the map. He floats after one opponent and explodes when he reaches them. He'll never chase you, but don't stand near the blast.",
				IconPath = "item_icon.png",
				BasedOnVanillaItem = text,
				HideVanillaThrownMesh = true
			});
			Sprite val5 = LoadSprite(Path.Combine(context.InstallPath, "item_icon.png"));
			if ((Object)(object)val5 != (Object)null)
			{
				val3.icon = val5;
			}
			TozoItem = val3;
			Debug.Log((object)("[TozoDestructo] Registered item based on vanilla '" + text + "'."));
		}

		private static string FindTeaTableItemName()
		{
			GameDesignData val = (((Object)(object)GameSingleton.Instance != (Object)null) ? GameSingleton.Instance.gameDesignData : null);
			if ((Object)(object)val == (Object)null || val.itemList == null)
			{
				return null;
			}
			string text = null;
			string text2 = null;
			List<string> list = new List<string>();
			foreach (Item item in val.itemList)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				list.Add(((Object)item).name + ((item is ThrowableConfig) ? "*" : ""));
				ThrowableConfig val2 = (ThrowableConfig)(object)((item is ThrowableConfig) ? item : null);
				if (val2 == null)
				{
					continue;
				}
				if ((Object)(object)val2.deployablePrefab != (Object)null)
				{
					if (val2.deployablePrefab is TeaTable || (Object)(object)((Component)val2.deployablePrefab).GetComponentInChildren<TeaTable>(true) != (Object)null)
					{
						return ((Object)item).name;
					}
					if (text == null)
					{
						text = ((Object)item).name;
					}
				}
				if ((Object)(object)val2.thrownPrefab != (Object)null && (Object)(object)val2.thrownPrefab.GetComponentInChildren<TeaTable>(true) != (Object)null)
				{
					return ((Object)item).name;
				}
				if (text2 == null && (Object)(object)val2.thrownPrefab != (Object)null)
				{
					text2 = ((Object)item).name;
				}
			}
			Debug.LogWarning((object)("[TozoDestructo] No Tea Table item found. Vanilla items (* = throwable): " + string.Join(", ", list)));
			return text ?? text2;
		}

		private static Sprite LoadSprite(string path)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_004f: 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)
			try
			{
				if (!File.Exists(path))
				{
					return null;
				}
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, File.ReadAllBytes(path)))
				{
					return null;
				}
				((Object)val).name = "tozo_icon";
				Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
				((Object)obj).name = "TozoDestructoIcon";
				return obj;
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[TozoDestructo] Could not load icon: " + ex.Message));
				return null;
			}
		}

		private static Texture2D LoadTexture(string path)
		{
			//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_0015: Expected O, but got Unknown
			//IL_0028: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(path)))
			{
				throw new Exception("Could not decode " + path);
			}
			((Object)val).name = "tozo";
			((Texture)val).wrapMode = (TextureWrapMode)1;
			((Texture)val).filterMode = (FilterMode)1;
			return val;
		}
	}
	internal class TozoServer : MonoBehaviour
	{
		private class Monster
		{
			public int Id;

			public Vector3 Position;

			public float Yaw;

			public PlayerController Owner;

			public CoreCharacterController OwnerCharacter;

			public CoreCharacterController Target;

			public float SpawnTime;
		}

		private const float MoveSpeed = 4f;

		private const float HoverHeight = 1f;

		private const float TriggerDistance = 1.6f;

		private const float ExplosionRadius = 4f;

		private const float ExplosionDamage = 60f;

		private const float MaxLifetime = 45f;

		private const float MinSpawnDistance = 12f;

		private const float ScanInterval = 0.1f;

		private const float SendInterval = 0.05f;

		private readonly List<Monster> _monsters = new List<Monster>();

		private readonly HashSet<int> _handledThrows = new HashSet<int>();

		private readonly List<Network.State> _stateBuffer = new List<Network.State>();

		private int _nextId = 1;

		private float _nextScan;

		private float _nextSend;

		public static TozoServer Instance { get; private set; }

		private static bool IsHost
		{
			get
			{
				if ((Object)(object)InstanceFinder.NetworkManager != (Object)null && InstanceFinder.NetworkManager.IsServerStarted && (Object)(object)RoundManager.Instance != (Object)null)
				{
					return ((NetworkBehaviour)RoundManager.Instance).IsServerInitialized;
				}
				return false;
			}
		}

		private void Awake()
		{
			Instance = this;
		}

		private void OnDestroy()
		{
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void Update()
		{
			//IL_010b: 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)
			if (!IsHost)
			{
				if (_monsters.Count > 0)
				{
					_monsters.Clear();
				}
				return;
			}
			if (Time.time >= _nextScan)
			{
				_nextScan = Time.time + 0.1f;
				ScanForThrows();
			}
			float deltaTime = Time.deltaTime;
			for (int num = _monsters.Count - 1; num >= 0; num--)
			{
				if (TickMonster(_monsters[num], deltaTime))
				{
					Network.SendRemove(_monsters[num].Id);
					_monsters.RemoveAt(num);
				}
			}
			if (!(Time.time >= _nextSend) || _monsters.Count <= 0)
			{
				return;
			}
			_nextSend = Time.time + 0.05f;
			_stateBuffer.Clear();
			foreach (Monster monster in _monsters)
			{
				_stateBuffer.Add(new Network.State
				{
					Id = monster.Id,
					Position = monster.Position,
					Yaw = monster.Yaw
				});
			}
			Network.SendStates(_stateBuffer);
		}

		public void ClearAll()
		{
			foreach (Monster monster in _monsters)
			{
				if (IsHost)
				{
					Network.SendRemove(monster.Id);
				}
			}
			_monsters.Clear();
			_handledThrows.Clear();
		}

		private void ScanForThrows()
		{
			if ((Object)(object)TozoMod.TozoItem == (Object)null)
			{
				return;
			}
			ThrownItem[] array = Object.FindObjectsByType<ThrownItem>((FindObjectsSortMode)0);
			foreach (ThrownItem val in array)
			{
				if (!((Object)(object)val == (Object)null) && ((NetworkBehaviour)val).IsSpawned && !((Object)(object)val.Item.Value != (Object)(object)TozoMod.TozoItem))
				{
					int instanceID = ((Object)val).GetInstanceID();
					if (_handledThrows.Add(instanceID))
					{
						PlayerController value = val.thrownPlayer.Value;
						CoreCharacterController value2 = val.thrownCharacter.Value;
						InstanceFinder.ServerManager.Despawn(((Component)val).gameObject, (DespawnType?)null);
						Summon(value, value2);
					}
				}
			}
		}

		private void Summon(PlayerController owner, CoreCharacterController ownerCharacter)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0093: 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_0099: 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)
			Monster monster = new Monster
			{
				Id = _nextId++,
				Owner = owner,
				OwnerCharacter = ownerCharacter,
				SpawnTime = Time.time
			};
			monster.Target = PickTarget(monster);
			monster.Position = PickSpawnPosition(monster.Target);
			if ((Object)(object)monster.Target != (Object)null)
			{
				Vector3 val = Vector3.ProjectOnPlane(TargetPoint(monster.Target) - monster.Position, Vector3.up);
				if (((Vector3)(ref val)).sqrMagnitude > 0.01f)
				{
					Quaternion val2 = Quaternion.LookRotation(val);
					monster.Yaw = ((Quaternion)(ref val2)).eulerAngles.y;
				}
			}
			_monsters.Add(monster);
			Network.SendSpawn(monster.Id, monster.Position, monster.Yaw);
			Debug.Log((object)(string.Format("[TozoDestructo] Tozo #{0} summoned by {1}, ", monster.Id, Object.op_Implicit((Object)(object)owner) ? ((Object)owner).name : "?") + "hunting " + (Object.op_Implicit((Object)(object)monster.Target) ? ((Object)monster.Target).name : "nobody") + "."));
		}

		private Vector3 PickSpawnPosition(CoreCharacterController target)
		{
			//IL_00e3: 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_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_00c9: 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_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)
			//IL_008b: 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_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: 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)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance != (Object)null && instance.CurrentStageSpawnPoints != null)
			{
				foreach (SpawnPoint currentStageSpawnPoint in instance.CurrentStageSpawnPoints)
				{
					if ((Object)(object)currentStageSpawnPoint != (Object)null)
					{
						list.Add(((Component)currentStageSpawnPoint).transform.position);
					}
				}
			}
			if (list.Count > 0)
			{
				if ((Object)(object)target != (Object)null)
				{
					Vector3 t = ((Component)target).transform.position;
					List<Vector3> list2 = list.Where(delegate(Vector3 p)
					{
						//IL_0000: Unknown result type (might be due to invalid IL or missing references)
						//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_000c: Unknown result type (might be due to invalid IL or missing references)
						Vector3 val3 = p - t;
						return ((Vector3)(ref val3)).sqrMagnitude >= 144f;
					}).ToList();
					if (list2.Count > 0)
					{
						list = list2;
					}
				}
				return list[Random.Range(0, list.Count)] + Vector3.up * 1f;
			}
			Vector3 val = Vector3.zero;
			if ((Object)(object)target != (Object)null)
			{
				val = ((Component)target).transform.position;
			}
			else if ((Object)(object)instance != (Object)null && instance.LivingCharacters.Count > 0 && (Object)(object)instance.LivingCharacters[0] != (Object)null)
			{
				val = ((Component)instance.LivingCharacters[0]).transform.position;
			}
			Vector2 insideUnitCircle = Random.insideUnitCircle;
			Vector2 val2 = ((Vector2)(ref insideUnitCircle)).normalized * 15f;
			return val + new Vector3(val2.x, 2f, val2.y);
		}

		private CoreCharacterController PickTarget(Monster m)
		{
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			List<CoreCharacterController> list = instance.LivingCharacters.Where((CoreCharacterController c) => IsValidTarget(m, c)).ToList();
			if (list.Count <= 0)
			{
				return null;
			}
			return list[Random.Range(0, list.Count)];
		}

		private bool IsValidTarget(Monster m, CoreCharacterController c)
		{
			if ((Object)(object)c == (Object)null || c.isGhost || !c.IsAlive)
			{
				return false;
			}
			if ((Object)(object)m.OwnerCharacter != (Object)null && (Object)(object)c == (Object)(object)m.OwnerCharacter)
			{
				return false;
			}
			if ((Object)(object)c.Player == (Object)null || (Object)(object)m.Owner == (Object)null)
			{
				return true;
			}
			if ((Object)(object)c.Player == (Object)(object)m.Owner)
			{
				return false;
			}
			GameCustomization val = (((Object)(object)SessionManager.Instance != (Object)null) ? SessionManager.Instance.CurrentGameCustomization.Value : null);
			if (val != null && val.teamsEnabled && c.Player.Customization.Value.GetPrimaryColor() == m.Owner.Customization.Value.GetPrimaryColor())
			{
				return false;
			}
			return true;
		}

		private static Vector3 TargetPoint(CoreCharacterController c)
		{
			//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_002e: 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_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_003b: Unknown result type (might be due to invalid IL or missing references)
			RagdollController ragdollController = c.RagdollController;
			return (((Object)(object)ragdollController != (Object)null && (Object)(object)ragdollController.RootRigidbody != (Object)null) ? ragdollController.RootRigidbody.position : (((Component)c).transform.position + Vector3.up)) + Vector3.up * 0.3f;
		}

		private bool TickMonster(Monster m, float dt)
		{
			//IL_0055: 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_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//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_0093: 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_009b: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time - m.SpawnTime > 45f)
			{
				return true;
			}
			if ((Object)(object)m.Target == (Object)null || !IsValidTarget(m, m.Target))
			{
				m.Target = PickTarget(m);
			}
			if ((Object)(object)m.Target == (Object)null)
			{
				return false;
			}
			Vector3 val = TargetPoint(m.Target) - m.Position;
			float magnitude = ((Vector3)(ref val)).magnitude;
			if (magnitude <= 1.6f)
			{
				Explode(m);
				return true;
			}
			Vector3 val2 = val / magnitude * Mathf.Min(4f * dt, magnitude);
			m.Position += val2;
			KeepAboveGround(m);
			Vector3 val3 = Vector3.ProjectOnPlane(val2, Vector3.up);
			if (((Vector3)(ref val3)).sqrMagnitude > 1E-06f)
			{
				Quaternion val4 = Quaternion.LookRotation(val3);
				float y = ((Quaternion)(ref val4)).eulerAngles.y;
				m.Yaw = Mathf.MoveTowardsAngle(m.Yaw, y, 360f * dt);
			}
			return false;
		}

		private static void KeepAboveGround(Monster m)
		{
			//IL_0014: 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_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_0050: Unknown result type (might be due to invalid IL or missing references)
			RoundManager instance = RoundManager.Instance;
			int num = (((Object)(object)instance != (Object)null) ? LayerMask.op_Implicit(instance.groundLayer) : (-5));
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(m.Position + Vector3.up * 3f, Vector3.down, ref val, 8f, num, (QueryTriggerInteraction)1))
			{
				float num2 = ((RaycastHit)(ref val)).point.y + 0.8f;
				if (m.Position.y < num2)
				{
					m.Position.y = num2;
				}
			}
		}

		private void Explode(Monster m)
		{
			//IL_0014: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ExplosionManager.Instance == (Object)null))
			{
				ExplosionManager.Instance.CreateExplosion(m.Position, m.Owner, TozoMod.TozoItem, 4f, 60f, (GameObject)null, true, false, default(GUID), (List<CoreCharacterController>)null, false, (ThrownItem)null);
			}
		}
	}
	internal class UprightSpinner : MonoBehaviour
	{
		private const float DegreesPerSecond = 45f;

		private float _yaw;

		private void OnEnable()
		{
			_yaw = Random.Range(0f, 360f);
		}

		private void LateUpdate()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			_yaw = (_yaw + 45f * Time.deltaTime) % 360f;
			((Component)this).transform.rotation = Quaternion.Euler(0f, _yaw, 0f);
		}
	}
	internal static class Visuals
	{
		private const float PedestalHeight = 0.9f;

		private const float HeldHeight = 0.3f;

		public const float MonsterHeight = 1.9f;

		private static readonly string[] ShaderCandidates = new string[5] { "Universal Render Pipeline/Unlit", "Sprites/Default", "Unlit/Texture", "Universal Render Pipeline/Lit", "Standard" };

		public static Material CreateMaterial(Texture2D tex)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_0088: 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_008e: Expected O, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			Shader val = null;
			string[] shaderCandidates = ShaderCandidates;
			for (int i = 0; i < shaderCandidates.Length; i++)
			{
				Shader val2 = Shader.Find(shaderCandidates[i]);
				if ((Object)(object)val2 != (Object)null && val2.isSupported)
				{
					val = val2;
					break;
				}
			}
			Material val3;
			if ((Object)(object)val != (Object)null)
			{
				val3 = new Material(val);
				Debug.Log((object)("[TozoDestructo] Using shader " + ((Object)val).name));
			}
			else
			{
				Renderer val4 = FindAnyVanillaRenderer();
				val3 = (((Object)(object)val4 != (Object)null) ? new Material(val4.sharedMaterial) : new Material(Shader.Find("Hidden/InternalErrorShader")));
				Debug.LogWarning((object)("[TozoDestructo] No unlit shader found, borrowed " + (((Object)(object)val4 != (Object)null) ? ((Object)val4.sharedMaterial.shader).name : "nothing")));
			}
			((Object)val3).name = "TozoMaterial";
			val3.mainTexture = (Texture)(object)tex;
			if (val3.HasProperty("_BaseMap"))
			{
				val3.SetTexture("_BaseMap", (Texture)(object)tex);
			}
			if (val3.HasProperty("_MainTex"))
			{
				val3.SetTexture("_MainTex", (Texture)(object)tex);
			}
			if (val3.HasProperty("_BaseColor"))
			{
				val3.SetColor("_BaseColor", Color.white);
			}
			if (val3.HasProperty("_Color"))
			{
				val3.SetColor("_Color", Color.white);
			}
			if (val3.HasProperty("_Cull"))
			{
				val3.SetFloat("_Cull", 0f);
			}
			return val3;
		}

		public static GameObject CreateQuad(Transform parent, float height, string name)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)5);
			((Object)obj).name = name;
			Object.DestroyImmediate((Object)(object)obj.GetComponent<Collider>());
			obj.transform.SetParent(parent, false);
			float num = (((Object)(object)TozoMod.Texture != (Object)null) ? ((float)((Texture)TozoMod.Texture).width / (float)((Texture)TozoMod.Texture).height) : 1f);
			obj.transform.localScale = new Vector3(height * num, height, 1f);
			MeshRenderer component = obj.GetComponent<MeshRenderer>();
			((Renderer)component).sharedMaterial = TozoMod.Material;
			((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)component).receiveShadows = false;
			return obj;
		}

		public static GameObject CreatePedestalTemplate(Transform holder)
		{
			//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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			GameObject val = new GameObject("TozoPedestal");
			val.transform.SetParent(holder, false);
			CreateQuad(val.transform, 0.9f, "Image").AddComponent<UprightSpinner>();
			return val;
		}

		public static GameObject CreateHeldTemplate(Transform holder)
		{
			//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_0017: 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_004b: Expected O, but got Unknown
			GameObject val = new GameObject("TozoHeld");
			val.transform.SetParent(holder, false);
			CreateQuad(val.transform, 0.3f, "TozoHeldImage").transform.localPosition = new Vector3(0f, 0.15f, 0f);
			return val;
		}

		private static Renderer FindAnyVanillaRenderer()
		{
			foreach (Item item in GameSingleton.Instance.gameDesignData.itemList)
			{
				if (!((Object)(object)item == (Object)null) && !((Object)(object)item.pedestalPrefab == (Object)null))
				{
					Renderer componentInChildren = item.pedestalPrefab.GetComponentInChildren<Renderer>(true);
					if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.sharedMaterial != (Object)null)
					{
						return componentInChildren;
					}
				}
			}
			return null;
		}
	}
}