Decompiled source of SOD Performance v1.0.0

SODPerformance.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.Scripting;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SODPerformance")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SODPerformance")]
[assembly: AssemblyTitle("SODPerformance")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SODPerformance
{
	internal static class CpuPlacement
	{
		internal struct L3
		{
			public ulong Mask;

			public int Group;

			public uint Bytes;
		}

		private const int RelationCache = 2;

		internal static bool Detected;

		internal static bool HasVCache;

		internal static bool Applied;

		internal static bool Broken;

		internal static ulong VCacheMask;

		internal static ulong OriginalMask;

		internal static string Layout = "not detected yet";

		internal static string Status = "-";

		internal static int Switches;

		internal static readonly long[] Frames = new long[2];

		internal static readonly long[] FramesOnVCache = new long[2];

		private static long unpinnedSamplesAtStart;

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GetLogicalProcessorInformationEx(int relationshipType, IntPtr buffer, ref uint returnedLength);

		[DllImport("kernel32.dll")]
		private static extern uint GetCurrentProcessorNumber();

		[DllImport("kernel32.dll")]
		private static extern IntPtr GetCurrentProcess();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GetProcessAffinityMask(IntPtr process, out UIntPtr processMask, out UIntPtr systemMask);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetProcessAffinityMask(IntPtr process, UIntPtr mask);

		internal static void Tick(bool optimizationsOn)
		{
			if (Broken)
			{
				return;
			}
			try
			{
				if (!Detected)
				{
					Detect();
				}
				if (HasVCache)
				{
					uint currentProcessorNumber = GetCurrentProcessorNumber();
					int num = (Applied ? 1 : 0);
					Frames[num]++;
					if (currentProcessorNumber < 64 && ((VCacheMask >> (int)currentProcessorNumber) & 1) != 0L)
					{
						FramesOnVCache[num]++;
					}
					if (!Applied)
					{
						unpinnedSamplesAtStart++;
					}
				}
				bool flag = optimizationsOn && HasVCache && PerfConfig.PreferVCacheCores.Value && unpinnedSamplesAtStart >= 120;
				if (flag != Applied)
				{
					Apply(flag);
				}
			}
			catch (Exception ex)
			{
				Broken = true;
				Status = "error: " + ex.GetType().Name;
				Runner.ReportError("cpu-placement", ex);
			}
		}

		private static void Apply(bool pin)
		{
			ulong num = (pin ? VCacheMask : OriginalMask);
			if (num == 0L)
			{
				Broken = true;
				Status = "no usable mask";
			}
			else if (!SetProcessAffinityMask(GetCurrentProcess(), new UIntPtr(num)))
			{
				Broken = true;
				Status = $"could not set affinity (error {Marshal.GetLastWin32Error()})";
				Plugin.L.LogWarning((object)("CPU: " + Status));
			}
			else
			{
				Applied = pin;
				Switches++;
				Status = (pin ? ("game kept on V-Cache cores " + MaskToText(num)) : ("normal (all cores " + MaskToText(num) + ")"));
				Plugin.L.LogInfo((object)("CPU: " + Status));
			}
		}

		private static void Detect()
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			Detected = true;
			if (!OperatingSystem.IsWindows())
			{
				Layout = "not Windows";
				return;
			}
			if (!GetProcessAffinityMask(GetCurrentProcess(), out var processMask, out var _))
			{
				Layout = $"affinity query failed (error {Marshal.GetLastWin32Error()})";
				return;
			}
			OriginalMask = processMask.ToUInt64();
			uint returnedLength = 0u;
			GetLogicalProcessorInformationEx(2, IntPtr.Zero, ref returnedLength);
			if (returnedLength == 0 || returnedLength > 1048576)
			{
				Layout = "cache query failed";
				return;
			}
			IntPtr intPtr = Marshal.AllocHGlobal((int)returnedLength);
			try
			{
				if (!GetLogicalProcessorInformationEx(2, intPtr, ref returnedLength))
				{
					Layout = $"cache query failed (error {Marshal.GetLastWin32Error()})";
					return;
				}
				byte[] array = new byte[returnedLength];
				Marshal.Copy(intPtr, array, 0, (int)returnedLength);
				Decide(ParseL3(array, (int)returnedLength), OriginalMask, out VCacheMask, out HasVCache, out Layout);
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(5, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("CPU: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Layout);
			}
			l.LogInfo(val);
		}

		internal static List<L3> ParseL3(byte[] b, int len)
		{
			List<L3> list = new List<L3>();
			int num2;
			for (int i = 0; i + 8 <= len; i += num2)
			{
				int num = BitConverter.ToInt32(b, i);
				num2 = BitConverter.ToInt32(b, i + 4);
				if (num2 <= 0 || i + num2 > len)
				{
					break;
				}
				if (num == 2 && num2 >= 50)
				{
					byte num3 = b[i + 8];
					uint bytes = BitConverter.ToUInt32(b, i + 12);
					ulong mask = BitConverter.ToUInt64(b, i + 40);
					int num4 = BitConverter.ToUInt16(b, i + 48);
					if (num3 == 3)
					{
						list.Add(new L3
						{
							Mask = mask,
							Group = num4,
							Bytes = bytes
						});
					}
				}
			}
			return list;
		}

		internal static void Decide(List<L3> l3, ulong allowed, out ulong vcache, out bool has, out string layout)
		{
			vcache = 0uL;
			has = false;
			StringBuilder stringBuilder = new StringBuilder();
			foreach (L3 item in l3)
			{
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(17, 3, stringBuilder2);
				handler.AppendLiteral("L3 ");
				handler.AppendFormatted(item.Bytes / 1048576);
				handler.AppendLiteral(" MB on CPUs ");
				handler.AppendFormatted(MaskToText(item.Mask));
				handler.AppendFormatted((item.Group != 0) ? $" (group {item.Group})" : "");
				handler.AppendLiteral("; ");
				stringBuilder2.Append(ref handler);
			}
			if (l3.Count < 2)
			{
				layout = stringBuilder.Append("one L3 domain: nothing to do").ToString();
				return;
			}
			if (l3.Exists((L3 c) => c.Group != 0))
			{
				layout = stringBuilder.Append("more than one processor group: left alone").ToString();
				return;
			}
			uint num = 0u;
			uint num2 = uint.MaxValue;
			foreach (L3 item2 in l3)
			{
				if (item2.Bytes > num)
				{
					num = item2.Bytes;
				}
				if (item2.Bytes < num2)
				{
					num2 = item2.Bytes;
				}
			}
			if (num2 == 0 || num < (ulong)((long)num2 * 3L) / 2uL)
			{
				layout = stringBuilder.Append("all L3 domains are the same size: nothing to do").ToString();
				return;
			}
			foreach (L3 item3 in l3)
			{
				if (item3.Bytes == num)
				{
					vcache |= item3.Mask;
				}
			}
			vcache &= allowed;
			has = vcache != 0;
			layout = stringBuilder.Append(has ? ("V-Cache cores: " + MaskToText(vcache)) : "V-Cache cores not in the allowed set").ToString();
		}

		internal static string MaskToText(ulong mask)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			while (num < 64)
			{
				if (((mask >> num) & 1) == 0L)
				{
					num++;
					continue;
				}
				int i;
				for (i = num; i + 1 < 64 && ((mask >> i + 1) & 1) != 0L; i++)
				{
				}
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(',');
				}
				stringBuilder.Append((num == i) ? $"{num}" : $"{num}-{i}");
				num = i + 1;
			}
			if (stringBuilder.Length != 0)
			{
				return stringBuilder.ToString();
			}
			return "none";
		}

		internal static string Percent(int i)
		{
			if (Frames[i] != 0L)
			{
				return $"{100.0 * (double)FramesOnVCache[i] / (double)Frames[i]:0}% of {Frames[i]} frames";
			}
			return "-";
		}
	}
	internal static class Phases
	{
		internal const int Wait = 0;

		internal const int Physics = 1;

		internal const int Scripts = 2;

		internal const int Render = 3;

		internal const int Count = 4;

		internal static readonly string[] Names = new string[4] { "wait (GPU/present/cap)", "physics + early update", "scripts + animation", "render (main thread)" };

		private static readonly double TicksToMs = 1000.0 / (double)Stopwatch.Frequency;

		private static long tUpdate;

		private static long tLate;

		private static long tRepaint;

		private static long tFirstFixed;

		private static bool haveFixed;

		private static bool haveLate;

		private static bool haveRepaint;

		private static bool haveUpdate;

		internal static int FixedSteps;

		internal static readonly double[] Last = new double[4];

		internal static double LastFrameMs;

		internal static int LastFixedSteps;

		private static readonly double[] win = new double[4];

		private static long winFrames;

		internal static readonly double[] WindowAvg = new double[4];

		internal static readonly double[][] Ses = new double[2][]
		{
			new double[4],
			new double[4]
		};

		internal static readonly long[] SesFrames = new long[2];

		internal static readonly long[] SesFixedSteps = new long[2];

		internal static void ResetSession()
		{
			for (int i = 0; i < 2; i++)
			{
				Array.Clear(Ses[i], 0, Ses[i].Length);
				SesFrames[i] = 0L;
				SesFixedSteps[i] = 0L;
			}
		}

		internal static void OnFixedUpdate()
		{
			if (!haveFixed)
			{
				tFirstFixed = Stopwatch.GetTimestamp();
				haveFixed = true;
			}
			FixedSteps++;
		}

		internal static void OnLateUpdate()
		{
			if (!haveLate)
			{
				tLate = Stopwatch.GetTimestamp();
				haveLate = true;
			}
		}

		internal static void OnRepaint()
		{
			if (!haveRepaint)
			{
				tRepaint = Stopwatch.GetTimestamp();
				haveRepaint = true;
			}
		}

		internal static bool OnUpdate(bool measuring, int state)
		{
			long timestamp = Stopwatch.GetTimestamp();
			bool result = false;
			if (haveUpdate && haveLate)
			{
				long num = tLate;
				long num2 = (haveRepaint ? tRepaint : num);
				long num3 = ((haveFixed && tFirstFixed > num2) ? tFirstFixed : timestamp);
				Last[2] = (double)Math.Max(0L, num - tUpdate) * TicksToMs;
				Last[3] = (double)Math.Max(0L, num2 - num) * TicksToMs;
				Last[0] = (double)Math.Max(0L, num3 - num2) * TicksToMs;
				Last[1] = (double)Math.Max(0L, timestamp - num3) * TicksToMs;
				LastFrameMs = (double)(timestamp - tUpdate) * TicksToMs;
				LastFixedSteps = FixedSteps;
				for (int i = 0; i < 4; i++)
				{
					win[i] += Last[i];
				}
				winFrames++;
				if (measuring)
				{
					for (int j = 0; j < 4; j++)
					{
						Ses[state][j] += Last[j];
					}
					SesFrames[state]++;
					SesFixedSteps[state] += FixedSteps;
				}
				result = true;
			}
			tUpdate = timestamp;
			haveUpdate = true;
			haveLate = (haveRepaint = (haveFixed = false));
			FixedSteps = 0;
			return result;
		}

		internal static void CloseWindow()
		{
			if (winFrames != 0L)
			{
				for (int i = 0; i < 4; i++)
				{
					WindowAvg[i] = win[i] / (double)winFrames;
					win[i] = 0.0;
				}
				winFrames = 0L;
			}
		}

		internal static double SesAvg(int state, int phase)
		{
			if (SesFrames[state] != 0L)
			{
				return Ses[state][phase] / (double)SesFrames[state];
			}
			return 0.0;
		}
	}
	internal static class GcStats
	{
		internal static int LastCount = -1;

		internal static int CollectionsThisFrame;

		internal static readonly long[] SesCollections = new long[2];

		internal static long HeapUsedMb;

		internal static long HeapSizeMb;

		internal static string Mode = "?";

		internal static bool Incremental;

		internal static ulong SliceNs;

		internal static bool Broken;

		private static readonly Queue<float> recent = new Queue<float>();

		internal static int PerMinute => recent.Count;

		internal static void ResetSession()
		{
			SesCollections[0] = (SesCollections[1] = 0L);
		}

		internal static void PerFrame(bool measuring, int state, float now)
		{
			if (Broken)
			{
				return;
			}
			try
			{
				int num = GC.CollectionCount(0);
				CollectionsThisFrame = ((LastCount >= 0) ? Math.Max(0, num - LastCount) : 0);
				LastCount = num;
				if (CollectionsThisFrame > 0)
				{
					for (int i = 0; i < CollectionsThisFrame; i++)
					{
						recent.Enqueue(now);
					}
					if (measuring)
					{
						SesCollections[state] += CollectionsThisFrame;
					}
				}
				while (recent.Count > 0 && now - recent.Peek() > 60f)
				{
					recent.Dequeue();
				}
			}
			catch (Exception e)
			{
				Broken = true;
				Runner.ReportError("gc-count", e);
			}
		}

		internal static void Sample()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				HeapUsedMb = Profiler.GetMonoUsedSizeLong() / 1048576;
				HeapSizeMb = Profiler.GetMonoHeapSizeLong() / 1048576;
				Incremental = GarbageCollector.isIncremental;
				Mode = ((object)GarbageCollector.GCMode/*cast due to .constrained prefix*/).ToString();
				SliceNs = GarbageCollector.incrementalTimeSliceNanoseconds;
			}
			catch (Exception e)
			{
				Runner.ReportError("gc-sample", e);
			}
		}
	}
	internal static class Spikes
	{
		internal sealed class Spike
		{
			public DateTime Time;

			public int State;

			public double FrameMs;

			public double[] Phases = new double[4];

			public int FixedSteps;

			public int GcCollections;

			public List<(string label, double ms)> TopSections = new List<(string, double)>();

			public List<string> SlowAi = new List<string>();

			public string Cause;
		}

		private const int Keep = 300;

		internal static readonly List<Spike> Recent = new List<Spike>();

		internal static readonly long[] SesCount = new long[2];

		internal static readonly Dictionary<string, (int count, double totalMs)>[] ByCause = new Dictionary<string, (int, double)>[2]
		{
			new Dictionary<string, (int, double)>(),
			new Dictionary<string, (int, double)>()
		};

		internal static string LastCause = "";

		internal static void ResetSession()
		{
			Recent.Clear();
			SesCount[0] = (SesCount[1] = 0L);
			ByCause[0].Clear();
			ByCause[1].Clear();
			LastCause = "";
		}

		internal static void Check(bool measuring, int state)
		{
			double lastFrameMs = Phases.LastFrameMs;
			if (!measuring || lastFrameMs < (double)PerfConfig.SpikeThresholdMs.Value)
			{
				AiSpikes.ClearFrame();
				return;
			}
			Spike spike = new Spike
			{
				Time = DateTime.Now,
				State = state,
				FrameMs = lastFrameMs,
				FixedSteps = Phases.LastFixedSteps,
				GcCollections = GcStats.CollectionsThisFrame
			};
			Array.Copy(Phases.Last, spike.Phases, 4);
			double num = 0.0;
			double num2 = 0.0;
			string text = null;
			string text2 = null;
			if (Profiler.Installed)
			{
				foreach (Profiler.Section item in Profiler.Active)
				{
					double num3 = (double)Profiler.FrameTicksOf(item.Id) * Profiler.TicksToMs;
					if (num3 >= 1.0)
					{
						spike.TopSections.Add((item.Label.Trim(), num3));
					}
					if (!item.Nested && num3 > num)
					{
						num = num3;
						text = item.Label.Trim();
					}
					if (item.Nested && num3 > num2)
					{
						num2 = num3;
						text2 = item.Label.Trim();
					}
				}
				spike.TopSections = spike.TopSections.OrderByDescending(((string label, double ms) x) => x.ms).Take(4).ToList();
			}
			spike.SlowAi.AddRange(AiSpikes.TakeFrame());
			if (spike.GcCollections > 0)
			{
				spike.Cause = "garbage collection (GC)";
			}
			else if (text != null && num >= lastFrameMs * 0.4)
			{
				spike.Cause = "script: " + text;
			}
			else if (text2 != null && num2 >= lastFrameMs * 0.4)
			{
				spike.Cause = "script: " + text2;
			}
			else if (spike.FixedSteps >= 4 && spike.Phases[1] >= lastFrameMs * 0.4)
			{
				spike.Cause = "physics catch-up";
			}
			else
			{
				int num4 = 0;
				for (int num5 = 1; num5 < 4; num5++)
				{
					if (spike.Phases[num5] > spike.Phases[num4])
					{
						num4 = num5;
					}
				}
				spike.Cause = num4 switch
				{
					0 => "wait (GPU/present/loading)", 
					3 => "rendering", 
					2 => "unprofiled scripts/animation", 
					_ => "physics", 
				};
			}
			LastCause = spike.Cause;
			SesCount[state]++;
			Dictionary<string, (int count, double totalMs)> obj = ByCause[state];
			obj.TryGetValue(spike.Cause, out (int, double) value);
			obj[spike.Cause] = (value.Item1 + 1, value.Item2 + lastFrameMs);
			Recent.Add(spike);
			if (Recent.Count > 300)
			{
				Recent.RemoveAt(0);
			}
		}

		internal static string Describe(Spike s)
		{
			StringBuilder stringBuilder = new StringBuilder();
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(7, 4, stringBuilder2);
			handler.AppendFormatted(s.Time, "HH:mm:ss");
			handler.AppendLiteral(" ");
			handler.AppendFormatted((s.State == 1) ? "ON " : "OFF");
			handler.AppendLiteral(" ");
			handler.AppendFormatted(s.FrameMs, 6, "0");
			handler.AppendLiteral(" ms  ");
			handler.AppendFormatted(s.Cause);
			stringBuilder3.Append(ref handler);
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder4 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(41, 5, stringBuilder2);
			handler.AppendLiteral("  | wait ");
			handler.AppendFormatted(s.Phases[0], "0");
			handler.AppendLiteral(" phys ");
			handler.AppendFormatted(s.Phases[1], "0");
			handler.AppendLiteral(" (");
			handler.AppendFormatted(s.FixedSteps);
			handler.AppendLiteral(" steps) scripts ");
			handler.AppendFormatted(s.Phases[2], "0");
			handler.AppendLiteral(" render ");
			handler.AppendFormatted(s.Phases[3], "0");
			stringBuilder4.Append(ref handler);
			if (s.GcCollections > 0)
			{
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder5 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(7, 1, stringBuilder2);
				handler.AppendLiteral(" | GC x");
				handler.AppendFormatted(s.GcCollections);
				stringBuilder5.Append(ref handler);
			}
			if (s.TopSections.Count > 0)
			{
				stringBuilder.Append(" | " + string.Join(", ", s.TopSections.Select(((string label, double ms) x) => $"{x.label} {x.ms:0}")));
			}
			foreach (string item in s.SlowAi)
			{
				stringBuilder.Append("\n            " + item);
			}
			return stringBuilder.ToString();
		}
	}
	internal sealed class SpikeCatcher
	{
		internal readonly string Name;

		private readonly long[] starts = new long[16];

		private int depth;

		internal readonly List<string> Frame = new List<string>();

		internal readonly Dictionary<string, (int count, double worstMs, double totalMs)> ByAction = new Dictionary<string, (int, double, double)>();

		internal readonly Dictionary<string, int> ByContext = new Dictionary<string, int>();

		internal long Total;

		internal SpikeCatcher(string name)
		{
			Name = name;
		}

		internal void ResetSession()
		{
			Frame.Clear();
			ByAction.Clear();
			ByContext.Clear();
			Total = 0L;
		}

		internal void Pre()
		{
			if (depth < starts.Length)
			{
				starts[depth] = Stopwatch.GetTimestamp();
			}
			depth++;
		}

		internal void Post(NewAIController ai)
		{
			depth--;
			if (depth < 0)
			{
				depth = 0;
			}
			else
			{
				if (depth >= starts.Length)
				{
					return;
				}
				double num = (double)(Stopwatch.GetTimestamp() - starts[depth]) * 1000.0 / (double)Stopwatch.Frequency;
				if (!(num < (double)PerfConfig.AiSpikeMs.Value) && Runner.MeasuringNow)
				{
					try
					{
						Record(ai, num);
					}
					catch (Exception e)
					{
						Runner.ReportError("spike-" + Name, e);
					}
				}
			}
		}

		private void Record(NewAIController ai, double ms)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			string value = "?";
			string text = "-";
			string text2 = "-";
			string value2 = "?";
			if ((Object)(object)ai != (Object)null)
			{
				Human human = ai.human;
				if ((Object)(object)human != (Object)null)
				{
					value = human.citizenName ?? "?";
				}
				NewAIGoal currentGoal = ai.currentGoal;
				if (currentGoal != null)
				{
					text = currentGoal.name ?? "-";
				}
				NewAIAction currentAction = ai.currentAction;
				if (currentAction != null)
				{
					text2 = currentAction.name ?? "-";
				}
				value2 = ((object)ai.tickRate/*cast due to .constrained prefix*/).ToString();
			}
			string text3 = (AiTimeBudget.InScheduler ? "AI queue" : (AiTimeBudget.InLateUpdate ? "movement" : "other"));
			Total++;
			string key = text + " / " + text2;
			ByAction.TryGetValue(key, out (int, double, double) value3);
			ByAction[key] = (value3.Item1 + 1, Math.Max(value3.Item2, ms), value3.Item3 + ms);
			ByContext.TryGetValue(text3, out var value4);
			ByContext[text3] = value4 + 1;
			if (Frame.Count < 8)
			{
				Frame.Add($"{Name} {ms:0.0} ms  {value}  goal '{text}'  action '{text2}'  tier {value2}  via {text3}");
			}
		}

		internal void Reset()
		{
			Frame.Clear();
			depth = 0;
		}
	}
	internal static class AiSpikes
	{
		internal static readonly SpikeCatcher Tick = new SpikeCatcher("slow decision");

		internal static readonly SpikeCatcher Move = new SpikeCatcher("slow movement");

		internal static void Install(Harmony harmony, bool movement)
		{
			Patch(harmony, "AITick", "TickPre", "TickPost");
			if (movement)
			{
				Patch(harmony, "FrequentUpdate", "MovePre", "MovePost");
			}
		}

		private static void Patch(Harmony harmony, string method, string pre, string post)
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00af: Expected O, but got Unknown
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				MethodInfo methodInfo = AccessTools.GetDeclaredMethods(typeof(NewAIController)).FirstOrDefault((MethodInfo m) => m.Name == method && !m.IsStatic);
				if (methodInfo == null)
				{
					ManualLogSource l = Plugin.L;
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(26, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Spike catcher: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" not found.");
					}
					l.LogWarning(val);
					return;
				}
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(AiSpikes), pre, (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(AiSpikes), post, (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource l2 = Plugin.L;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(44, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Spike catcher installed on NewAIController.");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(method);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(".");
				}
				l2.LogInfo(val2);
			}
			catch (Exception ex)
			{
				ManualLogSource l3 = Plugin.L;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(35, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Spike catcher not installed on ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				l3.LogWarning(val);
			}
		}

		public static void TickPre()
		{
			Tick.Pre();
		}

		public static void TickPost(NewAIController __instance)
		{
			Tick.Post(__instance);
		}

		public static void MovePre()
		{
			Move.Pre();
		}

		public static void MovePost(NewAIController __instance)
		{
			Move.Post(__instance);
		}

		internal static List<string> TakeFrame()
		{
			List<string> list = new List<string>(Tick.Frame);
			list.AddRange(Move.Frame);
			Tick.Reset();
			Move.Reset();
			return list;
		}

		internal static void ClearFrame()
		{
			Tick.Reset();
			Move.Reset();
		}
	}
	internal static class SlowSeconds
	{
		internal sealed class Entry
		{
			public DateTime Time;

			public double Fps;

			public double[] Phases = new double[4];

			public string Top = "";

			public int VeryHigh;

			public int Visible;
		}

		internal static readonly List<Entry> Recent = new List<Entry>();

		internal static long Total;

		private static double secMs;

		private static int secFrames;

		private static int secMeasured;

		internal static void ResetSession()
		{
			Recent.Clear();
			Total = 0L;
		}

		internal static void AddFrame(float frameMs, bool measuring)
		{
			secMs += frameMs;
			secFrames++;
			if (measuring)
			{
				secMeasured++;
			}
		}

		internal static void CloseSecond()
		{
			try
			{
				if (secFrames == 0)
				{
					return;
				}
				double num = secMs / (double)secFrames;
				if (secMeasured == secFrames && num > 22.22222222222222)
				{
					Total++;
					Entry entry = new Entry
					{
						Time = DateTime.Now,
						Fps = 1000.0 / num,
						VeryHigh = GameProbe.VeryHigh,
						Visible = GameProbe.VisibleHumans
					};
					for (int i = 0; i < 4; i++)
					{
						entry.Phases[i] = Phases.WindowAvg[i];
					}
					IEnumerable<string> values = from x in (from x in Profiler.Active
							where x.AvgMs >= 0.5
							orderby x.AvgMs descending
							select x).Take(5)
						select $"{x.Label.Trim()} {x.AvgMs:0.0}";
					entry.Top = string.Join(", ", values);
					Recent.Add(entry);
					if (Recent.Count > 40)
					{
						Recent.RemoveAt(0);
					}
				}
			}
			catch
			{
			}
			finally
			{
				secMs = 0.0;
				secFrames = 0;
				secMeasured = 0;
			}
		}
	}
	internal static class AiTimeBudget
	{
		internal static bool InScheduler;

		internal static bool InLateUpdate;

		internal static bool EnabledNow;

		private static bool active;

		private static bool cut;

		private static int restore;

		private static CitizenBehaviour cb;

		private static long tickStart;

		private static int depth;

		private static double spentMs;

		internal static double LastSpentMs;

		internal static long WindowCuts;

		internal static readonly long[] SesCuts = new long[2];

		internal static bool Installed;

		internal static string Status = "";

		internal static void Install(Harmony harmony)
		{
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				MethodInfo methodInfo = AccessTools.GetDeclaredMethods(typeof(CitizenBehaviour)).First((MethodInfo m) => m.Name == "Update" && m.GetParameters().Length == 0);
				MethodInfo methodInfo2 = AccessTools.GetDeclaredMethods(typeof(CitizenBehaviour)).First((MethodInfo m) => m.Name == "LateUpdate" && m.GetParameters().Length == 0);
				MethodInfo methodInfo3 = AccessTools.GetDeclaredMethods(typeof(NewAIController)).First((MethodInfo m) => m.Name == "AITick" && !m.IsStatic);
				harmony.Patch((MethodBase)methodInfo, H("SchedPrefix"), H("SchedPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo2, H("LatePrefix"), H("LatePostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo3, H("TickPrefix"), H("TickPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Installed = true;
				ManualLogSource l = Plugin.L;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(41, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AI time budget installed (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(PerfConfig.AiFrameBudgetMs.Value);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ms per frame).");
				}
				l.LogInfo(val);
			}
			catch (Exception ex)
			{
				ManualLogSource l2 = Plugin.L;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(32, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AI time budget not installed: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.GetType().Name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				l2.LogWarning(val2);
			}
		}

		private static HarmonyMethod H(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.Method(typeof(AiTimeBudget), name, (Type[])null, (Type[])null));
		}

		public static void SchedPrefix(CitizenBehaviour __instance)
		{
			InScheduler = true;
			depth = 0;
			spentMs = 0.0;
			cut = false;
			active = EnabledNow;
			cb = (active ? __instance : null);
		}

		public static void SchedPostfix()
		{
			if (cut && (Object)(object)cb != (Object)null)
			{
				try
				{
					cb.AITicksPerFrame = restore;
				}
				catch (Exception e)
				{
					Runner.ReportError("ai-budget-restore", e);
				}
			}
			LastSpentMs = spentMs;
			InScheduler = false;
			active = false;
			cut = false;
			cb = null;
			depth = 0;
		}

		public static void LatePrefix()
		{
			InLateUpdate = true;
		}

		public static void LatePostfix()
		{
			InLateUpdate = false;
		}

		public static void TickPrefix()
		{
			if (InScheduler && depth++ == 0)
			{
				tickStart = Stopwatch.GetTimestamp();
			}
		}

		public static void TickPostfix()
		{
			if (!InScheduler || --depth > 0)
			{
				return;
			}
			depth = 0;
			spentMs += (double)(Stopwatch.GetTimestamp() - tickStart) * 1000.0 / (double)Stopwatch.Frequency;
			if (!active || cut || spentMs < (double)PerfConfig.AiFrameBudgetMs.Value)
			{
				return;
			}
			try
			{
				restore = cb.AITicksPerFrame;
				cb.AITicksPerFrame = 0;
				cut = true;
				WindowCuts++;
				if (Runner.MeasuringNow)
				{
					SesCuts[Runner.OptimizationsOn ? 1u : 0u]++;
				}
			}
			catch (Exception e)
			{
				active = false;
				Runner.ReportError("ai-budget", e);
			}
		}

		internal static void FrameReset()
		{
			InScheduler = false;
			InLateUpdate = false;
			active = false;
			cut = false;
			cb = null;
			depth = 0;
		}
	}
	internal static class ShadowTuning
	{
		private static float gameMult = -1f;

		private static float appliedMult = -1f;

		private static int gameMaxUpdates = int.MinValue;

		private static int appliedMaxUpdates = int.MinValue;

		internal static int LastRefreshCount;

		internal static double LastRefreshMs;

		internal static float GameMult => gameMult;

		internal static float AppliedMult => appliedMult;

		internal static int GameMaxUpdates => gameMaxUpdates;

		internal static int AppliedMaxUpdates => appliedMaxUpdates;

		internal static void Tick(bool optimizationsOn)
		{
			Game instance = Game.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				float shadowFadeDistanceMultiplier = instance.shadowFadeDistanceMultiplier;
				if (appliedMult < 0f || Math.Abs(shadowFadeDistanceMultiplier - appliedMult) > 0.0001f)
				{
					gameMult = shadowFadeDistanceMultiplier;
				}
				float num = (optimizationsOn ? Math.Max(0.1f, Math.Min(1f, PerfConfig.ShadowDistanceScale.Value)) : 1f);
				float num2 = gameMult * num;
				if (Math.Abs(shadowFadeDistanceMultiplier - num2) > 0.0001f)
				{
					instance.shadowFadeDistanceMultiplier = num2;
					RefreshLights();
				}
				appliedMult = num2;
				int maxUpdateDynamicShadowsPerFrame = instance.maxUpdateDynamicShadowsPerFrame;
				if (appliedMaxUpdates == int.MinValue || maxUpdateDynamicShadowsPerFrame != appliedMaxUpdates)
				{
					gameMaxUpdates = maxUpdateDynamicShadowsPerFrame;
				}
				int value = PerfConfig.MaxShadowUpdatesPerFrame.Value;
				int num3 = ((optimizationsOn && value >= 0) ? value : gameMaxUpdates);
				if (maxUpdateDynamicShadowsPerFrame != num3)
				{
					instance.maxUpdateDynamicShadowsPerFrame = num3;
				}
				appliedMaxUpdates = num3;
			}
		}

		private static void RefreshLights()
		{
			long timestamp = Stopwatch.GetTimestamp();
			int num = 0;
			try
			{
				Il2CppReferenceArray<Object> val = Object.FindObjectsOfType(Il2CppType.Of<LightController>(), true);
				if (val != null)
				{
					for (int i = 0; i < ((Il2CppArrayBase<Object>)(object)val).Length; i++)
					{
						Object obj = ((Il2CppArrayBase<Object>)(object)val)[i];
						LightController val2 = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<LightController>() : null);
						if (!((Object)(object)val2 == (Object)null) && val2.isSetup)
						{
							val2.UpdateFadeDistances();
							num++;
						}
					}
				}
			}
			catch (Exception e)
			{
				Runner.ReportError("shadow-refresh", e);
			}
			LastRefreshCount = num;
			LastRefreshMs = (double)(Stopwatch.GetTimestamp() - timestamp) * 1000.0 / (double)Stopwatch.Frequency;
		}

		internal static void ResetForNewSession()
		{
			gameMult = (appliedMult = -1f);
			gameMaxUpdates = (appliedMaxUpdates = int.MinValue);
		}
	}
	internal static class MovementStagger
	{
		internal static bool EnabledNow;

		internal static bool Installed;

		private static bool active;

		private static int realCounter;

		private static int fakeCounter;

		private static CitizenBehaviour cb;

		internal static long WindowUpdates;

		internal static long WindowTicks;

		internal static double WindowMaxMs;

		internal static long UpdatesLastSecond;

		internal static long TicksLastSecond;

		internal static double MaxMsLastSecond;

		internal static void Install(Harmony harmony)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_008a: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.GetDeclaredMethods(typeof(CitizenBehaviour)).First((MethodInfo m) => m.Name == "LateUpdate" && m.GetParameters().Length == 0);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(MovementStagger), "Prefix", (Type[])null, (Type[])null))
				{
					priority = 800
				}, new HarmonyMethod(AccessTools.Method(typeof(MovementStagger), "Postfix", (Type[])null, (Type[])null))
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Installed = true;
				Plugin.L.LogInfo((object)"Movement stagger installed.");
			}
			catch (Exception ex)
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(34, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Movement stagger not installed: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				l.LogWarning(val);
			}
		}

		public static void Prefix(CitizenBehaviour __instance)
		{
			active = false;
			if (!EnabledNow || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			try
			{
				cb = __instance;
				realCounter = cb.frequentTickCounter;
				fakeCounter = FakeFor(realCounter);
				cb.frequentTickCounter = fakeCounter;
				active = true;
			}
			catch (Exception e)
			{
				Runner.ReportError("stagger-pre", e);
			}
		}

		public static void Postfix()
		{
			if (!active)
			{
				return;
			}
			active = false;
			try
			{
				bool num = cb.frequentTickCounter == fakeCounter + 1;
				int frequentTickCounter = ((!num) ? realCounter : ((realCounter + 1 >= 1501) ? 1 : (realCounter + 1)));
				cb.frequentTickCounter = frequentTickCounter;
				if (num)
				{
					RunSlices(realCounter);
				}
			}
			catch (Exception e)
			{
				Runner.ReportError("stagger-post", e);
			}
			finally
			{
				cb = null;
			}
		}

		internal static int FakeFor(int real)
		{
			int num = (real % 10 + 10) % 10;
			for (int i = 1; i < 140; i++)
			{
				int num2 = num + 10 * i;
				if (num2 % 11 != 0 && num2 % 17 != 0)
				{
					return num2;
				}
			}
			return 13;
		}

		private static void RunSlices(int phase)
		{
			long timestamp = Stopwatch.GetTimestamp();
			int num = 0;
			CityData instance = CityData.Instance;
			List<Citizen> val = ((instance != null) ? instance.citizenDirectory : null);
			if (val != null)
			{
				int count = val.Count;
				num += Slice(val, count, phase, 17, (AITickRate)0);
				num += Slice(val, count, phase, 11, (AITickRate)1);
				double num2 = (double)(Stopwatch.GetTimestamp() - timestamp) * 1000.0 / (double)Stopwatch.Frequency;
				WindowUpdates += num;
				WindowTicks++;
				if (num2 > WindowMaxMs)
				{
					WindowMaxMs = num2;
				}
			}
		}

		private static int Slice(List<Citizen> list, int n, int phase, int period, AITickRate tier)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			for (int i = (-phase % period + period) % period; i < n; i += period)
			{
				Citizen val = list[i];
				if (!((Object)(object)val == (Object)null) && !((Actor)val).visible)
				{
					NewAIController ai = ((Actor)val).ai;
					if (!((Object)(object)ai == (Object)null) && ((Behaviour)ai).enabled && ai.tickRate == tier)
					{
						ai.FrequentUpdate();
						num++;
					}
				}
			}
			return num;
		}

		internal static void CloseWindow()
		{
			UpdatesLastSecond = WindowUpdates;
			TicksLastSecond = WindowTicks;
			MaxMsLastSecond = WindowMaxMs;
			WindowUpdates = (WindowTicks = 0L);
			WindowMaxMs = 0.0;
		}
	}
	internal static class GcTuning
	{
		private static ulong original;

		private static bool captured;

		private static ulong applied;

		internal static ulong Original => original;

		internal static void Tick(bool optimizationsOn)
		{
			try
			{
				if (GarbageCollector.isIncremental)
				{
					ulong incrementalTimeSliceNanoseconds = GarbageCollector.incrementalTimeSliceNanoseconds;
					if (!captured || incrementalTimeSliceNanoseconds != applied)
					{
						original = incrementalTimeSliceNanoseconds;
						captured = true;
					}
					float value = PerfConfig.GcSliceMs.Value;
					ulong num = ((optimizationsOn && value > 0f) ? ((ulong)(value * 1000000f)) : original);
					if (incrementalTimeSliceNanoseconds != num)
					{
						GarbageCollector.incrementalTimeSliceNanoseconds = num;
					}
					applied = num;
				}
			}
			catch (Exception e)
			{
				Runner.ReportError("gc-slice", e);
			}
		}
	}
	internal static class OtherLightShadows
	{
		private sealed class Entry
		{
			public HDAdditionalLightData Hd;

			public float Original;

			public float Applied = -1f;

			public string Group;
		}

		private static readonly Dictionary<IntPtr, Entry> tracked = new Dictionary<IntPtr, Entry>();

		private static float nextScan;

		private static bool appliedOn;

		private static float appliedCap = -1f;

		internal static int Tracked;

		internal static int Capped;

		internal static double LastScanMs;

		internal static void Tick(bool optimizationsOn, float now)
		{
			float value = PerfConfig.OtherLightShadowDistance.Value;
			bool flag = optimizationsOn && value > 0f;
			if (!(now < nextScan) || flag != appliedOn || !(Math.Abs(value - appliedCap) < 0.001f))
			{
				nextScan = now + 20f;
				appliedOn = flag;
				appliedCap = value;
				Scan(flag, value);
			}
		}

		private static void Scan(bool want, float cap)
		{
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Invalid comparison between Unknown and I4
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			long timestamp = Stopwatch.GetTimestamp();
			try
			{
				HashSet<IntPtr> hashSet = new HashSet<IntPtr>();
				Il2CppReferenceArray<Object> val = Object.FindObjectsOfType(Il2CppType.Of<LightController>());
				if (val != null)
				{
					for (int i = 0; i < ((Il2CppArrayBase<Object>)(object)val).Length; i++)
					{
						Object obj = ((Il2CppArrayBase<Object>)(object)val)[i];
						LightController obj2 = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<LightController>() : null);
						Light val2 = ((obj2 != null) ? obj2.lightComponent : null);
						if ((Object)(object)val2 != (Object)null)
						{
							hashSet.Add(((Il2CppObjectBase)val2).Pointer);
						}
					}
				}
				Il2CppReferenceArray<Object> val3 = Object.FindObjectsOfType(Il2CppType.Of<Light>());
				int num = 0;
				if (val3 != null)
				{
					for (int j = 0; j < ((Il2CppArrayBase<Object>)(object)val3).Length; j++)
					{
						try
						{
							Object obj3 = ((Il2CppArrayBase<Object>)(object)val3)[j];
							Light val4 = ((obj3 != null) ? ((Il2CppObjectBase)obj3).TryCast<Light>() : null);
							if ((Object)(object)val4 == (Object)null)
							{
								continue;
							}
							IntPtr pointer = ((Il2CppObjectBase)val4).Pointer;
							if (hashSet.Contains(pointer))
							{
								continue;
							}
							if (tracked.TryGetValue(pointer, out var value) && (Object)(object)value.Hd == (Object)null)
							{
								tracked.Remove(pointer);
								value = null;
							}
							if (value != null)
							{
								goto IL_01f0;
							}
							if ((int)val4.type != 1 && (int)val4.shadows != 0)
							{
								HDAdditionalLightData component = ((Component)val4).GetComponent<HDAdditionalLightData>();
								if (!((Object)(object)component == (Object)null))
								{
									string n = (((Object)(object)((Component)val4).transform.parent != (Object)null) ? ((Object)((Component)val4).transform.parent).name : "-");
									value = new Entry
									{
										Hd = component,
										Original = component.shadowFadeDistance,
										Group = $"{val4.type} '{Clean(((Object)((Component)val4).gameObject).name)}' under '{Clean(n)}'"
									};
									tracked[pointer] = value;
									goto IL_01f0;
								}
							}
							goto end_IL_0086;
							IL_01f0:
							float num2 = (want ? Math.Min(value.Original, cap) : value.Original);
							if (Math.Abs(value.Applied - num2) > 0.01f)
							{
								value.Hd.shadowFadeDistance = num2;
								value.Applied = num2;
							}
							if (want && value.Original > cap)
							{
								num++;
							}
							end_IL_0086:;
						}
						catch (Exception e)
						{
							Runner.ReportError("other-light", e);
						}
					}
				}
				Tracked = tracked.Count;
				Capped = num;
			}
			catch (Exception e2)
			{
				Runner.ReportError("other-light-shadows", e2);
			}
			LastScanMs = (double)(Stopwatch.GetTimestamp() - timestamp) * 1000.0 / (double)Stopwatch.Frequency;
		}

		internal static string Clean(string n)
		{
			if (string.IsNullOrEmpty(n))
			{
				return "?";
			}
			int num = n.IndexOf('(');
			return ((num > 0) ? n.Substring(0, num) : n).Trim();
		}

		internal static IEnumerable<(string group, int count, float avgOriginal)> Groups()
		{
			return from e in tracked.Values
				group e by e.Group into g
				select (Key: g.Key, g.Count(), g.Average((Entry e) => e.Original)) into g
				orderby g.Item2 descending
				select g;
		}
	}
	internal static class TrashTrickle
	{
		private const int GameLimit = 250;

		private static float next;

		internal static int Calls;

		internal static int LastRemoved;

		internal static int TotalRemoved;

		internal static double LastMs;

		internal static double WorstMs;

		internal static void Tick(bool optimizationsOn, bool playing, float now)
		{
			if (!optimizationsOn || !playing || !PerfConfig.TrashTrickle.Value || now < next)
			{
				return;
			}
			next = now + 10f;
			try
			{
				CleanupController instance = CleanupController.Instance;
				List<Interactable> val = ((instance != null) ? instance.trash : null);
				if (val != null && val.Count > 260)
				{
					long timestamp = Stopwatch.GetTimestamp();
					instance.TrashUpdate();
					LastMs = (double)(Stopwatch.GetTimestamp() - timestamp) * 1000.0 / (double)Stopwatch.Frequency;
					if (LastMs > WorstMs)
					{
						WorstMs = LastMs;
					}
					Calls++;
					LastRemoved = instance.trashRemovedLastUpdate;
					TotalRemoved += Math.Max(0, LastRemoved);
				}
			}
			catch (Exception e)
			{
				Runner.ReportError("trash-trickle", e);
			}
		}
	}
	internal static class FrameStats
	{
		private const int RingSize = 600;

		private const float BinMs = 0.25f;

		private const int Bins = 2000;

		private static readonly float[] ring = new float[600];

		private static readonly float[] sortBuf = new float[600];

		private static int ringCount;

		private static int ringPos;

		private static readonly int[][] hist = new int[2][]
		{
			new int[2000],
			new int[2000]
		};

		internal static readonly long[] Frames = new long[2];

		internal static readonly double[] SumMs = new double[2];

		internal static readonly float[] WorstMs = new float[2];

		internal static float AvgMs;

		internal static float P99Ms;

		internal static float WorstWindowMs;

		internal static void ResetSession()
		{
			for (int i = 0; i < 2; i++)
			{
				Frames[i] = 0L;
				SumMs[i] = 0.0;
				WorstMs[i] = 0f;
				Array.Clear(hist[i], 0, hist[i].Length);
			}
		}

		internal static void Add(float ms, bool measuring, int state)
		{
			if (ms <= 0f || float.IsNaN(ms))
			{
				return;
			}
			ring[ringPos] = ms;
			ringPos = (ringPos + 1) % 600;
			if (ringCount < 600)
			{
				ringCount++;
			}
			if (measuring)
			{
				Frames[state]++;
				SumMs[state] += ms;
				if (ms > WorstMs[state])
				{
					WorstMs[state] = ms;
				}
				int num = (int)(ms / 0.25f);
				if (num >= 2000)
				{
					num = 1999;
				}
				hist[state][num]++;
			}
		}

		internal static void ComputeWindow()
		{
			if (ringCount == 0)
			{
				return;
			}
			double num = 0.0;
			float num2 = 0f;
			for (int i = 0; i < ringCount; i++)
			{
				float num3 = ring[i];
				sortBuf[i] = num3;
				num += (double)num3;
				if (num3 > num2)
				{
					num2 = num3;
				}
			}
			Array.Sort(sortBuf, 0, ringCount);
			AvgMs = (float)(num / (double)ringCount);
			P99Ms = sortBuf[Math.Min(ringCount - 1, (int)((float)ringCount * 0.99f))];
			WorstWindowMs = num2;
		}

		internal static float Percentile(int state, double p)
		{
			long num = Frames[state];
			if (num == 0L)
			{
				return 0f;
			}
			long num2 = (long)Math.Ceiling((double)num * p);
			long num3 = 0L;
			int[] array = hist[state];
			for (int i = 0; i < 2000; i++)
			{
				num3 += array[i];
				if (num3 >= num2)
				{
					return ((float)i + 0.5f) * 0.25f;
				}
			}
			return 500f;
		}

		internal static double AvgFor(int state)
		{
			if (Frames[state] != 0L)
			{
				return SumMs[state] / (double)Frames[state];
			}
			return 0.0;
		}
	}
	internal static class GameProbe
	{
		internal static bool HasCity;

		internal static int VeryHigh;

		internal static int High;

		internal static int Medium;

		internal static int Low;

		internal static int VeryLow;

		internal static int Queue;

		internal static int Backlog;

		internal static int Executed;

		internal static int VisibleHumans;

		internal static int Citizens;

		internal static int LightsTracked;

		internal static int LightsCulled;

		internal static int LightsNotCulled;

		internal static int LightChecks;

		internal static float TimeMult = 1f;

		internal static int ShadowQueue;

		internal static int LastShadowsUpdated;

		internal static int MaxShadowUpdates;

		internal static float ShadowFadeMult;

		internal static string TimeSpeed = "-";

		private static IntPtr lastCitizenBehaviour = IntPtr.Zero;

		internal static bool IsPlaying()
		{
			SessionData instance = SessionData.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				return instance.play;
			}
			return false;
		}

		internal static float TimeMultiplierNow()
		{
			SessionData instance = SessionData.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return instance.currentTimeMultiplier;
			}
			return 1f;
		}

		internal static void CheckSession()
		{
			CitizenBehaviour instance = CitizenBehaviour.Instance;
			IntPtr intPtr = (((Object)(object)instance == (Object)null) ? IntPtr.Zero : ((Il2CppObjectBase)instance).Pointer);
			if (intPtr != lastCitizenBehaviour)
			{
				lastCitizenBehaviour = intPtr;
				AiGovernor.ResetForNewSession();
				RoomHideDefer.Reset();
				BreakerLookup.Reset();
				LightBudget.ResetForNewSession();
			}
		}

		internal static void Sample()
		{
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CitizenBehaviour instance = CitizenBehaviour.Instance;
				HasCity = (Object)(object)instance != (Object)null;
				if (HasCity)
				{
					VeryHigh = Count<NewAIController>(instance.veryHighTickRate);
					High = Count<NewAIController>(instance.highTickRate);
					Medium = Count<NewAIController>(instance.mediumTickRate);
					Low = Count<NewAIController>(instance.lowTickRate);
					VeryLow = Count<NewAIController>(instance.veryLowTickRate);
					Queue = Count<NewAIController>(instance.updateList);
					Backlog = instance.aiTickBacklog;
					Executed = instance.executionsThisFrame;
					VisibleHumans = instance.visibleHumans;
					ShadowQueue = Count<LightController>(instance.lightUpdateQueue);
				}
				Game instance2 = Game.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					LastShadowsUpdated = instance2.lastShadowsUpdatedCount;
					MaxShadowUpdates = instance2.maxUpdateDynamicShadowsPerFrame;
					ShadowFadeMult = instance2.shadowFadeDistanceMultiplier;
				}
				CityData instance3 = CityData.Instance;
				Citizens = (((Object)(object)instance3 != (Object)null) ? Count<Citizen>(instance3.citizenDirectory) : 0);
				LightCullingController instance4 = LightCullingController.Instance;
				if ((Object)(object)instance4 != (Object)null)
				{
					LightsTracked = Count<LightController>(instance4.lightsToCheck);
					LightsCulled = Count<LightController>(instance4.culledLights);
					LightsNotCulled = Count<LightController>(instance4.notCulled);
					LightChecks = instance4.lightsToCheckPerFrame;
				}
				SessionData instance5 = SessionData.Instance;
				if ((Object)(object)instance5 != (Object)null)
				{
					TimeMult = instance5.currentTimeMultiplier;
					TimeSpeed = ((object)instance5.currentTimeSpeed/*cast due to .constrained prefix*/).ToString();
				}
			}
			catch (Exception e)
			{
				Runner.ReportError("sample", e);
			}
		}

		private static int Count<T>(List<T> list)
		{
			return list?.Count ?? 0;
		}
	}
	internal static class LoadProfiler
	{
		internal static int MainThreadId;

		internal static bool Loading;

		private static long loadStart;

		internal static double LastLoadSeconds = -1.0;

		internal static string LastLoadKind = "";

		internal static readonly List<(double t, string text)> Timeline = new List<(double, string)>();

		internal static readonly List<(double t, string text)> LastTimeline = new List<(double, string)>();

		internal static readonly long[] GenMainCount = new long[2];

		internal static readonly long[] GenWorkerCount = new long[2];

		internal static readonly long[] GenMainTicks = new long[2];

		internal static readonly long[] GenWorkerTicks = new long[2];

		internal static readonly long[] GenMainMaxTicks = new long[2];

		[ThreadStatic]
		private static long tStart;

		[ThreadStatic]
		private static int tDepth;

		internal static int LoadsThisGame;

		private static string lastState;

		private static int stateFrames;

		private static double stateWorstMs;

		private static double stateStart;

		internal static bool OnMainThread => Environment.CurrentManagedThreadId == MainThreadId;

		internal static void Install(Harmony harmony)
		{
			TryPatch(harmony, typeof(CityConstructor), "SetLoadingText", "SetLoadingTextPrefix", null);
			string[] array = new string[4] { "StartLoading", "LoadSaveGame", "LoadCityStartNewGame", "GenerateNewCity" };
			foreach (string method in array)
			{
				TryPatch(harmony, typeof(CityConstructor), method, "LoadStartPrefix", null);
			}
		}

		internal static void TryPatch(Harmony harmony, Type type, string method, string prefix, string postfix, Type hookType = null, int priority = -1)
		{
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			bool flag = default(bool);
			try
			{
				MethodInfo methodInfo = AccessTools.GetDeclaredMethods(type).FirstOrDefault((MethodInfo x) => x.Name == method && !x.IsGenericMethodDefinition);
				if (methodInfo == null)
				{
					ManualLogSource l = Plugin.L;
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(27, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Load profiler: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(type.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" not found.");
					}
					l.LogWarning(val);
					return;
				}
				if ((object)hookType == null)
				{
					hookType = typeof(LoadProfiler);
				}
				HarmonyMethod val2 = ((prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(hookType, prefix, (Type[])null, (Type[])null)));
				HarmonyMethod val3 = ((postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(hookType, postfix, (Type[])null, (Type[])null)));
				if (priority >= 0)
				{
					if (val2 != null)
					{
						val2.priority = priority;
					}
					if (val3 != null)
					{
						val3.priority = priority;
					}
				}
				harmony.Patch((MethodBase)methodInfo, val2, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				ManualLogSource l2 = Plugin.L;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(20, 4, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not hook ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(type.Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(method);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				l2.LogWarning(val);
			}
		}

		private static void Begin(string kind)
		{
			if (!Loading)
			{
				Loading = true;
				LoadsThisGame++;
				for (int i = 0; i < 2; i++)
				{
					GenMainCount[i] = 0L;
					GenMainTicks[i] = 0L;
					GenMainMaxTicks[i] = 0L;
					GenWorkerCount[i] = 0L;
					GenWorkerTicks[i] = 0L;
				}
				try
				{
					Runner.ResetSessionStats();
				}
				catch
				{
				}
				CullingCache.ForgetCity();
				LastLoadKind = kind;
				loadStart = Stopwatch.GetTimestamp();
				Timeline.Clear();
				lastState = null;
			}
		}

		private static void PollState()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CityConstructor instance = CityConstructor.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					return;
				}
				string text = ((object)instance.loadState/*cast due to .constrained prefix*/).ToString();
				double num = Elapsed();
				double num2 = (double)Time.unscaledDeltaTime * 1000.0;
				if (text != lastState)
				{
					CloseState(num);
					lastState = text;
					stateFrames = 0;
					stateWorstMs = 0.0;
					stateStart = num;
					if (Timeline.Count < 400)
					{
						Timeline.Add((num, text));
					}
				}
				else
				{
					stateFrames++;
					if (num2 > stateWorstMs)
					{
						stateWorstMs = num2;
					}
				}
			}
			catch
			{
			}
		}

		private static void CloseState(double now)
		{
			if (lastState != null && Timeline.Count != 0)
			{
				int index = Timeline.Count - 1;
				if (!(Timeline[index].text != lastState))
				{
					Timeline[index] = (Timeline[index].t, $"{lastState,-28} {now - stateStart,6:0.0} s, {stateFrames} frames, longest frame {stateWorstMs:0} ms");
				}
			}
		}

		public static void LoadStartPrefix()
		{
			Begin("load");
		}

		public static void SetLoadingTextPrefix(CityConstructor __instance)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Begin("load");
				if (Timeline.Count < 400 && (Object)(object)__instance != (Object)null)
				{
					string text = ((object)__instance.loadState/*cast due to .constrained prefix*/).ToString();
					if (Timeline.Count == 0 || Timeline[Timeline.Count - 1].text != text)
					{
						Timeline.Add((Elapsed(), text));
					}
				}
			}
			catch
			{
			}
		}

		internal static double Elapsed()
		{
			return (double)(Stopwatch.GetTimestamp() - loadStart) / (double)Stopwatch.Frequency;
		}

		internal static void Tick(bool playing)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			if (Loading && !playing)
			{
				PollState();
			}
			if (Loading && playing)
			{
				LastLoadSeconds = Elapsed();
				CloseState(LastLoadSeconds);
				Runner.ToastUntil = Time.realtimeSinceStartup + 12f;
				Loading = false;
				LastTimeline.Clear();
				LastTimeline.AddRange(Timeline);
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(106, 5, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("City load took ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<double>(LastLoadSeconds, "0.0");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s (culling trees generated during load: main thread ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<long>(GenMainCount[0]);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" in ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<double>((double)GenMainTicks[0] * 1000.0 / (double)Stopwatch.Frequency / 1000.0, "0.0");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s, worker threads ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<long>(GenWorkerCount[0]);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; from cache ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(CullingCache.HitsDuringLoad);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(").");
				}
				l.LogInfo(val);
			}
		}

		internal static void GenBegin()
		{
			if (tDepth++ == 0)
			{
				tStart = Stopwatch.GetTimestamp();
			}
		}

		internal static void GenEnd()
		{
			if (--tDepth > 0)
			{
				return;
			}
			tDepth = 0;
			long num = Stopwatch.GetTimestamp() - tStart;
			int num2 = ((!Loading) ? 1 : 0);
			if (OnMainThread)
			{
				Interlocked.Increment(ref GenMainCount[num2]);
				Interlocked.Add(ref GenMainTicks[num2], num);
				if (num > GenMainMaxTicks[num2])
				{
					GenMainMaxTicks[num2] = num;
				}
			}
			else
			{
				Interlocked.Increment(ref GenWorkerCount[num2]);
				Interlocked.Add(ref GenWorkerTicks[num2], num);
			}
		}
	}
	internal static class CullingCache
	{
		internal sealed class RoomRec
		{
			public int FloorId;

			public int[] Targets;

			public int[][] Doors;

			public int[] Occ;

			public int[] DoorCheck;
		}

		private const int FileVersion = 1;

		private static readonly Dictionary<int, RoomRec> cache = new Dictionary<int, RoomRec>();

		private static readonly HashSet<int> captured = new HashSet<int>();

		private static string key;

		private static string identity;

		private static string path;

		private static bool dirty;

		private static float nextSave;

		private static int captureCursor;

		private static int prefillCursor;

		private static volatile bool saving;

		private static int selfChecks;

		internal static int Loaded;

		internal static int Captured;

		internal static int Hits;

		internal static int HitsDuringLoad;

		internal static int Misses;

		internal static int Prefilled;

		internal static int ApplyErrors;

		internal static int SelfCheckOk;

		internal static int SelfCheckBad;

		internal static int Saves;

		internal static int CaptureErrors;

		internal static int NotReady;

		internal static double LastSaveMs;

		internal static double ApplyTicks;

		internal static string Status = "waiting for city";

		private static readonly Dictionary<int, IntPtr> idMap = new Dictionary<int, IntPtr>();

		private static long idMapSig = -1L;

		internal static int IdMapSize;

		internal static int ResolvedViaMap;

		internal static bool Enabled => PerfConfig.CullingCache.Value;

		internal static int Count => cache.Count;

		internal static string Key => key ?? "-";

		internal static void Install(Harmony harmony)
		{
			LoadProfiler.TryPatch(harmony, typeof(NewRoom), "GenerateCullingTree", "GenPrefix", "GenPostfix", typeof(CullingCache), 800);
		}

		public static bool GenPrefix(NewRoom __instance, bool __0)
		{
			LoadProfiler.GenBegin();
			if (!Enabled || __0 || !LoadProfiler.OnMainThread)
			{
				return true;
			}
			try
			{
				EnsureKey();
				if (key == null || (Object)(object)__instance == (Object)null)
				{
					return true;
				}
				if (!cache.TryGetValue(__instance.roomID, out var value) || value.FloorId != __instance.roomFloorID)
				{
					Misses++;
					return true;
				}
				long timestamp = Stopwatch.GetTimestamp();
				bool num = Apply(__instance, value);
				ApplyTicks += Stopwatch.GetTimestamp() - timestamp;
				if (!num)
				{
					return true;
				}
				Hits++;
				if (LoadProfiler.Loading)
				{
					HitsDuringLoad++;
				}
				return false;
			}
			catch (Exception e)
			{
				ApplyErrors++;
				Runner.ReportError("culling-cache", e);
				return true;
			}
		}

		public static void GenPostfix()
		{
			LoadProfiler.GenEnd();
		}

		private static void EnsureKey()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			CityData instance = CityData.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			string cityName = instance.cityName;
			string seed = instance.seed;
			string cityBuiltWith = instance.cityBuiltWith;
			if (string.IsNullOrEmpty(cityName) && string.IsNullOrEmpty(seed))
			{
				return;
			}
			string text = cityName + "|" + seed;
			if (key != null)
			{
				if (text == identity)
				{
					return;
				}
				ResetForNewSession();
			}
			identity = text;
			Vector2 citySize = instance.citySize;
			key = Hash($"{cityName}|{seed}|{citySize.x}x{citySize.y}|{cityBuiltWith}|{Application.version}|v{1}");
			string path = Path.Combine(Paths.CachePath, "SODPerformance");
			Directory.CreateDirectory(path);
			CullingCache.path = Path.Combine(path, $"culling-{Safe(cityName)}-{key}.bin");
			LoadFile();
			Status = $"city '{cityName}': {cache.Count} rooms cached";
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(44, 4, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Culling cache for '");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(cityName);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' (");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(key);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(cache.Count);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" rooms loaded from ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(CullingCache.path);
			}
			l.LogInfo(val);
		}

		internal static void ResetForNewSession()
		{
			if (dirty)
			{
				SaveNow(sync: true);
			}
			key = null;
			identity = null;
			path = null;
			cache.Clear();
			captured.Clear();
			captureCursor = (prefillCursor = 0);
			Loaded = 0;
			Status = "waiting for city";
		}

		internal static string Hash(string s)
		{
			ulong num = 14695981039346656037uL;
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			foreach (byte b in bytes)
			{
				num ^= b;
				num *= 1099511628211L;
			}
			return num.ToString("x16");
		}

		private static string Safe(string n)
		{
			if (string.IsNullOrEmpty(n))
			{
				return "city";
			}
			return new string(n.Select((char c) => (!char.IsLetterOrDigit(c)) ? '_' : c).Take(32).ToArray());
		}

		private static void LoadFile()
		{
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Expected O, but got Unknown
			cache.Clear();
			captured.Clear();
			if (path == null || !File.Exists(path))
			{
				return;
			}
			try
			{
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				if (binaryReader.ReadInt32() != 1128550227 || binaryReader.ReadInt32() != 1 || binaryReader.ReadString() != key)
				{
					return;
				}
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					int num2 = binaryReader.ReadInt32();
					RoomRec roomRec = new RoomRec
					{
						FloorId = binaryReader.ReadInt32()
					};
					int num3 = binaryReader.ReadInt32();
					roomRec.Targets = new int[num3];
					roomRec.Doors = new int[num3][];
					for (int j = 0; j < num3; j++)
					{
						roomRec.Targets[j] = binaryReader.ReadInt32();
						int num4 = binaryReader.ReadInt32();
						int[] array = new int[num4];
						for (int k = 0; k < num4; k++)
						{
							array[k] = binaryReader.ReadInt32();
						}
						roomRec.Doors[j] = array;
					}
					roomRec.Occ = ReadInts(binaryReader);
					roomRec.DoorCheck = ReadInts(binaryReader);
					cache[num2] = roomRec;
				}
				Loaded = cache.Count;
			}
			catch (Exception ex)
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(47, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Culling cache file unreadable, starting fresh: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				l.LogWarning(val);
				cache.Clear();
			}
		}

		private static int[] ReadInts(BinaryReader br)
		{
			int num = br.ReadInt32();
			int[] array = new int[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = br.ReadInt32();
			}
			return array;
		}

		private static void SaveNow(bool sync)
		{
			KeyValuePair<int, RoomRec>[] snapshot;
			string p;
			string k;
			if (path != null && !saving && cache.Count != 0)
			{
				snapshot = cache.ToArray();
				p = path;
				k = key;
				dirty = false;
				saving = true;
				if (sync)
				{
					Write();
				}
				else
				{
					Task.Run((Action)Write);
				}
			}
			void Write()
			{
				//IL_0176: Unknown result type (might be due to invalid IL or missing references)
				//IL_017d: Expected O, but got Unknown
				Stopwatch stopwatch = Stopwatch.StartNew();
				try
				{
					string sourceFileName = p + ".tmp";
					using (BinaryWriter binaryWriter = new BinaryWriter(File.Create(sourceFileName)))
					{
						binaryWriter.Write(1128550227);
						binaryWriter.Write(1);
						binaryWriter.Write(k);
						binaryWriter.Write(snapshot.Length);
						KeyValuePair<int, RoomRec>[] array = snapshot;
						for (int i = 0; i < array.Length; i++)
						{
							KeyValuePair<int, RoomRec> keyValuePair = array[i];
							RoomRec value = keyValuePair.Value;
							binaryWriter.Write(keyValuePair.Key);
							binaryWriter.Write(value.FloorId);
							binaryWriter.Write(value.Targets.Length);
							for (int j = 0; j < value.Targets.Length; j++)
							{
								binaryWriter.Write(value.Targets[j]);
								binaryWriter.Write(value.Doors[j].Length);
								int[] array2 = value.Doors[j];
								foreach (int value2 in array2)
								{
									binaryWriter.Write(value2);
								}
							}
							WriteInts(binaryWriter, value.Occ);
							WriteInts(binaryWriter, value.DoorCheck);
						}
					}
					if (File.Exists(p))
					{
						File.Delete(p);
					}
					File.Move(sourceFileName, p);
					Saves++;
				}
				catch (Exception ex)
				{
					ManualLogSource l2 = Plugin.L;
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(27, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Culling cache save failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					l2.LogWarning(val);
				}
				finally
				{
					LastSaveMs = stopwatch.Elapsed.TotalMilliseconds;
					saving = false;
				}
			}
		}

		private static void WriteInts(BinaryWriter bw, int[] a)
		{
			bw.Write(a.Length);
			foreach (int value in a)
			{
				bw.Write(value);
			}
		}

		internal static void ForgetCity()
		{
			idMap.Clear();
			idMapSig = -1L;
			ResetForNewSession();
			Captured = (Hits = (HitsDuringLoad = (Misses = (Prefilled = (NotReady = (SelfCheckOk = (SelfCheckBad = (ResolvedViaMap = 0))))))));
			selfChecks = 0;
			ApplyTicks = 0.0;
		}

		private static void RebuildIdMapIfChanged()
		{
			CityData instance = CityData.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			long num = (long)(instance.roomDirectory?.Count ?? 0) * 1000003L + (long)(instance.gameLocationDirectory?.Count ?? 0) * 1009L + (instance.streetDirectory?.Count ?? 0);
			if (num == idMapSig)
			{
				return;
			}
			idMapSig = num;
			idMap.Clear();
			List<NewRoom> roomDirectory = instance.roomDirectory;
			if (roomDirectory != null)
			{
				for (int i = 0; i < roomDirectory.Count; i++)
				{
					AddRoom(roomDirectory[i]);
				}
			}
			List<NewGameLocation> gameLocationDirectory = instance.gameLocationDirectory;
			if (gameLocationDirectory != null)
			{
				for (int j = 0; j < gameLocationDirectory.Count; j++)
				{
					NewGameLocation val = gameLocationDirectory[j];
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					AddRoom(val.nullRoom);
					List<NewRoom> rooms = val.rooms;
					if (rooms != null)
					{
						for (int k = 0; k < rooms.Count; k++)
						{
							AddRoom(rooms[k]);
						}
					}
				}
			}
			List<StreetController> streetDirectory = instance.streetDirectory;
			if (streetDirectory != null)
			{
				for (int l = 0; l < streetDirectory.Count; l++)
				{
					StreetController val2 = streetDirectory[l];
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					AddRoom(((NewGameLocation)val2).nullRoom);
					List<NewRoom> rooms2 = ((NewGameLocation)val2).rooms;
					if (rooms2 != null)
					{
						for (int m = 0; m < rooms2.Count; m++)
						{
							AddRoom(rooms2[m]);
						}
					}
				}
			}
			IdMapSize = idMap.Count;
			static void AddRoom(NewRoom r)
			{
				if ((Object)(object)r != (Object)null && !idMap.ContainsKey(r.roomID))
				{
					idMap[r.roomID] = ((Il2CppObjectBase)r).Pointer;
				}
			}
		}

		private static NewRoom Resolve(int id, Dictionary<int, NewRoom> dict)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			if (dict != null && dict.ContainsKey(id))
			{
				NewRoom val = dict[id];
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			if (idMap.TryGetValue(id, out var value) && value != IntPtr.Zero)
			{
				ResolvedViaMap++;
				return new NewRoom(value);
			}
			return null;
		}

		private static void NotFound(int id)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			NotReady++;
			if (NotReady <= 5)
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(86, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Culling cache: room ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(id);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" not found yet (map ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(IdMapSize);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" rooms); the game calculates this tree itself.");
				}
				l.LogInfo(val);
			}
		}

		private static bool Apply(NewRoom room, RoomRec rec)
		{
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Expected O, but got Unknown
			CityData instance = CityData.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			Dictionary<int, NewRoom> roomDictionary = instance.roomDictionary;
			RebuildIdMapIfChanged();
			NewRoom[] array = (NewRoom[])(object)new NewRoom[rec.Targets.Length];
			for (int i = 0; i < array.Length; i++)
			{
				if ((Object)(object)(array[i] = Resolve(rec.Targets[i], roomDictionary)) == (Object)null)
				{
					NotFound(rec.Targets[i]);
					return false;
				}
			}
			NewRoom[] array2 = (NewRoom[])(object)new NewRoom[rec.Occ.Length];
			for (int j = 0; j < array2.Length; j++)
			{
				if ((Object)(object)(array2[j] = Resolve(rec.Occ[j], roomDictionary)) == (Object)null)
				{
					NotFound(rec.Occ[j]);
					return false;
				}
			}
			Dictionary<NewRoom, List<CullTreeEntry>> val = room.cullingTree;
			if (val == null)
			{
				val = (room.cullingTree = new Dictionary<NewRoom, List<CullTreeEntry>>());
			}
			else
			{
				val.Clear();
			}
			int[] array3;
			for (int k = 0; k < array.Length; k++)
			{
				List<CullTreeEntry> val3;
				if (val.ContainsKey(array[k]))
				{
					val3 = val[array[k]];
				}
				else
				{
					val3 = new List<CullTreeEntry>();
					val.Add(array[k], val3);
				}
				List<int> val4 = new List<int>();
				array3 = rec.Doors[k];
				foreach (int num in array3)
				{
					val4.Add(num);
				}
				val3.Add(new CullTreeEntry(val4));
			}
			HashSet<NewRoom> val5 = room.nonAudioOccludedRooms;
			if (val5 == null)
			{
				val5 = (room.nonAudioOccludedRooms = new HashSet<NewRoom>());
			}
			else
			{
				val5.Clear();
			}
			NewRoom[] array4 = array2;
			foreach (NewRoom val7 in array4)
			{
				val5.Add(val7);
			}
			HashSet<int> val8 = room.doorCheckSet;
			if (val8 == null)
			{
				val8 = (room.doorCheckSet = new HashSet<int>());
			}
			else
			{
				val8.Clear();
			}
			array3 = rec.DoorCheck;
			foreach (int num2 in array3)
			{
				val8.Add(num2);
			}
			room.completedTreeCull = true;
			captured.Add(room.roomID);
			if (selfChecks < 40)
			{
				selfChecks++;
				RoomRec roomRec = Read(room);
				if (roomRec != null && Same(roomRec, rec))
				{
					SelfCheckOk++;
				}
				else
				{
					SelfCheckBad++;
				}
			}
			return true;
		}

		private static RoomRec Read(NewRoom room)
		{
			Dictionary<NewRoom, List<CullTreeEntry>> cullingTree = room.cullingTree;
			if (cullingTree == null)
			{
				return null;
			}
			List<int> list = new List<int>();
			List<int[]> list2 = new List<int[]>();
			Enumerator<NewRoom, List<CullTreeEntry>> enumerator = cullingTree.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<NewRoom, List<CullTreeEntry>> current = enumerator.Current;
				NewRoom val = current.Key;
				List<CullTreeEntry> value = current.Value;
				if ((Object)(object)val == (Object)null || value == null)
				{
					continue;
				}
				int roomID = val.roomID;
				for (int i = 0; i < value.Count; i++)
				{
					CullTreeEntry obj = value[i];
					List<int> val2 = ((obj != null) ? obj.requiredOpenDoors : null);
					int[] array;
					if (val2 == null)
					{
						array = Array.Empty<int>();
					}
					else
					{
						array = new int[val2.Count];
						for (int j = 0; j < array.Length; j++)
						{
							array[j] = val2[j];
						}
					}
					list.Add(roomID);
					list2.Add(array);
				}
			}
			List<int> list3 = new List<int>();
			HashSet<NewRoom> nonAudioOccludedRooms = room.nonAudioOccludedRooms;
			if (nonAudioOccludedRooms != null)
			{
				Enumerator<NewRoom> enumerator2 = nonAudioOccludedRooms.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					NewRoom current2 = enumerator2.Current;
					if ((Object)(object)current2 != (Object)null)
					{
						list3.Add(current2.roomID);
					}
				}
			}
			List<int> list4 = new List<int>();
			HashSet<int> doorCheckSet = room.doorCheckSet;
			if (doorCheckSet != null)
			{
				Enumerator<int> enumerator3 = doorCheckSet.GetEnumerator();
				while (enumerator3.MoveNext())
				{
					int current3 = enumerator3.Current;
					list4.Add(current3);
				}
			}
			return new RoomRec
			{
				FloorId = room.roomFloorID,
				Targets = list.ToArray(),
				Doors = list2.ToArray(),
				Occ = list3.ToArray(),
				DoorCheck = list4.ToArray()
			};
		}

		private static bool Same(RoomRec a, RoomRec b)
		{
			if (a.Targets.Length != b.Targets.Length)
			{
				return false;
			}
			IOrderedEnumerable<string> first = from i in Enumerable.Range(0, a.Targets.Length)
				select a.Targets[i] + ":" + string.Join(",", a.Doors[i].OrderBy((int x) => x)) into x
				orderby x
				select x;
			IOrderedEnumerable<string> second = from i in Enumerable.Range(0, b.Targets.Length)
				select b.Targets[i] + ":" + string.Join(",", b.Doors[i].OrderBy((int x) => x)) into x
				orderby x
				select x;
			if (first.SequenceEqual(second) && a.Occ.OrderBy((int x) => x).SequenceEqual(b.Occ.OrderBy((int x) => x)))
			{
				return a.DoorCheck.OrderBy((int x) => x).SequenceEqual(b.DoorCheck.OrderBy((int x) => x));
			}
			return false;
		}

		internal static void Tick(bool optimizationsOn, bool playing, float now)
		{
			if (!Enabled)
			{
				return;
			}
			try
			{
				EnsureKey();
				if (key == null)
				{
					return;
				}
				CityData instance = CityData.Instance;
				List<NewRoom> val = ((instance != null) ? instance.roomDirectory : null);
				if (val == null || val.Count == 0)
				{
					return;
				}
				int count = val.Count;
				double num = (LoadProfiler.Loading ? 6.0 : 1.5);
				long num2 = Stopwatch.GetTimestamp() + (long)(num * (double)Stopwatch.Frequency / 1000.0);
				if (optimizationsOn && playing && cache.Count > 0 && prefillCursor < count)
				{
					GeometryCullingController instance2 = GeometryCullingController.Instance;
					NewRoom val2 = null;
					if ((Object)(object)instance2 != (Object)null && instance2.asyncCullingTreeActive && instance2.toCalculateList != null && instance2.toCalculateList.Count > 0)
					{
						val2 = instance2.toCalculateList[0];
					}
					while (prefillCursor < count && Stopwatch.GetTimestamp() < num2)
					{
						NewRoom val3 = val[prefillCursor++];
						if (!((Object)(object)val3 == (Object)null) && !val3.completedTreeCull && (!((Object)(object)val2 != (Object)null) || !(((Il2CppObjectBase)val3).Pointer == ((Il2CppObjectBase)val2).Pointer)) && cache.TryGetValue(val3.roomID, out var value) && value.FloorId == val3.roomFloorID)
						{
							long timestamp = Stopwatch.GetTimestamp();
							if (Apply(val3, value))
							{
								Prefilled++;
							}
							ApplyTicks += Stopwatch.GetTimestamp() - timestamp;
						}
					}
				}
				if (playing)
				{
					int num3 = 0;
					while (num3 < count && Stopwatch.GetTimestamp() < num2)
					{
						if (captureCursor >= count)
						{
							captureCursor = 0;
						}
						NewRoom val4 = val[captureCursor++];
						num3++;
						if ((Object)(object)val4 == (Object)null || !val4.completedTreeCull)
						{
							continue;
						}
						int roomID = val4.roomID;
						if (captured.Contains(roomID))
						{
							continue;
						}
						captured.Add(roomID);
						if (cache.ContainsKey(roomID))
						{
							continue;
						}
						RoomRec roomRec;
						try
						{
							roomRec = Read(val4);
						}
						catch (Exception e)
						{
							CaptureErrors++;
							if (CaptureErrors <= 3)
							{
								Runner.ReportError("culling-capture", e);
							}
							continue;
						}
						if (roomRec != null)
						{
							cache[roomID] = roomRec;
							Captured++;
							dirty = true;
						}
					}
				}
				if (dirty && now >= nextSave)
				{
					nextSave = now + 60f;
					SaveNow(sync: false);
				}
				Status = $"{cache.Count} rooms cached ({Loaded} from disk, {Captured} new), {Hits} used, {Prefilled} pre-filled";
			}
			catch (Exception e2)
			{
				Runner.ReportError("culling-cache-tick", e2);
			}
		}
	}
	public static class Mod
	{
		private const string ClaimKey = "com.adronyus.sod.performance.running";

		private static readonly object claimLock = new object();

		public static string RunningHost => (AppDomain.CurrentDomain.GetData("com.adronyus.sod.performance.running") as string) ?? "";

		public static bool TryClaim(string host)
		{
			lock (claimLock)
			{
				if (AppDomain.CurrentDomain.GetData("com.adronyus.sod.performance.running") is string)
				{
					return false;
				}
				AppDomain.CurrentDomain.SetData("com.adronyus.sod.performance.running", host + ": " + typeof(Mod).Assembly.Location);
				return true;
			}
		}

		public static void Start(ManualLogSource log, ConfigFile config, string host, Harmony harmony = null)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			Plugin.L = log;
			Plugin.Host = host;
			PerfConfig.Bind(config);
			LoadProfiler.MainThreadId = Environment.CurrentManagedThreadId;
			Sampler.CaptureMainThread();
			object obj = ((object)harmony) ?? ((object)new Harmony("com.adronyus.sod.performance"));
			Plugin.Harmony = (Harmony)obj;
			harmony = (Harmony)obj;
			LoadProfiler.Install(harmony);
			if (PerfConfig.CullingCache.Value)
			{
				CullingCache.Install(harmony);
			}
			if (PerfConfig.DeferSoundOcclusion.Value)
			{
				SoundOcclusionDefer.Install(harmony);
			}
			if (PerfConfig.FastPresetCompareOn.Value)
			{
				FastPresetCompare.Install();
			}
			if (PerfConfig.FastBreakerLookup.Value)
			{
				BreakerLookup.Install(harmony);
			}
			RoomHideDefer.Install(harmony);
			if (PerfConfig.AiFrameBudgetMs.Value > 0f)
			{
				AiTimeBudget.Install(harmony);
			}
			if (PerfConfig.StaggerFarMovement.Value)
			{
				MovementStagger.Install(harmony);
			}
			if (PerfConfig.ProfilerEnabled.Value)
			{
				Profiler.Install(harmony, PerfConfig.ProfilePerInstanceUpdates.Value);
				if (PerfConfig.CatchAiSpikes.Value)
				{
					AiSpikes.Install(harmony, PerfConfig.CatchMovementSpikes.Value);
				}
			}
			if (PerfConfig.SamplingProfiler.Value)
			{
				Sampler.Start();
			}
			ClassInjector.RegisterTypeInIl2Cpp<PerfRunner>();
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(77, 7, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("SOD Performance");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.0.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded as ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(host);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". Optimizations ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(PerfConfig.OptimizationsEnabled.Value ? "ON" : "OFF");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Keys: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<KeyCode>(PerfConfig.OverlayKey.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("=overlay, ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<KeyCode>(PerfConfig.ReportKey.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("=report, ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<KeyCode>(PerfConfig.ToggleKey.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("=optimizations on/off.");
			}
			log.LogInfo(val);
		}

		public static void CreateRunner()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("SODPerformance");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<PerfRunner>();
		}
	}
	internal static class Il2CppFields
	{
		internal static int Offset(IntPtr klass, string field)
		{
			if (klass == IntPtr.Zero)
			{
				return -1;
			}
			IntPtr intPtr = klass;
			while (intPtr != IntPtr.Zero)
			{
				IntPtr intPtr2 = IL2CPP.il2cpp_class_get_field_from_name(intPtr, field);
				if (intPtr2 != IntPtr.Zero)
				{
					return (int)IL2CPP.il2cpp_field_get_offset(intPtr2);
				}
				intPtr = IL2CPP.il2cpp_class_get_parent(intPtr);
			}
			return -1;
		}
	}
	internal static class Native
	{
		internal static IntPtr Lib;

		internal static string Error = "";

		internal static bool Load()
		{
			if (Lib != IntPtr.Zero)
			{
				return true;
			}
			try
			{
				if (!OperatingSystem.IsWindows())
				{
					Error = "not Windows";
					return false;
				}
				string text = Path.Combine(Path.GetDirectoryName(typeof(Native).Assembly.Location) ?? "", "sodsampler.native");
				if (!File.Exists(text))
				{
					Error = "sodsampler.native missing next to SODPerformance.dll";
					return false;
				}
				Lib = NativeLibrary.Load(text);
				return true;
			}
			catch (Exception ex)
			{
				Error = ex.GetType().Name + ": " + ex.Message;
				return false;
			}
		}

		internal static IntPtr Export(string name)
		{
			return NativeLibrary.GetExport(Lib, name);
		}
	}
	internal static class FastPresetCompare
	{
		internal static bool Installed;

		internal static string Status = "off";

		private unsafe static delegate* unmanaged[Cdecl]<long> pCalls;

		internal unsafe static long Calls
		{
			get
			{
				if (pCalls != (delegate* unmanaged[Cdecl]<long>)null)
				{
					return pCalls();
				}
				return 0L;
			}
		}

		internal unsafe static void Install()
		{
			try
			{
				if (!Native.Load())
				{
					Status = "native helper not loaded: " + Native.Error;
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				IntPtr nativeClassPtr = Il2CppClassPointerStore<SoCustomComparison>.NativeClassPtr;
				if (nativeClassPtr == IntPtr.Zero)
				{
					Status = "class not found";
					return;
				}
				IntPtr intPtr = IntPtr.Zero;
				IntPtr intPtr2 = IntPtr.Zero;
				IntPtr zero = IntPtr.Zero;
				IntPtr intPtr3;
				while ((intPtr3 = IL2CPP.il2cpp_class_get_methods(nativeClassPtr, ref zero)) != IntPtr.Zero)
				{
					string text = IL2CPP.il2cpp_method_get_name_(intPtr3);
					uint num = IL2CPP.il2cpp_method_get_param_count(intPtr3);
					if (text == "Equals" && num == 1 && IL2CPP.il2cpp_type_get_name_(IL2CPP.il2cpp_method_get_param(intPtr3, 0u)) == "System.Object")
					{
						intPtr = intPtr3;
					}
					else if (text == "GetPresetName" && num == 0)
					{
						intPtr2 = intPtr3;
					}
				}
				if (intPtr == IntPtr.Zero || intPtr2 == IntPtr.Zero)
				{
					Status = "methods not found";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				IntPtr intPtr4 = Marshal.ReadIntPtr(intPtr);
				IntPtr intPtr5 = Marshal.ReadIntPtr(intPtr2);
				if (intPtr4 == IntPtr.Zero || intPtr5 == IntPtr.Zero)
				{
					Status = "no native code pointer";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				if (((delegate* unmanaged[Cdecl]<IntPtr, int>)(void*)Native.Export("sod_is_function_start"))(intPtr4) != 1)
				{
					Status = "target is not a function start: left alone";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				int num2 = CountMethodsAt(intPtr4);
				if (num2 != 1)
				{
					Status = $"code shared by {num2} methods: left alone";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				byte b = Marshal.ReadByte(intPtr4);
				byte b2 = Marshal.ReadByte(intPtr4, 1);
				if (b == 233 || (b == byte.MaxValue && b2 == 37) || (b == 72 && b2 == 184))
				{
					Status = "already hooked by something else: left alone";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				int num3 = Il2CppFields.Offset(nativeClassPtr, "presetName");
				if (num3 <= 0)
				{
					Status = "presetName field not found (game changed?)";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
					return;
				}
				delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, int, int> delegate* = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, int, int>)(void*)Native.Export("sod_patch_preset_equals");
				pCalls = (delegate* unmanaged[Cdecl]<long>)(void*)Native.Export("sod_preset_equals_calls");
				int num4 = delegate*(intPtr4, intPtr5, intPtr2, num3);
				if (num4 != 0)
				{
					Status = $"patch failed ({num4})";
					Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
				}
				else
				{
					Installed = true;
					Status = "installed";
					Plugin.L.LogInfo((object)"Fast preset compare installed (SoCustomComparison.Equals).");
				}
			}
			catch (Exception ex)
			{
				Status = "error: " + ex.GetType().Name + ": " + ex.Message;
				Plugin.L.LogWarning((object)("Fast preset compare: " + Status));
			}
		}

		private unsafe static int CountMethodsAt(IntPtr code)
		{
			int num = 0;
			IntPtr intPtr = IL2CPP.il2cpp_domain_get();
			uint num2 = 0u;
			IntPtr* ptr = IL2CPP.il2cpp_domain_get_assemblies(intPtr, ref num2);
			for (uint num3 = 0u; num3 < num2; num3++)
			{
				IntPtr intPtr2 = IL2CPP.il2cpp_assembly_get_image(ptr[num3]);
				if (IL2CPP.il2cpp_image_get_name_(intPtr2) != "Assembly-CSharp.dll")
				{
					continue;
				}
				uint num4 = IL2CPP.il2cpp_image_get_class_count(intPtr2);
				for (uint num5 = 0u; num5 < num4; num5++)
				{
					IntPtr intPtr3 = IL2CPP.il2cpp_image_get_class(intPtr2, num5);
					if (intPtr3 == IntPtr.Zero)
					{
						continue;
					}
					IntPtr zero = IntPtr.Zero;
					IntPtr ptr2;
					while ((ptr2 = IL2CPP.il2cpp_class_get_methods(intPtr3, ref zero)) != IntPtr.Zero)
					{
						if (Marshal.ReadIntPtr(ptr2) == code)
						{
							num++;
						}
					}
				}
			}
			return num;
		}
	}
	internal static class BreakerLookup
	{
		internal static bool Installed;

		internal static bool EnabledNow;

		internal static bool Broken;

		internal static long Answered;

		internal static long NotFound;

		internal static long Rebuilds;

		internal static long Appends;

		internal static long HandedBack;

		internal static double LastRebuildMs;

		private static readonly Dictionary<int, (IntPtr p, IntPtr klass)> index = new Dictionary<int, (IntPtr, IntPtr)>();

		private static IntPtr indexedList;

		private static int indexedSize;

		private static IntPtr lastIndexedItem;

		private static int AddrFloor = -1;

		private static int InteractableId = -1;

		private static int UnityCachedPtr = -1;

		private static readonly int[] AddrId = new int[3];

		private static readonly int[] AddrCache = new int[3];

		private static readonly int[] FloorId = new int[3];

		private static readonly int[] FloorCache = new int[3];

		private static int ListItems = -1;

		private static int ListSize = -1;

		internal static string OffsetStatus = "-";

		private static IntPtr listPtr;

		private const int ArrayData = 32;

		private static bool indexCurrent;

		private static float lastFullRebuild = -100f;

		private static bool Main => Environment.CurrentManagedThreadId == LoadProfiler.MainThreadId;

		private static bool ResolveOffsets()
		{
			IntPtr nativeClassPtr = Il2CppClassPointerStore<NewAddress>.NativeClassPtr;
			IntPtr nativeClassPtr2 = Il2CppClassPointerStore<NewFloor>.NativeClassPtr;
			IntPtr nativeClassPtr3 = Il2CppClassPointerStore<Interactable>.NativeClassPtr;
			IntPtr nativeClassPtr4 = Il2CppClassPointerStore<Object>.NativeClassPtr;
			string[] array = new string[3] { "Security", "Doors", "Lights" };
			AddrFloor = Il2CppFields.Offset(nativeClassPtr, "floor");
			InteractableId = Il2CppFields.Offset(nativeClassPtr3, "id");
			UnityCachedPtr = Il2CppFields.Offset(nativeClassPtr4, "m_CachedPtr");
			bool flag = AddrFloor > 0 && InteractableId > 0 && UnityCachedPtr > 0;
			for (int i = 0; i < 3; i++)
			{
				AddrId[i] = Il2CppFields.Offset(nativeClassPtr, "breaker" + array[i] + "ID");
				AddrCache[i] = Il2CppFields.Offset(nativeClassPtr, "breaker" + array[i]);
				FloorId[i] = Il2CppFields.Offset(nativeClassPtr2, "breaker" + array[i] + "ID");
				FloorCache[i] = Il2CppFields.Offset(nativeClassPtr2, "breaker" + array[i]);
				flag &= AddrId[i] > 0 && AddrCache[i] > 0 && FloorId[i] > 0 && FloorCache[i] > 0;
			}
			OffsetStatus = (flag ? $"fields found (address floor 0x{AddrFloor:X}, security id 0x{AddrId[0]:X}, cache 0x{AddrCache[0]:X})" : "a field was not found (game changed?)");
			return flag;
		}

		internal static void Install(Harmony harmony)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			try
			{
				if (!ResolveOffsets())
				{
					Plugin.L.LogWarning((object)("Breaker lookup not installed: " + OffsetStatus));
					return;
				}
				Patch(harmony, typeof(NewAddress), "GetBreakerSecurity", "AddrSecurity");
				Patch(harmony, typeof(NewAddress), "GetBreakerDoors", "AddrDoors");
				Patch(harmony, typeof(NewAddress), "GetBreakerLights", "AddrLights");
				Patch(harmony, typeof(NewFloor), "GetBreakerSecurity", "FloorSecurity");
				Patch(harmony, typeof(NewFloor), "GetBreakerDoors", "FloorDoors");
				Patch(harmony, typeof(NewFloor), "GetBreakerLights", "FloorLights");
				Installed = true;
				Plugin.L.LogInfo((object)"Breaker lookup index installed.");
			}
			catch (Exception ex)
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(32, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Breaker lookup not installed: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				l.LogWarning(val);
			}
		}

		private static void Patch(Harmony harmony, Type t, string method, string prefix)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(t, method, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException(t.Name, method);
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BreakerLookup), prefix, (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static bool AddrSecurity(NewAddress __instance, ref Interactable __result)
		{
			return Address(__instance, ref __result, 0);
		}

		public static bool AddrDoors(NewAddress __instance, ref Interactable __result)
		{
			return Address(__instance, ref __result, 1);
		}

		public static bool AddrLights(NewAddress __instance, ref Interactable __result)
		{
			return Address(__instance, ref __result, 2);
		}

		public static bool FloorSecurity(NewFloor __instance, ref Interactable __result)
		{
			return Floor(__instance, ref __result, 0);
		}

		public static bool FloorDoors(NewFloor __instance, ref Interactable __result)
		{
			return Floor(__instance, ref __result, 1);
		}

		public static bool FloorLights(NewFloor __instance, ref Interactable __result)
		{
			return Floor(__instance, ref __result, 2);
		}

		private unsafe static bool Address(NewAddress inst, ref Interactable result, int kind)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Expected O, but got Unknown
			if (!EnabledNow || Broken || !Main || (Object)(object)inst == (Object)null)
			{
				return true;
			}
			try
			{
				byte* ptr = (byte*)(void*)((Il2CppObjectBase)inst).Pointer;
				if (*(IntPtr*)(ptr + AddrCache[kind]) != IntPtr.Zero)
				{
					return true;
				}
				if (!Ready())
				{
					return true;
				}
				IntPtr intPtr = Lookup(*(int*)(ptr + AddrId[kind]));
				if (intPtr != IntPtr.Zero)
				{
					Interactable val = new Interactable(intPtr);
					SetAddr(inst, kind, val);
					result = val;