Decompiled source of FPSDoctor v0.23.2

FPSDoctor.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using FPSDoctor.FidelityFX;
using FPSDoctor.FidelityFX.FSR3;
using FPSDoctor.Optimizations;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Profiling;
using Unity.Profiling.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.LowLevel;
using UnityEngine.PostProcessing;
using UnityEngine.Profiling;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.Scripting;
using UnityEngine.UI;
using UnityStandardAssets.ImageEffects;
using Valheim.SettingsGui;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("FPSDoctor")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.23.2.0")]
[assembly: AssemblyInformationalVersion("0.23.2+1b9b326fdface827aa157d2495aea5283fbde27a")]
[assembly: AssemblyProduct("FPSDoctor")]
[assembly: AssemblyTitle("FPSDoctor")]
[assembly: AssemblyVersion("0.23.2.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FPSDoctor
{
	internal enum AckDecision
	{
		Wait,
		Applied,
		Fallback,
		Fatal,
		TimedOut
	}
	internal enum SwitchStep
	{
		Idle,
		WaitOff,
		Settle,
		WaitActive,
		Done,
		Failed
	}
	internal static class AnrAckPolicy
	{
		internal const int AbiMismatch = -2;

		internal const int SrFallback = 2;

		internal const float FgTimeout = 15f;

		internal const float SrTimeout = 30f;

		internal const float AttachWarning = 60f;

		internal const float SwitchSettle = 1f;

		internal const float SwitchTimeout = 15f;

		internal static AckDecision Fg(int pending, int applied, int lastResult, float waited)
		{
			if (lastResult == -2)
			{
				return AckDecision.Fatal;
			}
			if (applied == pending)
			{
				return AckDecision.Applied;
			}
			if (!(waited > 15f))
			{
				return AckDecision.Wait;
			}
			return AckDecision.TimedOut;
		}

		internal static SwitchStep Switch(SwitchStep step, bool offAcknowledged, float inStep, bool wantOn, int activeProvider, int target, out bool requestProvider)
		{
			requestProvider = false;
			switch (step)
			{
			case SwitchStep.WaitOff:
				if (offAcknowledged)
				{
					return SwitchStep.Settle;
				}
				if (!(inStep > 15f))
				{
					return SwitchStep.WaitOff;
				}
				return SwitchStep.Failed;
			case SwitchStep.Settle:
				if (inStep < 1f)
				{
					return SwitchStep.Settle;
				}
				requestProvider = true;
				if (!wantOn)
				{
					return SwitchStep.Done;
				}
				return SwitchStep.WaitActive;
			case SwitchStep.WaitActive:
				if (activeProvider == target)
				{
					return SwitchStep.Done;
				}
				if (!(inStep > 15f))
				{
					return SwitchStep.WaitActive;
				}
				return SwitchStep.Failed;
			default:
				return step;
			}
		}

		internal static AckDecision Sr(int pending, int applied, float waited)
		{
			if (applied == pending)
			{
				return AckDecision.Applied;
			}
			if (applied == 2)
			{
				return AckDecision.Fallback;
			}
			if (!(waited > 30f))
			{
				return AckDecision.Wait;
			}
			return AckDecision.TimedOut;
		}
	}
	internal sealed class AnrGameSettings : MonoBehaviour
	{
		private Component _method;

		private Component _quality;

		private Component _frameGen;

		private Component _model;

		private Component _template;

		private TMP_Text _srHeading;

		private TMP_Text _fgHeading;

		private TMP_Text _methodLabel;

		private TMP_Text _qualityLabel;

		private TMP_Text _frameGenLabel;

		private TMP_Text _modelLabel;

		private TMP_Text _labelTemplate;

		private bool _built;

		private TMP_Text _resolutionLabel;

		private TMP_Text _resolutionValue;

		private RectTransform _list;

		private GameObject _original;

		private int _insert;

		private readonly List<Selectable> _navigation = new List<Selectable>();

		private Selectable _navigationBefore;

		private Selectable _navigationAfter;

		private static readonly string[] Hooks = new string[4] { "Initialize", "OnOkAsync", "OnTabOpen", "UpdateUI" };

		private Component _otherTemplate;

		private Component _resolution;

		private bool Ru => GraphicsIntegration.Russian;

		internal static MethodBase[] Targets()
		{
			MethodBase[] array = new MethodBase[Hooks.Length];
			for (int i = 0; i < Hooks.Length; i++)
			{
				array[i] = AccessTools.Method(typeof(GraphicsSettings), Hooks[i], (Type[])null, (Type[])null) ?? throw new InvalidOperationException("Unsupported game graphics settings: " + Hooks[i]);
			}
			return array;
		}

		internal static void Patch(Harmony harmony, MethodBase[] targets, List<KeyValuePair<MethodBase, MethodInfo>> patched)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			string[] array = new string[4] { "InitializePostfix", "SavePrefix", "TabPostfix", "UpdateUiPostfix" };
			for (int i = 0; i < targets.Length; i++)
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(AnrGameSettings), array[i], (Type[])null, (Type[])null);
				if (i == 1)
				{
					harmony.Patch(targets[i], new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					harmony.Patch(targets[i], (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				patched.Add(new KeyValuePair<MethodBase, MethodInfo>(targets[i], methodInfo));
			}
		}

		private static void UpdateUiPostfix(GraphicsSettings __instance)
		{
			AnrGameSettings component = ((Component)__instance).GetComponent<AnrGameSettings>();
			if ((Object)(object)component != (Object)null && component._built)
			{
				component._original.SetActive(false);
				component.RebuildLayout();
			}
		}

		private static void InitializePostfix(GraphicsSettings __instance)
		{
			try
			{
				if (GraphicsIntegration.ManagedAnr && !((Object)(object)((Component)__instance).GetComponent<AnrGameSettings>() != (Object)null))
				{
					((Component)__instance).gameObject.AddComponent<AnrGameSettings>().Build(__instance);
					Plugin.Log.LogMessage((object)"Native graphics rows added: SR method/quality, ANR enable/multiplier; HUDFix always on.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not add graphics controls: " + ex));
			}
		}

		private static bool SavePrefix(GraphicsSettings __instance)
		{
			AnrGameSettings component = ((Component)__instance).GetComponent<AnrGameSettings>();
			if (!((Object)(object)component == (Object)null))
			{
				return component.Commit();
			}
			return true;
		}

		private static void TabPostfix(GraphicsSettings __instance, Button backButton, Button okButton)
		{
			AnrGameSettings component = ((Component)__instance).GetComponent<AnrGameSettings>();
			if ((Object)(object)component == (Object)null || !component._built)
			{
				return;
			}
			component._original.SetActive(false);
			component.RefreshLabels();
			Selectable navigationAfter = (Selectable)(object)backButton;
			foreach (Slider item in Traverse.Create((object)__instance).Field("m_dynamicQualitySliders").GetValue<List<Slider>>())
			{
				if (((Behaviour)item).isActiveAndEnabled)
				{
					navigationAfter = (Selectable)(object)item;
					break;
				}
			}
			object value = Traverse.Create((object)__instance).Field("m_graphicPresetRight").GetValue();
			Selectable navigationBefore = (Selectable)((value is Selectable) ? value : null);
			component._navigationBefore = navigationBefore;
			component._navigationAfter = navigationAfter;
			component.WireNavigation();
			component.RebuildLayout();
		}

		private void WireNavigation()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_navigationAfter == (Object)null)
			{
				return;
			}
			List<Selectable> list = _navigation.FindAll((Selectable s) => s.IsInteractable());
			for (int num = 0; num < list.Count; num++)
			{
				Navigation navigation = list[num].navigation;
				((Navigation)(ref navigation)).mode = (Mode)4;
				((Navigation)(ref navigation)).selectOnUp = ((num == 0) ? _navigationBefore : list[num - 1]);
				((Navigation)(ref navigation)).selectOnDown = ((num + 1 < list.Count) ? list[num + 1] : _navigationAfter);
				((Navigation)(ref navigation)).selectOnLeft = null;
				((Navigation)(ref navigation)).selectOnRight = null;
				list[num].navigation = navigation;
			}
			if (list.Count > 0)
			{
				if ((Object)(object)_navigationBefore != (Object)null)
				{
					Navigation navigation2 = _navigationBefore.navigation;
					((Navigation)(ref navigation2)).selectOnDown = list[0];
					_navigationBefore.navigation = navigation2;
				}
				Navigation navigation3 = _navigationAfter.navigation;
				((Navigation)(ref navigation3)).selectOnUp = list[list.Count - 1];
				_navigationAfter.navigation = navigation3;
			}
		}

		private void Build(GraphicsSettings owner)
		{
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			Traverse val = Traverse.Create((object)owner);
			_list = val.Field("m_listRoot").GetValue<RectTransform>();
			_original = val.Field("m_upscalingOptionsRoot").GetValue<GameObject>();
			ref Component template = ref _template;
			object value = val.Field("m_renderScaleDropdown").GetValue();
			template = (Component)((value is Component) ? value : null);
			ref Component otherTemplate = ref _otherTemplate;
			object value2 = val.Field("m_upscalingAlgorithmDropdown").GetValue();
			otherTemplate = (Component)((value2 is Component) ? value2 : null);
			Component template2 = _template;
			object labelTemplate;
			if (template2 == null)
			{
				labelTemplate = null;
			}
			else
			{
				Transform obj = template2.transform.parent.Find("Label");
				labelTemplate = ((obj != null) ? ((Component)obj).GetComponent<TMP_Text>() : null);
			}
			_labelTemplate = (TMP_Text)labelTemplate;
			if ((Object)(object)_list == (Object)null || (Object)(object)_original == (Object)null || (Object)(object)_template == (Object)null || (Object)(object)_otherTemplate == (Object)null || (Object)(object)_labelTemplate == (Object)null)
			{
				throw new InvalidOperationException("Unsupported native graphics template");
			}
			_insert = _original.transform.GetSiblingIndex();
			_srHeading = Heading("FPSDoctor SR", 26f);
			_method = Dropdown("SR Method", new string[3]
			{
				"NVIDIA DLSS",
				"AMD FSR 2.2",
				Ru ? "Нет" : "None"
			}, Array.IndexOf(GraphicsIntegration.SrMethods, GraphicsIntegration.SrMethod.Value), out _methodLabel);
			_quality = Dropdown("SR Quality", (!Ru) ? new string[6] { "DLAA (100%)", "Ultra Quality", "Quality", "Balanced", "Performance", "Ultra Performance" } : new string[6] { "DLAA (100%)", "Ультракачество", "Качество", "Баланс", "Производительность", "Ультрапроизв." }, Array.IndexOf(GraphicsIntegration.SrQualities, GraphicsIntegration.SrQuality.Value), out _qualityLabel);
			_resolution = Dropdown("Render Resolution", new string[1] { "" }, 0, out _resolutionLabel);
			_resolutionValue = ((TMP_Dropdown)_resolution).captionText;
			((Selectable)_resolution).interactable = false;
			_fgHeading = Heading("FPSDoctor FG", 26f);
			_frameGen = Dropdown("ANR Frame Generation", new string[6]
			{
				Ru ? "Выкл." : "Off",
				"×2",
				"×3",
				"×4",
				"×5",
				"×6"
			}, GraphicsIntegration.AnrEnabled.Value ? (GraphicsIntegration.AnrMultiplier.Value - 1) : 0, out _frameGenLabel);
			_model = Dropdown("FG Model", new string[2] { "ANR (×2–×6)", "NVIDIA DLSS-G (×2–×6)" }, Array.IndexOf(GraphicsIntegration.FgModels, GraphicsIntegration.FgModel.Value), out _modelLabel);
			_built = true;
			_original.SetActive(false);
			RefreshLabels();
			RebuildLayout();
		}

		private static Transform Corresponding(Transform source, Transform root, Transform clone)
		{
			Stack<int> stack = new Stack<int>();
			while ((Object)(object)source != (Object)(object)root)
			{
				stack.Push(source.GetSiblingIndex());
				source = source.parent;
			}
			while (stack.Count > 0)
			{
				clone = clone.GetChild(stack.Pop());
			}
			return clone;
		}

		private GameObject NativeRow(string name, out Component dropdown, out TMP_Text label)
		{
			GameObject val = Object.Instantiate<GameObject>(_original, _original.transform.parent);
			((Object)val).name = name;
			val.transform.SetSiblingIndex(_insert++);
			dropdown = ((Component)Corresponding(_template.transform, _original.transform, val.transform)).GetComponent(((object)_template).GetType());
			label = ((Component)dropdown.transform.parent.Find("Label")).GetComponent<TMP_Text>();
			Transform obj = Corresponding(_otherTemplate.transform, _original.transform, val.transform);
			((Component)obj).gameObject.SetActive(false);
			((Component)obj.parent.Find("Label")).gameObject.SetActive(false);
			val.SetActive(true);
			return val;
		}

		private TMP_Text Heading(string name, float height)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			Component dropdown;
			TMP_Text label;
			GameObject obj = NativeRow(name, out dropdown, out label);
			dropdown.gameObject.SetActive(false);
			((RectTransform)obj.transform).SetSizeWithCurrentAnchors((Axis)1, height);
			label.textWrappingMode = (TextWrappingModes)0;
			return label;
		}

		private Component Dropdown(string name, string[] options, int value, out TMP_Text label)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			NativeRow(name, out var dropdown, out label);
			UnityEvent<int> val = Traverse.Create((object)dropdown).Property("onValueChanged", (object[])null).GetValue() as UnityEvent<int>;
			if (val != null)
			{
				((UnityEventBase)val).RemoveAllListeners();
			}
			Type type = ((object)dropdown).GetType();
			AccessTools.Method(type, "ClearOptions", (Type[])null, (Type[])null).Invoke(dropdown, null);
			AccessTools.Method(type, "AddOptions", new Type[1] { typeof(List<string>) }, (Type[])null).Invoke(dropdown, new object[1]
			{
				new List<string>(options)
			});
			AccessTools.Method(type, "SetValueWithoutNotify", new Type[1] { typeof(int) }, (Type[])null).Invoke(dropdown, new object[1] { Math.Max(0, value) });
			AccessTools.Method(type, "RefreshShownValue", (Type[])null, (Type[])null)?.Invoke(dropdown, null);
			val?.AddListener((UnityAction<int>)delegate
			{
				RefreshLabels();
			});
			_navigation.Add((Selectable)dropdown);
			return dropdown;
		}

		private static int Value(Component control)
		{
			return (int)Traverse.Create((object)control).Property("value", (object[])null).GetValue();
		}

		private void RefreshLabels()
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Invalid comparison between Unknown and I4
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Expected O, but got Unknown
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			if (!_built)
			{
				return;
			}
			_srHeading.text = (Ru ? "МАСШТАБИРОВАНИЕ" : "UPSCALING");
			_fgHeading.text = (Ru ? "ГЕНЕРАЦИЯ КАДРОВ" : "FRAME GENERATION");
			_methodLabel.text = (Ru ? "Метод масштабирования" : "Upscaling method");
			bool flag = GraphicsIntegration.SrMethods[Value(_method)] == "fsr22";
			bool flag2 = GraphicsIntegration.SrMethods[Value(_method)] == "none";
			_qualityLabel.text = ((!flag2) ? ((!flag) ? (Ru ? "Качество NVIDIA DLSS" : "NVIDIA DLSS quality") : (Ru ? "Качество AMD FSR" : "AMD FSR quality")) : (Ru ? "Качество масштабирования" : "Upscaling quality"));
			((Selectable)_quality).interactable = !flag2;
			TMP_Dropdown val = (TMP_Dropdown)_quality;
			val.options[0].text = ((!flag) ? "DLAA (100%)" : (Ru ? "Нативное AA (100%)" : "Native AA (100%)"));
			val.RefreshShownValue();
			_resolutionLabel.text = (Ru ? "Разрешение рендера" : "Render resolution");
			(int, int) tuple = AnrSettingsPolicy.RenderSize(GraphicsIntegration.SrMethods[Value(_method)], GraphicsIntegration.SrQualities[Value(_quality)], Screen.width, Screen.height);
			TMP_Dropdown val2 = (TMP_Dropdown)_resolution;
			val2.options[0].text = $"{tuple.Item1}×{tuple.Item2}";
			val2.RefreshShownValue();
			bool flag3 = (int)SystemInfo.graphicsDeviceType == 18;
			_frameGenLabel.text = ((!flag2) ? (flag3 ? (GraphicsIntegration.FgReady ? (Ru ? "Генерация кадров" : "Frame generation") : (Ru ? "Генерация кадров (после перезапуска)" : "Frame generation (after restart)")) : (Ru ? "Генерация кадров (нужен DirectX 12)" : "Frame generation (needs DirectX 12)")) : (Ru ? "Генерация кадров (нужен DLSS или FSR)" : "Frame generation (needs DLSS or FSR)"));
			TMP_Dropdown val3 = (TMP_Dropdown)_frameGen;
			int num = GraphicsIntegration.MaxMultiplier(GraphicsIntegration.FgModels[Value(_model)]);
			if (val3.options.Count != num)
			{
				int valueWithoutNotify = Math.Min(val3.value, num - 1);
				List<string> list = new List<string> { Ru ? "Выкл." : "Off" };
				for (int i = 2; i <= num; i++)
				{
					list.Add("×" + i);
				}
				val3.ClearOptions();
				val3.AddOptions(list);
				val3.SetValueWithoutNotify(valueWithoutNotify);
			}
			val3.options[0].text = (Ru ? "Выкл." : "Off");
			val3.RefreshShownValue();
			((Selectable)_frameGen).interactable = flag3 && !flag2;
			bool flag4 = !GraphicsIntegration.LiveModelSwitch && GraphicsIntegration.FgModels[Value(_model)] != GraphicsIntegration.RunningFgModel;
			_modelLabel.text = (Ru ? "Модель генерации" : "Generation model") + ((!flag4) ? "" : (Ru ? " (после перезапуска)" : " (after restart)"));
			((Selectable)_model).interactable = flag3;
			WireNavigation();
		}

		private void RebuildLayout()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Canvas.ForceUpdateCanvases();
			VerticalLayoutGroup component = ((Component)_list).GetComponent<VerticalLayoutGroup>();
			float num = 0f;
			foreach (RectTransform item in (Transform)_list)
			{
				RectTransform val = item;
				if (((Component)val).gameObject.activeSelf)
				{
					float num2 = num;
					Rect rect = val.rect;
					num = num2 + (((Rect)(ref rect)).height + (((Object)(object)component != (Object)null) ? ((HorizontalOrVerticalLayoutGroup)component).spacing : 0f));
				}
			}
			_list.SetSizeWithCurrentAnchors((Axis)1, num);
			LayoutRebuilder.ForceRebuildLayoutImmediate(_list);
		}

		private bool Commit()
		{
			if (!_built)
			{
				return true;
			}
			bool flag = true;
			try
			{
				int num = Value(_frameGen);
				bool enabled = num > 0;
				int multiplier = (enabled ? (num + 1) : GraphicsIntegration.AnrMultiplier.Value);
				string method = GraphicsIntegration.SrMethods[Value(_method)];
				string quality = GraphicsIntegration.SrQualities[Value(_quality)];
				bool multiplierChanged = multiplier != GraphicsIntegration.AnrMultiplier.Value;
				bool enabledChanged = enabled != GraphicsIntegration.AnrEnabled.Value;
				bool methodChanged = method != GraphicsIntegration.SrMethod.Value;
				flag &= Try("upscaling", delegate
				{
					GraphicsIntegration.SaveSuperResolution(method, quality);
					if (methodChanged)
					{
						LiveSrControl.NotifyWhenApplied(method);
					}
					string text = null;
					if (methodChanged && method == "none" && GraphicsIntegration.FgReady)
					{
						text = (Ru ? "Без масштабирования игра работает быстрее после перезапуска." : "Without upscaling the game runs faster after a restart.");
					}
					else if (methodChanged && method != "none" && !GraphicsIntegration.FgReady && enabled)
					{
						text = (Ru ? "Генерация кадров включится после перезапуска игры." : "Frame generation turns on after the game restarts.");
					}
					if (text != null && (Object)(object)MessageHud.instance != (Object)null)
					{
						MessageHud.instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true);
					}
				});
				string model = GraphicsIntegration.FgModels[Value(_model)];
				bool modelChanged = model != GraphicsIntegration.RunningFgModel;
				bool liveModel = modelChanged && GraphicsIntegration.LiveModelSwitch;
				flag &= Try("frame generation model", delegate
				{
					if (GraphicsIntegration.SaveFgModel(model) && modelChanged && (Object)(object)MessageHud.instance != (Object)null)
					{
						MessageHud.instance.ShowMessage((MessageType)2, Ru ? "Модель генерации сменится после перезапуска игры." : "The generation model changes after the game restarts.", 0, (Sprite)null, false, true);
					}
				});
				flag &= Try("frame generation", delegate
				{
					GraphicsIntegration.SavePreset(enabled, multiplier, !liveModel);
					if (liveModel)
					{
						LiveAnrControl.SwitchModel(model, enabled && method != "none", Math.Min(multiplier, GraphicsIntegration.MaxMultiplier(model)));
					}
					else if ((multiplierChanged || enabledChanged) && !methodChanged && method != "none")
					{
						LiveAnrControl.NotifyWhenApplied(enabled, GraphicsIntegration.Effective(multiplier));
					}
				});
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not read FPSDoctor graphics controls: " + ex));
				flag = false;
			}
			if (!flag && (Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)2, Ru ? "Настройки FPSDoctor сохранены, но не применены на лету. Перезапустите игру; подробности в журнале." : "FPSDoctor settings saved but not applied live. Restart the game; details in the log.", 0, (Sprite)null, false, true);
			}
			return true;
		}

		private static bool Try(string part, Action action)
		{
			try
			{
				action();
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not apply " + part + " settings: " + ex));
				return false;
			}
		}
	}
	internal static class AnrSettingsPolicy
	{
		internal static string Read(string text, string section, string key, string fallback)
		{
			string a = "";
			string[] array = text.Split(new char[1] { '\n' });
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length == 0 || text2[0] == ';' || text2[0] == '#')
				{
					continue;
				}
				if (text2[0] == '[' && text2.EndsWith("]"))
				{
					a = text2.Substring(1, text2.Length - 2).Trim();
					continue;
				}
				int num = text2.IndexOf('=');
				if (num > 0 && string.Equals(a, section, StringComparison.OrdinalIgnoreCase) && string.Equals(text2.Substring(0, num).Trim(), key, StringComparison.OrdinalIgnoreCase))
				{
					return text2.Substring(num + 1).Trim();
				}
			}
			return fallback;
		}

		internal static string Set(string text, string section, string key, string value)
		{
			Match match = Regex.Match(text, "(?im)^[ \\t]*\\[" + Regex.Escape(section) + "\\][ \\t]*\\r?$");
			if (!match.Success)
			{
				return text.TrimEnd(Array.Empty<char>()) + "\r\n\r\n[" + section + "]\r\n" + key + " = " + value + "\r\n";
			}
			int num = match.Index + match.Length;
			Match match2 = Regex.Match(text.Substring(num), "(?m)^[ \\t]*\\[");
			int num2 = (match2.Success ? match2.Index : (text.Length - num));
			string text2 = text.Substring(num, num2);
			string pattern = "(?im)^[ \\t]*" + Regex.Escape(key) + "[ \\t]*=[^\\r\\n]*";
			int count = Regex.Matches(text2, pattern).Count;
			if (count > 1)
			{
				throw new InvalidOperationException("Duplicate ANR INI setting: [" + section + "] " + key);
			}
			text2 = ((count == 1) ? Regex.Replace(text2, pattern, (Match _) => key + " = " + value) : (text2.TrimEnd(Array.Empty<char>()) + "\r\n" + key + " = " + value + "\r\n\r\n"));
			return text.Substring(0, num) + text2 + text.Substring(num + num2);
		}

		internal static (int Width, int Height) RenderSize(string method, string quality, int screenWidth, int screenHeight)
		{
			if (screenWidth <= 0 || screenHeight <= 0)
			{
				return (Width: screenWidth, Height: screenHeight);
			}
			double num = ((!(method == "none")) ? (quality switch
			{
				"UltraQuality" => 1.3, 
				"Quality" => 1.5, 
				"Balanced" => 1.7, 
				"Performance" => 2.0, 
				"UltraPerformance" => 3.0, 
				_ => 1.0, 
			}) : 1.0);
			double num2 = num;
			int num3 = Math.Max(8, Math.Min(screenHeight, (int)((double)screenHeight / num2)));
			return (Width: (int)((uint)(num3 * screenWidth) / (uint)screenHeight), Height: num3);
		}

		internal static string Apply(string text, bool enabled, int multiplier)
		{
			if (multiplier < 2 || multiplier > 6)
			{
				throw new ArgumentOutOfRangeException("multiplier");
			}
			text = Set(text, "FrameGen", "Enabled", enabled ? "true" : "false");
			text = Set(text, "DLSSG", "InterpolationCount", (multiplier - 1).ToString());
			text = Set(text, "DLSSG", "ForceDMFG", "false");
			text = Set(text, "OptiFG", "HUDFix", "true");
			text = Set(text, "OptiFG", "DisableHUDFix", "false");
			text = Set(text, "OptiFG", "HUDLimit", "1");
			text = Set(text, "Menu", "ShortcutKey", "-1");
			text = Set(text, "Menu", "FGShortcutKey", "-1");
			text = Set(text, "DLSS", "RenderPresetOverride", "true");
			text = Set(text, "DLSS", "RenderPresetForAll", "13");
			text = Set(text, "InitFlags", "AutoExposure", "true");
			return text;
		}
	}
	internal sealed class Benchmark : MonoBehaviour
	{
		internal sealed class Experiment
		{
			public string Name;

			public Action Apply;

			public Action Revert;

			public float ExtraWarmup;
		}

		private sealed class Result
		{
			public int N;

			public double FrameMs;

			public double BusyMs;

			public double SetPass;

			public double Draws;

			public static Result Mean(Result a, Result b)
			{
				return new Result
				{
					FrameMs = (a.FrameMs + b.FrameMs) / 2.0,
					BusyMs = (a.BusyMs + b.BusyMs) / 2.0,
					SetPass = (a.SetPass + b.SetPass) / 2.0,
					Draws = (a.Draws + b.Draws) / 2.0
				};
			}

			public string Line(string name, Result reference)
			{
				string text = ((reference == null) ? "" : $"{(FrameMs / reference.FrameMs - 1.0) * 100.0,7:+0.0;-0.0}%");
				string text2 = ((SetPass <= 0.0) ? "     n/a" : ((reference == null) ? $"{SetPass,8:0}" : $"{SetPass - reference.SetPass,8:+0;-0;0}"));
				string text3 = ((Draws <= 0.0) ? "     n/a" : ((reference == null) ? $"{Draws,8:0}" : $"{Draws - reference.Draws,8:+0;-0;0}"));
				return $"{FrameMs,10:0.00}{BusyMs,10:0.00}{1000.0 / FrameMs,8:0}{text,14}{text2}{text3}   {name}\n";
			}
		}

		private const float Warmup = 1.5f;

		private const float Measure = 5f;

		private bool _wasGhost;

		private bool _wasGod;

		private static readonly FieldRef<Character, Vector3> _moveDir = AccessTools.FieldRefAccess<Character, Vector3>("m_moveDir");

		public static string Progress = "";

		private GUIStyle _style;

		private const int Rounds = 2;

		private static ProfilerRecorder _spRec;

		private static ProfilerRecorder _dcRec;

		private static float _lastHp = -1f;

		private static bool _healthChanged;

		public static bool Running { get; private set; }

		public static void Patch(Harmony harmony)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			HarmonyMethod val = new HarmonyMethod(typeof(Benchmark), "SkipWhileRunning", (Type[])null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(PlayerController), "FixedUpdate", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(PlayerController), "LateUpdate", (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool SkipWhileRunning()
		{
			if (!Running)
			{
				return !RouteBench.Playing;
			}
			return false;
		}

		private void Shield(bool on)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				if (on)
				{
					_wasGhost = ((Character)localPlayer).InGhostMode();
					_wasGod = ((Character)localPlayer).InGodMode();
					localPlayer.SetGhostMode(true);
					localPlayer.SetGodMode(true);
					_moveDir.Invoke((Character)(object)localPlayer) = Vector3.zero;
				}
				else
				{
					localPlayer.SetGhostMode(_wasGhost);
					localPlayer.SetGodMode(_wasGod);
				}
			}
		}

		private void Update()
		{
			if (!Running && !RouteBench.Playing && !((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				if (Plugin.DevKey(Plugin.DeepScanKey))
				{
					((MonoBehaviour)this).StartCoroutine(Run(DeepScan.BuildExperiments(), 1, "FPSDoctor DEEP SCAN: what loads the game the most", sortByImpact: true, DeepScan.AppendCensus));
				}
				else if (Plugin.DevKey(Plugin.WeatherScanKey))
				{
					((MonoBehaviour)this).StartCoroutine(Run(DeepScan.BuildWeatherExperiments(), 1, "FPSDoctor WEATHER SCAN: what each biome's weather costs", sortByImpact: true, null));
				}
				else if (Plugin.DevKey(Plugin.LogicScanKey))
				{
					((MonoBehaviour)this).StartCoroutine(LogicScan());
				}
				else if (Plugin.DevKey(Plugin.ShadowScanKey))
				{
					((MonoBehaviour)this).StartCoroutine(Run(DeepScan.BuildShadowExperiments(), 3, "FPSDoctor SHADOW SCAN: what the shadows cost", sortByImpact: true, null));
				}
				else if (Plugin.DevKey(Plugin.BenchKey))
				{
					((MonoBehaviour)this).StartCoroutine(Run(BuildExperiments(), 2, "FPSDoctor benchmark", sortByImpact: false, null));
				}
			}
		}

		private IEnumerator LogicScan()
		{
			yield return Run(DeepScan.BuildLogicExperiments(), 2, "FPSDoctor LOGIC SCAN: drawing or game logic?", sortByImpact: false, null);
			if ((Object)(object)ProfilerOverlay.Instance != (Object)null)
			{
				Running = true;
				Progress = "profiling the game systems (12 s)...";
				yield return ProfilerOverlay.Instance.TimedDump(12f);
				Running = false;
				Progress = "";
			}
		}

		private IEnumerator Run(List<Experiment> exps, int rounds, string title, bool sortByImpact, Action<StringBuilder> extra)
		{
			Running = true;
			Shield(on: true);
			EnvMan env = EnvMan.instance;
			string heldEnv = (((Object)(object)env != (Object)null) ? env.m_debugEnv : null);
			bool heldTod = (Object)(object)env != (Object)null && env.m_debugTimeOfDay;
			float heldTime = (((Object)(object)env != (Object)null) ? env.m_debugTime : 0.5f);
			string current = (((Object)(object)env != (Object)null) ? "Clear, noon" : null);
			if ((Object)(object)env != (Object)null)
			{
				env.m_debugEnv = "Clear";
				env.m_debugTimeOfDay = true;
				env.m_debugTime = 0.5f;
			}
			if ((Object)(object)env != (Object)null)
			{
				env.ForceInstantEnvironmentSwitch();
				Progress = "setting clear noon...";
				yield return (object)new WaitForSecondsRealtime(4f);
			}
			StringBuilder sb = new StringBuilder();
			sb.AppendFormat("\n{0} ({1} experiments x {2} rounds, {3:0.#}s phases, baselines between)\n", title, exps.Count, rounds, 6.5f);
			sb.Append("   ms/frame   busy ms     FPS    vs baseline setpass   draws   experiment  (setpass/draws: absolute for the baseline, change for experiments)\n");
			_lastHp = -1f;
			_healthChanged = false;
			Result baseline = new Result();
			yield return MeasurePhase("baseline", baseline);
			sb.Append(baseline.Line("baseline", null));
			Dictionary<Experiment, Result> sumExp = new Dictionary<Experiment, Result>();
			Dictionary<Experiment, Result> sumRef = new Dictionary<Experiment, Result>();
			for (int round = 0; round < rounds; round++)
			{
				foreach (Experiment e in exps)
				{
					Result r = new Result();
					bool applied = false;
					try
					{
						e.Apply();
						applied = true;
					}
					catch (Exception ex)
					{
						sb.AppendFormat("   {0}: failed to apply: {1}\n", e.Name, ex.Message);
					}
					if (applied)
					{
						yield return MeasurePhase(e.Name, r, e.ExtraWarmup);
						try
						{
							e.Revert();
						}
						catch (Exception ex2)
						{
							Plugin.Log.LogWarning((object)("Benchmark: revert of " + e.Name + " failed: " + ex2.Message));
						}
					}
					Result after = new Result();
					yield return MeasurePhase("baseline", after);
					if (applied)
					{
						Accumulate(sumExp, e, r);
						Accumulate(sumRef, e, Result.Mean(baseline, after));
					}
					baseline = after;
				}
			}
			List<Experiment> list = new List<Experiment>(exps);
			if (sortByImpact)
			{
				list.Sort(delegate(Experiment x, Experiment y)
				{
					Result value2;
					double num = (sumExp.TryGetValue(x, out value2) ? (Scale(value2).FrameMs / Scale(sumRef[x]).FrameMs) : 1.0);
					Result value4;
					double value3 = (sumExp.TryGetValue(y, out value4) ? (Scale(value4).FrameMs / Scale(sumRef[y]).FrameMs) : 1.0);
					return num.CompareTo(value3);
				});
			}
			foreach (Experiment item in list)
			{
				if (sumExp.TryGetValue(item, out var value))
				{
					sb.Append(Scale(value).Line(item.Name, Scale(sumRef[item])));
				}
			}
			sb.Append("(negative % = faster than baseline; 'busy' = main thread time per frame)\n");
			if (_healthChanged)
			{
				sb.Append("WARNING: you took damage during the benchmark (combat?). Results are unreliable, run it again in a quiet spot.\n");
			}
			sb.Append("\nState after benchmark (everything back on):\n");
			PieceStats.Append(sb);
			PieceRenderer.AppendBlockDiagnostics(sb);
			foreach (Optimization item2 in OptimizationManager.All)
			{
				sb.AppendFormat("  {0} [cost {1:0.000} ms/frame]: {2}\n", item2.Name, item2.CostMs, item2.Active ? item2.Status() : "off");
			}
			if (extra != null)
			{
				try
				{
					extra(sb);
				}
				catch (Exception ex3)
				{
					sb.Append("census failed: " + ex3.Message + "\n");
				}
			}
			if ((Object)(object)env != (Object)null)
			{
				env.m_debugEnv = heldEnv ?? "";
				env.m_debugTimeOfDay = heldTod;
				env.m_debugTime = heldTime;
			}
			Shield(on: false);
			if (current != null)
			{
				sb.AppendLine("(conditions during the run: " + current + "; controls frozen, ghost + god mode)");
			}
			Plugin.Log.LogMessage((object)sb.ToString());
			Progress = "benchmark done, results in LogOutput.log";
			Running = false;
			yield return (object)new WaitForSecondsRealtime(4f);
			if (!Running)
			{
				Progress = "";
			}
		}

		private void OnGUI()
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			string text = ((!string.IsNullOrEmpty(Progress)) ? Progress : RouteBench.Progress);
			if (!string.IsNullOrEmpty(text))
			{
				if (_style == null)
				{
					_style = new GUIStyle(GUI.skin.box)
					{
						fontSize = 18,
						alignment = (TextAnchor)4
					};
					_style.normal.textColor = Color.yellow;
				}
				GUI.Box(new Rect((float)Screen.width / 2f - 260f, 40f, 520f, 36f), text, _style);
			}
		}

		private static void Accumulate(Dictionary<Experiment, Result> into, Experiment e, Result r)
		{
			if (!into.TryGetValue(e, out var value))
			{
				value = (into[e] = new Result());
			}
			value.FrameMs += r.FrameMs;
			value.BusyMs += r.BusyMs;
			value.SetPass += r.SetPass;
			value.Draws += r.Draws;
			value.N++;
		}

		private static Result Scale(Result r)
		{
			return new Result
			{
				FrameMs = r.FrameMs / (double)r.N,
				BusyMs = r.BusyMs / (double)r.N,
				SetPass = r.SetPass / (double)r.N,
				Draws = r.Draws / (double)r.N
			};
		}

		private IEnumerator MeasurePhase(string name, Result into, float extraWarmup = 0f)
		{
			Progress = "benchmark: " + name + " (don't move)";
			float t = 0f;
			while (t < 1.5f + extraWarmup)
			{
				t += Time.unscaledDeltaTime;
				yield return null;
			}
			FrameSplit.ResetAccumulators();
			if (!((ProfilerRecorder)(ref _spRec)).Valid)
			{
				try
				{
					_spRec = ProfilerRecorder.StartNew(ProfilerCategory.Render, "SetPass Calls Count", 1, (ProfilerRecorderOptions)24);
				}
				catch
				{
				}
			}
			if (!((ProfilerRecorder)(ref _dcRec)).Valid)
			{
				try
				{
					_dcRec = ProfilerRecorder.StartNew(ProfilerCategory.Render, "Draw Calls Count", 1, (ProfilerRecorderOptions)24);
				}
				catch
				{
				}
			}
			double sum = 0.0;
			double sp = 0.0;
			double dc = 0.0;
			int n = 0;
			int nsp = 0;
			t = 0f;
			while (t < 5f)
			{
				yield return null;
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null)
				{
					float health = ((Character)localPlayer).GetHealth();
					if (_lastHp >= 0f && health < _lastHp - 0.01f)
					{
						_healthChanged = true;
					}
					_lastHp = health;
				}
				t += Time.unscaledDeltaTime;
				sum += (double)Time.unscaledDeltaTime * 1000.0;
				n++;
				if (((ProfilerRecorder)(ref _spRec)).Valid && ((ProfilerRecorder)(ref _spRec)).Count > 0 && ((ProfilerRecorder)(ref _dcRec)).Valid && ((ProfilerRecorder)(ref _dcRec)).Count > 0)
				{
					sp += (double)((ProfilerRecorder)(ref _spRec)).LastValue;
					dc += (double)((ProfilerRecorder)(ref _dcRec)).LastValue;
					nsp++;
				}
			}
			into.FrameMs = sum / (double)Math.Max(1, n);
			into.SetPass = ((nsp > 0) ? (sp / (double)nsp) : 0.0);
			into.Draws = ((nsp > 0) ? (dc / (double)nsp) : 0.0);
			into.BusyMs = FrameSplit.AverageBusySinceReset();
		}

		private static List<Experiment> BuildExperiments()
		{
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			List<Experiment> list = new List<Experiment>();
			bool master = Optimization.MasterOn;
			list.Add(new Experiment
			{
				Name = (master ? "FPSDoctor optimizations OFF" : "FPSDoctor optimizations ON"),
				Apply = delegate
				{
					OptimizationManager.SetMaster(!master);
				},
				Revert = delegate
				{
					OptimizationManager.SetMaster(master);
				}
			});
			foreach (Optimization item in OptimizationManager.All)
			{
				Optimization opt = item;
				if (opt.Active && opt.Benchmarkable)
				{
					list.Add(new Experiment
					{
						Name = "only " + opt.Name + " OFF",
						Apply = delegate
						{
							opt.Suspended = true;
							OptimizationManager.SafeRefresh(opt);
						},
						Revert = delegate
						{
							opt.Suspended = false;
							OptimizationManager.SafeRefresh(opt);
						}
					});
				}
			}
			foreach (Optimization item2 in OptimizationManager.All)
			{
				OcclusionCulling occ = item2 as OcclusionCulling;
				if (occ != null && !item2.Active)
				{
					list.Add(new Experiment
					{
						Name = "OcclusionCulling forced ON (Auto has it off here)",
						Apply = delegate
						{
							OcclusionCulling.ForcedOn = true;
							OptimizationManager.SafeRefresh(occ);
						},
						Revert = delegate
						{
							OcclusionCulling.ForcedOn = false;
							OptimizationManager.SafeRefresh(occ);
						}
					});
				}
			}
			list.Add(new Experiment
			{
				Name = "only chunk meshes OFF (pieces instanced instead of merged)",
				Apply = delegate
				{
					PieceRenderer.SetCellsSuspended(suspended: true);
				},
				Revert = delegate
				{
					PieceRenderer.SetCellsSuspended(suspended: false);
				}
			});
			ShadowQuality shadows = QualitySettings.shadows;
			list.Add(new Experiment
			{
				Name = "all shadows off (upper bound for shadow work)",
				Apply = delegate
				{
					QualitySettings.shadows = (ShadowQuality)0;
				},
				Revert = delegate
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					QualitySettings.shadows = shadows;
				}
			});
			List<Renderer> hidden = new List<Renderer>();
			list.Add(new Experiment
			{
				Name = "build pieces hidden (upper bound for piece rendering)",
				Apply = delegate
				{
					SuspendPieces(suspend: true);
					hidden.Clear();
					foreach (WearNTear allInstance in WearNTear.GetAllInstances())
					{
						if ((Object)(object)allInstance != (Object)null)
						{
							Renderer[] componentsInChildren = ((Component)allInstance).GetComponentsInChildren<Renderer>();
							foreach (Renderer val in componentsInChildren)
							{
								if (val.enabled)
								{
									val.enabled = false;
									hidden.Add(val);
								}
							}
						}
					}
				},
				Revert = delegate
				{
					foreach (Renderer item3 in hidden)
					{
						if ((Object)(object)item3 != (Object)null)
						{
							item3.enabled = true;
						}
					}
					hidden.Clear();
					SuspendPieces(suspend: false);
				}
			});
			List<(Renderer, ShadowCastingMode)> shadowOff = new List<(Renderer, ShadowCastingMode)>();
			list.Add(new Experiment
			{
				Name = "build piece shadows off (upper bound for piece shadows)",
				Apply = delegate
				{
					//IL_0041: Unknown result type (might be due to invalid IL or missing references)
					//IL_0052: Unknown result type (might be due to invalid IL or missing references)
					SuspendPieces(suspend: true);
					shadowOff.Clear();
					foreach (WearNTear allInstance2 in WearNTear.GetAllInstances())
					{
						if ((Object)(object)allInstance2 != (Object)null)
						{
							Renderer[] componentsInChildren = ((Component)allInstance2).GetComponentsInChildren<Renderer>();
							foreach (Renderer val in componentsInChildren)
							{
								if ((int)val.shadowCastingMode != 0)
								{
									shadowOff.Add((val, val.shadowCastingMode));
									val.shadowCastingMode = (ShadowCastingMode)0;
								}
							}
						}
					}
				},
				Revert = delegate
				{
					//IL_001c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0021: Unknown result type (might be due to invalid IL or missing references)
					//IL_002c: Unknown result type (might be due to invalid IL or missing references)
					foreach (var (val, shadowCastingMode) in shadowOff)
					{
						if ((Object)(object)val != (Object)null)
						{
							val.shadowCastingMode = shadowCastingMode;
						}
					}
					shadowOff.Clear();
					SuspendPieces(suspend: false);
				}
			});
			return list;
		}

		private static void SuspendPieces(bool suspend)
		{
			foreach (Optimization item in OptimizationManager.All)
			{
				if (item is PieceRenderer)
				{
					item.Suspended = suspend;
					OptimizationManager.SafeRefresh(item);
				}
			}
		}
	}
	internal static class BufferPoolBudget
	{
		public static long PerType = 33554432L;

		public static void SetByRam(int ramMb)
		{
			PerType = (long)((ramMb >= 24000) ? 256 : ((ramMb >= 12000) ? 128 : 64)) << 20;
		}
	}
	internal static class BufferPool<T>
	{
		private const int MinShift = 10;

		private const int Classes = 88;

		private static readonly Stack<T[]>[] _bins;

		private static readonly long[] _lastUse;

		private static long _clock;

		private static readonly int ElemBytes;

		private static long _kept;

		public static int Hits;

		public static int Misses;

		public static long DroppedBytes;

		private static long MaxKeptBytes => BufferPoolBudget.PerType;

		public static long KeptBytes => Interlocked.Read(in _kept) * ElemBytes;

		static BufferPool()
		{
			_bins = new Stack<T[]>[88];
			_lastUse = new long[88];
			ElemBytes = Marshal.SizeOf(typeof(T));
			for (int i = 0; i < 88; i++)
			{
				_bins[i] = new Stack<T[]>();
			}
		}

		private static int Class(int n, out int size)
		{
			if (n <= 1024)
			{
				size = 1024;
				return 0;
			}
			int num = 0;
			for (uint num2 = (uint)(n - 1); num2 > 1; num2 >>= 1)
			{
				num++;
			}
			int num3 = 1 << num - 2;
			int num4 = (n + num3 - 1) / num3;
			size = num4 * num3;
			return (num - 10) * 4 + (num4 - 4);
		}

		public static T[] Rent(int n)
		{
			int size;
			int num = Class(n, out size);
			if (num >= 88)
			{
				PieceRenderer.CountAlloc((long)n * (long)ElemBytes);
				return new T[n];
			}
			Stack<T[]> stack = _bins[num];
			_lastUse[num] = Interlocked.Increment(ref _clock);
			lock (stack)
			{
				if (stack.Count > 0)
				{
					T[] array = stack.Pop();
					Interlocked.Add(ref _kept, -array.Length);
					Interlocked.Increment(ref Hits);
					return array;
				}
			}
			Interlocked.Increment(ref Misses);
			PieceRenderer.CountAlloc((long)size * (long)ElemBytes);
			return new T[size];
		}

		private static void Drop(long length)
		{
			Interlocked.Add(ref DroppedBytes, length * ElemBytes);
		}

		private static bool EvictOldest(int except)
		{
			int num = -1;
			for (int i = 0; i < 88; i++)
			{
				if (i != except && _bins[i].Count > 0 && (num < 0 || _lastUse[i] < _lastUse[num]))
				{
					num = i;
				}
			}
			if (num < 0)
			{
				return false;
			}
			Stack<T[]> stack = _bins[num];
			T[] array;
			lock (stack)
			{
				if (stack.Count == 0)
				{
					return true;
				}
				array = stack.Pop();
			}
			Interlocked.Add(ref _kept, -array.Length);
			Drop(array.Length);
			return true;
		}

		public static void Return(T[] a)
		{
			if (a == null)
			{
				return;
			}
			int size;
			int num = Class(a.Length, out size);
			if (num >= 88 || size != a.Length)
			{
				return;
			}
			if ((long)a.Length * (long)ElemBytes > MaxKeptBytes / 4)
			{
				Drop(a.Length);
				return;
			}
			_lastUse[num] = Interlocked.Increment(ref _clock);
			while (Interlocked.Read(in _kept) * ElemBytes + (long)a.Length * (long)ElemBytes > MaxKeptBytes)
			{
				if (!EvictOldest(num))
				{
					Drop(a.Length);
					return;
				}
			}
			Interlocked.Add(ref _kept, a.Length);
			Stack<T[]> stack = _bins[num];
			lock (stack)
			{
				stack.Push(a);
			}
		}
	}
	internal sealed class BuildBench : MonoBehaviour
	{
		private sealed class Variant
		{
			public string Name;

			public bool KeepParked;

			public Action Apply;

			public Action Revert;
		}

		private sealed class Result
		{
			public string Name;

			public float Created = -1f;

			public float Solved = -1f;

			public float Total;

			public bool TimedOut;

			public int Frames;

			public int Over33;

			public int Over50;

			public int Gcs;

			public int Pieces;

			public double FrameAvg;

			public double Fps;

			public double Low1;

			public double Worst;

			public double CaptureMs;

			public double SolveMs;

			public double PaceMs;

			public long Fell;

			public long Made;

			public long PaceMade;

			public long PaceTicks;

			public long Woken;

			public long Held;

			public int WouldFall;

			public float Near = -1f;

			public float Near90 = -1f;

			public float Near99 = -1f;

			public double InstMs;

			public long CatchUp;

			public long JobFrames;

			public long TailFrames;

			public double TailSolverMs;
		}

		public static bool HidePieces;

		private bool _abort;

		private static readonly FieldRef<ZNetScene, Dictionary<ZDO, ZNetView>> _instances = AccessTools.FieldRefAccess<ZNetScene, Dictionary<ZDO, ZNetView>>("m_instances");

		private static readonly HashSet<ZDOID> _wouldFall = new HashSet<ZDOID>();

		private static float _passStart;

		private static int _wouldLogged;

		private static readonly FieldRef<WearNTear, float> _support = AccessTools.FieldRefAccess<WearNTear, float>("m_support");

		private static readonly Func<WearNTear, float> _minSupport = AccessTools.MethodDelegate<Func<WearNTear, float>>(AccessTools.Method(typeof(WearNTear), "GetMinSupport", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Predicate<ZDO> _isPiece = (ZDO z) => z != null && LoadGuard.IsPiece(z.GetPrefab());

		private const float NearRadius = 30f;

		public static bool Running { get; private set; }

		private static bool WearDamagePrefix(WearNTear __instance, HitData hitData, ref bool __result)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			if (!Running || hitData != null || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			ZDOID item = (((Object)(object)component != (Object)null && component.GetZDO() != null) ? component.GetZDO().m_uid : ZDOID.None);
			if (_wouldFall.Add(item) && _wouldLogged < 40)
			{
				_wouldLogged++;
				Vector3 position = ((Component)__instance).transform.position;
				Plugin.Log.LogInfo((object)(string.Format("BuildBench: would have broken (wear / support) {0} at {1:F1}, ", ((Object)__instance).name.Replace("(Clone)", ""), position) + $"{Time.realtimeSinceStartup - _passStart:0.0} s into the pass: " + $"support {_support.Invoke(__instance):0.#} (min {_minSupport(__instance):0.#}), solver: {SupportSolver.SourceOf(__instance)}, " + $"area loading {LoadGuard.Why(position)}, building still coming {SupportSolver.BuildingLoading(__instance)}, health {__instance.GetHealthPercentage() * 100f:0}%; " + "chain: " + SupportSolver.ChainOf(__instance)));
			}
			__result = false;
			return false;
		}

		public static void Patch(Harmony harmony)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(WearNTear), "ApplyDamage", (Type[])null, (Type[])null), new HarmonyMethod(typeof(BuildBench), "WearDamagePrefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZDOMan), "FindSectorObjects", new Type[4]
			{
				typeof(Vector2s),
				typeof(SimulationDistance),
				typeof(List<ZDO>),
				typeof(List<ZDO>)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(BuildBench), "FindPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void FindPostfix(List<ZDO> sectorObjects, List<ZDO> distantSectorObjects)
		{
			if (HidePieces)
			{
				sectorObjects?.RemoveAll(_isPiece);
				distantSectorObjects?.RemoveAll(_isPiece);
			}
		}

		private void Update()
		{
			if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && Plugin.DevKey(Plugin.BuildBenchKey))
			{
				if (Running)
				{
					_abort = true;
					Msg("Бенчмарк построек: останавливаю после этого шага");
				}
				else if (!Benchmark.Running && !RouteBench.Playing)
				{
					((MonoBehaviour)this).StartCoroutine(Run());
				}
			}
		}

		private static void Msg(string s)
		{
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)1, s, 0, (Sprite)null, false, true);
			}
			Plugin.Log.LogInfo((object)("BuildBench: " + s));
		}

		private static int PiecesOnScene()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			int near;
			return PiecesOnScene(Vector3.zero, -1f, out near);
		}

		private static int PiecesOnScene(Vector3 at, float radius, out int near)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			near = 0;
			float num2 = radius * radius;
			foreach (KeyValuePair<ZDO, ZNetView> item in _instances.Invoke(ZNetScene.instance))
			{
				if (item.Key == null || !LoadGuard.IsPiece(item.Key.GetPrefab()))
				{
					continue;
				}
				num++;
				if (radius > 0f)
				{
					Vector3 position = item.Key.GetPosition();
					float num3 = position.x - at.x;
					float num4 = position.z - at.z;
					if (num3 * num3 + num4 * num4 < num2)
					{
						near++;
					}
				}
			}
			return num;
		}

		private static void SetPacing(int order, float budgetMs)
		{
			ObjectPacing.Order = order;
			ObjectPacing.ForceBudgetMs = budgetMs;
		}

		private List<Variant> Variants()
		{
			List<Variant> list = new List<Variant>();
			Optimization pacing = OptimizationManager.All.Find((Optimization o) => o.Name == "ObjectPacing");
			Action revert = delegate
			{
				SetPacing(0, 0f);
			};
			list.Add(new Variant
			{
				Name = "по опорам, 4 мс за кадр",
				Apply = delegate
				{
					SetPacing(0, 4f);
				},
				Revert = revert
			});
			list.Add(new Variant
			{
				Name = "по опорам, 6 мс за кадр",
				Apply = delegate
				{
					SetPacing(0, 6f);
				},
				Revert = revert
			});
			list.Add(new Variant
			{
				Name = "по опорам, 8 мс за кадр",
				Apply = delegate
				{
					SetPacing(0, 8f);
				},
				Revert = revert
			});
			list.Add(new Variant
			{
				Name = "как есть (обычные настройки)",
				Apply = delegate
				{
				},
				Revert = delegate
				{
				}
			});
			list.Add(new Variant
			{
				Name = "возврат (узлы решателя сохранены)",
				KeepParked = true,
				Apply = delegate
				{
				},
				Revert = delegate
				{
				}
			});
			if (pacing != null)
			{
				list.Add(new Variant
				{
					Name = "порядок и темп создания игры (без ObjectPacing)",
					Apply = delegate
					{
						pacing.Suspended = true;
					},
					Revert = delegate
					{
						pacing.Suspended = false;
					}
				});
			}
			return list;
		}

		private IEnumerator Run()
		{
			Running = true;
			_abort = false;
			Player p = Player.m_localPlayer;
			bool ghost = ((Character)p).InGhostMode();
			bool god = ((Character)p).InGodMode();
			p.SetGhostMode(true);
			p.SetGodMode(true);
			Optimization scanSkip = OptimizationManager.All.Find((Optimization o) => o.Name == "ObjectScanSkip");
			bool scanWas = scanSkip?.Suspended ?? false;
			if (scanSkip != null)
			{
				scanSkip.Suspended = true;
			}
			List<Result> results = new List<Result>();
			Vector3 where = ((Component)p).transform.position;
			int nearBefore;
			int before = PiecesOnScene(where, 30f, out nearBefore);
			int num = SupportSolver.SaveLinks();
			Plugin.Log.LogInfo((object)$"BuildBench: supporters saved for {num} pieces before the passes");
			Msg($"Бенчмарк построек: {before} деталей на сцене. Не двигайся. Alt+F1 ещё раз - остановить.");
			yield return (object)new WaitForSeconds(2f);
			List<Variant> variants = Variants();
			for (int vi = 0; vi < variants.Count; vi++)
			{
				if (_abort)
				{
					break;
				}
				Variant v = variants[vi];
				Result r = new Result
				{
					Name = v.Name
				};
				Msg($"Проход {vi + 1}/{variants.Count}: {v.Name} - выгружаю постройки");
				HidePieces = true;
				float t0 = Time.realtimeSinceStartup;
				while (PiecesOnScene() > 0 && Time.realtimeSinceStartup - t0 < 30f)
				{
					yield return (object)new WaitForSeconds(0.25f);
				}
				yield return (object)new WaitForSeconds(1.5f);
				if (!v.KeepParked)
				{
					SupportSolver.Clear();
				}
				LoadGuard.ResetForBench();
				GC.Collect();
				yield return (object)new WaitForSeconds(1f);
				v.Apply();
				Msg($"Проход {vi + 1}/{variants.Count}: {v.Name} - загружаю");
				List<float> frames = new List<float>(4096);
				int gc0 = GC.CollectionCount(0);
				double cap0 = SupportSolver.CaptureMs;
				double sol0 = SupportSolver.SolveMs;
				long fell0 = SupportSolver.DestroyedCount;
				long made0 = LoadGuard.CreatedPieces;
				long cu0 = WearSleep._catchUpFrames;
				long pm0 = ObjectPacing.MadeTotal;
				long pt0 = ObjectPacing.TicksWithWork;
				long wk0 = ObjectPacing.Woken;
				long hd0 = SupportSolver.BuildingHeld;
				double pms0 = ObjectPacing.CreateMs;
				double ims0 = ObjectPacing.InstantiateMs;
				_wouldFall.Clear();
				_wouldLogged = 0;
				HidePieces = false;
				float start = Time.realtimeSinceStartup;
				float lastCheck = 0f;
				float quietSince = -1f;
				float lastTail = -10f;
				long tf0 = WearSleep.SolverFrames;
				double tm0 = WearSleep.SolverMsTotal;
				_passStart = start;
				while (true)
				{
					yield return null;
					frames.Add(Time.unscaledDeltaTime * 1000f);
					float num2 = Time.realtimeSinceStartup - start;
					if (r.Created >= 0f && r.Solved < 0f)
					{
						r.TailFrames++;
						if (SupportSolver.JobRunning)
						{
							r.JobFrames++;
						}
						if (num2 - lastTail >= 2f)
						{
							lastTail = num2;
							double num3 = ((WearSleep.SolverFrames > tf0) ? ((WearSleep.SolverMsTotal - tm0) / (double)(WearSleep.SolverFrames - tf0)) : 0.0);
							Plugin.Log.LogInfo((object)($"BuildBench tail {num2:0.0} s: solver {num3:0.00} ms a frame (allowed now {WearSleep.Allowed:0.0}), " + $"catching up {WearSleep._catchUpFrames - cu0} frames so far, build pieces waiting to be created {ObjectPacing.PiecesWaiting}, " + $"backlog {SupportSolver.Backlog}; {SupportSolver.NowText()}"));
							tf0 = WearSleep.SolverFrames;
							tm0 = WearSleep.SolverMsTotal;
						}
					}
					if (!(num2 - lastCheck >= 0.5f))
					{
						continue;
					}
					lastCheck = num2;
					int near;
					int num4 = PiecesOnScene(where, 30f, out near);
					if (r.Created < 0f && (float)num4 >= (float)before * 0.995f)
					{
						r.Created = num2;
					}
					if (r.Near90 < 0f && (float)near >= (float)nearBefore * 0.9f)
					{
						r.Near90 = num2;
					}
					if (r.Near99 < 0f && (float)near >= (float)nearBefore * 0.99f)
					{
						r.Near99 = num2;
					}
					if (r.Near < 0f && near >= nearBefore)
					{
						r.Near = num2;
					}
					int num5 = SupportSolver.WorkLeft();
					if (r.Created >= 0f && r.Solved < 0f && num5 == 0)
					{
						r.Solved = num2;
					}
					if (r.Created >= 0f && r.Solved >= 0f)
					{
						if (quietSince < 0f)
						{
							quietSince = num2;
						}
						if (num2 - quietSince > 2f)
						{
							break;
						}
					}
					if (num2 > 200f)
					{
						r.TimedOut = true;
						break;
					}
					if (_abort)
					{
						break;
					}
					r.Pieces = num4;
				}
				r.Total = Time.realtimeSinceStartup - start;
				v.Revert();
				r.Gcs = GC.CollectionCount(0) - gc0;
				r.CaptureMs = SupportSolver.CaptureMs - cap0;
				r.SolveMs = SupportSolver.SolveMs - sol0;
				r.Fell = SupportSolver.DestroyedCount - fell0;
				r.Made = LoadGuard.CreatedPieces - made0;
				r.WouldFall = _wouldFall.Count;
				r.PaceMade = ObjectPacing.MadeTotal - pm0;
				r.PaceTicks = ObjectPacing.TicksWithWork - pt0;
				r.PaceMs = ObjectPacing.CreateMs - pms0;
				r.Woken = ObjectPacing.Woken - wk0;
				r.Held = SupportSolver.BuildingHeld - hd0;
				r.CatchUp = WearSleep._catchUpFrames - cu0;
				r.InstMs = ObjectPacing.InstantiateMs - ims0;
				r.Frames = frames.Count;
				if (frames.Count > 0)
				{
					double num6 = 0.0;
					foreach (float item in frames)
					{
						num6 += (double)item;
						if (item > 33.3f)
						{
							r.Over33++;
						}
						if (item > 50f)
						{
							r.Over50++;
						}
					}
					r.FrameAvg = num6 / (double)frames.Count;
					r.Fps = 1000.0 / r.FrameAvg;
					List<float> list = new List<float>(frames);
					list.Sort();
					r.Worst = list[list.Count - 1];
					int num7 = Math.Max(1, list.Count / 100);
					double num8 = 0.0;
					for (int num9 = list.Count - num7; num9 < list.Count; num9++)
					{
						num8 += (double)list[num9];
					}
					r.Low1 = 1000.0 / (num8 / (double)num7);
				}
				results.Add(r);
				Msg($"Проход {vi + 1}: все детали за {Fmt(r.Created)}, посчитано за {Fmt(r.Solved)}, упало бы {r.WouldFall}, {r.Fps:0} FPS, худший кадр {r.Worst:0} мс");
				yield return (object)new WaitForSeconds(2f);
			}
			HidePieces = false;
			if (scanSkip != null)
			{
				scanSkip.Suspended = scanWas;
			}
			p.SetGhostMode(ghost);
			p.SetGodMode(god);
			Running = false;
			Write(results, before, where, nearBefore);
		}

		private static string Fmt(float t)
		{
			if (!(t < 0f))
			{
				return t.ToString("0.0") + " с";
			}
			return "не дождался";
		}

		private static string F(float t)
		{
			if (!(t < 0f))
			{
				return t.ToString("0.0");
			}
			return "-";
		}

		private static void Write(List<Result> results, int before, Vector3 where, int nearBefore)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine(string.Format("FPSDoctor building benchmark - {0:yyyy-MM-dd HH:mm} - FPSDoctor {1} - at {2:F0}, {3} build pieces on the scene", DateTime.Now, "0.23.2", where, before));
			stringBuilder.AppendLine("Each pass: the base's pieces unloaded, the building systems reset to a clean start, the variant set, the pieces loaded again as on arrival.");
			stringBuilder.AppendLine($"Near: until 90% / 99% / every piece within {30f:0} m horizontally ({nearBefore} pieces) is back. Created: until every piece is back on the scene. Solved: until the solver has nothing left to work out.");
			stringBuilder.AppendLine("Would fall: unique pieces the wear pass would have broken (no damage is done while the benchmark runs; the first ones are in the log with their chain). Held: wear passes under the minimum held because the rest of the building was still coming.");
			stringBuilder.AppendLine(">33 / >50: frames over 33 / 50 ms per 1000 frames. GC/min: garbage collections a minute. Create: objects made by ObjectPacing, its ms per object (incl. picking), its ticks a second, pieces made right after their supporter.");
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(string.Format("{0,-36} {1,16} {2,8} {3,7} {4,6} {5,5} {6,6} {7,6} {8,6} {9,6} {10,6} {11,8} {12,8} {13,7} {14,7} {15,6} {16,6} {17,6}", "pass", "near 90/99/all", "created", "solved", "fall", "held", "FPS", "1%low", "worst", ">33", ">50", "GC/min", "geom ms", "solv ms", "made", "ms/obj", "tick/s", "woken"));
			foreach (Result result in results)
			{
				double num = ((result.Frames > 0) ? (1000.0 / (double)result.Frames) : 0.0);
				double num2 = Math.Max(0.01, (double)result.Total / 60.0);
				stringBuilder.AppendLine(string.Format("{0,-36} {1,16} {2,8} {3,7} {4,6} {5,5} {6,6:0} {7,6:0} {8,6:0} {9,6:0} {10,6:0.0} {11,8:0.0} {12,8:0} {13,7:0} {14,7} {15,6:0.000} {16,6:0.0} {17,6}{18}", result.Name, F(result.Near90) + "/" + F(result.Near99) + "/" + F(result.Near), (result.Created < 0f) ? "-" : result.Created.ToString("0.0"), (result.Solved < 0f) ? "-" : result.Solved.ToString("0.0"), result.WouldFall, result.Held, result.Fps, result.Low1, result.Worst, (double)result.Over33 * num, (double)result.Over50 * num, (double)result.Gcs / num2, result.CaptureMs, result.SolveMs, result.PaceMade, (result.PaceMade > 0) ? (result.PaceMs / (double)result.PaceMade) : 0.0, (result.Total > 0f) ? ((float)result.PaceTicks / result.Total) : 0f, result.Woken, result.TimedOut ? "  (stopped at 200 s)" : ""));
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("Creating an object: ms per object inside the game's CreateObject (clone, components' Awake, registering) / the rest (picking, waking, bookkeeping):");
			foreach (Result result2 in results)
			{
				if (result2.PaceMade > 0)
				{
					stringBuilder.AppendLine($"  {result2.Name}: {result2.InstMs / (double)result2.PaceMade:0.000} / {(result2.PaceMs - result2.InstMs) / (double)result2.PaceMade:0.000}");
				}
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("Tail (everything created, the solver still at it): frames, of them with a drop job running, frames the solver caught up (>= SolverCatchUpMs) over the whole pass. Details every 2 s in the log ('BuildBench tail').");
			foreach (Result result3 in results)
			{
				stringBuilder.AppendLine($"  {result3.Name}: tail {result3.TailFrames} frames, drop job running in {result3.JobFrames}, catching up {result3.CatchUp} frames");
			}
			string text = stringBuilder.ToString();
			Plugin.Log.LogInfo((object)("\n" + text));
			try
			{
				string text2 = Path.Combine(Paths.BepInExRootPath, "FPSDoctor-sessions");
				Directory.CreateDirectory(text2);
				string path = Path.Combine(text2, $"buildbench_{DateTime.Now:yyyy-MM-dd_HH-mm}.txt");
				File.WriteAllText(path, text);
				Msg("Бенчмарк построек готов: " + Path.GetFileName(path));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("BuildBench: report not written: " + ex.Message));
			}
		}
	}
	internal static class DeepScan
	{
		private enum Group
		{
			Vegetation,
			Rocks,
			Terrain,
			Water,
			Characters,
			Other
		}

		private static readonly string[] HeavyWeathers = new string[4] { "Ashlands_storm", "Twilight_SnowStorm", "SnowStorm", "Ashlands_misty" };

		private static Group GroupOf(Renderer r)
		{
			if (r is SkinnedMeshRenderer)
			{
				return Group.Characters;
			}
			if ((Object)(object)((Component)r).GetComponent<Heightmap>() != (Object)null)
			{
				return Group.Terrain;
			}
			Material sharedMaterial = r.sharedMaterial;
			string text = (((Object)(object)sharedMaterial != (Object)null && (Object)(object)sharedMaterial.shader != (Object)null) ? ((Object)sharedMaterial.shader).name : "");
			if (text.IndexOf("Water", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return Group.Water;
			}
			if (text.IndexOf("Vegetation", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Tree", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Leaf", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Bush", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return Group.Vegetation;
			}
			if (text.IndexOf("Rock", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return Group.Rocks;
			}
			if (text.IndexOf("Heightmap", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Terrain", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return Group.Terrain;
			}
			return Group.Other;
		}

		private static bool IsPiece(Renderer r)
		{
			if (!PieceRenderer.CellRenderers.Contains(r))
			{
				return (Object)(object)((Component)r).GetComponentInParent<WearNTear>() != (Object)null;
			}
			return true;
		}

		private static Benchmark.Experiment HideGroup(string name, Group g)
		{
			List<Renderer> hidden = new List<Renderer>();
			return new Benchmark.Experiment
			{
				Name = name,
				Apply = delegate
				{
					hidden.Clear();
					Renderer[] array = Object.FindObjectsByType<Renderer>((FindObjectsSortMode)0);
					foreach (Renderer val in array)
					{
						if (val.enabled && !val.forceRenderingOff && ((Component)val).gameObject.activeInHierarchy && !(val is ParticleSystemRenderer) && !(val is LineRenderer) && !(val is TrailRenderer) && !IsPiece(val) && GroupOf(val) == g)
						{
							val.forceRenderingOff = true;
							hidden.Add(val);
						}
					}
				},
				Revert = delegate
				{
					foreach (Renderer item in hidden)
					{
						if ((Object)(object)item != (Object)null)
						{
							item.forceRenderingOff = false;
						}
					}
					hidden.Clear();
				}
			};
		}

		private static Benchmark.Experiment ShadowGroup(string name, Func<Renderer, bool> filter)
		{
			List<(Renderer, ShadowCastingMode)> changed = new List<(Renderer, ShadowCastingMode)>();
			return new Benchmark.Experiment
			{
				Name = name,
				Apply = delegate
				{
					//IL_0023: Unknown result type (might be due to invalid IL or missing references)
					//IL_0048: Unknown result type (might be due to invalid IL or missing references)
					changed.Clear();
					Renderer[] array = Object.FindObjectsByType<Renderer>((FindObjectsSortMode)0);
					foreach (Renderer val in array)
					{
						if (val.enabled && (int)val.shadowCastingMode != 0 && !(val is ParticleSystemRenderer) && filter(val))
						{
							changed.Add((val, val.shadowCastingMode));
							val.shadowCastingMode = (ShadowCastingMode)0;
						}
					}
					Plugin.Log.LogInfo((object)$"Deep scan: '{name}' affects {changed.Count} renderers");
				},
				Revert = delegate
				{
					//IL_001c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0021: Unknown result type (might be due to invalid IL or missing references)
					//IL_002c: Unknown result type (might be due to invalid IL or missing references)
					foreach (var (val, shadowCastingMode) in changed)
					{
						if ((Object)(object)val != (Object)null)
						{
							val.shadowCastingMode = shadowCastingMode;
						}
					}
					changed.Clear();
				}
			};
		}

		private static Benchmark.Experiment Toggle<T>(string name, Func<T, bool> isOn, Action<T, bool> set) where T : Object
		{
			List<T> changed = new List<T>();
			return new Benchmark.Experiment
			{
				Name = name,
				Apply = delegate
				{
					changed.Clear();
					T[] array = Object.FindObjectsByType<T>((FindObjectsSortMode)0);
					foreach (T val in array)
					{
						if (isOn(val))
						{
							set(val, arg2: false);
							changed.Add(val);
						}
					}
				},
				Revert = delegate
				{
					foreach (T item in changed)
					{
						if ((Object)(object)item != (Object)null)
						{
							set(item, arg2: true);
						}
					}
					changed.Clear();
				}
			};
		}

		private static Benchmark.Experiment Setting(string name, Action apply, Action revert)
		{
			return new Benchmark.Experiment
			{
				Name = name,
				Apply = apply,
				Revert = revert
			};
		}

		public static List<Benchmark.Experiment> BuildShadowExperiments()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			List<Benchmark.Experiment> list = new List<Benchmark.Experiment>();
			ShadowQuality shadows = QualitySettings.shadows;
			list.Add(Setting("quality: all shadows off", delegate
			{
				QualitySettings.shadows = (ShadowQuality)0;
			}, delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				QualitySettings.shadows = shadows;
			}));
			AddShadowDetail(list);
			return list;
		}

		private static void AddShadowDetail(List<Benchmark.Experiment> list)
		{
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_0446: Unknown result type (might be due to invalid IL or missing references)
			//IL_0452: Unknown result type (might be due to invalid IL or missing references)
			list.Add(ShadowGroup("shadows: trees & bushes cast none", (Renderer r) => !IsPiece(r) && GroupOf(r) == Group.Vegetation));
			list.Add(ShadowGroup("shadows: rocks & cliffs cast none", (Renderer r) => !IsPiece(r) && GroupOf(r) == Group.Rocks));
			list.Add(ShadowGroup("shadows: terrain casts none", (Renderer r) => GroupOf(r) == Group.Terrain));
			list.Add(ShadowGroup("shadows: characters & creatures cast none", (Renderer r) => r is SkinnedMeshRenderer));
			list.Add(ShadowGroup("shadows: everything else casts none (items, props, locations)", (Renderer r) => !IsPiece(r) && !(r is SkinnedMeshRenderer) && GroupOf(r) == Group.Other));
			Benchmark.Experiment experiment = Setting("[test] build piece chunk cells 64 m instead of 16 m (fewer, bigger merged meshes)", delegate
			{
				PieceRenderer.SetCellSizeOverride(64);
			}, delegate
			{
				PieceRenderer.SetCellSizeOverride(0);
			});
			experiment.ExtraWarmup = 4f;
			list.Add(experiment);
			Benchmark.Experiment experiment2 = Setting("[test] merged piece shadows off (one shadow per cell x material again)", delegate
			{
				PieceRenderer.SetMergedShadowsSuspended(suspended: true);
			}, delegate
			{
				PieceRenderer.SetMergedShadowsSuspended(suspended: false);
			});
			experiment2.ExtraWarmup = 4f;
			list.Add(experiment2);
			Benchmark.Experiment experiment3 = Setting("[test] build piece chunk cells 256 m (one merged mesh per material for the whole base)", delegate
			{
				PieceRenderer.SetCellSizeOverride(256);
			}, delegate
			{
				PieceRenderer.SetCellSizeOverride(0);
			});
			experiment3.ExtraWarmup = 5f;
			list.Add(experiment3);
			foreach (Optimization item in OptimizationManager.All)
			{
				if (item is MaterialSort || item is GrassBatching || item is WearNTearSmoothing || item is GpuOcclusion || item is DoorSleep || item is AnimatorCulling || item is SupportCache || item is VegetationDetail || item is IdleParticles)
				{
					Optimization opt = item;
					list.Add(Setting("[test] " + opt.Name + " off", delegate
					{
						opt.Suspended = true;
						opt.Refresh();
					}, delegate
					{
						opt.Suspended = false;
						opt.Refresh();
					}));
				}
			}
			list.Add(Setting("[test] build piece shadow proxies off (detailed piece shadows)", delegate
			{
				PieceRenderer.SetProxiesSuspended(suspended: true);
			}, delegate
			{
				PieceRenderer.SetProxiesSuspended(suspended: false);
			}));
			List<Renderer> cellShadows = new List<Renderer>();
			list.Add(Setting("shadows: build pieces cast none", delegate
			{
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Invalid comparison between Unknown and I4
				PieceRenderer.NoShadows = true;
				cellShadows.Clear();
				foreach (Renderer cellRenderer in PieceRenderer.CellRenderers)
				{
					if ((Object)(object)cellRenderer != (Object)null && (int)cellRenderer.shadowCastingMode == 3 && !cellRenderer.forceRenderingOff)
					{
						cellRenderer.forceRenderingOff = true;
						cellShadows.Add(cellRenderer);
					}
				}
			}, delegate
			{
				PieceRenderer.NoShadows = false;
				foreach (Renderer item2 in cellShadows)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						item2.forceRenderingOff = false;
					}
				}
				cellShadows.Clear();
			}));
			List<InstanceRenderer> grass = new List<InstanceRenderer>();
			list.Add(Setting("shadows: grass & clutter cast none", delegate
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				grass.Clear();
				InstanceRenderer[] array = Object.FindObjectsByType<InstanceRenderer>((FindObjectsSortMode)0);
				foreach (InstanceRenderer val in array)
				{
					if ((int)val.m_shadowCasting != 0)
					{
						val.m_shadowCasting = (ShadowCastingMode)0;
						grass.Add(val);
					}
				}
				Plugin.Log.LogInfo((object)$"Deep scan: {grass.Count} grass/clutter renderers were casting shadows");
			}, delegate
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				foreach (InstanceRenderer item3 in grass)
				{
					if ((Object)(object)item3 != (Object)null)
					{
						item3.m_shadowCasting = (ShadowCastingMode)1;
					}
				}
				grass.Clear();
			}));
			int cascades = QualitySettings.shadowCascades;
			if (cascades > 2)
			{
				list.Add(Setting($"shadows: {cascades} -> 2 cascades", delegate
				{
					QualitySettings.shadowCascades = 2;
				}, delegate
				{
					QualitySettings.shadowCascades = cascades;
				}));
			}
			if (cascades > 1)
			{
				list.Add(Setting($"shadows: {cascades} -> 1 cascade", delegate
				{
					QualitySettings.shadowCascades = 1;
				}, delegate
				{
					QualitySettings.shadowCascades = cascades;
				}));
			}
			ShadowResolution shadowRes = QualitySettings.shadowResolution;
			list.Add(Setting($"shadows: resolution {shadowRes} -> Low", delegate
			{
				QualitySettings.shadowResolution = (ShadowResolution)0;
			}, delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				QualitySettings.shadowResolution = shadowRes;
			}));
		}

		public static List<Benchmark.Experiment> BuildLogicExperiments()
		{
			string[] obj = ((!TestWorld.Active) ? new string[6] { "objects: EVERYTHING hidden", "objects: build pieces hidden", "objects: build pieces' scripts paused", "engine: physics simulation paused", "engine: animations off", "[reference] FPSDoctor optimizations OFF" } : new string[12]
			{
				"objects: EVERYTHING hidden", "effects: post-processing off", "engine: game UI hidden", "objects: water hidden", "quality: all shadows off", "quality: 3D render resolution halved", "objects: characters & creatures hidden", "engine: all sound sources off", "engine: physics simulation paused", "engine: animations off",
				"effects: fog off", "[reference] FPSDoctor optimizations OFF"
			});
			List<Benchmark.Experiment> list = BuildExperiments();
			List<Benchmark.Experiment> list2 = new List<Benchmark.Experiment>();
			string[] array = obj;
			foreach (string value in array)
			{
				foreach (Benchmark.Experiment item in list)
				{
					if (item.Name.StartsWith(value, StringComparison.Ordinal))
					{
						list2.Add(item);
						break;
					}
				}
			}
			if (TestWorld.Active)
			{
				AddPostEffects(list2);
			}
			return list2;
		}

		public static List<Benchmark.Experiment> BuildWeatherExperiments()
		{
			List<Benchmark.Experiment> list = new List<Benchmark.Experiment>();
			EnvMan instance = EnvMan.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return list;
			}
			foreach (var item2 in WeatherTour.All())
			{
				string item = item2.Biome;
				string env = item2.Env;
				EnvSetup setup = instance.m_environments.Find((EnvSetup e) => e != null && e.m_name == env);
				if (setup == null || setup.m_psystems == null || setup.m_psystems.Length == 0)
				{
					continue;
				}
				string name = env;
				list.Add(new Benchmark.Experiment
				{
					Name = "weather: " + item + " - " + env,
					Apply = delegate
					{
						WeatherTour.Force(name);
					},
					Revert = delegate
					{
						LogParticles(setup);
						WeatherTour.Force("Clear");
					},
					ExtraWarmup = 3f
				});
				List<GameObject> off = new List<GameObject>();
				list.Add(new Benchmark.Experiment
				{
					Name = "weather: " + env + " with its particles off",
					Apply = delegate
					{
						WeatherTour.Force(name);
						off.Clear();
						GameObject[] psystems = setup.m_psystems;
						foreach (GameObject val in psystems)
						{
							if ((Object)(object)val != (Object)null && val.activeSelf)
							{
								val.SetActive(false);
								off.Add(val);
							}
						}
					},
					Revert = delegate
					{
						foreach (GameObject item3 in off)
						{
							if ((Object)(object)item3 != (Object)null)
							{
								item3.SetActive(true);
							}
						}
						off.Clear();
						WeatherTour.Force("Clear");
					},
					ExtraWarmup = 3f
				});
				if (Array.IndexOf(HeavyWeathers, env) < 0)
				{
					continue;
				}
				List<(ParticleSystemRenderer, float)> sizes = new List<(ParticleSystemRenderer, float)>();
				list.Add(new Benchmark.Experiment
				{
					Name = "weather: " + env + " with particles at most 10% of the screen",
					Apply = delegate
					{
						WeatherTour.Force(name);
						sizes.Clear();
						GameObject[] psystems = setup.m_psystems;
						foreach (GameObject val in psystems)
						{
							if ((Object)(object)val != (Object)null)
							{
								ParticleSystemRenderer[] componentsInChildren = val.GetComponentsInChildren<ParticleSystemRenderer>(true);
								foreach (ParticleSystemRenderer val2 in componentsInChildren)
								{
									if (val2.maxParticleSize > 0.1f)
									{
										sizes.Add((val2, val2.maxParticleSize));
										val2.maxParticleSize = 0.1f;
									}
								}
							}
						}
					},
					Revert = delegate
					{
						foreach (var (val, maxParticleSize) in sizes)
						{
							if ((Object)(object)val != (Object)null)
							{
								val.maxParticleSize = maxParticleSize;
							}
						}
						sizes.Clear();
						WeatherTour.Force("Clear");
					},
					ExtraWarmup = 3f
				});
				List<(ParticleSystem, float, int)> rates = new List<(ParticleSystem, float, int)>();
				list.Add(new Benchmark.Experiment
				{
					Name = "weather: " + env + " with half the particles",
					Apply = delegate
					{
						//IL_004b: Unknown result type (might be due to invalid IL or missing references)
						//IL_0050: Unknown result type (might be due to invalid IL or missing references)
						//IL_0054: Unknown result type (might be due to invalid IL or missing references)
						//IL_0059: Unknown result type (might be due to invalid IL or missing references)
						WeatherTour.Force(name);
						rates.Clear();
						GameObject[] psystems = setup.m_psystems;
						foreach (GameObject val in psystems)
						{
							if ((Object)(object)val != (Object)null)
							{
								ParticleSystem[] componentsInChildren = val.GetComponentsInChildren<ParticleSystem>(true);
								foreach (ParticleSystem val2 in componentsInChildren)
								{
									EmissionModule emission = val2.emission;
									MainModule main = val2.main;
									rates.Add((val2, ((EmissionModule)(ref emission)).rateOverTimeMultiplier, ((MainModule)(ref main)).maxParticles));
									((EmissionModule)(ref emission)).rateOverTimeMultiplier = ((EmissionModule)(ref emission)).rateOverTimeMultiplier * 0.5f;
									((MainModule)(ref main)).maxParticles = Mathf.Max(1, ((MainModule)(ref main)).maxParticles / 2);
								}
							}
						}
					},
					Revert = delegate
					{
						//IL_0033: Unknown result type (might be due to invalid IL or missing references)
						//IL_0038: Unknown result type (might be due to invalid IL or missing references)
						//IL_0043: Unknown result type (might be due to invalid IL or missing references)
						//IL_0048: Unknown result type (might be due to invalid IL or missing references)
						foreach (var (val, rateOverTimeMultiplier, maxParticles) in rates)
						{
							if ((Object)(object)val != (Object)null)
							{
								EmissionModule emission = val.emission;
								((EmissionModule)(ref emission)).rateOverTimeMultiplier = rateOverTimeMultiplier;
								MainModule main = val.main;
								((MainModule)(ref main)).maxParticles = maxParticles;
							}
						}
						rates.Clear();
						WeatherTour.Force("Clear");
					},
					ExtraWarmup = 3f
				});
			}
			return list;
		}

		private static void LogParticles(EnvSetup setup)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder("Weather " + setup.m_name + " particles:");
			GameObject[] psystems = setup.m_psystems;
			foreach (GameObject val in psystems)
			{
				if (!((Object)(object)val == (Object)null))
				{
					ParticleSystem[] componentsInChildren = val.GetComponentsInChildren<ParticleSystem>(true);
					foreach (ParticleSystem val2 in componentsInChildren)
					{
						MainModule main = val2.main;
						ParticleSystemRenderer component = ((Component)val2).GetComponent<ParticleSystemRenderer>();
						object[] obj = new object[5]
						{
							((Object)val).name,
							((Object)val2).name,
							val2.particleCount,
							((MainModule)(ref main)).maxParticles,
							null
						};
						EmissionModule emission = val2.emission;
						obj[4] = ((EmissionModule)(ref emission)).rateOverTimeMultiplier;
						string text = string.Format("\n  {0}/{1}: live {2}, max {3}, rate {4:0}/s, ", obj);
						MinMaxCurve val3 = ((MainModule)(ref main)).startSize;
						object arg = ((MinMaxCurve)(ref val3)).constantMin;
						val3 = ((MainModule)(ref main)).startSize;
						object arg2 = ((MinMaxCurve)(ref val3)).constantMax;
						val3 = ((MainModule)(ref main)).startLifetime;
						stringBuilder.Append(text + $"size {arg:0.##}-{arg2:0.##}, life {((MinMaxCurve)(ref val3)).constantMax:0.#} s, " + string.Format("screen cap {0:0.##}, mode {1}, ", ((Object)(object)component != (Object)null) ? component.maxParticleSize : 0f, ((Object)(object)component != (Object)null) ? ((object)component.renderMode/*cast due to .constrained prefix*/).ToString() : "-") + string.Format("shader {0}, sim {1}", ((Object)(object)component != (Object)null && (Object)(object)((Renderer)component).sharedMaterial != (Object)null) ? ((Object)((Renderer)component).sharedMaterial.shader).name : "-", ((MainModule)(ref main)).simulationSpace));
					}
				}
			}
			Plugin.Log.LogInfo((object)stringBuilder.ToString());
		}

		private static void AddPostEffects(List<Benchmark.Experiment> list)
		{
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera == (Object)null)
			{
				return;
			}
			PostProcessingBehaviour component = ((Component)mainCamera).GetComponent<PostProcessingBehaviour>();
			PostProcessingProfile val = (((Object)(object)component != (Object)null) ? component.profile : null);
			if ((Object)(object)val != (Object)null)
			{
				(string, PostProcessingModel)[] obj = new(string, PostProcessingModel)[14]
				{
					("ambient occlusion (SSAO)", (PostProcessingModel)(object)val.ambientOcclusion),
					("screen-space reflections", (PostProcessingModel)(object)val.screenSpaceReflection),
					("motion blur", (PostProcessingModel)(object)val.motionBlur),
					("antialiasing", (PostProcessingModel)(object)val.antialiasing),
					("eye adaptation", (PostProcessingModel)(object)val.eyeAdaptation),
					("depth of field", (PostProcessingModel)(object)val.depthOfField),
					("bloom", (PostProcessingModel)(object)val.bloom),
					("color grading", (PostProcessingModel)(object)val.colorGrading),
					("chromatic aberration", (PostProcessingModel)(object)val.chromaticAberration),
					("grain", (PostProcessingModel)(object)val.grain),
					("vignette", (PostProcessingModel)(object)val.vignette),
					("dithering", (PostProcessingModel)(object)val.dithering),
					("user LUT", (PostProcessingModel)(object)val.userLut),
					("post fog", (PostProcessingModel)(object)val.fog)
				};
				StringBuilder stringBuilder = new StringBuilder();
				(string, PostProcessingModel)[] array = obj;
				for (int i = 0; i < array.Length; i++)
				{
					(string, PostProcessingModel) tuple = array[i];
					string item = tuple.Item1;
					PostProcessingModel item2 = tuple.Item2;
					if (item2 != null && item2.enabled)
					{
						stringBuilder.Append(item).Append(", ");
						PostProcessingModel mm = item2;
						list.Add(Setting("post: " + item + " off", delegate
						{
							mm.enabled = false;
						}, delegate
						{
							mm.enabled = true;
						}));
					}
				}
				Settings settings = val.ambientOcclusion.settings;
				Plugin.Log.LogInfo((object)($"Post-processing stack: on = {stringBuilder}AO samples {settings.sampleCount}, downsampling {settings.downsampling}, " + $"radius {settings.radius}, intensity {settings.intensity}; AA {val.antialiasing.settings.method}; camera depth {mainCamera.depthTextureMode}"));
			}
			Behaviour[] components = ((Component)mainCamera).GetComponents<Behaviour>();
			foreach (Behaviour val2 in components)
			{
				if (!((Object)(object)val2 == (Object)null) && val2.enabled && !(val2 is PostProcessingBehaviour) && IsImageEffect(val2))
				{
					Behaviour bb = val2;
					list.Add(Setting("post: " + ((object)val2).GetType().Name + " off", delegate
					{
						bb.enabled = false;
					}, delegate
					{
						bb.enabled = true;
					}));
				}
			}
		}

		public static List<Benchmark.Experiment> BuildExperiments()
		{
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0434: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Unknown result type (might be due to invalid IL or missing references)
			//IL_0539: Unknown result type (might be due to invalid IL or missing references)
			List<Benchmark.Experiment> list = new List<Benchmark.Experiment>();
			bool master = Optimization.MasterOn;
			list.Add(Setting("[reference] FPSDoctor optimizations OFF", delegate
			{
				OptimizationManager.SetMaster(on: false);
			}, delegate
			{
				OptimizationManager.SetMaster(master);
			}));
			List<Renderer> pieceHidden = new List<Renderer>();
			list.Add(Setting("objects: build pieces hidden", delegate
			{
				PieceRenderer.SkipDraw = true;
				pieceHidden.Clear();
				Renderer[] array = Object.FindObjectsByType<Renderer>((FindObjectsSortMode)0);
				foreach (Renderer val in array)
				{
					if (val.enabled && !val.forceRenderingOff && IsPiece(val))
					{
						val.forceRenderingOff = true;
						pieceHidden.Add(val);
					}
				}
			}, delegate
			{
				PieceRenderer.SkipDraw = false;
				foreach (Renderer item in pieceHidden)
				{
					if ((Object)(object)item != (Object)null)
					{
						item.forceRenderingOff = false;
					}
				}
				pieceHidden.Clear();
			}));
			List<Renderer> allHidden = new List<Renderer>();
			List<InstanceRenderer> grassOff = new List<InstanceRenderer>();
			list.Add(Setting("objects: EVERYTHING hidden (only game logic, physics, engine left)", delegate
			{
				PieceRenderer.SkipDraw = true;
				allHidden.Clear();
				grassOff.Clear();
				Renderer[] array = Object.FindObjectsByType<Renderer>((FindObjectsSortMode)0);
				foreach (Renderer val in array)
				{
					if (val.enabled && !val.forceRenderingOff)
					{
						val.forceRenderingOff = true;
						allHidden.Add(val);
					}
				}
				InstanceRenderer[] array2 = Object.FindObjectsByType<InstanceRenderer>((FindObjectsSortMode)0);
				foreach (InstanceRenderer val2 in array2)
				{
					if (((Behaviour)val2).enabled)
					{
						((Behaviour)val2).enabled = false;
						grassOff.Add(val2);
					}
				}
			}, delegate
			{
				PieceRenderer.SkipDraw = false;
				foreach (Renderer item2 in allHidden)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						item2.forceRenderingOff = false;
					}
				}
				foreach (InstanceRenderer item3 in grassOff)
				{
					if ((Object)(object)item3 != (Object)null)
					{
						((Behaviour)item3).enabled = true;
					}
				}
				allHidden.Clear();
				grassOff.Clear();
			}));
			List<WearNTearUpdater> updaters = new List<WearNTearUpdater>();
			list.Add(Setting("objects: build pieces' scripts paused (wear/support pass off, still drawn)", delegate
			{
				updaters.Clear();
				WearNTearUpdater[] array = Object.FindObjectsByType<WearNTearUpdater>((FindObjectsSortMode)0);
				foreach (WearNTearUpdater val in array)
				{
					if (((Behaviour)val).enabled)
					{
						((Behaviour)val).enabled = false;
						updaters.Add(val);
					}
				}
			}, delegate
			{
				foreach (WearNTearUpdater item4 in updaters)
				{
					if ((Object)(object)item4 != (Object)null)
					{
						((Behaviour)item4).enabled = true;
					}
				}
				updaters.Clear();
			}));
			list.Add(HideGroup("objects: trees & bushes hidden", Group.Vegetation));
			list.Add(HideGroup("objects: rocks & cliffs hidden", Group.Rocks));
			list.Add(HideGroup("objects: terrain hidden", Group.Terrain));
			list.Add(HideGroup("objects: water hidden", Group.Water));
			list.Add(HideGroup("objects: characters & creatures hidden", Group.Characters));
			list.Add(HideGroup("objects: everything else hidden (items, props, dungeon/location meshes)", Group.Other));
			list.Add(Toggle<InstanceRenderer>("objects: grass & ground clutter off", (Func<InstanceRenderer, bool>)((InstanceRenderer x) => ((Behaviour)x).enabled), (Action<InstanceRenderer, bool>)delegate(InstanceRenderer x, bool on)
			{
				((Behaviour)x).enabled = on;
			}));
			list.Add(Toggle<ParticleSystemRenderer>("effects: particles off (smoke, fire, mist, sparks)", (Func<ParticleSystemRenderer, bool>)((ParticleSystemRenderer x) => ((Renderer)x).enabled), (Action<ParticleSystemRenderer, bool>)delegate(ParticleSystemRenderer x, bool on)
			{
				((Renderer)x).enabled = on;
			}));
			list.Add(Toggle<Light>("effects: point & spot lights off (fires, torches, candles)", (Func<Light, bool>)((Light x) => ((Behaviour)x).enabled && ((int)x.type == 2 || (int)x.type == 0)), (Action<Light, bool>)delegate(Light x, bool on)
			{
				((Behaviour)x).enabled = on;
			}));
			list.Add(Toggle<ReflectionProbe>("effects: reflection probes off", (Func<ReflectionProbe, bool>)((ReflectionProbe x) => ((Behaviour)x).enabled), (Action<ReflectionProbe, bool>)delegate(ReflectionProbe x, bool on)
			{
				((Behaviour)x).enabled = on;
			}));
			bool fog = RenderSettings.fog;
			list.Add(Setting("effects: fog off", delegate
			{
				RenderSettings.fog = false;
			}, delegate
			{
				RenderSettings.fog = fog;
			}));
			List<Behaviour> postFx = new List<Behaviour>();
			list.Add(Setting("effects: post-processing off (SSAO, bloom, sun shafts, color grading...)", delegate
			{
				postFx.Clear();
				Camera mainCamera = Utils.GetMainCamera();
				if (!((Object)(object)mainCamera == (Object)null))
				{
					Behaviour[] components = ((Component)mainCamera).GetComponents<Behaviour>();
					foreach (Behaviour val in components)
					{
						if ((Object)(object)val != (Object)null && val.enabled && IsImageEffect(val))
						{
							val.enabled = false;
							postFx.Add(val);
						}
					}
				}
			}, delegate
			{
				foreach (Behaviour item5 in postFx)
				{
					if ((Object)(object)item5 != (Object)null)
					{
						item5.enabled = true;
					}
				}
				postFx.Clear();
			}));
			ShadowQuality shadows = QualitySettings.shadows;
			list.Add(Setting("quality: all shadows off", delegate
			{
				QualitySettings.shadows = (ShadowQuality)0;
			}, delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				QualitySettings.shadows = shadows;
			}));
			AddShadowDetail(list);
			float shadowDist = QualitySettings.shadowDistance;
			list.Add(Setting($"quality: shadow distance {shadowDist:0} -> {shadowDist / 2f:0} m", delegate
			{
				QualitySettings.shadowDistance = shadowDist / 2f;
			}, delegate
			{
				QualitySettings.shadowDistance = shadowDist;
			}));
			float lodBias = QualitySettings.lodBias;
			list.Add(Setting($"quality: LOD distance halved (bias {lodBias:0.##} -> {lodBias / 2f:0.##})", delegate
			{
				QualitySettings.lodBias = lodBias / 2f;
			}, delegate
			{
				QualitySettings.lodBias = lodBias;
			}));
			int mip = QualitySettings.globalTextureMipmapLimit;
			list.Add(Setting("quality: textures at half resolution", delegate
			{
				QualitySettings.globalTextureMipmapLimit = mip + 1;
			}, delegate
			{
				QualitySettings.globalTextureMipmapLimit = mip;
			}));
			AnisotropicFiltering aniso = QualitySettings.anisotropicFiltering;
			list.Add(Setting("quality: anisotropic filtering off", delegate
			{
				QualitySettings.anisotropicFiltering = (AnisotropicFiltering)0;
			}, delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				QualitySettings.anisotropicFiltering = aniso;
			}));
			bool autoRes = UpscaledFrameBuffer.m_autoTargetResolution;
			uint resV = UpscaledFrameBuffer.m_targetResolutionVertical;
			list.Add(Setting($"quality: 3D render resolution halved ({Screen.height}p -> {Screen.height / 2}p, GPU fill-rate test)", delegate
			{
				UpscaledFrameBuffer.m_autoTargetResolution = false;
				UpscaledFrameBuffer.m_targetResolutionVertical = (uint)(Screen.height / 2);
			}, delegate
			{
				UpscaledFrameBuffer.m_autoTargetResolution = autoRes;
				UpscaledFrameBuffer.m_targetResolutionVertical = resV;
			}));
			list.Add(Toggle<Animator>("engine: animations off (characters, doors, windmills...)", (Func<Animator, bool>)((Animator x) => ((Behaviour)x).enabled), (Action<Animator, bool>)delegate(Animator x, bool on)
			{
				((Behaviour)x).enabled = on;
			}));
			SimulationMode sim = Physics.simulationMode;
			list.Add(Setting("engine: physics simulation paused", delegate
			{
				Physics.simulationMode = (SimulationMode)2;
			}, delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				Physics.simulationMode = sim;
			}));
			list.Add(Setting("engine: audio paused", delegate
			{
				AudioListener.pause = true;
			}, delegate
			{
				AudioListener.pause = false;
			}));
			list.Add(Toggle<AudioSource>("engine: all sound sources off (what the sounds really cost)", (Func<AudioSource, bool>)((AudioSource x) => ((Behaviour)x).enabled), (Action<AudioSource, bool>)delegate(AudioSource x, bool on)
			{
				((Behaviour)x).enabled = on;
			}));
			list.Add(Toggle<Canvas>("engine: game UI hidden (HUD, minimap, hotbar)", (Func<Canvas, bool>)((Canvas x) => ((Behaviour)x).enabled && x.isRootCanvas), (Action<Canvas, bool>)delegate(Canvas x, bo