Decompiled source of ScopePartitioningLibrary v1.0.0

ScopePartitioningLibrary.dll

Decompiled 25 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("ScopePartitioningLibrary")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ScopePartitioningLibrary")]
[assembly: AssemblyTitle("ScopePartitioningLibrary")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ScopePartitioningLibrary;

internal static class DebugProxy
{
	internal static ConfigEntry<KeyboardShortcut> Key;

	private static ProxyPlayer proxy;

	private static GameObject made;

	private static int health;

	private static float nextProbe;

	private static readonly FieldRef<Enemy, EnemyVision> VisionOf = AccessTools.FieldRefAccess<Enemy, EnemyVision>("Vision");

	private static readonly FieldRef<Enemy, LayerMask> MaskOf = AccessTools.FieldRefAccess<Enemy, LayerMask>("VisionMask");

	internal static void Bind(ConfigFile c)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		Key = c.Bind<KeyboardShortcut>("Debug", "TestProxyKey", KeyboardShortcut.Empty, "A key that makes a test proxy (seen only by enemies): the item or valuable you're looking at becomes its body, or a pink capsule appears 3 m ahead; press again to remove it. Single player / host only. Empty = off.");
	}

	private static void Probe()
	{
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_0289: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_028f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0291: Unknown result type (might be due to invalid IL or missing references)
		//IL_0296: Unknown result type (might be due to invalid IL or missing references)
		//IL_029a: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		if (proxy == null || !proxy.Alive || (Object)(object)proxy.VisionPoint == (Object)null || Time.time < nextProbe)
		{
			return;
		}
		nextProbe = Time.time + 3f;
		EnemyDirector instance = EnemyDirector.instance;
		if ((Object)(object)instance == (Object)null || instance.enemiesSpawned == null)
		{
			return;
		}
		Vector3 position = proxy.VisionPoint.position;
		foreach (EnemyParent item in instance.enemiesSpawned)
		{
			if ((Object)(object)item == (Object)null || !((Component)item).gameObject.activeInHierarchy)
			{
				continue;
			}
			Enemy componentInChildren = ((Component)item).GetComponentInChildren<Enemy>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				continue;
			}
			EnemyVision val = VisionOf.Invoke(componentInChildren);
			string text = ((Object)item).name.Replace("(Clone)", "").Trim();
			if ((Object)(object)val == (Object)null || (Object)(object)val.VisionTransform == (Object)null)
			{
				Plugin.Log.LogInfo((object)("Probe: " + text + " has no sight."));
				continue;
			}
			Vector3 position2 = val.VisionTransform.position;
			float num = Vector3.Distance(position2, position);
			if (num > 25f)
			{
				continue;
			}
			string text2 = "nothing";
			float num2 = float.MaxValue;
			Vector3 val2 = position - position2;
			RaycastHit[] array = Physics.RaycastAll(position2, ((Vector3)(ref val2)).normalized, num + 0.5f, LayerMask.op_Implicit(MaskOf.Invoke(componentInChildren)), (QueryTriggerInteraction)1);
			for (int i = 0; i < array.Length; i++)
			{
				RaycastHit val3 = array[i];
				if (!((Component)((RaycastHit)(ref val3)).transform).CompareTag("Enemy") && !((Object)(object)((Component)((RaycastHit)(ref val3)).transform).GetComponentInParent<EnemyRigidbody>() != (Object)null) && ((RaycastHit)(ref val3)).distance < num2)
				{
					num2 = ((RaycastHit)(ref val3)).distance;
					bool flag = ((Component)((RaycastHit)(ref val3)).transform).CompareTag("Player") || ProxyRegistry.ByObject(((Component)((RaycastHit)(ref val3)).transform).gameObject) != null;
					text2 = string.Format("'{0}' (layer {1}, tag {2}) at {3:0.0} m: {4}", ((Object)((RaycastHit)(ref val3)).transform).name, LayerMask.LayerToName(((Component)((RaycastHit)(ref val3)).transform).gameObject.layer), ((Component)((RaycastHit)(ref val3)).transform).tag, ((RaycastHit)(ref val3)).distance, flag ? "counts as the proxy" : "a wall");
				}
			}
			Vector3 forward = val.VisionTransform.forward;
			val2 = position - position2;
			float num3 = Vector3.Dot(forward, ((Vector3)(ref val2)).normalized);
			Plugin.Log.LogInfo((object)$"Probe: {text} {num:0.0} m away (sight range {val.VisionDistance:0.#} m, facing {num3:0.00}, state {componentInChildren.CurrentState}); first hit {text2}.");
		}
	}

	internal static void Tick()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: 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_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0221: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Expected O, but got Unknown
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: 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_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0247: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0296: Expected O, but got Unknown
		//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Unknown result type (might be due to invalid IL or missing references)
		//IL_0285: Unknown result type (might be due to invalid IL or missing references)
		//IL_0342: Unknown result type (might be due to invalid IL or missing references)
		//IL_0347: Unknown result type (might be due to invalid IL or missing references)
		//IL_0354: Expected O, but got Unknown
		//IL_0333: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
		Probe();
		if (Key == null)
		{
			return;
		}
		KeyboardShortcut value = Key.Value;
		if ((int)((KeyboardShortcut)(ref value)).MainKey == 0)
		{
			return;
		}
		value = Key.Value;
		if (!((KeyboardShortcut)(ref value)).IsDown())
		{
			return;
		}
		if (proxy != null && (Object)(object)proxy.Avatar != (Object)null && proxy.Alive)
		{
			proxy.Remove();
			Cleanup();
			return;
		}
		if (!SemiFunc.IsMasterClientOrSingleplayer() || !SemiFunc.RunIsLevel())
		{
			Plugin.Log.LogInfo((object)"Test proxy: only in a level, as the host or in single player.");
			return;
		}
		PlayerAvatar instance = PlayerAvatar.instance;
		Camera main = Camera.main;
		if ((Object)(object)instance == (Object)null || (Object)(object)main == (Object)null)
		{
			return;
		}
		ProxySettings proxySettings = new ProxySettings
		{
			Name = "Test Proxy",
			Scopes = PlayerScope.Enemies,
			MaxHealth = 100
		};
		PhysGrabObject val = null;
		RaycastHit[] array = Physics.RaycastAll(((Component)main).transform.position, ((Component)main).transform.forward, 6f, -1, (QueryTriggerInteraction)1);
		for (int i = 0; i < array.Length; i++)
		{
			RaycastHit val2 = array[i];
			if (!((Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<PlayerAvatar>() != (Object)null))
			{
				PhysGrabObject componentInParent = ((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<PhysGrabObject>();
				if ((Object)(object)componentInParent != (Object)null && ((Object)(object)val == (Object)null || ((RaycastHit)(ref val2)).distance < Vector3.Distance(((Component)main).transform.position, val.centerPoint)))
				{
					val = componentInParent;
				}
			}
		}
		string arg;
		if ((Object)(object)val != (Object)null)
		{
			made = new GameObject("Test Proxy Eye");
			made.transform.SetParent(((Component)val).transform, false);
			made.transform.position = val.centerPoint;
			proxySettings.Anchor = made.transform;
			proxySettings.VisionPoint = made.transform;
			proxySettings.FeetOffset = Vector3.down * 0.2f;
			proxySettings.Body = val;
			arg = "'" + ((Object)val).name + "' is its body";
		}
		else
		{
			Vector3 forward = ((Component)instance).transform.forward;
			forward.y = 0f;
			Vector3 val3 = ((Component)instance).transform.position + ((((Vector3)(ref forward)).sqrMagnitude > 0.0001f) ? ((Vector3)(ref forward)).normalized : Vector3.forward) * 3f;
			RaycastHit val4 = default(RaycastHit);
			if (Physics.Raycast(val3 + Vector3.up * 1.5f, Vector3.down, ref val4, 4f, -1, (QueryTriggerInteraction)1))
			{
				val3 = ((RaycastHit)(ref val4)).point;
			}
			made = new GameObject("ScopePartitioningLibrary Test Proxy");
			made.transform.position = val3 + Vector3.up * 0.9f;
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)1);
			((Object)obj).name = "Look";
			Object.Destroy((Object)(object)obj.GetComponent<Collider>());
			obj.transform.SetParent(made.transform, false);
			obj.transform.localScale = new Vector3(0.5f, 0.9f, 0.5f);
			Renderer component = obj.GetComponent<Renderer>();
			if ((Object)(object)component != (Object)null)
			{
				component.material.color = new Color(1f, 0.3f, 0.8f);
			}
			GameObject val5 = new GameObject("Hit Collider")
			{
				tag = "Player"
			};
			int num = LayerMask.NameToLayer("Player");
			if (num >= 0)
			{
				val5.layer = num;
			}
			val5.transform.SetParent(made.transform, false);
			CapsuleCollider val6 = val5.AddComponent<CapsuleCollider>();
			val6.radius = 0.25f;
			val6.height = 1.8f;
			proxySettings.Anchor = made.transform;
			proxySettings.FeetOffset = Vector3.down * 0.9f;
			proxySettings.EyeHeight = 1.5f;
			proxySettings.HitColliders = (Collider[])(object)new Collider[1] { (Collider)val6 };
			arg = "a pink capsule";
		}
		health = 100;
		proxy = ProxyPlayer.Create(proxySettings);
		if (proxy == null)
		{
			Cleanup();
			return;
		}
		proxy.Hurt += delegate(ProxyPlayer p, ProxyDamage hit)
		{
			health -= hit.Amount;
			p.SetHealth(health, 100);
			Plugin.Log.LogInfo((object)$"Test proxy hurt for {hit.Amount} by {EnemyName(hit.EnemyIndex)}; {Mathf.Max(0, health)}/100 left.");
			if (health <= 0)
			{
				p.Remove();
				Cleanup();
			}
		};
		proxy.Healed += delegate(ProxyPlayer p, int amount)
		{
			Plugin.Log.LogInfo((object)$"Test proxy healed for {amount}.");
		};
		Plugin.Log.LogInfo((object)$"Test proxy made (ID {proxy.ViewId}), {arg}: only enemies can see it.");
	}

	private static string EnemyName(int index)
	{
		List<EnemyParent> list = (((Object)(object)EnemyDirector.instance != (Object)null) ? EnemyDirector.instance.enemiesSpawned : null);
		if (index < 0 || list == null || index >= list.Count || (Object)(object)list[index] == (Object)null)
		{
			if (index >= 0)
			{
				return $"enemy #{index}";
			}
			return "no enemy (an explosion, a fall...)";
		}
		return ((Object)list[index]).name.Replace("(Clone)", "").Trim() + $" (#{index})";
	}

	private static void Cleanup()
	{
		if ((Object)(object)made != (Object)null)
		{
			Object.Destroy((Object)(object)made, (proxy != null) ? (proxy.RemoveDelayOf() + 0.5f) : 0f);
		}
		made = null;
	}
}
public sealed class PlayerLookup
{
	public MethodBase Method { get; internal set; }

	public string Name { get; internal set; }

	public PlayerScope Scope { get; internal set; }

	public string Rule { get; internal set; }

	public bool ReadsListDirectly { get; internal set; }

	public bool WritesList { get; internal set; }

	public IReadOnlyList<string> HelpersCalled { get; internal set; }

	public bool Patched { get; internal set; }
}
internal static class Discovery
{
	internal sealed class Result
	{
		public readonly List<PlayerLookup> Lookups = new List<PlayerLookup>();

		public readonly List<MethodBase> HelperReaders = new List<MethodBase>();

		public readonly List<string> HelperNames = new List<string>();

		public readonly List<MethodBase> ComponentLookups = new List<MethodBase>();
	}

	private static readonly HashSet<string> NotHelpers = new HashSet<string>
	{
		"MasterOnlyRPC", "OwnerOnlyRPC", "MasterAndOwnerOnlyRPC", "PlayerAvatarGetFromPhotonPlayer", "PlayerAvatarGetFromSteamID", "PlayerAvatarGetFromSteamIDshort", "PlayerGetFromSteamID", "InPlayerCameraAny", "PlayerCameraRemoteRefresh", "NetworkThrottleViewpointsTick",
		"NetworkThrottleSendViewpointsTick"
	};

	private static readonly HashSet<string> Mutators = new HashSet<string>
	{
		"Add", "AddRange", "Insert", "InsertRange", "Remove", "RemoveAt", "RemoveAll", "RemoveRange", "Clear", "Sort",
		"Reverse", "set_Item"
	};

	internal static Result Scan(Action<string> warn)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Expected O, but got Unknown
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Invalid comparison between Unknown and I4
		//IL_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Invalid comparison between Unknown and I4
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Invalid comparison between Unknown and I4
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Invalid comparison between Unknown and I4
		//IL_03d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fe: Invalid comparison between Unknown and I4
		//IL_0402: Unknown result type (might be due to invalid IL or missing references)
		//IL_0407: Unknown result type (might be due to invalid IL or missing references)
		//IL_040b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0412: Invalid comparison between Unknown and I4
		Assembly assembly = typeof(GameDirector).Assembly;
		Module manifestModule = assembly.ManifestModule;
		Result result = new Result();
		AssemblyDefinition val = AssemblyDefinition.ReadAssembly(assembly.Location, new ReaderParameters
		{
			ReadSymbols = false
		});
		try
		{
			List<MethodDefinition> list = new List<MethodDefinition>();
			foreach (TypeDefinition type in val.MainModule.GetTypes())
			{
				Enumerator<MethodDefinition> enumerator2 = type.Methods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current = enumerator2.Current;
						if (current.HasBody)
						{
							list.Add(current);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
			}
			HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>();
			Dictionary<MethodDefinition, List<string>> dictionary = new Dictionary<MethodDefinition, List<string>>();
			HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>();
			OpCode opCode;
			foreach (MethodDefinition item in list)
			{
				Collection<Instruction> instructions = item.Body.Instructions;
				for (int i = 0; i < instructions.Count; i++)
				{
					Instruction val2 = instructions[i];
					opCode = val2.OpCode;
					if ((int)((OpCode)(ref opCode)).Code != 120)
					{
						opCode = val2.OpCode;
						if ((int)((OpCode)(ref opCode)).Code != 121)
						{
							goto IL_0184;
						}
					}
					object operand = val2.Operand;
					FieldReference val3 = (FieldReference)((operand is FieldReference) ? operand : null);
					if (val3 != null && ((MemberReference)val3).Name == "PlayerList" && ((MemberReference)((MemberReference)val3).DeclaringType).FullName == "GameDirector")
					{
						hashSet.Add(item);
						if (ChangesListRightAway(instructions, i))
						{
							hashSet2.Add(item);
						}
						continue;
					}
					goto IL_0184;
					IL_0184:
					opCode = val2.OpCode;
					if ((int)((OpCode)(ref opCode)).Code != 39)
					{
						opCode = val2.OpCode;
						if ((int)((OpCode)(ref opCode)).Code != 110)
						{
							continue;
						}
					}
					object operand2 = val2.Operand;
					MethodReference val4 = (MethodReference)((operand2 is MethodReference) ? operand2 : null);
					if (val4 != null && ((MemberReference)((MemberReference)val4).DeclaringType).FullName == "SemiFunc")
					{
						if (!dictionary.TryGetValue(item, out var value))
						{
							value = (dictionary[item] = new List<string>());
						}
						if (!value.Contains(((MemberReference)val4).Name))
						{
							value.Add(((MemberReference)val4).Name);
						}
					}
				}
			}
			HashSet<string> hashSet3 = new HashSet<string>();
			foreach (MethodDefinition item2 in hashSet)
			{
				if (((MemberReference)item2.DeclaringType).FullName == "SemiFunc" && !NotHelpers.Contains(((MemberReference)item2).Name))
				{
					hashSet3.Add(((MemberReference)item2).Name);
				}
			}
			bool flag = true;
			while (flag)
			{
				flag = false;
				foreach (KeyValuePair<MethodDefinition, List<string>> item3 in dictionary)
				{
					if (((MemberReference)item3.Key.DeclaringType).FullName == "SemiFunc" && !hashSet3.Contains(((MemberReference)item3.Key).Name) && !NotHelpers.Contains(((MemberReference)item3.Key).Name) && item3.Value.Exists(hashSet3.Contains))
					{
						hashSet3.Add(((MemberReference)item3.Key).Name);
						flag = true;
					}
				}
			}
			foreach (MethodDefinition item4 in list)
			{
				string text = Outer(item4.DeclaringType);
				if (text != "HurtCollider" && text != "SemiFunc" && ScopeRules.Decide(text, ((MemberReference)item4).Name, out var _) != PlayerScope.Enemies)
				{
					continue;
				}
				bool flag2 = false;
				Enumerator<Instruction> enumerator6 = item4.Body.Instructions.GetEnumerator();
				try
				{
					while (enumerator6.MoveNext())
					{
						Instruction current6 = enumerator6.Current;
						opCode = current6.OpCode;
						if ((int)((OpCode)(ref opCode)).Code != 39)
						{
							opCode = current6.OpCode;
							if ((int)((OpCode)(ref opCode)).Code != 110)
							{
								continue;
							}
						}
						object operand3 = current6.Operand;
						GenericInstanceMethod val5 = (GenericInstanceMethod)((operand3 is GenericInstanceMethod) ? operand3 : null);
						if (val5 != null && (((MemberReference)val5).Name == "GetComponentInParent" || ((MemberReference)val5).Name == "GetComponent") && (((MemberReference)((MemberReference)val5).DeclaringType).FullName == "UnityEngine.Component" || ((MemberReference)((MemberReference)val5).DeclaringType).FullName == "UnityEngine.GameObject") && val5.GenericArguments.Count == 1 && (((MemberReference)val5.GenericArguments[0]).FullName == "PlayerTumble" || ((MemberReference)val5.GenericArguments[0]).FullName == "PlayerAvatar"))
						{
							flag2 = true;
							break;
						}
					}
				}
				finally
				{
					((IDisposable)enumerator6/*cast due to .constrained prefix*/).Dispose();
				}
				if (flag2)
				{
					MethodBase methodBase = Resolve(manifestModule, item4, warn);
					if (methodBase != null)
					{
						result.ComponentLookups.Add(methodBase);
					}
				}
			}
			result.HelperNames.AddRange(hashSet3);
			result.HelperNames.Sort(StringComparer.Ordinal);
			foreach (MethodDefinition item5 in list)
			{
				bool flag3 = hashSet.Contains(item5);
				List<string> value2;
				List<string> list3 = (dictionary.TryGetValue(item5, out value2) ? value2.FindAll(hashSet3.Contains) : new List<string>());
				if (!flag3 && list3.Count == 0)
				{
					continue;
				}
				MethodBase methodBase2 = Resolve(manifestModule, item5, warn);
				if (((MemberReference)item5.DeclaringType).FullName == "SemiFunc")
				{
					if (!NotHelpers.Contains(((MemberReference)item5).Name) && flag3 && methodBase2 != null && !hashSet2.Contains(item5))
					{
						result.HelperReaders.Add(methodBase2);
					}
					continue;
				}
				string rule2;
				PlayerScope playerScope = ScopeRules.Decide(Outer(item5.DeclaringType), ((MemberReference)item5).Name, out rule2);
				result.Lookups.Add(new PlayerLookup
				{
					Method = methodBase2,
					Name = ((MemberReference)item5.DeclaringType).FullName + "." + ((MemberReference)item5).Name,
					Scope = ((methodBase2 != null) ? playerScope : PlayerScope.None),
					Rule = ((methodBase2 != null) ? rule2 : "not found at runtime"),
					ReadsListDirectly = flag3,
					WritesList = hashSet2.Contains(item5),
					HelpersCalled = list3
				});
			}
		}
		finally
		{
			((IDisposable)val)?.Dispose();
		}
		result.Lookups.Sort((PlayerLookup a, PlayerLookup b) => string.CompareOrdinal(a.Name, b.Name));
		return result;
	}

	private static bool ChangesListRightAway(Collection<Instruction> body, int i)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Invalid comparison between Unknown and I4
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Invalid comparison between Unknown and I4
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Invalid comparison between Unknown and I4
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Invalid comparison between Unknown and I4
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Invalid comparison between Unknown and I4
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Invalid comparison between Unknown and I4
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Invalid comparison between Unknown and I4
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Invalid comparison between Unknown and I4
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Invalid comparison between Unknown and I4
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Invalid comparison between Unknown and I4
		int num = i + 1;
		while (num < body.Count && num <= i + 6)
		{
			Instruction val = body[num];
			OpCode opCode = val.OpCode;
			if ((int)((OpCode)(ref opCode)).Code != 39)
			{
				opCode = val.OpCode;
				if ((int)((OpCode)(ref opCode)).Code != 110)
				{
					goto IL_006e;
				}
			}
			object operand = val.Operand;
			MethodReference val2 = (MethodReference)((operand is MethodReference) ? operand : null);
			if (val2 != null)
			{
				if (Mutators.Contains(((MemberReference)val2).Name))
				{
					return ((MemberReference)((MemberReference)val2).DeclaringType).FullName == "System.Collections.Generic.List`1<PlayerAvatar>";
				}
				return false;
			}
			goto IL_006e;
			IL_006e:
			opCode = val.OpCode;
			if ((int)((OpCode)(ref opCode)).FlowControl != 5)
			{
				return false;
			}
			opCode = val.OpCode;
			if ((int)((OpCode)(ref opCode)).Code != 204)
			{
				opCode = val.OpCode;
				if ((int)((OpCode)(ref opCode)).Code != 19)
				{
					opCode = val.OpCode;
					if ((int)((OpCode)(ref opCode)).Code != 10)
					{
						opCode = val.OpCode;
						if ((int)((OpCode)(ref opCode)).Code != 11)
						{
							opCode = val.OpCode;
							if ((int)((OpCode)(ref opCode)).Code != 12)
							{
								opCode = val.OpCode;
								if ((int)((OpCode)(ref opCode)).Code != 13)
								{
									opCode = val.OpCode;
									if ((int)((OpCode)(ref opCode)).Code != 122)
									{
										num++;
										continue;
									}
								}
							}
						}
					}
				}
			}
			return false;
		}
		return false;
	}

	private static string Outer(TypeDefinition t)
	{
		while (t.DeclaringType != null)
		{
			t = t.DeclaringType;
		}
		return ((MemberReference)t).FullName;
	}

	private static MethodBase Resolve(Module module, MethodDefinition m, Action<string> warn)
	{
		//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)
		try
		{
			MetadataToken metadataToken = ((MemberReference)m).MetadataToken;
			return module.ResolveMethod(((MetadataToken)(ref metadataToken)).ToInt32());
		}
		catch (Exception ex)
		{
			warn("Couldn't find " + ((MemberReference)m).FullName + " at runtime: " + ex.Message);
			return null;
		}
	}
}
internal static class Patcher
{
	private static readonly Dictionary<MethodBase, PlayerScope> scopeOf = new Dictionary<MethodBase, PlayerScope>();

	private static readonly FieldInfo PlayerListField = AccessTools.Field(typeof(GameDirector), "PlayerList");

	private static readonly MethodInfo ScopedList = AccessTools.Method(typeof(ScopedPlayers), "PlayerListForCurrentScope", (Type[])null, (Type[])null);

	internal static int Rewrites { get; private set; }

	internal static int Failures { get; private set; }

	internal static void Apply(Harmony harmony, Discovery.Result found, Action<string> warn)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Expected O, but got Unknown
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Expected O, but got Unknown
		HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(Patcher), "Enter", (Type[])null, (Type[])null));
		HarmonyMethod val2 = new HarmonyMethod(AccessTools.Method(typeof(Patcher), "Exit", (Type[])null, (Type[])null));
		HarmonyMethod val3 = new HarmonyMethod(AccessTools.Method(typeof(Patcher), "RewriteListReads", (Type[])null, (Type[])null));
		foreach (PlayerLookup lookup in found.Lookups)
		{
			if (lookup.Scope != PlayerScope.None && !(lookup.Method == null))
			{
				try
				{
					scopeOf[lookup.Method] = lookup.Scope;
					MethodBase method = lookup.Method;
					HarmonyMethod val4 = val2;
					harmony.Patch(method, val, (HarmonyMethod)null, (lookup.ReadsListDirectly && !lookup.WritesList) ? val3 : null, val4, (HarmonyMethod)null);
					lookup.Patched = true;
				}
				catch (Exception ex)
				{
					Failures++;
					scopeOf.Remove(lookup.Method);
					warn($"Couldn't patch {lookup.Name} ({lookup.Scope}); it keeps seeing real players only. {ex.Message}");
				}
			}
		}
		HarmonyMethod val5 = new HarmonyMethod(AccessTools.Method(typeof(ProxyLookups), "Rewrite", (Type[])null, (Type[])null));
		foreach (MethodBase componentLookup in found.ComponentLookups)
		{
			try
			{
				harmony.Patch(componentLookup, (HarmonyMethod)null, (HarmonyMethod)null, val5, (HarmonyMethod)null, (HarmonyMethod)null);
				ProxyLookups.Targets.Add(componentLookup);
			}
			catch (Exception ex2)
			{
				Failures++;
				warn("Couldn't patch " + componentLookup.DeclaringType?.Name + "." + componentLookup.Name + " for proxy hit colliders: " + ex2.Message);
			}
		}
		foreach (MethodBase helperReader in found.HelperReaders)
		{
			try
			{
				harmony.Patch(helperReader, (HarmonyMethod)null, (HarmonyMethod)null, val3, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex3)
			{
				Failures++;
				warn("Couldn't patch the helper SemiFunc." + helperReader.Name + ": " + ex3.Message);
			}
		}
	}

	private static void Enter(MethodBase __originalMethod, out PlayerScope __state)
	{
		__state = ScopeContext.Enter((__originalMethod != null && scopeOf.TryGetValue(__originalMethod, out var value)) ? value : ScopeContext.Current);
	}

	private static Exception Exit(PlayerScope __state, Exception __exception)
	{
		ScopeContext.Restore(__state);
		return __exception;
	}

	private static IEnumerable<CodeInstruction> RewriteListReads(IEnumerable<CodeInstruction> instructions)
	{
		foreach (CodeInstruction instruction in instructions)
		{
			if (instruction.opcode == OpCodes.Ldfld && instruction.operand is FieldInfo fieldInfo && fieldInfo == PlayerListField)
			{
				instruction.opcode = OpCodes.Call;
				instruction.operand = ScopedList;
				Rewrites++;
			}
			yield return instruction;
		}
	}
}
[Flags]
public enum PlayerScope
{
	None = 0,
	Enemies = 1,
	Hazards = 2,
	Valuables = 4,
	NPCs = 8,
	Items = 0x10,
	LevelFlow = 0x20,
	CameraAndUI = 0x40,
	VoiceAndEyes = 0x80,
	Network = 0x100,
	Mods = 0x200,
	All = 0x3FF
}
[BepInPlugin("ScopePartitioningLibrary", "ScopePartitioningLibrary", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "ScopePartitioningLibrary";

	public const string Name = "ScopePartitioningLibrary";

	public const string Version = "1.0.0";

	private ConfigEntry<bool> enabledSetting;

	private ConfigEntry<bool> logReport;

	private ConfigEntry<bool> logUnscoped;

	internal static ConfigEntry<bool> Verbose;

	private ConfigEntry<string> overrides;

	internal static ManualLogSource Log { get; private set; }

	public static bool Active { get; private set; }

	internal static void Info(string line)
	{
		if (Verbose != null && Verbose.Value)
		{
			Log.LogInfo((object)line);
		}
	}

	private void Awake()
	{
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Expected O, but got Unknown
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Turns the library on. Off: nothing is patched, and mods that use it get real players only (restart to apply).");
		overrides = ((BaseUnityPlugin)this).Config.Bind<string>("Scopes", "Overrides", "", "Moves game classes or methods to another scope: 'Class=Scope' or 'Class.Method=Scope', separated by ';'. Scope names: None, Enemies, Hazards, Valuables, NPCs, Items, LevelFlow, CameraAndUI, VoiceAndEyes, Network, Mods (join several with '|'). Example: 'RockSlide=None; ShopKeeper=NPCs|Enemies' (restart to apply).");
		logReport = ((BaseUnityPlugin)this).Config.Bind<bool>("Report", "LogFullReport", false, "Also writes every player lookup the library found, with its scope, to LogOutput.log at startup (a few hundred lines; the one-line summary is always written).");
		Verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLog", false, "Logs proxies being created and removed, enemies first seeing them, and calls dropped on them (LogOutput.log).");
		DebugProxy.Bind(((BaseUnityPlugin)this).Config);
		logUnscoped = ((BaseUnityPlugin)this).Config.Bind<bool>("Report", "IncludeUnscoped", true, "The report also lists lookups left in scope None (unpatched), so new ones after a game update are easy to spot.");
		if (!enabledSetting.Value)
		{
			Log.LogInfo((object)"ScopePartitioningLibrary 1.0.0 is switched off in the config: nothing patched.");
			return;
		}
		try
		{
			ScopeRules.SetOverrides(overrides.Value, delegate(string w)
			{
				Log.LogWarning((object)("[Scopes] " + w));
			});
			Discovery.Result found = Discovery.Scan(delegate(string w)
			{
				Log.LogWarning((object)w);
			});
			Harmony val = new Harmony("ScopePartitioningLibrary");
			Patcher.Apply(val, found, delegate(string w)
			{
				Log.LogWarning((object)w);
			});
			val.PatchAll(typeof(ProxyPatches));
			val.PatchAll(typeof(ProxyTumbleIgnore));
			val.PatchAll(typeof(ProxyEnemies.CoroutineKeys));
			Active = true;
			ProxyNetwork.Listen();
			ProxyDriver.Ensure();
			ScopeReport.Set(found, Patcher.Rewrites, Patcher.Failures);
			Log.LogInfo((object)ScopeReport.Summary());
			if (logReport.Value)
			{
				Log.LogInfo((object)ScopeReport.Full(logUnscoped.Value));
			}
		}
		catch (Exception arg)
		{
			Log.LogError((object)string.Format("{0} failed to start; the game runs unmodified by it. {1}", "ScopePartitioningLibrary", arg));
		}
	}
}
internal static class ProxyBuilder
{
	internal sealed class Parts
	{
		public GameObject Root;

		public Transform Eye;

		public Transform CustomEye;

		public Transform Camera;

		public Transform Visuals;

		public PlayerHealth Health;

		public PlayerTumble Tumble;

		public RoomVolumeCheck Rooms;

		public PhysGrabObject StandIn;

		public GameObject Trigger;
	}

	private static GameObject holder;

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

	private static readonly Dictionary<(Type, string), FieldInfo> fields = new Dictionary<(Type, string), FieldInfo>();

	internal static ProxyPlayer Build(ProxySettings s, int id)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Expected O, but got Unknown
		//IL_0435: Unknown result type (might be due to invalid IL or missing references)
		//IL_043a: Unknown result type (might be due to invalid IL or missing references)
		//IL_044c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0530: Unknown result type (might be due to invalid IL or missing references)
		//IL_0537: Expected O, but got Unknown
		try
		{
			if ((Object)(object)holder == (Object)null)
			{
				holder = new GameObject("ScopePartitioningLibrary Proxies");
			}
			ProxyPlayer proxyPlayer = new ProxyPlayer
			{
				ViewId = id,
				Name = (string.IsNullOrEmpty(s.Name) ? "Proxy" : s.Name),
				Anchor = s.Anchor,
				Body = s.Body,
				RemoveDelay = Mathf.Max(0f, s.RemoveDelay),
				FeetOffset = s.FeetOffset,
				EyeHeight = s.EyeHeight,
				OwnVisionPoint = ((Object)(object)s.VisionPoint != (Object)null)
			};
			proxyPlayer.SetScopesSilently(s.Scopes);
			proxyPlayer.hitColliders = (Collider[])(s.HitColliders ?? (((Object)(object)s.Body != (Object)null) ? ((Array)((Component)s.Body).GetComponentsInChildren<Collider>(true)) : ((Array)new Collider[0])));
			proxyPlayer.InitHealth(s.MaxHealth);
			GameObject val = new GameObject($"Proxy {proxyPlayer.Name} ({id})");
			val.SetActive(false);
			val.transform.SetParent(holder.transform, false);
			Parts parts = (proxyPlayer.Parts = new Parts
			{
				Root = val
			});
			PhotonView val2 = val.AddComponent<PhotonView>();
			Set(val2, "viewIdField", id);
			PlayerHealth val3 = val.AddComponent<PlayerHealth>();
			PlayerVisionTarget val4 = val.AddComponent<PlayerVisionTarget>();
			PlayerTumble val5 = val.AddComponent<PlayerTumble>();
			PhysGrabber val6 = val.AddComponent<PhysGrabber>();
			RoomVolumeCheck val7 = val.AddComponent<RoomVolumeCheck>();
			PlayerAvatar val8 = val.AddComponent<PlayerAvatar>();
			parts.Health = val3;
			parts.Tumble = val5;
			parts.Rooms = val7;
			Transform val9 = (parts.Eye = Child(val.transform, "Eye"));
			parts.CustomEye = s.VisionPoint;
			parts.Camera = Child(val.transform, "Camera");
			PlayerLocalCamera val10 = ((Component)parts.Camera).gameObject.AddComponent<PlayerLocalCamera>();
			parts.Visuals = Child(val.transform, "Visuals");
			PlayerAvatarVisuals val11 = ((Component)parts.Visuals).gameObject.AddComponent<PlayerAvatarVisuals>();
			Transform headLookAtTransform = Child(parts.Visuals, "Head Look At");
			Transform attachPointJawTop = Child(parts.Visuals, "Jaw Top");
			Transform attachPointJawBottom = Child(parts.Visuals, "Jaw Bottom");
			Transform attachPointTopHeadMiddle = Child(parts.Visuals, "Head Top");
			proxyPlayer.VisionPoint = val9;
			proxyPlayer.Avatar = val8;
			val8.photonView = val2;
			val8.playerHealth = val3;
			val8.PlayerVisionTarget = val4;
			val8.physGrabber = val6;
			val8.localCamera = val10;
			val8.playerAvatarVisuals = val11;
			val8.RoomVolumeCheck = val7;
			Set(val8, "tumble", val5);
			Set(val8, "playerName", proxyPlayer.Name);
			Set(val8, "steamID", "PROXY" + id);
			Set(val8, "isLocal", false);
			Set(val8, "isDisabled", false);
			Set(val8, "deadSet", false);
			Set(val8, "isTumbling", (Object)(object)s.Body != (Object)null);
			Set(val8, "isGrounded", true);
			Set(val3, "playerAvatar", val8);
			Set(val3, "photonView", val2);
			WriteHealth(proxyPlayer);
			val4.VisionTransform = val9;
			Set(val4, "PlayerAvatar", val8);
			Set(val4, "PhotonView", val2);
			val5.playerAvatar = val8;
			Set(val5, "photonView", val2);
			Set(val5, "setup", true);
			if ((Object)(object)s.Body != (Object)null)
			{
				Set(val5, "physGrabObject", s.Body);
				Set(val5, "rb", ((Object)(object)s.Body.rb != (Object)null) ? s.Body.rb : ((Component)s.Body).GetComponent<Rigidbody>());
				Set(val5, "isTumbling", true);
				val5.colliders = ((Component)s.Body).GetComponentsInChildren<Collider>();
			}
			else
			{
				GameObject val12 = new GameObject("Stand-in Body");
				val12.transform.SetParent(val.transform, false);
				Rigidbody val13 = val12.AddComponent<Rigidbody>();
				val13.isKinematic = true;
				val13.useGravity = false;
				PhysGrabObject val14 = val12.AddComponent<PhysGrabObject>();
				Set(val14, "rb", val13);
				parts.StandIn = val14;
				Set(val5, "physGrabObject", val14);
				Set(val5, "rb", val13);
				val5.colliders = (Collider[])(object)new Collider[0];
			}
			Set(val6, "playerAvatar", val8);
			Set(val6, "photonView", val2);
			val7.CurrentRooms = new List<RoomVolume>();
			Set(val7, "player", val8);
			Set(val10, "playerAvatar", val8);
			val11.playerAvatar = val8;
			val11.headLookAtTransform = headLookAtTransform;
			val11.attachPointJawTop = attachPointJawTop;
			val11.attachPointJawBottom = attachPointJawBottom;
			val11.attachPointTopHeadMiddle = attachPointTopHeadMiddle;
			GameObject val15 = new GameObject($"Proxy {proxyPlayer.Name} ({id}) Player Trigger");
			val15.transform.SetParent(holder.transform, false);
			val15.layer = PlayerTriggerLayer();
			SphereCollider obj = val15.AddComponent<SphereCollider>();
			((Collider)obj).isTrigger = true;
			obj.radius = 0.45f;
			val15.AddComponent<PlayerTrigger>().PlayerAvatar = val8;
			parts.Trigger = val15;
			ProxyDriver.Place(proxyPlayer);
			return proxyPlayer;
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Building proxy '{s.Name}' (ID {id}) failed: {arg}");
			return null;
		}
	}

	internal static void WriteHealth(ProxyPlayer p)
	{
		if (!((Object)(object)p.Parts?.Health == (Object)null))
		{
			Set(p.Parts.Health, "maxHealth", p.MaxHealth);
			Set(p.Parts.Health, "health", p.Health);
		}
	}

	internal static void MarkDead(ProxyPlayer p)
	{
		if (!((Object)(object)p.Avatar == (Object)null))
		{
			Set(p.Avatar, "isDisabled", true);
			Set(p.Avatar, "deadSet", true);
			Set(p.Avatar, "isTumbling", false);
			if ((Object)(object)p.Parts?.Tumble != (Object)null)
			{
				Set(p.Parts.Tumble, "isTumbling", false);
			}
			if ((Object)(object)p.Parts?.Health != (Object)null)
			{
				Set(p.Parts.Health, "health", 0);
			}
			if ((Object)(object)p.Parts?.Trigger != (Object)null)
			{
				p.Parts.Trigger.SetActive(false);
			}
		}
	}

	internal static void Destroy(ProxyPlayer p)
	{
		if ((Object)(object)p.Parts?.Root != (Object)null)
		{
			Object.Destroy((Object)(object)p.Parts.Root);
		}
		if ((Object)(object)p.Parts?.Trigger != (Object)null)
		{
			Object.Destroy((Object)(object)p.Parts.Trigger);
		}
		if (p.Parts != null)
		{
			p.Parts.Root = null;
		}
	}

	private static int PlayerTriggerLayer()
	{
		PlayerAvatar instance = PlayerAvatar.instance;
		PlayerTrigger val = (((Object)(object)instance != (Object)null) ? ((Component)instance).GetComponentInChildren<PlayerTrigger>(true) : null);
		if ((Object)(object)val == (Object)null && (Object)(object)instance != (Object)null)
		{
			val = ((Component)((Component)instance).transform.root).GetComponentInChildren<PlayerTrigger>(true);
		}
		if ((Object)(object)val != (Object)null)
		{
			return ((Component)val).gameObject.layer;
		}
		int num = LayerMask.NameToLayer("Triggers");
		if (num < 0)
		{
			num = LayerMask.NameToLayer("Player");
		}
		if (num >= 0)
		{
			return num;
		}
		return 0;
	}

	private static Transform Child(Transform parent, string name)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		Transform transform = new GameObject(name).transform;
		transform.SetParent(parent, false);
		return transform;
	}

	internal static void Set(object target, string field, object value)
	{
		if (target == null)
		{
			return;
		}
		Type type = target.GetType();
		if (!fields.TryGetValue((type, field), out var value2))
		{
			value2 = (fields[(type, field)] = AccessTools.Field(type, field));
		}
		if (value2 == null)
		{
			if (missing.Add(type.Name + "." + field))
			{
				Plugin.Log.LogWarning((object)("Proxy builder: " + type.Name + "." + field + " not found in this game version; skipped."));
			}
		}
		else
		{
			value2.SetValue(target, value);
		}
	}
}
[DefaultExecutionOrder(-1000)]
internal sealed class ProxyDriver : MonoBehaviour
{
	private static ProxyDriver instance;

	private const float SlowEvery = 0.25f;

	private float nextSlow;

	private static readonly List<ProxyPlayer> work = new List<ProxyPlayer>();

	private static readonly Dictionary<ProxyPlayer, Vector3> lastFeet = new Dictionary<ProxyPlayer, Vector3>();

	private static readonly Collider[] overlap = (Collider[])(object)new Collider[16];

	internal static void Ensure()
	{
		//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_001e: Expected O, but got Unknown
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)instance != (Object)null))
		{
			GameObject val = new GameObject("ScopePartitioningLibrary Proxy Driver");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			instance = val.AddComponent<ProxyDriver>();
		}
	}

	private void Update()
	{
		ProxyNetwork.Tick();
		DebugProxy.Tick();
		if (ProxyRegistry.Count == 0)
		{
			return;
		}
		bool flag = Time.time >= nextSlow;
		if (flag)
		{
			nextSlow = Time.time + 0.25f;
		}
		work.Clear();
		work.AddRange(ProxyRegistry.All);
		foreach (ProxyPlayer item in work)
		{
			if ((Object)(object)item.Avatar == (Object)null || (Object)(object)item.Parts?.Root == (Object)null)
			{
				lastFeet.Remove(item);
				item.Destroy();
				continue;
			}
			if (item.RemoveAt >= 0f && Time.time >= item.RemoveAt)
			{
				lastFeet.Remove(item);
				item.Destroy();
				continue;
			}
			if ((Object)(object)item.Anchor == (Object)null)
			{
				if (item.Alive)
				{
					item.RemoveLocal();
				}
				continue;
			}
			Place(item);
			if (flag)
			{
				SlowUpdate(item);
			}
		}
		if (flag)
		{
			ProxyEnemies.Sync();
		}
	}

	internal static void Place(ProxyPlayer p)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: 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_0066: 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_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0157: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_028d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0292: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_0247: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0262: Unknown result type (might be due to invalid IL or missing references)
		//IL_0274: Unknown result type (might be due to invalid IL or missing references)
		//IL_0286: Unknown result type (might be due to invalid IL or missing references)
		//IL_0288: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_0217: Unknown result type (might be due to invalid IL or missing references)
		//IL_021c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_030d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)p.Anchor == (Object)null) && !((Object)(object)p.Parts?.Root == (Object)null))
		{
			Vector3 val = p.Anchor.position + p.FeetOffset;
			Vector3 forward = p.Anchor.forward;
			forward.y = 0f;
			Quaternion val2 = ((((Vector3)(ref forward)).sqrMagnitude > 0.0001f) ? Quaternion.LookRotation(((Vector3)(ref forward)).normalized, Vector3.up) : Quaternion.identity);
			p.Parts.Root.transform.SetPositionAndRotation(val, val2);
			Vector3 val3 = (((Object)(object)p.Parts.CustomEye != (Object)null) ? p.Parts.CustomEye.position : (val + Vector3.up * p.EyeHeight));
			if ((Object)(object)p.Parts.Eye != (Object)null)
			{
				p.Parts.Eye.position = val3;
			}
			p.Parts.Camera.SetPositionAndRotation(val3, val2);
			Transform visuals = p.Parts.Visuals;
			visuals.SetPositionAndRotation(val, val2);
			SetChild(visuals, "Head Look At", val3 + val2 * Vector3.forward * 0.5f);
			SetChild(visuals, "Jaw Top", val3 - Vector3.up * 0.08f + val2 * Vector3.forward * 0.08f);
			SetChild(visuals, "Jaw Bottom", val3 - Vector3.up * 0.14f + val2 * Vector3.forward * 0.08f);
			SetChild(visuals, "Head Top", val3 + Vector3.up * 0.12f);
			if ((Object)(object)p.Parts.Trigger != (Object)null)
			{
				p.Parts.Trigger.transform.position = (((Object)(object)p.Body != (Object)null) ? p.Body.centerPoint : (val + Vector3.up * (p.EyeHeight * 0.5f)));
			}
			if ((Object)(object)p.Parts.StandIn != (Object)null)
			{
				Vector3 val4 = val + Vector3.up * (p.EyeHeight * 0.5f);
				((Component)p.Parts.StandIn).transform.position = val4;
				p.Parts.StandIn.centerPoint = val4;
			}
			Vector3 val5 = Vector3.zero;
			Rigidbody val6 = (((Object)(object)p.Body != (Object)null) ? p.Body.rb : null);
			Vector3 value;
			if ((Object)(object)val6 != (Object)null)
			{
				val5 = val6.linearVelocity;
			}
			else if (lastFeet.TryGetValue(p, out value) && Time.deltaTime > 1E-05f)
			{
				val5 = (val - value) / Time.deltaTime;
			}
			lastFeet[p] = val;
			ProxyBuilder.Set(p.Avatar, "rbVelocity", val5);
			ProxyBuilder.Set(p.Avatar, "rbVelocityRaw", val5);
			ProxyBuilder.Set(p.Avatar, "isMoving", ((Vector3)(ref val5)).sqrMagnitude > 0.01f);
			if (p.Alive && (Object)(object)p.Body != (Object)null)
			{
				ProxyBuilder.Set(p.Avatar, "isTumbling", true);
				ProxyBuilder.Set(p.Parts.Tumble, "isTumbling", true);
			}
		}
	}

	private static void SetChild(Transform parent, string name, Vector3 at)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		Transform val = parent.Find(name);
		if ((Object)(object)val != (Object)null)
		{
			val.position = at;
		}
	}

	private static void SlowUpdate(ProxyPlayer p)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = p.Parts.Root.transform.position;
		NavMeshHit val = default(NavMeshHit);
		if (NavMesh.SamplePosition(position, ref val, 3f, -1))
		{
			ProxyBuilder.Set(p.Avatar, "LastNavmeshPosition", ((NavMeshHit)(ref val)).position);
			ProxyBuilder.Set(p.Avatar, "LastNavMeshPositionTimer", 0f);
		}
		RoomVolumeCheck rooms = p.Parts.Rooms;
		if ((Object)(object)rooms == (Object)null)
		{
			return;
		}
		rooms.CurrentRooms.Clear();
		bool flag = false;
		bool flag2 = false;
		int num = Physics.OverlapSphereNonAlloc(position + Vector3.up * 0.5f, 0.25f, overlap, -1, (QueryTriggerInteraction)2);
		for (int i = 0; i < num; i++)
		{
			RoomVolume val2 = (((Object)(object)overlap[i] != (Object)null) ? ((Component)overlap[i]).GetComponentInParent<RoomVolume>() : null);
			if (!((Object)(object)val2 == (Object)null) && !rooms.CurrentRooms.Contains(val2))
			{
				rooms.CurrentRooms.Add(val2);
				flag |= val2.Truck;
				flag2 |= val2.Extraction;
			}
		}
		ProxyBuilder.Set(rooms, "inTruck", flag);
		ProxyBuilder.Set(rooms, "inExtractionPoint", flag2);
	}
}
internal static class ProxyEnemies
{
	[HarmonyPatch]
	internal static class CoroutineKeys
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			Type[] array = new Type[2]
			{
				typeof(EnemyVision),
				typeof(EnemyOnScreen)
			};
			foreach (Type type in array)
			{
				Type[] nestedTypes = type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic);
				foreach (Type type2 in nestedTypes)
				{
					if (type2.Name.StartsWith("<Vision>d__") || type2.Name.StartsWith("<Logic>d__"))
					{
						MethodInfo methodInfo = AccessTools.Method(type2, "MoveNext", (Type[])null, (Type[])null);
						if (methodInfo != null)
						{
							yield return methodInfo;
						}
					}
				}
			}
		}

		private static void Prefix(object __instance)
		{
			if (ProxyRegistry.Count == 0 || __instance == null)
			{
				return;
			}
			object obj = AccessTools.Field(__instance.GetType(), "<>4__this")?.GetValue(__instance);
			foreach (ProxyPlayer item in ProxyRegistry.All)
			{
				if (!Wanted(item))
				{
					continue;
				}
				EnemyVision val = (EnemyVision)((obj is EnemyVision) ? obj : null);
				if (val != null)
				{
					val.PlayerAdded(item.ViewId);
					continue;
				}
				EnemyOnScreen val2 = (EnemyOnScreen)((obj is EnemyOnScreen) ? obj : null);
				if (val2 != null)
				{
					val2.PlayerAdded(item.ViewId);
				}
			}
		}
	}

	private static IEnumerable<Enemy> Enemies()
	{
		EnemyDirector instance = EnemyDirector.instance;
		if ((Object)(object)instance == (Object)null || instance.enemiesSpawned == null)
		{
			yield break;
		}
		foreach (EnemyParent item in instance.enemiesSpawned)
		{
			if (!((Object)(object)item == (Object)null))
			{
				Enemy componentInChildren = ((Component)item).GetComponentInChildren<Enemy>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					yield return componentInChildren;
				}
			}
		}
	}

	private static bool Wanted(ProxyPlayer p)
	{
		if (p != null && p.Alive && (Object)(object)p.Avatar != (Object)null)
		{
			return (p.Scopes & PlayerScope.Enemies) != 0;
		}
		return false;
	}

	internal static void Sync()
	{
		if (ProxyRegistry.Count == 0)
		{
			return;
		}
		foreach (Enemy item in Enemies())
		{
			foreach (ProxyPlayer item2 in ProxyRegistry.All)
			{
				if (Wanted(item2))
				{
					try
					{
						item.PlayerAdded(item2.ViewId);
					}
					catch (Exception ex)
					{
						Plugin.Log.LogWarning((object)$"Adding proxy {item2.ViewId} to {((Object)item).name} failed: {ex.Message}");
					}
				}
			}
		}
	}

	internal static void Removed(int viewId)
	{
		foreach (Enemy item in Enemies())
		{
			try
			{
				item.PlayerRemoved(viewId);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"Removing proxy {viewId} from {((Object)item).name} failed: {ex.Message}");
			}
		}
	}
}
public static class ProxyLookups
{
	internal static readonly List<MethodBase> Targets = new List<MethodBase>();

	private static readonly Type[] Mapped = new Type[2]
	{
		typeof(PlayerTumble),
		typeof(PlayerAvatar)
	};

	internal static int Rewrites { get; private set; }

	private static T Resolve<T>(T found, GameObject from) where T : Component
	{
		if ((Object)(object)found != (Object)null || ProxyRegistry.Count == 0)
		{
			return found;
		}
		ProxyPlayer proxyPlayer = ProxyRegistry.ByObject(from);
		if (proxyPlayer == null)
		{
			return found;
		}
		if (!proxyPlayer.RecognisedLogged)
		{
			proxyPlayer.RecognisedLogged = true;
			Plugin.Info($"Proxy '{proxyPlayer.Name}' (ID {proxyPlayer.ViewId}) recognised through its collider '{((Object)from).name}' (layer {LayerMask.LayerToName(from.layer)}): sight rays / hits reach it.");
		}
		if (typeof(T) == typeof(PlayerTumble))
		{
			PlayerTumble obj = proxyPlayer.Parts?.Tumble;
			return (T)(object)((obj is T) ? obj : null);
		}
		if (typeof(T) == typeof(PlayerAvatar))
		{
			PlayerAvatar avatar = proxyPlayer.Avatar;
			return (T)(object)((avatar is T) ? avatar : null);
		}
		return found;
	}

	public static T InParentC<T>(Component c) where T : Component
	{
		return Resolve(c.GetComponentInParent<T>(), c.gameObject);
	}

	public static T InParentCI<T>(Component c, bool includeInactive) where T : Component
	{
		return Resolve(c.GetComponentInParent<T>(includeInactive), c.gameObject);
	}

	public static T InParentG<T>(GameObject g) where T : Component
	{
		return Resolve(g.GetComponentInParent<T>(), g);
	}

	public static T InParentGI<T>(GameObject g, bool includeInactive) where T : Component
	{
		return Resolve(g.GetComponentInParent<T>(includeInactive), g);
	}

	public static T GetC<T>(Component c) where T : Component
	{
		return Resolve(c.GetComponent<T>(), c.gameObject);
	}

	public static T GetG<T>(GameObject g) where T : Component
	{
		return Resolve(g.GetComponent<T>(), g);
	}

	internal static MethodInfo WrapperFor(MethodInfo m)
	{
		if (m == null || !m.IsGenericMethod)
		{
			return null;
		}
		Type[] genericArguments = m.GetGenericArguments();
		if (genericArguments.Length != 1 || Array.IndexOf(Mapped, genericArguments[0]) < 0)
		{
			return null;
		}
		bool flag = m.DeclaringType == typeof(GameObject);
		if (!flag && m.DeclaringType != typeof(Component))
		{
			return null;
		}
		int num = m.GetParameters().Length;
		string text = ((!(m.Name == "GetComponentInParent")) ? ((m.Name == "GetComponent" && num == 0) ? (flag ? "GetG" : "GetC") : null) : ((!flag) ? ((num == 0) ? "InParentC" : "InParentCI") : ((num == 0) ? "InParentG" : "InParentGI")));
		if (text == null)
		{
			return null;
		}
		return AccessTools.Method(typeof(ProxyLookups), text, (Type[])null, (Type[])null).MakeGenericMethod(genericArguments[0]);
	}

	internal static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> instructions)
	{
		foreach (CodeInstruction instruction in instructions)
		{
			if ((instruction.opcode == OpCodes.Call || instruction.opcode == OpCodes.Callvirt) && instruction.operand is MethodInfo m)
			{
				MethodInfo methodInfo = WrapperFor(m);
				if (methodInfo != null)
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = methodInfo;
					Rewrites++;
				}
			}
			yield return instruction;
		}
	}
}
internal static class ProxyNetwork
{
	private sealed class Pending
	{
		public object[] Data;

		public float Until;
	}

	internal const byte CreateCode = 161;

	internal const byte RemoveCode = 162;

	internal const string Magic = "SPL1";

	private const float RetrySeconds = 5f;

	private static readonly List<Pending> pending = new List<Pending>();

	private static readonly Dictionary<int, object[]> sent = new Dictionary<int, object[]>();

	private static bool listening;

	internal static void Listen()
	{
		if (!listening && PhotonNetwork.NetworkingClient != null)
		{
			PhotonNetwork.NetworkingClient.EventReceived += OnEvent;
			listening = true;
		}
	}

	internal static ProxyPlayer CreateOnAll(ProxySettings s, PhotonView anchorView, int slot)
	{
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		if (!SemiFunc.IsMasterClientOrSingleplayer())
		{
			Plugin.Log.LogWarning((object)"ProxyPlayer.CreateNetworked: only the host can create networked proxies.");
			return null;
		}
		if (s == null || (Object)(object)anchorView == (Object)null)
		{
			Plugin.Log.LogError((object)"ProxyPlayer.CreateNetworked: settings and anchorView are required.");
			return null;
		}
		if ((Object)(object)s.Anchor == (Object)null)
		{
			s.Anchor = ((Component)anchorView).transform;
		}
		int num = (s.ViewId = ProxyIds.Networked(anchorView.ViewID, slot));
		ProxyPlayer proxyPlayer = ProxyPlayer.Create(s);
		if (proxyPlayer == null)
		{
			return null;
		}
		proxyPlayer.Networked = true;
		if (!SemiFunc.IsMultiplayer())
		{
			return proxyPlayer;
		}
		PhotonView val = (((Object)(object)s.Body != (Object)null) ? ((Component)s.Body).GetComponent<PhotonView>() : null);
		if ((Object)(object)s.Body != (Object)null && (Object)(object)val == (Object)null)
		{
			Plugin.Log.LogWarning((object)("Proxy '" + proxyPlayer.Name + "': its body has no PhotonView; the other games build it without a body."));
		}
		string text = (((Object)(object)s.VisionPoint != (Object)null) ? PathUnder(((Component)anchorView).transform, s.VisionPoint) : "");
		if ((Object)(object)s.VisionPoint != (Object)null && text == null)
		{
			Plugin.Log.LogWarning((object)("Proxy '" + proxyPlayer.Name + "': its VisionPoint isn't under the anchor; the other games use EyeHeight."));
			text = "";
		}
		object[] array = new object[12]
		{
			"SPL1",
			num,
			anchorView.ViewID,
			((Object)(object)val != (Object)null) ? val.ViewID : 0,
			proxyPlayer.Name,
			(int)s.Scopes,
			s.MaxHealth,
			((Object)(object)s.Anchor == (Object)(object)((Component)anchorView).transform) ? "" : (PathUnder(((Component)anchorView).transform, s.Anchor) ?? ""),
			s.FeetOffset,
			s.EyeHeight,
			text,
			s.RemoveDelay
		};
		sent[num] = array;
		Raise(161, array, cache: true);
		return proxyPlayer;
	}

	internal static void SendRemove(ProxyPlayer p)
	{
		if (SemiFunc.IsMultiplayer() && PhotonNetwork.IsMasterClient)
		{
			Raise(162, new object[2] { "SPL1", p.ViewId }, cache: false);
			Forget(p.ViewId);
		}
	}

	internal static void Forget(int id)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0031: Expected O, but got Unknown
		if (!sent.Remove(id) || !PhotonNetwork.IsMasterClient)
		{
			return;
		}
		PhotonNetwork.RaiseEvent((byte)161, (object)null, new RaiseEventOptions
		{
			CachingOption = (EventCaching)6
		}, SendOptions.SendReliable);
		foreach (object[] value in sent.Values)
		{
			Raise(161, value, cache: true);
		}
	}

	private static void Raise(byte code, object[] data, bool cache)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		RaiseEventOptions val = new RaiseEventOptions
		{
			Receivers = (ReceiverGroup)0,
			CachingOption = (EventCaching)(cache ? 4 : 0)
		};
		PhotonNetwork.RaiseEvent(code, (object)data, val, SendOptions.SendReliable);
	}

	private static void OnEvent(EventData e)
	{
		if ((e.Code != 161 && e.Code != 162) || !(e.CustomData is object[] array) || array.Length < 2 || !(array[0] is string text) || text != "SPL1")
		{
			return;
		}
		try
		{
			if (e.Code == 162)
			{
				ProxyPlayer.FindById((int)array[1])?.RemoveLocal();
			}
			else if (!TryBuild(array))
			{
				pending.Add(new Pending
				{
					Data = array,
					Until = Time.time + 5f
				});
			}
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"A proxy network event couldn't be read: {arg}");
		}
	}

	internal static void Tick()
	{
		if (!listening)
		{
			Listen();
		}
		for (int num = pending.Count - 1; num >= 0; num--)
		{
			if (TryBuild(pending[num].Data))
			{
				pending.RemoveAt(num);
			}
			else if (Time.time > pending[num].Until)
			{
				Plugin.Info($"Proxy '{pending[num].Data[4]}' (ID {pending[num].Data[1]}) not built here: its anchor never appeared (normal for proxies of an earlier level).");
				pending.RemoveAt(num);
			}
		}
	}

	private static bool TryBuild(object[] d)
	{
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		int viewId = (int)d[1];
		if (ProxyRegistry.FindById(viewId) != null)
		{
			return true;
		}
		PhotonView val = PhotonView.Find((int)d[2]);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		int num = (int)d[3];
		PhotonView val2 = ((num != 0) ? PhotonView.Find(num) : null);
		string text = (string)d[7];
		string text2 = (string)d[10];
		ProxyPlayer proxyPlayer = ProxyPlayer.Create(new ProxySettings
		{
			ViewId = viewId,
			Name = (string)d[4],
			Scopes = (PlayerScope)(int)d[5],
			MaxHealth = (int)d[6],
			Anchor = (string.IsNullOrEmpty(text) ? ((Component)val).transform : (((Component)val).transform.Find(text) ?? ((Component)val).transform)),
			FeetOffset = (Vector3)d[8],
			EyeHeight = (float)d[9],
			VisionPoint = (string.IsNullOrEmpty(text2) ? null : ((Component)val).transform.Find(text2)),
			RemoveDelay = (float)d[11],
			Body = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<PhysGrabObject>() : null)
		});
		if (proxyPlayer != null)
		{
			proxyPlayer.Networked = true;
		}
		return true;
	}

	private static string PathUnder(Transform root, Transform t)
	{
		if ((Object)(object)t == (Object)(object)root)
		{
			return "";
		}
		List<string> list = new List<string>();
		Transform val = t;
		while ((Object)(object)val != (Object)null)
		{
			if ((Object)(object)val == (Object)(object)root)
			{
				list.Reverse();
				return string.Join("/", list);
			}
			list.Add(((Object)val).name);
			val = val.parent;
		}
		return null;
	}
}
[HarmonyPatch]
internal static class ProxyPatches
{
	private static readonly HashSet<string> sawLogged = new HashSet<string>();

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

	private static ProxyPlayer ByHealth(PlayerHealth h)
	{
		if (ProxyRegistry.Count == 0 || (Object)(object)h == (Object)null)
		{
			return null;
		}
		foreach (ProxyPlayer item in ProxyRegistry.All)
		{
			if (item.Parts != null && (Object)(object)item.Parts.Health == (Object)(object)h)
			{
				return item;
			}
		}
		return null;
	}

	private static ProxyPlayer ByTumble(PlayerTumble t)
	{
		if (ProxyRegistry.Count == 0 || (Object)(object)t == (Object)null)
		{
			return null;
		}
		foreach (ProxyPlayer item in ProxyRegistry.All)
		{
			if (item.Parts != null && (Object)(object)item.Parts.Tumble == (Object)(object)t)
			{
				return item;
			}
		}
		return null;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerHealth), "Hurt")]
	private static bool Hurt(PlayerHealth __instance, int damage, int enemyIndex, bool hurtByHeal)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		ProxyPlayer proxyPlayer = ByHealth(__instance);
		if (proxyPlayer == null)
		{
			return true;
		}
		if (SemiFunc.IsMasterClientOrSingleplayer() && damage > 0)
		{
			proxyPlayer.RaiseHurt(new ProxyDamage
			{
				Amount = damage,
				Position = ((Component)proxyPlayer.Avatar).transform.position,
				EnemyIndex = enemyIndex,
				ByHeal = hurtByHeal
			});
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerHealth), "HurtOther")]
	private static bool HurtOther(PlayerHealth __instance, int damage, Vector3 hurtPosition, int enemyIndex, bool hurtByHeal)
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		ProxyPlayer proxyPlayer = ByHealth(__instance);
		if (proxyPlayer == null)
		{
			return true;
		}
		if (SemiFunc.IsMasterClientOrSingleplayer() && damage > 0)
		{
			proxyPlayer.RaiseHurt(new ProxyDamage
			{
				Amount = damage,
				Position = hurtPosition,
				EnemyIndex = enemyIndex,
				ByHeal = hurtByHeal
			});
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerHealth), "Heal")]
	private static bool Heal(PlayerHealth __instance, int healAmount)
	{
		ProxyPlayer proxyPlayer = ByHealth(__instance);
		if (proxyPlayer == null)
		{
			return true;
		}
		if (SemiFunc.IsMasterClientOrSingleplayer() && healAmount > 0)
		{
			proxyPlayer.RaiseHealed(healAmount);
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerHealth), "HealOther")]
	private static bool HealOther(PlayerHealth __instance, int healAmount)
	{
		ProxyPlayer proxyPlayer = ByHealth(__instance);
		if (proxyPlayer == null)
		{
			return true;
		}
		if (SemiFunc.IsMasterClientOrSingleplayer() && healAmount > 0)
		{
			proxyPlayer.RaiseHealed(healAmount);
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(SemiFunc), "PlayerGetName")]
	private static bool PlayerGetName(PlayerAvatar player, ref string __result)
	{
		ProxyPlayer proxyPlayer = ProxyRegistry.Find(player);
		if (proxyPlayer == null)
		{
			return true;
		}
		__result = proxyPlayer.Name;
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(SemiFunc), "PlayerEyesOverride")]
	private static bool PlayerEyesOverride(PlayerAvatar _player)
	{
		if (ProxyRegistry.Count != 0)
		{
			return ProxyRegistry.Find(_player) == null;
		}
		return true;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(EnemyVision), "VisionTrigger")]
	private static void VisionTrigger(EnemyVision __instance, PlayerAvatar player)
	{
		ProxyPlayer proxyPlayer = ProxyRegistry.Find(player);
		if (proxyPlayer != null && !((Object)(object)__instance == (Object)null))
		{
			EnemyParent componentInParent = ((Component)__instance).GetComponentInParent<EnemyParent>();
			string text = (((Object)(object)componentInParent != (Object)null) ? ((Object)componentInParent).name.Replace("(Clone)", "").Trim() : ((Object)__instance).name);
			if (sawLogged.Add(text + "/" + proxyPlayer.ViewId))
			{
				Plugin.Info($"{text} saw proxy '{proxyPlayer.Name}' (ID {proxyPlayer.ViewId}).");
			}
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerTumble), "TumbleForce")]
	private static bool TumbleForce(PlayerTumble __instance, Vector3 _force)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		ProxyPlayer proxyPlayer = ByTumble(__instance);
		if (proxyPlayer == null)
		{
			return true;
		}
		Rigidbody val = (((Object)(object)proxyPlayer.Body != (Object)null) ? proxyPlayer.Body.rb : null);
		if ((Object)(object)val != (Object)null && SemiFunc.IsMasterClientOrSingleplayer() && proxyPlayer.Alive)
		{
			val.AddForce(_force, (ForceMode)1);
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerTumble), "TumbleTorque")]
	private static bool TumbleTorque(PlayerTumble __instance, Vector3 _torque)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		ProxyPlayer proxyPlayer = ByTumble(__instance);
		if (proxyPlayer == null)
		{
			return true;
		}
		Rigidbody val = (((Object)(object)proxyPlayer.Body != (Object)null) ? proxyPlayer.Body.rb : null);
		if ((Object)(object)val != (Object)null && SemiFunc.IsMasterClientOrSingleplayer() && proxyPlayer.Alive)
		{
			val.AddTorque(_torque, (ForceMode)1);
		}
		return false;
	}

	private static bool Guard(PhotonView view, string methodName)
	{
		if ((Object)(object)view == (Object)null || !ProxyIds.IsProxyRange(view.ViewID) || ProxyRegistry.FindById(view.ViewID) == null)
		{
			return true;
		}
		if (blocked.Add(methodName))
		{
			Plugin.Info("Network call '" + methodName + "' on a proxy dropped (proxies aren't on the network; shown once per call name).");
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PhotonView), "RPC", new Type[]
	{
		typeof(string),
		typeof(RpcTarget),
		typeof(object[])
	})]
	private static bool RpcToTarget(PhotonView __instance, string methodName)
	{
		return Guard(__instance, methodName);
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PhotonView), "RPC", new Type[]
	{
		typeof(string),
		typeof(Player),
		typeof(object[])
	})]
	private static bool RpcToPlayer(PhotonView __instance, string methodName)
	{
		return Guard(__instance, methodName);
	}
}
[HarmonyPatch]
internal static class ProxyTumbleIgnore
{
	private static readonly string[] Names = new string[14]
	{
		"TumbleRequest", "TumbleSet", "TumbleOverride", "TumbleOverrideTime", "TumbleStunTime", "ImpactHurtSet", "DisableCustomGravity", "OverrideEnemyHurt", "OverrideLookAtCamera", "OverrideDisableLookAtCamera",
		"OverrideTumbleUIDisable", "TumbleImpact", "HitEnemy", "BreakImpact"
	};

	private static IEnumerable<MethodBase> TargetMethods()
	{
		string[] names = Names;
		foreach (string text in names)
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(PlayerTumble), text, (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				yield return methodInfo;
			}
			else
			{
				Plugin.Log.LogWarning((object)("PlayerTumble." + text + " not found in this game version; not ignored on proxies."));
			}
		}
	}

	private static bool Prefix(PlayerTumble __instance)
	{
		if (ProxyRegistry.Count == 0 || (Object)(object)__instance == (Object)null)
		{
			return true;
		}
		foreach (ProxyPlayer item in ProxyRegistry.All)
		{
			if (item.Parts != null && (Object)(object)item.Parts.Tumble == (Object)(object)__instance)
			{
				return false;
			}
		}
		return true;
	}
}
public sealed class ProxySettings
{
	public string Name = "Proxy";

	public PlayerScope Scopes = PlayerScope.Enemies;

	public Transform Anchor;

	public Vector3 FeetOffset = Vector3.zero;

	public float EyeHeight = 1.4f;

	public Transform VisionPoint;

	public PhysGrabObject Body;

	public Collider[] HitColliders;

	public int MaxHealth = 100;

	public int ViewId;

	public float RemoveDelay = 3f;
}
public struct ProxyDamage
{
	public int Amount;

	public Vector3 Position;

	public int EnemyIndex;

	public bool ByHeal;
}
public sealed class ProxyPlayer
{
	internal Collider[] hitColliders = (Collider[])(object)new Collider[0];

	private PlayerScope scopes;

	internal float RemoveDelay;

	internal float CreatedAt = Time.time;

	internal bool RecognisedLogged;

	internal float RemoveAt = -1f;

	internal Vector3 FeetOffset;

	internal float EyeHeight;

	internal bool OwnVisionPoint;

	internal ProxyBuilder.Parts Parts;

	public PlayerAvatar Avatar { get; internal set; }

	public int ViewId { get; internal set; }

	public string Name { get; internal set; }

	public Transform Anchor { get; internal set; }

	public PhysGrabObject Body { get; internal set; }

	public Transform VisionPoint { get; internal set; }

	public IReadOnlyList<Collider> HitColliders => hitColliders;

	public int Health { get; private set; }

	public int MaxHealth { get; private set; }

	public bool Alive { get; internal set; } = true;

	public bool Networked { get; internal set; }

	public PlayerScope Scopes
	{
		get
		{
			return scopes;
		}
		set
		{
			scopes = value;
			ProxyRegistry.Changed();
		}
	}

	public static IReadOnlyList<ProxyPlayer> All => ProxyRegistry.All;

	public event Action<ProxyPlayer, ProxyDamage> Hurt;

	public event Action<ProxyPlayer, int> Healed;

	internal ProxyPlayer()
	{
	}

	public static ProxyPlayer Create(ProxySettings settings)
	{
		if (!Plugin.Active)
		{
			Plugin.Log.LogWarning((object)"ProxyPlayer.Create: the library is switched off (or failed to start), so no proxy was made.");
			return null;
		}
		if (settings == null || (Object)(object)settings.Anchor == (Object)null)
		{
			Plugin.Log.LogError((object)"ProxyPlayer.Create: settings.Anchor is required.");
			return null;
		}
		int num = ((settings.ViewId != 0) ? settings.ViewId : ProxyIds.NextLocal());
		if (ProxyRegistry.FindById(num) != null)
		{
			Plugin.Log.LogError((object)$"ProxyPlayer.Create: a proxy with ID {num} already exists.");
			return null;
		}
		ProxyPlayer proxyPlayer = ProxyBuilder.Build(settings, num);
		if (proxyPlayer == null)
		{
			return null;
		}
		ProxyRegistry.Add(proxyPlayer);
		ProxyDriver.Ensure();
		ProxyEnemies.Sync();
		Plugin.Info($"Proxy '{proxyPlayer.Name}' (ID {num}) created; seen by {proxyPlayer.Scopes}.");
		return proxyPlayer;
	}

	public static ProxyPlayer CreateNetworked(ProxySettings settings, PhotonView anchorView, int slot = 0)
	{
		return ProxyNetwork.CreateOnAll(settings, anchorView, slot);
	}

	public static ProxyPlayer Find(PlayerAvatar avatar)
	{
		return ProxyRegistry.Find(avatar);
	}

	public static ProxyPlayer FindById(int viewId)
	{
		return ProxyRegistry.FindById(viewId);
	}

	public static bool IsProxy(PlayerAvatar avatar)
	{
		if (ProxyRegistry.Count > 0)
		{
			return ProxyRegistry.Find(avatar) != null;
		}
		return false;
	}

	public void SetHealth(int health, int maxHealth)
	{
		MaxHealth = Mathf.Max(1, maxHealth);
		Health = Mathf.Clamp(health, 0, MaxHealth);
		ProxyBuilder.WriteHealth(this);
	}

	public void Remove()
	{
		if (Alive)
		{
			if (Networked && SemiFunc.IsMasterClientOrSingleplayer())
			{
				ProxyNetwork.SendRemove(this);
			}
			RemoveLocal();
		}
	}

	internal void RemoveLocal()
	{
		if (Alive)
		{
			Alive = false;
			ProxyBuilder.MarkDead(this);
			RemoveAt = Time.time + RemoveDelay;
			Plugin.Info($"Proxy '{Name}' (ID {ViewId}) removed after {Time.time - CreatedAt:0.0} s; gone in {RemoveDelay:0.#} s.");
		}
	}

	internal void Destroy()
	{
		Alive = false;
		if (Networked && SemiFunc.IsMasterClientOrSingleplayer())
		{
			ProxyNetwork.Forget(ViewId);
		}
		ProxyRegistry.Remove(this);
		ProxyEnemies.Removed(ViewId);
		ProxyBuilder.Destroy(this);
		Avatar = null;
	}

	internal void RaiseHurt(ProxyDamage hit)
	{
		if (!Alive)
		{
			return;
		}
		try
		{
			this.Hurt?.Invoke(this, hit);
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Proxy '{Name}': a Hurt handler failed: {arg}");
		}
	}

	internal void RaiseHealed(int amount)
	{
		if (!Alive)
		{
			return;
		}
		try
		{
			this.Healed?.Invoke(this, amount);
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Proxy '{Name}': a Healed handler failed: {arg}");
		}
	}

	internal float RemoveDelayOf()
	{
		return RemoveDelay;
	}

	internal void InitHealth(int max)
	{
		MaxHealth = Mathf.Max(1, max);
		Health = MaxHealth;
	}

	internal void SetScopesSilently(PlayerScope s)
	{
		scopes = s;
	}
}
internal static class ProxyIds
{
	internal const int NetworkedBase = 16000000;

	internal const int LocalBase = 16600000;

	private static int next;

	internal static int Networked(int anchorViewId, int slot)
	{
		return 16000000 + anchorViewId * 10 + Mathf.Clamp(slot, 0, 9);
	}

	internal static int NextLocal()
	{
		return 16600000 + ++next % 99999;
	}

	internal static bool IsProxyRange(int id)
	{
		if (id >= 16000000)
		{
			return id < 16700000;
		}
		return false;
	}
}
internal static class ProxyRegistry
{
	private static readonly List<ProxyPlayer> proxies = new List<ProxyPlayer>();

	private static PlayerScope union;

	private static readonly Dictionary<GameObject, ProxyPlayer> byObject = new Dictionary<GameObject, ProxyPlayer>();

	internal static int Version { get; private set; }

	internal static int Count => proxies.Count;

	internal static IReadOnlyList<ProxyPlayer> All => proxies;

	internal static bool AnyVisibleTo(PlayerScope scope)
	{
		return (union & scope) != 0;
	}

	internal static void Add(ProxyPlayer proxy)
	{
		if (proxy == null || proxies.Contains(proxy))
		{
			return;
		}
		proxies.Add(proxy);
		Collider[] hitColliders = proxy.hitColliders;
		foreach (Collider val in hitColliders)
		{
			if (!((Object)(object)val == (Object)null))
			{
				byObject[((Component)val).gameObject] = proxy;
				if ((Object)(object)val.attachedRigidbody != (Object)null)
				{
					byObject[((Component)val.attachedRigidbody).gameObject] = proxy;
				}
			}
		}
		if ((Object)(object)proxy.Body != (Object)null)
		{
			byObject[((Component)proxy.Body).gameObject] = proxy;
		}
		Changed();
	}

	internal static void Remove(ProxyPlayer proxy)
	{
		List<GameObject> list = new List<GameObject>();
		foreach (KeyValuePair<GameObject, ProxyPlayer> item in byObject)
		{
			if (item.Value == proxy || (Object)(object)item.Key == (Object)null)
			{
				list.Add(item.Key);
			}
		}
		foreach (GameObject item2 in list)
		{
			byObject.Remove(item2);
		}
		if (proxies.Remove(proxy))
		{
			Changed();
		}
	}

	internal static ProxyPlayer ByObject(GameObject go)
	{
		if ((Object)(object)go == (Object)null || byObject.Count == 0)
		{
			return null;
		}
		Transform val = go.transform;
		int num = 0;
		while (num < 5 && (Object)(object)val != (Object)null)
		{
			if (byObject.TryGetValue(((Component)val).gameObject, out var value) && value != null && value.Alive && (Object)(object)value.Avatar != (Object)null)
			{
				return value;
			}
			num++;
			val = val.parent;
		}
		return null;
	}

	internal static void Changed()
	{
		proxies.RemoveAll((ProxyPlayer p) => p == null || (Object)(object)p.Avatar == (Object)null);
		union = PlayerScope.None;
		foreach (ProxyPlayer proxy in proxies)
		{
			union |= proxy.Scopes;
		}
		Version++;
	}

	internal static ProxyPlayer Find(PlayerAvatar avatar)
	{
		if ((Object)(object)avatar == (Object)null || proxies.Count == 0)
		{
			return null;
		}
		foreach (ProxyPlayer proxy in proxies)
		{
			if ((Object)(object)proxy.Avatar == (Object)(object)avatar)
			{
				return proxy;
			}
		}
		return null;
	}

	internal static ProxyPlayer FindById(int viewId)
	{
		foreach (ProxyPlayer proxy in proxies)
		{
			if (proxy.ViewId == viewId)
			{
				return proxy;
			}
		}
		return null;
	}
}
internal static class ScopeContext
{
	[ThreadStatic]
	private static PlayerScope current;

	private static readonly Assembly GameAssembly = typeof(GameDirector).Assembly;

	private static readonly Assembly OwnAssembly = typeof(ScopeContext).Assembly;

	internal static PlayerScope Current => current;

	internal static PlayerScope Enter(PlayerScope scope)
	{
		PlayerScope result = current;
		current = scope;
		return result;
	}

	internal static void Restore(PlayerScope previous)
	{
		current = previous;
	}

	internal static PlayerScope Effective()
	{
		if (current != PlayerScope.None)
		{
			return current;
		}
		if (!ProxyRegistry.AnyVisibleTo(PlayerScope.Mods))
		{
			return PlayerScope.None;
		}
		if (!CalledFromMod())
		{
			return PlayerScope.None;
		}
		return PlayerScope.Mods;
	}

	private static bool CalledFromMod()
	{
		StackTrace stackTrace = new StackTrace(2, fNeedFileInfo: false);
		for (int i = 0; i < stackTrace.FrameCount; i++)
		{
			Type type = (stackTrace.GetFrame(i)?.GetMethod())?.DeclaringType;
			if (type == null)
			{
				continue;
			}
			Assembly assembly = type.Assembly;
			if (!(assembly == OwnAssembly) && (!(assembly == GameAssembly) || !(type == typeof(SemiFunc))))
			{
				string name = assembly.GetName().Name;
				if (!name.StartsWith("0Harmony") && !name.StartsWith("MonoMod") && !name.StartsWith("HarmonySharedState"))
				{
					return assembly != GameAssembly;
				}
			}
		}
		return false;
	}
}
public static class ScopedPlayers
{
	public readonly struct ScopeHandle : IDisposable
	{
		private readonly PlayerScope previous;

		internal ScopeHandle(PlayerScope previous)
		{
			this.previous = previous;
		}

		public void Dispose()
		{
			ScopeContext.Restore(previous);
		}
	}

	private static readonly List<PlayerAvatar> Empty = new List<PlayerAvatar>();

	private static readonly Dictionary<PlayerScope, List<PlayerAvatar>> cache = new Dictionary<PlayerScope, List<PlayerAvatar>>();

	private static readonly Dictionary<PlayerScope, int> cacheFrame = new Dictionary<PlayerScope, int>();

	private static int cacheVersion = -1;

	public static PlayerScope Current => ScopeContext.Current;

	public static bool HasProxies => ProxyRegistry.Count > 0;

	public static List<PlayerAvatar> Get(PlayerScope scope)
	{
		return ListFor(GameDirector.instance, scope);
	}

	public static ScopeHandle Enter(PlayerScope scope)
	{
		return new ScopeHandle(ScopeContext.Enter(scope));
	}

	public static List<PlayerAvatar> PlayerListForCurrentScope(GameDirector director)
	{
		return ListFor(director, ScopeContext.Effective());
	}

	internal static List<PlayerAvatar> ListFor(GameDirector director, PlayerScope scope)
	{
		List<PlayerAvatar> list = (((Object)(object)director != (Object)null) ? director.PlayerList : null);
		if (scope == PlayerScope.None || !ProxyRegistry.AnyVisibleTo(scope))
		{
			return list ?? Empty;
		}
		if (cacheVersion != ProxyRegistry.Version)
		{
			cache.Clear();
			cacheFrame.Clear();
			cacheVersion = ProxyRegistry.Version;
		}
		int frameCount = Time.frameCount;
		if (cache.TryGetValue(scope, out var value) && cacheFrame[scope] == frameCount)
		{
			return value;
		}
		if (value == null)
		{
			value = (cache[scope] = new List<PlayerAvatar>());
		}
		value.Clear();
		if (list != null)
		{
			value.AddRange(list);
		}
		foreach (ProxyPlayer item in ProxyRegistry.All)
		{
			if ((Object)(object)item.Avatar != (Object)null && (item.Scopes & scope) != PlayerScope.None && !value.Contains(item.Avatar))
			{
				value.Add(item.Avatar);
			}
		}
		cacheFrame[scope] = frameCount;
		return value;
	}
}
public static class ScopeReport
{
	private static readonly List<PlayerLookup> lookups = new List<PlayerLookup>();

	private static readonly List<string> helpers = new List<string>();

	public static IReadOnlyList<PlayerLookup> Lookups => lookups;

	public static IReadOnlyList<string> Helpers => helpers;

	public static int ListReadsRewritten { get; private set; }

	public static int PatchFailures { get; private set; }

	public static bool Ready { get; private set; }

	public static PlayerScope ScopeOf(string className, string methodName)
	{
		string name = className + "." + methodName;
		PlayerLookup playerLookup = lookups.FirstOrDefault((PlayerLookup x) => x.Name == name);
		if (playerLookup == null || !playerLookup.Patched)
		{
			return PlayerScope.None;
		}
		return playerLookup.Scope;
	}

	internal static void Set(Discovery.Result found, int rewrites, int failures)
	{
		lookups.Clear();
		lookups.AddRange(found.Lookups);
		helpers.Clear();
		helpers.AddRange(found.HelperNames);
		ListReadsRewritten = rewrites;
		PatchFailures = failures;
		Ready = true;
	}

	public static string Summary()
	{
		StringBuilder stringBuilder = new StringBuilder(string.Format("{0} {1}: {2} player lookups found, {3} SemiFunc helpers; ", "ScopePartitioningLibrary", "1.0.0", lookups.Count, helpers.Count));
		List<string> list = new List<string>();
		foreach (IGrouping<PlayerScope, PlayerLookup> item in from l in lookups
			where l.Patched
			group l by l.Scope into g
			orderby (int)g.Key
			select g)
		{
			list.Add($"{item.Key} {item.Count()}");
		}
		stringBuilder.Append((list.Count > 0) ? string.Join(", ", list) : "none scoped");
		stringBuilder.Append($"; {lookups.Count((PlayerLookup l) => !l.Patched)} left alone (real players only); {ListReadsRewritten} list reads rewritten");
		if (PatchFailures > 0)
		{
			stringBuilder.Append($"; {PatchFailures} could not be patched (see the warnings)");
		}
		stringBuilder.Append($"; {ProxyLookups.Targets.Count} enemy / hurt-collider methods know proxy hit colliders ({ProxyLookups.Rewrites} calls)");
		stringBuilder.Append(". With no proxies the game sees exactly its own players.");
		return stringBuilder.ToString();
	}

	public static string Full(bool includeUnscoped)
	{
		StringBuilder stringBuilder = new StringBuilder("Player lookups by scope (rule; R = reads GameDirector.PlayerList, W = also changes it so its reads are left alone, H = calls SemiFunc helpers):");
		foreach (IGrouping<PlayerScope, PlayerLookup> item in from l in lookups
			group l by l.Patched ? l.Scope : PlayerScope.None into g
			orderby (int)((g.Key != PlayerScope.None) ? g.Key : ((PlayerScope)2147483647))
			select g)
		{
			if (item.Key == PlayerScope.None && !includeUnscoped)
			{
				continue;
			}
			stringBuilder.Append(string.Format("\n[{0}] {1}", (item.Key == PlayerScope.None) ? "None: left alone" : item.Key.ToString(), item.Count()));
			foreach (PlayerLookup item2 in item)
			{
				string text = (item2.ReadsListDirectly ? "R" : "") + (item2.WritesList ? "W" : "") + ((item2.HelpersCalled.Count > 0) ? ("H " + string.Join(",", item2.HelpersCalled)) : "");
				stringBuilder.Append("\n  " + item2.Name + "  (" + item2.Rule + "; " + text + ")");
			}
		}
		stringBuilder.Append("\nSemiFunc helpers: " + string.Join(", ", helpers));
		return stringBuilder.ToString();
	}
}
internal static class ScopeRules
{
	private static readonly Dictionary<string, PlayerScope> Exact = new Dictionary<string, PlayerScope>
	{
		["GameDirector"] = PlayerScope.None,
		["PlayerAvatar"] = PlayerScope.None,
		["EnemyOnScreen"] = PlayerScope.None,
		["BirthdayBoyBalloon"] = PlayerScope.Enemies,
		["FloaterAttackLogic"] = PlayerScope.Enemies,
		["SlowWalkerAttack"] = PlayerScope.Enemies,
		["VirusEnemyInfection"] = PlayerScope.Enemies,
		["VirusPopUp"] = PlayerScope.Enemies,
		["RockSlide"] = PlayerScope.Hazards,
		["RockSlideRock"] = PlayerScope.Hazards,
		["BreakableFloorTrigger"] = PlayerScope.Hazards,
		["Larva"] = PlayerScope.Hazards,
		["LarvaPimpleSpawner"] = PlayerScope.Hazards,
		["MineCart"] = PlayerScope.Hazards,
		["LightManager"] = PlayerScope.Hazards,
		["AmbienceBreakers"] = PlayerScope.Hazards,
		["SlowProjectile"] = PlayerScope.Hazards,
		["BreakableFloor"] = PlayerScope.Hazards,
		["MonkeyBox"] = PlayerScope.Hazards,
		["ToiletFun"] = PlayerScope.Hazards,
		["FlatScreenTV"] = PlayerScope.Hazards,
		["MuseumLaserLogic"] = PlayerScope.Hazards,
		["MuseumPropMoneyHead"] = PlayerScope.Hazards,
		["WizardAquaHabitat"] = PlayerScope.Valuables,
		["Cauldron"] = PlayerScope.Valuables,
		["LevitationSphere"] = PlayerScope.Valuables,
		["MusicalValuableLogic"] = PlayerScope.Valuables,
		["ShopKeeper"] = PlayerScope.NPCs,
		["MuseumMegaSemiBot"] = PlayerScope.NPCs,
		["CosmeticShopMachine"] = PlayerScope.NPCs,
		["CosmeticShopMachineAnimator"] = PlayerScope.NPCs,
		["TruckHealer"] = PlayerScope.Items,
		["ChargingStation"] = PlayerScope.Items,
		["PhysGrabCart"] = PlayerScope.Items,
		["LevelGenerator"] = PlayerScope.LevelFlow,
		["RunManager"] = PlayerScope.LevelFlow,
		["ExtractionPoint"] = PlayerScope.LevelFlow,
		["TruckScreenText"] = PlayerScope.LevelFlow,
		["StatsManager"] = PlayerScope.LevelFlow,
		["ShopManager"] = PlayerScope.LevelFlow,
		["UpgradeStand"] = PlayerScope.LevelFlow,
		["Arena"] = PlayerScope.LevelFlow,
		["ArenaRace"] = PlayerScope.LevelFlow,
		["TutorialDirector"] = PlayerScope.LevelFlow,
		["ValuableDirector"] = PlayerScope.LevelFlow,
		["RoundDirector"] = PlayerScope.LevelFlow,
		["RunManagerPUN"] = PlayerScope.LevelFlow,
		["ReloadScene"] = PlayerScope.LevelFlow,
		["SessionManager"] = PlayerScope.LevelFlow,
		["Module"] = PlayerScope.LevelFlow,
		["ModuleConnectObject"] = PlayerScope.LevelFlow,
		["ExtractionHalloweenTower"] = PlayerScope.LevelFlow,
		["TruckDoor"] = PlayerScope.LevelFlow,
		["TruckMenuAnimated"] = PlayerScope.LevelFlow,
		["TruckScreenOpen"] = PlayerScope.LevelFlow,
		["ShopKeycardDoor"] = PlayerScope.LevelFlow,
		["SpectateCamera"] = PlayerScope.CameraAndUI,
		["LoadingUI"] = PlayerScope.CameraAndUI,
		["ChatManager"] = PlayerScope.CameraAndUI,
		["DebugCommandHandler"] = PlayerScope.CameraAndUI,
		["DirtFinderCounter"] = PlayerScope.CameraAndUI,
		["GameplayButtonCosmetics"] = PlayerScope.CameraAndUI,
		["MapToolController"] = PlayerScope.CameraAndUI,
		["PlayerListDisplay"] = PlayerScope.CameraAndUI,
		["PlayerVoiceChat"] = PlayerScope.VoiceAndEyes,
		["PlayerEyes"] = PlayerScope.VoiceAndEyes,
		["SemiEyes"] = PlayerScope.VoiceAndEyes,
		["DebugComputerCheck"] = PlayerScope.VoiceAndEyes,
		["PunManager"] = PlayerScope.Network,
		["NetworkManager"] = PlayerScope.Network
	};

	private static readonly (Func<string, bool> match, PlayerScope scope, string rule)[] Patterns = new(Func<string, bool>, PlayerScope, string)[5]
	{
		((string n) => n.StartsWith("Enemy"), PlayerScope.Enemies, "name starts with Enemy"),
		((string n) => n.StartsWith("Valuable") || n.EndsWith("Valuable"), PlayerScope.Valuables, "name starts or ends with Valuable"),
		((string n) => n.StartsWith("Item"), PlayerScope.Items, "name starts with Item"),
		((string n) => n.EndsWith("Trap") || n.StartsWith("Trap") || n.StartsWith("Animatronic"), PlayerScope.Hazards, "a trap or animatronic"),
		((string n) => n.StartsWith("Menu") || n.StartsWith("Platforms."), PlayerScope.CameraAndUI, "a menu or platform class")
	};

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

	internal static void SetOverrides(string text, Action<string> warn)
	{
		overrides = new Dictionary<string, PlayerScope>();
		if (string.IsNullOrWhiteSpace(text))
		{
			return;
		}
		string[] array = text.Split(';', ',');
		for (int i = 0; i < array.Length; i++)
		{
			string text2 = array[i].Trim();
			if (text2.Length == 0)
			{
				continue;
			}
			int num = text2.IndexOf('=');
			if (num <= 0)
			{
				warn("Override '" + text2 + "' has no '=': skipped.");
				continue;
			}
			string key = text2.Substring(0, num).Trim();
			if (!Enum.TryParse<PlayerScope>(text2.Substring(num + 1).Trim().Replace('|', ','), ignoreCase: true, out var result))
			{
				warn("Override '" + text2 + "': unknown scope: skipped.");
			}
			else
			{
				overrides[key] = result;
			}
		}
	}

	internal static PlayerScope Decide(string outerClass, string method, out string rule)
	{
		if (overrides.TryGetValue(outerClass + "." + method, out var value))
		{
			rule = "config override (method)";
			return value;
		}
		if (overrides.TryGetValue(outerClass, out value))
		{
			rule = "config override (class)";
			return value;
		}
		if (Exact.TryGetValue(oute