Decompiled source of Nivalis Unofficial Patch v0.4.1

BepInEx/plugins/NivalisUnofficialPatch/NivalisUnofficialPatch.dll

Decompiled 2 months ago
using System;
using System.Buffers.Binary;
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.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using CrazyMinnow.SALSA;
using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using Funly.SkyStudio;
using HarmonyLib;
using Hvizeu.NivalisMods;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using MagicaCloth;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using Nivalis;
using Nivalis.CraftingSystem;
using Nivalis.DayNightCycle;
using Nivalis.Dialogue;
using Nivalis.Economy;
using Nivalis.GhostSystem;
using Nivalis.GhostSystem.Ai;
using Nivalis.GhostSystem.CustomerLoop;
using Nivalis.InventorySystem;
using Nivalis.Locale;
using Nivalis.Locale.UI;
using Nivalis.Localization;
using Nivalis.Player;
using Nivalis.UI;
using Nivalis.UI.CharacterEditor;
using Nivalis.UI.Concrete;
using Nivalis.UI.InGameMenu;
using Nivalis.Utility;
using Nivalis.Weather;
using NivalisCompatibility;
using NivalisRecovery;
using NivalisUnofficialPatch.Core;
using RootMotion.FinalIK;
using TMPro;
using TheraBytes.BetterUi;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyMetadata("Nivalis.Requirements.Schema", "1")]
[assembly: AssemblyMetadata("Nivalis.NativeBuild", "F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A")]
[assembly: AssemblyMetadata("Nivalis.MetadataBuild", "61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA")]
[assembly: AssemblyMetadata("Nivalis.BindingRequirements", "compiled-member-references;Assembly-CSharp:Nivalis.SerializationManager.Load(System.String);Assembly-CSharp:Nivalis.SerializationManager.Save(System.String,System.Boolean)")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Hvizeu")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.1.0")]
[assembly: AssemblyInformationalVersion("0.4.1")]
[assembly: AssemblyProduct("NivalisUnofficialPatch")]
[assembly: AssemblyTitle("NivalisUnofficialPatch")]
[assembly: AssemblyMetadata("PrivateDiagnosticsBuild", "false")]
[assembly: AssemblyMetadata("Nivalis.Capabilities", "shared-settings-v1;native-recovery-v1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.4.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace NivalisRecovery
{
	public sealed class RecoveryGeneration
	{
		public int Schema { get; set; } = 1;

		public string Id { get; set; } = "";

		public string SourceSlot { get; set; } = "";

		public string TargetSlot { get; set; } = "";

		public string NativeHash { get; set; } = "";

		public string State { get; set; } = "Prepared";

		public string OutputHash { get; set; } = "";

		public string PublishedSlot { get; set; } = "";

		public bool DestinationOwned { get; set; }

		public List<string> OwnedCopies { get; set; } = new List<string>();

		public string FirstFailure { get; set; } = "";

		public int FailureOccurrences { get; set; }

		public List<string> CleanupFailures { get; set; } = new List<string>();

		public Dictionary<string, string> Workers { get; set; } = new Dictionary<string, string>();

		public Dictionary<string, List<int[]>> Goods { get; set; } = new Dictionary<string, List<int[]>>();

		public Dictionary<string, string> Companions { get; set; } = new Dictionary<string, string>();

		public Dictionary<string, string> CompanionHashes { get; set; } = new Dictionary<string, string>();

		public string Describe()
		{
			return $"{SourceSlot} → {TargetSlot}\n{Workers.Count} retired worker identities; {Goods.Sum<KeyValuePair<string, List<int[]>>>((KeyValuePair<string, List<int[]>> p) => p.Value.Count)} original inventory records.\nNative save and companions are preserved. Tables require a native relationship audit. State: {State}.";
		}

		public void Validate()
		{
			if (Schema != 1 || Id == null || Id.Length != 32 || !Id.All(Uri.IsHexDigit) || !RecoveryFiles.IsHash(NativeHash) || Workers == null || Goods == null || Companions == null || CompanionHashes == null || PublishedSlot == null)
			{
				throw new InvalidDataException("Unsupported recovery generation.");
			}
			RecoveryFiles.Slot(SourceSlot);
			RecoveryFiles.Slot(TargetSlot);
			if (PublishedSlot.Length != 0)
			{
				RecoveryFiles.Slot(PublishedSlot);
			}
			if (SourceSlot == TargetSlot || !TargetSlot.StartsWith("Recovered ", StringComparison.Ordinal) || Workers.Count > 3840 || Goods.Count > 4096 || Goods.Sum<KeyValuePair<string, List<int[]>>>((KeyValuePair<string, List<int[]>> p) => p.Value.Count) > 65536)
			{
				throw new InvalidDataException("Recovery limits or destination identity are invalid.");
			}
			bool flag;
			switch (State)
			{
			case "Claiming":
			case "Complete":
			case "Prepared":
			case "Loading":
			case "Publishing":
			case "Failed":
			case "Abandoned":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (!flag)
			{
				throw new InvalidDataException("Unknown recovery state.");
			}
			if (State == "Complete" && (PublishedSlot.Length == 0 || !RecoveryFiles.IsHash(OutputHash)))
			{
				throw new InvalidDataException("Completed recovery has no verified native publication.");
			}
			Guid result;
			foreach (KeyValuePair<string, string> worker in Workers)
			{
				if (worker.Key.Length != 32 || !worker.Key.StartsWith("a11e2026", StringComparison.Ordinal) || !Guid.TryParse(worker.Value, out result))
				{
					throw new InvalidDataException("Invalid retired worker identity.");
				}
			}
			foreach (KeyValuePair<string, List<int[]>> good in Goods)
			{
				if (!Guid.TryParse(good.Key, out result) || good.Value == null || good.Value.Any((int[] r) => r == null || r.Length != 4))
				{
					throw new InvalidDataException("Invalid recovery inventory record.");
				}
			}
			if (Companions.Count > 3 || CompanionHashes.Count != Companions.Count || OwnedCopies == null || OwnedCopies.Count > 8)
			{
				throw new InvalidDataException("Invalid companion ownership set.");
			}
			foreach (string ownedCopy in OwnedCopies)
			{
				RecoveryFiles.Relative(ownedCopy);
			}
			foreach (KeyValuePair<string, string> companion in Companions)
			{
				RecoveryFiles.Relative(companion.Key);
				switch (companion.Value)
				{
				case "hauling":
				case "manager":
				case "city":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (!flag || !CompanionHashes.TryGetValue(companion.Key, out string value) || !RecoveryFiles.IsHash(value))
				{
					throw new InvalidDataException("Missing or invalid companion receipt.");
				}
			}
		}
	}
	public static class RecoveryFiles
	{
		public static bool IsHash(string? value)
		{
			if (value != null && value.Length == 64)
			{
				return value.All(Uri.IsHexDigit);
			}
			return false;
		}

		public static string Hash(string path)
		{
			using FileStream inputStream = File.OpenRead(path);
			using SHA256 sHA = SHA256.Create();
			return Convert.ToHexString(sHA.ComputeHash(inputStream));
		}

		public static string Slot(string value)
		{
			if (string.IsNullOrWhiteSpace(value) || value.Length > 100 || value.IndexOfAny(new char[10] { '/', '\\', ':', '\0', '<', '>', '|', '?', '*', '"' }) >= 0 || value != Path.GetFileName(value) || value.EndsWith('.') || value.EndsWith(' '))
			{
				throw new InvalidDataException("Invalid save slot name.");
			}
			return value;
		}

		public static string Relative(string value)
		{
			if (string.IsNullOrWhiteSpace(value) || value.StartsWith('/') || value.Contains('\\') || value.Contains(':') || value.Split('/').Any((string s) => ((s != null && s.Length == 0) || s == "." || s == "..") ? true : false))
			{
				throw new InvalidDataException("Invalid recovery relative path.");
			}
			return value;
		}

		public static string Under(string root, string relative)
		{
			Relative(relative);
			string fullPath = Path.GetFullPath(Path.Combine(root, relative));
			DirectoryInfo directoryInfo = new FileInfo(fullPath).Directory;
			if (File.Exists(fullPath) && (File.GetAttributes(fullPath) & FileAttributes.ReparsePoint) != FileAttributes.None)
			{
				throw new IOException("Recovery does not follow file links.");
			}
			string value = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
			while (directoryInfo != null)
			{
				if (directoryInfo.Exists && (directoryInfo.Attributes & FileAttributes.ReparsePoint) != FileAttributes.None)
				{
					throw new IOException("Recovery does not follow directory links.");
				}
				if (directoryInfo.FullName.Equals(value, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
				{
					return fullPath;
				}
				directoryInfo = directoryInfo.Parent;
			}
			throw new IOException("Recovery path escapes its owner.");
		}

		public static void Write(string path, RecoveryGeneration value)
		{
			value.Validate();
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			string text = path + ".tmp";
			using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.Write, FileShare.None))
			{
				JsonSerializer.Serialize(fileStream, value);
				fileStream.Flush(flushToDisk: true);
			}
			File.Move(text, path, overwrite: true);
		}

		public static RecoveryGeneration Read(string path)
		{
			if (new FileInfo(path).Length > 33554432)
			{
				throw new InvalidDataException("Recovery record exceeds its size limit.");
			}
			RecoveryGeneration? obj = JsonSerializer.Deserialize<RecoveryGeneration>(File.ReadAllText(path)) ?? throw new InvalidDataException("Empty recovery record.");
			obj.Validate();
			return obj;
		}

		private static string Key(string slot)
		{
			return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(slot)));
		}

		public static RecoveryGeneration Inspect(string saves, string config, string slot)
		{
			return InspectNative(Under(saves, Slot(slot) + ".sav"), config, slot);
		}

		private static RecoveryGeneration InspectNative(string native, string config, string slot)
		{
			Slot(slot);
			if (new FileInfo(native).Length > 134217728)
			{
				throw new InvalidDataException("Native recovery input exceeds 128 MiB.");
			}
			string text = Hash(native);
			string text2 = Guid.NewGuid().ToString("N");
			RecoveryGeneration recoveryGeneration = new RecoveryGeneration
			{
				Id = text2,
				SourceSlot = slot,
				TargetSlot = "Recovered " + slot.Substring(0, Math.Min(48, slot.Length)) + " " + text2.Substring(0, 8),
				NativeHash = text
			};
			string text3 = Key(slot);
			string text4 = Key(Path.GetFileNameWithoutExtension(slot).ToUpperInvariant());
			Dictionary<string, string> dictionary = new Dictionary<string, string>
			{
				["NivalisUnofficialPatch/Hauling/" + text3 + ".json"] = "hauling",
				["NivalisUnofficialPatch/ManagerPolicies/" + text3 + ".json"] = "manager",
				["NivalisCityLife/Saves/" + text4 + ".json"] = "city"
			};
			foreach (KeyValuePair<string, string> item in dictionary)
			{
				string text5 = Under(config, item.Key);
				if (!File.Exists(text5))
				{
					if (File.Exists(text5 + ".required"))
					{
						throw new InvalidDataException("Required companion is missing: " + item.Key);
					}
					continue;
				}
				if (new FileInfo(text5).Length > 16777216)
				{
					throw new InvalidDataException("Companion exceeds its size limit.");
				}
				JsonObject jsonObject = JsonNode.Parse(File.ReadAllText(text5))?.AsObject() ?? throw new InvalidDataException("Invalid companion.");
				int num = ((int?)(jsonObject["Schema"] ?? jsonObject["Version"])) ?? (-1);
				bool flag2;
				if (item.Value == "hauling")
				{
					bool flag = ((num < 1 || num > 4) ? true : false);
					flag2 = flag;
				}
				else
				{
					bool flag;
					if (item.Value == "city")
					{
						bool flag3 = ((num < 1 || num > 3) ? true : false);
						flag = flag3;
					}
					else
					{
						flag = num != 2;
					}
					flag2 = flag;
				}
				if (flag2)
				{
					throw new InvalidDataException("Unsupported companion schema: " + item.Key);
				}
				if ((string?)jsonObject["Revision"] != text)
				{
					throw new InvalidDataException("Companion revision mismatch: " + item.Key);
				}
				if (File.Exists(text5 + ".required") && (new FileInfo(text5 + ".required").Length > 256 || !File.ReadAllText(text5 + ".required").Trim().Equals(text, StringComparison.OrdinalIgnoreCase)))
				{
					throw new InvalidDataException("Required companion marker differs from the native generation: " + item.Key);
				}
				recoveryGeneration.Companions[item.Key] = item.Value;
				recoveryGeneration.CompanionHashes[item.Key] = Hash(text5);
				if (item.Value == "hauling")
				{
					ExtractHauling(jsonObject, recoveryGeneration);
				}
			}
			foreach (string item2 in RequiredMarkers(config))
			{
				if (Path.GetFileName(item2).StartsWith(text3) || Path.GetFileName(item2).StartsWith(text4))
				{
					string key3 = item2;
					if (!dictionary.ContainsKey(Path.GetRelativePath(config, key3.Substring(0, key3.Length - 9)).Replace('\\', '/')))
					{
						throw new InvalidDataException("Unsupported required save companion: " + Path.GetRelativePath(config, item2));
					}
				}
			}
			if (Hash(native) != text)
			{
				throw new IOException("Native save changed during recovery inspection.");
			}
			recoveryGeneration.Validate();
			return recoveryGeneration;
		}

		private static IEnumerable<string> RequiredMarkers(string root)
		{
			if (!Directory.Exists(root))
			{
				yield break;
			}
			Stack<string> pending = new Stack<string>();
			pending.Push(root);
			int count = 0;
			while (pending.Count != 0)
			{
				string path = pending.Pop();
				foreach (string item in Directory.EnumerateFileSystemEntries(path))
				{
					int num = count + 1;
					count = num;
					if (num > 20000)
					{
						throw new InvalidDataException("Save companion inspection exceeds its file limit.");
					}
					string text = Under(root, Path.GetRelativePath(root, item).Replace('\\', '/'));
					if (!Path.GetRelativePath(root, text).Replace('\\', '/').Equals("NivalisUnofficialPatch/Recovery", StringComparison.Ordinal))
					{
						if (Directory.Exists(text))
						{
							pending.Push(text);
						}
						else if (text.EndsWith(".required", StringComparison.Ordinal))
						{
							yield return text;
						}
					}
				}
			}
		}

		public static void ValidateCapture(string folder, RecoveryGeneration value, bool remaining = false)
		{
			value.Validate();
			RecoveryGeneration recoveryGeneration = InspectNative(Under(folder, "source.sav"), Under(folder, "source"), value.SourceSlot);
			if (recoveryGeneration.NativeHash != value.NativeHash || !recoveryGeneration.Companions.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key).SequenceEqual(value.Companions.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key)) || !recoveryGeneration.CompanionHashes.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key).SequenceEqual(value.CompanionHashes.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key)) || !recoveryGeneration.Workers.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key).SequenceEqual(value.Workers.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key)))
			{
				throw new InvalidDataException("Recovery request differs from its captured ownership records.");
			}
			foreach (KeyValuePair<string, List<int[]>> good in value.Goods)
			{
				if (!recoveryGeneration.Goods.TryGetValue(good.Key, out List<int[]> value2))
				{
					throw new InvalidDataException("Recovery contains an uncaptured item type.");
				}
				Dictionary<string, int> dictionary = (from r in value2
					group r by string.Join(",", r)).ToDictionary((IGrouping<string, int[]> g) => g.Key, (IGrouping<string, int[]> g) => g.Count());
				foreach (int[] item in good.Value)
				{
					string key = string.Join(",", item);
					if (!dictionary.TryGetValue(key, out var value3) || value3 == 0)
					{
						throw new InvalidDataException("Recovery contains additional or altered goods.");
					}
					dictionary[key] = value3 - 1;
				}
				if (!remaining && dictionary.Values.Any((int n) => n != 0))
				{
					throw new InvalidDataException("Recovery dropped captured goods.");
				}
			}
			if (!remaining && recoveryGeneration.Goods.Keys.Any((string k) => !value.Goods.ContainsKey(k)))
			{
				throw new InvalidDataException("Recovery dropped a captured inventory.");
			}
		}

		private static void ExtractHauling(JsonObject document, RecoveryGeneration result)
		{
			JsonObject obj = document["Greenhouses"]?.AsObject() ?? throw new InvalidDataException("Missing greenhouse records.");
			if (obj.Count > 640)
			{
				throw new InvalidDataException("Too many greenhouse records.");
			}
			foreach (KeyValuePair<string, JsonNode> item in obj)
			{
				JsonObject jsonObject = item.Value.AsObject();
				string text = ((string?)jsonObject["Greenhouse"]) ?? "";
				int valueOrDefault = ((int?)jsonObject["Slot"]).GetValueOrDefault();
				Guid result2;
				bool flag = !Guid.TryParse(text, out result2);
				if (!flag)
				{
					bool flag2 = ((valueOrDefault < 0 || valueOrDefault > 4) ? true : false);
					flag = flag2;
				}
				if (flag)
				{
					throw new InvalidDataException("Invalid greenhouse ownership.");
				}
				JsonArray jsonArray = jsonObject["Candidates"].AsArray();
				int count = jsonArray.Count;
				if ((count != 3 && count != 6) || 1 == 0)
				{
					throw new InvalidDataException("Unsupported worker candidate record.");
				}
				for (int i = 0; i < jsonArray.Count; i++)
				{
					string text2 = "a11e2026" + Key("Hvizeu.Hauler/" + text + "/" + ((i < 3) ? (valueOrDefault * 3 + i) : (15 + valueOrDefault * 3 + i - 3))).ToLowerInvariant().Substring(0, 24);
					if ((string?)jsonArray[i]["Id"] != text2)
					{
						throw new InvalidDataException("Retired worker identity does not match its owner.");
					}
					result.Workers.Add(text2, ((string?)jsonArray[i]["Template"]) ?? "");
				}
				string[] array = new string[2] { "Cargo", "Surplus" };
				foreach (string text3 in array)
				{
					foreach (KeyValuePair<string, JsonNode> item2 in jsonObject[text3]?.AsObject() ?? throw new InvalidDataException("Missing greenhouse inventory: " + text3))
					{
						if (!result.Goods.TryGetValue(item2.Key, out List<int[]> value))
						{
							result.Goods.Add(item2.Key, value = new List<int[]>());
						}
						foreach (JsonNode item3 in item2.Value.AsArray())
						{
							value.Add((from n in item3.AsArray()
								select n.GetValue<int>()).ToArray());
						}
					}
				}
			}
		}

		public static string Prepare(string saves, string config, RecoveryGeneration value)
		{
			value.Validate();
			RecoveryGeneration recoveryGeneration = Inspect(saves, config, value.SourceSlot);
			if (value.State != "Prepared" || recoveryGeneration.NativeHash != value.NativeHash || !recoveryGeneration.CompanionHashes.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key).SequenceEqual(value.CompanionHashes.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key)) || !recoveryGeneration.Workers.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key).SequenceEqual(value.Workers.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key)) || JsonSerializer.Serialize(recoveryGeneration.Goods) != JsonSerializer.Serialize(value.Goods))
			{
				throw new IOException("Recovery inputs changed after preview.");
			}
			string text = Under(config, "NivalisUnofficialPatch/Recovery/" + value.Id);
			if (Directory.Exists(text))
			{
				throw new IOException("Recovery generation already exists.");
			}
			Directory.CreateDirectory(text);
			RecoveryGeneration recoveryGeneration2 = JsonSerializer.Deserialize<RecoveryGeneration>(JsonSerializer.Serialize(value));
			recoveryGeneration2.State = "Failed";
			Write(Path.Combine(text, "journal.json"), recoveryGeneration2);
			File.Copy(Under(saves, value.SourceSlot + ".sav"), Path.Combine(text, "source.sav"));
			foreach (KeyValuePair<string, string> companion in value.Companions)
			{
				string text2 = Under(text, "source/" + companion.Key);
				Directory.CreateDirectory(Path.GetDirectoryName(text2));
				File.Copy(Under(config, companion.Key), text2);
				if (File.Exists(Under(config, companion.Key) + ".required"))
				{
					File.Copy(Under(config, companion.Key) + ".required", text2 + ".required");
				}
				if (Hash(text2) != value.CompanionHashes[companion.Key])
				{
					throw new IOException("Companion changed while capturing recovery.");
				}
			}
			if (Hash(Path.Combine(text, "source.sav")) != value.NativeHash)
			{
				throw new IOException("Save changed while capturing recovery.");
			}
			ValidateCapture(text, value);
			Write(Path.Combine(text, "request.json"), value);
			Write(Path.Combine(text, "journal.json"), value);
			return text;
		}

		public static string TargetCompanion(RecoveryGeneration value, string source)
		{
			string text = value.Companions[source];
			if (text == "hauling")
			{
				throw new InvalidOperationException("Retired hauling state is archived, never resumed.");
			}
			string text2 = Key((text == "city") ? Path.GetFileNameWithoutExtension(value.TargetSlot).ToUpperInvariant() : value.TargetSlot);
			return source.Substring(0, source.LastIndexOf('/') + 1) + text2 + ".json";
		}

		public static RecoveryGeneration RestorePending(string saves, string config, string id, bool abandon)
		{
			if (id.Length != 32 || !id.All(Uri.IsHexDigit))
			{
				throw new InvalidDataException("Invalid recovery generation identity.");
			}
			string text = Under(config, "NivalisUnofficialPatch/Recovery/" + id);
			RecoveryGeneration recoveryGeneration = Read(Path.Combine(text, "journal.json"));
			bool flag;
			switch (recoveryGeneration.State)
			{
			case "Complete":
			case "Prepared":
			case "Abandoned":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (flag)
			{
				throw new InvalidOperationException("This generation has no interrupted recovery.");
			}
			string path = Path.Combine(text, "pending", "write-set.json");
			if (File.Exists(path))
			{
				using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(path));
				if (jsonDocument.RootElement.GetProperty("State").GetString() == "Pending")
				{
					recoveryGeneration = RecoveryWriteSet.Restore(saves, config, text);
				}
			}
			if (recoveryGeneration.State == "Complete")
			{
				return recoveryGeneration;
			}
			string path2 = Path.Combine(text, "request.json");
			if (!File.Exists(path2))
			{
				if (!abandon || recoveryGeneration.DestinationOwned || recoveryGeneration.OwnedCopies.Count != 0)
				{
					throw new InvalidDataException("Capture is incomplete; only abandonment of its private journal is available.");
				}
				recoveryGeneration.State = "Abandoned";
				Write(Path.Combine(text, "journal.json"), recoveryGeneration);
				return recoveryGeneration;
			}
			RecoveryGeneration recoveryGeneration2 = Read(path2);
			ValidateCapture(text, recoveryGeneration2);
			string text2 = Under(saves, recoveryGeneration.TargetSlot + ".sav");
			List<string> list = new List<string>();
			if (recoveryGeneration.DestinationOwned && File.Exists(text2))
			{
				if (!CapturedPrefix(text2, Path.Combine(text, "source.sav")))
				{
					throw new IOException("Unpublished native destination differs from its verified captured source.");
				}
				list.Add(text2);
			}
			foreach (KeyValuePair<string, string> item in recoveryGeneration2.Companions.Where<KeyValuePair<string, string>>((KeyValuePair<string, string> p) => p.Value != "hauling"))
			{
				string text3 = Under(config, TargetCompanion(recoveryGeneration2, item.Key));
				if (File.Exists(text3))
				{
					if (!recoveryGeneration.OwnedCopies.Contains("config/" + TargetCompanion(recoveryGeneration2, item.Key)) || !CapturedPrefix(text3, Under(text, "source/" + item.Key)))
					{
						throw new IOException("Unpublished companion is unowned or changed externally.");
					}
					list.Add(text3);
				}
				if (File.Exists(text3 + ".required"))
				{
					if (!recoveryGeneration.OwnedCopies.Contains("config/" + TargetCompanion(recoveryGeneration2, item.Key) + ".required") || File.ReadAllText(text3 + ".required").Trim() != recoveryGeneration2.NativeHash)
					{
						throw new IOException("Unpublished requirement changed externally.");
					}
					list.Add(text3 + ".required");
				}
			}
			foreach (string item2 in list)
			{
				File.Delete(item2);
			}
			recoveryGeneration2.State = (abandon ? "Abandoned" : "Prepared");
			Write(Path.Combine(text, "journal.json"), recoveryGeneration2);
			return recoveryGeneration2;
		}

		private static bool CapturedPrefix(string candidate, string source)
		{
			using FileStream fileStream = File.OpenRead(candidate);
			using FileStream fileStream2 = File.OpenRead(source);
			if (fileStream.Length > fileStream2.Length)
			{
				return false;
			}
			byte[] array = new byte[65536];
			byte[] array2 = new byte[65536];
			int num;
			while ((num = fileStream.Read(array, 0, array.Length)) > 0)
			{
				int num2;
				for (int i = 0; i < num; i += num2)
				{
					num2 = fileStream2.Read(array2, i, num - i);
					if (num2 == 0)
					{
						return false;
					}
				}
				if (!array.AsSpan(0, num).SequenceEqual(array2.AsSpan(0, num)))
				{
					return false;
				}
			}
			return true;
		}
	}
	public sealed class RecoveryWriteSet
	{
		public int Schema { get; set; } = 1;

		public string State { get; set; } = "Pending";

		public string Slot { get; set; } = "";

		public RecoveryGeneration Before { get; set; } = new RecoveryGeneration();

		public Dictionary<string, string> Hashes { get; set; } = new Dictionary<string, string>();

		public Dictionary<string, string> Observed { get; set; } = new Dictionary<string, string>();

		public static string ReceiptRelative(string slot)
		{
			return "NivalisUnofficialPatch/Recovery/slots/" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(slot))) + ".json";
		}

		private static string Location(string saves, string config, string key)
		{
			if (!key.StartsWith("save/", StringComparison.Ordinal))
			{
				if (!key.StartsWith("config/", StringComparison.Ordinal))
				{
					throw new InvalidDataException("Unrecognized recovery write owner.");
				}
				return RecoveryFiles.Under(config, key.Substring(7));
			}
			return RecoveryFiles.Under(saves, key.Substring(5));
		}

		private static string HashOrAbsent(string path)
		{
			if (!File.Exists(path))
			{
				return "absent";
			}
			return RecoveryFiles.Hash(path);
		}

		private static RecoveryWriteSet Read(string path)
		{
			if (new FileInfo(path).Length > 33554432)
			{
				throw new InvalidDataException("Recovery write set exceeds its size limit.");
			}
			RecoveryWriteSet value = JsonSerializer.Deserialize<RecoveryWriteSet>(File.ReadAllText(path)) ?? throw new InvalidDataException("Missing recovery write set.");
			bool flag = value.Schema != 1;
			if (!flag)
			{
				bool flag2;
				switch (value.State)
				{
				case "Pending":
				case "Committed":
				case "Restored":
					flag2 = true;
					break;
				default:
					flag2 = false;
					break;
				}
				flag = !flag2;
			}
			if (flag || value.Hashes == null || value.Observed == null)
			{
				throw new InvalidDataException("Unsupported recovery write set.");
			}
			value.Before.Validate();
			RecoveryFiles.Slot(value.Slot);
			if (!(from k in Keys(value.Before, value.Slot)
				orderby k
				select k).SequenceEqual(value.Hashes.Keys.OrderBy((string k) => k)) || value.Hashes.Values.Any((string h) => h != "absent" && !RecoveryFiles.IsHash(h)) || value.Observed.Any<KeyValuePair<string, string>>((KeyValuePair<string, string> p) => !value.Hashes.ContainsKey(p.Key) || (p.Value != "absent" && !RecoveryFiles.IsHash(p.Value))))
			{
				throw new InvalidDataException("Recovery write set has ambiguous file ownership.");
			}
			return value;
		}

		private static List<string> Keys(RecoveryGeneration generation, string slot)
		{
			List<string> list = new List<string> { "config/" + ReceiptRelative(slot) };
			string[] array = new string[2] { ".sav", ".png" };
			foreach (string text in array)
			{
				string[] array2 = new string[3] { "", ".bak", ".temp" };
				foreach (string text2 in array2)
				{
					list.Add("save/" + slot + text + text2);
				}
			}
			string targetSlot = generation.TargetSlot;
			generation.TargetSlot = slot;
			try
			{
				foreach (KeyValuePair<string, string> item in generation.Companions.Where<KeyValuePair<string, string>>((KeyValuePair<string, string> p) => p.Value != "hauling"))
				{
					string text3 = RecoveryFiles.TargetCompanion(generation, item.Key);
					list.Add("config/" + text3);
					list.Add("config/" + text3 + ".required");
				}
				return list;
			}
			finally
			{
				generation.TargetSlot = targetSlot;
			}
		}

		private static void Write(string path, RecoveryWriteSet value)
		{
			using (FileStream fileStream = new FileStream(path + ".tmp", FileMode.Create, FileAccess.Write, FileShare.None))
			{
				JsonSerializer.Serialize(fileStream, value);
				fileStream.Flush(flushToDisk: true);
			}
			File.Move(path + ".tmp", path, overwrite: true);
		}

		public static void Capture(string saves, string config, string folder, RecoveryGeneration generation, string slot)
		{
			RecoveryFiles.Slot(slot);
			if (slot == generation.SourceSlot)
			{
				throw new InvalidOperationException("Recovery must preserve its original slot.");
			}
			string text = Path.Combine(folder, "pending");
			string path = Path.Combine(text, "write-set.json");
			if (File.Exists(path))
			{
				if (Read(path).State == "Pending")
				{
					throw new InvalidOperationException("A recovery write is already pending.");
				}
				Directory.Move(text, Path.Combine(folder, "checkpoint-" + Guid.NewGuid().ToString("N")));
			}
			Directory.CreateDirectory(text);
			RecoveryWriteSet recoveryWriteSet = new RecoveryWriteSet
			{
				Slot = slot,
				Before = JsonSerializer.Deserialize<RecoveryGeneration>(JsonSerializer.Serialize(generation))
			};
			foreach (string item in Keys(generation, slot))
			{
				string text2 = Location(saves, config, item);
				string text3 = HashOrAbsent(text2);
				recoveryWriteSet.Hashes.Add(item, text3);
				if (!(text3 == "absent"))
				{
					string text4 = RecoveryFiles.Under(text, "before/" + item);
					Directory.CreateDirectory(Path.GetDirectoryName(text4));
					File.Copy(text2, text4, overwrite: true);
					if (RecoveryFiles.Hash(text4) != text3 || HashOrAbsent(text2) != text3)
					{
						throw new IOException("Recovery write inputs changed while checkpointing.");
					}
				}
			}
			Write(path, recoveryWriteSet);
		}

		public static void Observe(string saves, string config, string folder, bool committed)
		{
			string path = Path.Combine(folder, "pending", "write-set.json");
			if (File.Exists(path))
			{
				RecoveryWriteSet recoveryWriteSet = Read(path);
				recoveryWriteSet.Observed = recoveryWriteSet.Hashes.ToDictionary<KeyValuePair<string, string>, string, string>((KeyValuePair<string, string> p) => p.Key, (KeyValuePair<string, string> p) => HashOrAbsent(Location(saves, config, p.Key)));
				recoveryWriteSet.State = (committed ? "Committed" : "Pending");
				Write(path, recoveryWriteSet);
			}
		}

		public static RecoveryGeneration Restore(string saves, string config, string folder)
		{
			string text = Path.Combine(folder, "pending");
			string path = Path.Combine(text, "write-set.json");
			RecoveryWriteSet recoveryWriteSet = Read(path);
			if (recoveryWriteSet.Schema != 1 || recoveryWriteSet.State != "Pending")
			{
				throw new InvalidDataException("No pending recovery write to restore.");
			}
			recoveryWriteSet.Before.Validate();
			RecoveryFiles.Slot(recoveryWriteSet.Slot);
			foreach (KeyValuePair<string, string> hash in recoveryWriteSet.Hashes)
			{
				string text2 = HashOrAbsent(Location(saves, config, hash.Key));
				if (text2 != hash.Value && (!recoveryWriteSet.Observed.TryGetValue(hash.Key, out string value) || text2 != value))
				{
					throw new IOException("Recovery destination changed externally: " + hash.Key);
				}
				if (hash.Value != "absent" && RecoveryFiles.Hash(RecoveryFiles.Under(text, "before/" + hash.Key)) != hash.Value)
				{
					throw new InvalidDataException("Recovery checkpoint is incomplete.");
				}
			}
			foreach (KeyValuePair<string, string> hash2 in recoveryWriteSet.Hashes)
			{
				string text3 = Location(saves, config, hash2.Key);
				if (hash2.Value == "absent")
				{
					if (File.Exists(text3))
					{
						File.Delete(text3);
					}
				}
				else
				{
					Directory.CreateDirectory(Path.GetDirectoryName(text3));
					string text4 = text3 + ".recovery-restore";
					File.Copy(RecoveryFiles.Under(text, "before/" + hash2.Key), text4, overwrite: true);
					File.Move(text4, text3, overwrite: true);
				}
				if (HashOrAbsent(text3) != hash2.Value)
				{
					throw new IOException("Recovery checkpoint restoration verification failed.");
				}
			}
			recoveryWriteSet.State = "Restored";
			Write(path, recoveryWriteSet);
			RecoveryFiles.Write(Path.Combine(folder, "journal.json"), recoveryWriteSet.Before);
			return recoveryWriteSet.Before;
		}
	}
	public static class RecoveryRecordRules
	{
		public static bool Retired(IReadOnlyDictionary<string, string> workers, string packet, string person)
		{
			if (!workers.ContainsKey(packet))
			{
				return false;
			}
			if (packet != person)
			{
				throw new InvalidDataException("Retired person packet identity is ambiguous.");
			}
			return true;
		}

		public static void PayloadBoundary(long position, long length, long end)
		{
			if (position < 0 || end < position || end > length)
			{
				throw new InvalidDataException("Invalid retired ghost object boundary.");
			}
		}

		public static void Table(string id, bool runtime, bool placement, bool ghost, string? parent, IReadOnlySet<string> retired)
		{
			if (!runtime || !placement)
			{
				throw new InvalidDataException("Retired table " + id + " lacks a unique native placement record.");
			}
			if (!ghost)
			{
				throw new InvalidDataException("Table " + id + " has no surviving ghost record to establish contents and relationships uniquely. Destination was not published.");
			}
			if (parent != null && retired.Contains(parent))
			{
				throw new InvalidDataException("Table " + id + " still references a retired worker.");
			}
		}
	}
	public static class RecoveryTransfer
	{
		public static int Run<T>(IReadOnlyList<T> stock, Func<T, bool> fits, Func<T, bool> take, Func<T, bool> add, Func<T, bool> returnToSource, Func<T, bool> removeFromDestination, Action publish)
		{
			List<T> list = new List<T>();
			bool flag = false;
			try
			{
				foreach (T item3 in stock)
				{
					if (!fits(item3))
					{
						continue;
					}
					if (!take(item3))
					{
						throw new InvalidOperationException("Recovery item could not leave its source.");
					}
					list.Add(item3);
					if (!add(item3))
					{
						if (!returnToSource(item3))
						{
							throw new InvalidOperationException("Rejected recovery transfer could not roll back.");
						}
						list.RemoveAt(list.Count - 1);
					}
				}
				if (list.Count == 0)
				{
					return 0;
				}
				flag = true;
				publish();
				return list.Count;
			}
			catch (Exception item)
			{
				List<Exception> list2 = new List<Exception> { item };
				if (!flag)
				{
					foreach (T item4 in list.AsEnumerable().Reverse())
					{
						try
						{
							if (!removeFromDestination(item4) || !returnToSource(item4))
							{
								throw new InvalidOperationException("Recovery transfer rollback unresolved.");
							}
						}
						catch (Exception item2)
						{
							list2.Add(item2);
						}
					}
				}
				if (list2.Count != 1)
				{
					throw new AggregateException("Recovery transfer remains unresolved.", list2);
				}
				throw;
			}
		}
	}
}
namespace NivalisCompatibility
{
	internal static class NativeCompatibility
	{
		internal const string SupportedHash = "F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A";

		internal const string SupportedMetadata = "61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA";

		internal static bool Check(string game, Action<string> error, bool verifyNative = true)
		{
			try
			{
				if (!Environment.Is64BitProcess)
				{
					throw new NotSupportedException("Windows x64 IL2CPP is required.");
				}
				if (verifyNative)
				{
					using FileStream inputStream = File.OpenRead(Path.Combine(game, "GameAssembly.dll"));
					using SHA256 sHA = SHA256.Create();
					string text = Convert.ToHexString(sHA.ComputeHash(inputStream));
					if (text != "F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A")
					{
						throw new NotSupportedException("Unsupported GameAssembly: expected F67D5C384A12B67EF4458633AE48D3B3986C91E466C5CB8DADB1130EE2DA244A, observed " + text);
					}
					using FileStream inputStream2 = File.OpenRead(Path.Combine(game, "Nivalis Nights_Data", "il2cpp_data", "Metadata", "global-metadata.dat"));
					string text2 = Convert.ToHexString(sHA.ComputeHash(inputStream2));
					if (text2 != "61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA")
					{
						throw new NotSupportedException("Unsupported IL2CPP metadata: expected 61B766DC7C43848E596D223B6EDF0C893346CEC51F716C1CCBD73395CA3550FA, observed " + text2);
					}
				}
				Type type = (AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "Assembly-CSharp") ?? Assembly.Load("Assembly-CSharp")).GetType("Nivalis.SerializationManager", throwOnError: true);
				if (type.GetMethod("Load", new Type[1] { typeof(string) }) == null || type.GetMethod("Save", new Type[2]
				{
					typeof(string),
					typeof(bool)
				}) == null)
				{
					throw new MissingMethodException("Generated bindings do not provide the required native save/load contract. Refresh bindings before retrying.");
				}
				return true;
			}
			catch (Exception ex)
			{
				error("Compatibility validation failed before activation: " + ex);
				return false;
			}
		}
	}
	internal sealed class FeatureHooks
	{
		private readonly string owner;

		private readonly Action<string, Exception> report;

		private readonly List<Harmony> installed = new List<Harmony>();

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

		internal static bool Available(string owner, string root)
		{
			return !disabled.Contains(owner + "/" + root);
		}

		internal FeatureHooks(string owner, Action<string, Exception> report)
		{
			this.owner = owner;
			this.report = report;
		}

		internal void Install(Assembly assembly, IReadOnlySet<string> optionalRoots)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			foreach (IGrouping<Type, Type> item in (from t in assembly.GetTypes()
				where t.IsDefined(typeof(HarmonyPatch), inherit: false)
				select t).GroupBy(Root))
			{
				if (disabled.Contains(owner + "/" + item.Key.Name))
				{
					continue;
				}
				Harmony val = new Harmony(optionalRoots.Contains(item.Key.Name) ? (owner + ".feature." + item.Key.Name) : owner);
				installed.Add(val);
				try
				{
					foreach (Type item2 in item)
					{
						val.CreateClassProcessor(item2).Patch();
					}
				}
				catch (Exception ex)
				{
					disabled.Add(owner + "/" + item.Key.Name);
					try
					{
						val.UnpatchSelf();
						installed.Remove(val);
					}
					catch (Exception ex2)
					{
						throw new AggregateException("Feature hook rollback unresolved: " + item.Key.Name, ex, ex2);
					}
					if (!optionalRoots.Contains(item.Key.Name))
					{
						throw;
					}
					report(item.Key.Name + " disabled before activation for this session", ex);
				}
			}
		}

		private static Type Root(Type type)
		{
			while (type.DeclaringType != null)
			{
				type = type.DeclaringType;
			}
			return type;
		}

		internal void Stop()
		{
			List<Exception> list = new List<Exception>();
			Harmony[] array = installed.ToArray();
			foreach (Harmony val in array)
			{
				try
				{
					val.UnpatchSelf();
					installed.Remove(val);
				}
				catch (Exception item)
				{
					list.Add(item);
				}
			}
			if (list.Count != 0)
			{
				throw new AggregateException("Feature hook cleanup remains pending.", list);
			}
		}
	}
}
namespace Hvizeu.NivalisMods
{
	internal static class CharacterClearance
	{
		internal static void Volume(Character character, out Vector3 lower, out Vector3 upper, out float radius)
		{
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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_009f: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			Collider collide = character.Collide;
			CapsuleCollider val = ((collide != null) ? ((Il2CppObjectBase)collide).TryCast<CapsuleCollider>() : null);
			Vector3 val2;
			float num;
			if ((Object)(object)val != (Object)null && val.direction == 1)
			{
				Vector3 lossyScale = ((Component)val).transform.lossyScale;
				val2 = ((Component)val).transform.TransformPoint(val.center);
				radius = val.radius * Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.z));
				num = val.height * Mathf.Abs(lossyScale.y);
			}
			else
			{
				if ((Object)(object)collide != (Object)null && collide.enabled)
				{
					Bounds bounds = collide.bounds;
					Vector3 size = ((Bounds)(ref bounds)).size;
					if (((Vector3)(ref size)).sqrMagnitude > 0.01f)
					{
						Bounds bounds2 = collide.bounds;
						val2 = ((Bounds)(ref bounds2)).center;
						radius = Mathf.Max(((Bounds)(ref bounds2)).extents.x, ((Bounds)(ref bounds2)).extents.z);
						num = ((Bounds)(ref bounds2)).size.y;
						goto IL_013a;
					}
				}
				NavMeshAgent agent = character.Movement.Agent;
				radius = agent.radius;
				num = agent.height;
				val2 = ((BaseCharacter)character).ThisTransform.position + Vector3.up * (num * 0.5f + agent.baseOffset);
			}
			goto IL_013a;
			IL_013a:
			radius = Mathf.Max(0.1f, radius);
			float num2 = Mathf.Max(0f, num * 0.5f - radius);
			lower = val2 - Vector3.up * num2;
			upper = val2 + Vector3.up * num2;
		}

		internal static bool Blocks(Character character, Collider collider)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Character componentInParent = ((Component)collider).GetComponentInParent<Character>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return ((Il2CppObjectBase)componentInParent).Pointer != ((Il2CppObjectBase)character).Pointer;
			}
			Collider collide = character.Collide;
			if ((Object)(object)collide == (Object)null)
			{
				return true;
			}
			int layer = ((Component)collider).gameObject.layer;
			if (Singleton<CharacterManager>.InstanceExist() && (LayerMask.op_Implicit(Singleton<CharacterManager>.Instance.EnvironmentLayer) & (1 << layer)) != 0)
			{
				return true;
			}
			return !Physics.GetIgnoreLayerCollision(((Component)collide).gameObject.layer, layer);
		}
	}
}
namespace NivalisUnofficialPatch
{
	[HarmonyPatch(typeof(Character), "DoLateUpdate")]
	internal static class AnimationLodPatch
	{
		private static bool failed;

		private static bool Prepare()
		{
			return PerformanceCompatibility.Owns(PerformanceFeature.Animation);
		}

		private static void Prefix(Character __instance, out int __state)
		{
			__state = 0;
			if (failed || !PerformanceCompatibility.Owns(PerformanceFeature.Animation))
			{
				return;
			}
			try
			{
				float value = RenderingOptions.AnimationLodReduction.Value;
				if (!(value <= 0f) && __instance.AnimatorUpdateStep <= 0 && ((BaseCharacter)__instance).CameraVisible)
				{
					__state = AnimationLodPolicy.Step(((BaseCharacter)__instance).SqrVisibleDistance, value);
				}
			}
			catch (Exception ex)
			{
				failed = true;
				PerformanceCompatibility.Health(PerformanceFeature.Animation, ex.Message);
				ModFaults.Report("Animation cadence (disabled for session)", ex);
			}
		}

		private static void Postfix(Character __instance, int __state)
		{
			try
			{
				if (__state > 0 && !failed)
				{
					__instance.AnimatorUpdateStep = RuntimePerformance.Stagger(__instance, __state);
				}
			}
			catch (Exception ex)
			{
				failed = true;
				PerformanceCompatibility.Health(PerformanceFeature.Animation, ex.Message);
				ModFaults.Report("Animation cadence (disabled for session)", ex);
			}
		}
	}
	internal static class AvaVoice
	{
		private sealed record VoiceSource(AudioSource Source, bool OriginalMute);

		internal const string PersonGuid = "7aa86416-295d-40ad-a22b-3eb7a32c638f";

		private static readonly Dictionary<int, VoiceSource> Sources = new Dictionary<int, VoiceSource>();

		private static AudioSource? phoneSource;

		internal static bool Enabled;

		internal static AudioSource? CharacterSource(CharacterCommunication character)
		{
			if (!((Object)(object)character != (Object)null) || !((Object)(object)character.Salsa != (Object)null))
			{
				return null;
			}
			return character.Salsa.audioSrc;
		}

		internal static void BeginPhone(NewPageShownArgs line)
		{
			AudioSource inEarVOSource = AudioHandler.InEarVOSource;
			if ((Object)(object)phoneSource != (Object)(object)inEarVOSource)
			{
				Release(phoneSource);
			}
			phoneSource = inEarVOSource;
			Begin(inEarVOSource, line, line != null && line.isPhoneCall);
		}

		internal static void ReleasePhone()
		{
			Release(phoneSource);
			phoneSource = null;
		}

		internal static void Begin(AudioSource? source, NewPageShownArgs? line, bool audiblePath = true)
		{
			if ((Object)(object)source == (Object)null)
			{
				return;
			}
			KeyValuePair<int, VoiceSource>[] array = Sources.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, VoiceSource> keyValuePair = array[i];
				if ((Object)(object)keyValuePair.Value.Source == (Object)null)
				{
					Sources.Remove(keyValuePair.Key);
				}
			}
			object obj;
			if (line == null)
			{
				obj = null;
			}
			else
			{
				DialogueStepDisplayData dialogue = line.dialogue;
				obj = ((dialogue != null) ? dialogue.Speaker : null);
			}
			Person val = (Person)obj;
			if (!audiblePath || !((Object)(object)val != (Object)null) || !string.Equals(val.Guid, "7aa86416-295d-40ad-a22b-3eb7a32c638f", StringComparison.OrdinalIgnoreCase))
			{
				Release(source);
				return;
			}
			int instanceID = ((Object)source).GetInstanceID();
			if (!Sources.TryGetValue(instanceID, out VoiceSource value))
			{
				Sources.Add(instanceID, value = new VoiceSource(source, source.mute));
			}
			source.mute = value.OriginalMute || Enabled;
		}

		internal static void Apply(bool enabled)
		{
			Enabled = enabled;
			KeyValuePair<int, VoiceSource>[] array = Sources.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, VoiceSource> keyValuePair = array[i];
				if ((Object)(object)keyValuePair.Value.Source == (Object)null)
				{
					Sources.Remove(keyValuePair.Key);
				}
				else
				{
					keyValuePair.Value.Source.mute = keyValuePair.Value.OriginalMute || enabled;
				}
			}
		}

		internal static void Release(AudioSource? source)
		{
			if ((Object)(object)source != (Object)null && Sources.Remove(((Object)source).GetInstanceID(), out VoiceSource value))
			{
				source.mute = value.OriginalMute;
			}
		}

		internal static void Clear()
		{
			foreach (VoiceSource value in Sources.Values)
			{
				if ((Object)(object)value.Source != (Object)null)
				{
					value.Source.mute = value.OriginalMute;
				}
			}
			Sources.Clear();
			phoneSource = null;
		}
	}
	[HarmonyPatch(typeof(DialoguePhoneAudioPlayer), "OnNewDialogueLine")]
	internal static class AvaPhoneVoicePatch
	{
		internal static void Prefix(NewPageShownArgs obj)
		{
			AvaVoice.BeginPhone(obj);
		}
	}
	[HarmonyPatch(typeof(DialoguePhoneAudioPlayer), "OnDialogueEnd")]
	internal static class AvaPhoneVoiceEndPatch
	{
		internal static void Postfix()
		{
			AvaVoice.ReleasePhone();
		}
	}
	[HarmonyPatch(typeof(DialoguePhoneAudioPlayer), "OnDestroy")]
	internal static class AvaPhoneVoiceDestroyPatch
	{
		internal static void Prefix()
		{
			AvaVoice.ReleasePhone();
		}
	}
	[HarmonyPatch(typeof(CharacterCommunication), "StartTalk")]
	internal static class AvaCharacterVoicePatch
	{
		internal static void Prefix(CharacterCommunication __instance, NewPageShownArgs lineArgs)
		{
			AvaVoice.Begin(AvaVoice.CharacterSource(__instance), lineArgs);
		}
	}
	[HarmonyPatch(typeof(CharacterCommunication), "OnPostRelease")]
	internal static class AvaCharacterVoiceReleasePatch
	{
		internal static void Postfix(CharacterCommunication __instance)
		{
			AvaVoice.Release(AvaVoice.CharacterSource(__instance));
		}
	}
	internal static class BalancedDetailOptimizations
	{
		private sealed class ChangedLod
		{
			internal LODGroup Group;

			internal LOD[] Original;
		}

		private static readonly Dictionary<int, ChangedLod> lods = new Dictionary<int, ChangedLod>();

		private static readonly Dictionary<int, BaseCloth> cloth = new Dictionary<int, BaseCloth>();

		private static readonly List<int> retired = new List<int>();

		internal static int LodCount => lods.Count;

		internal static int ClothCount => cloth.Count;

		internal static void Inspect(LODGroup group)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			if (!RenderingOptions.BalancedDetailEnabled || (Object)(object)group == (Object)null || lods.ContainsKey(((Object)group).GetInstanceID()))
			{
				return;
			}
			LOD[] array = ((IEnumerable<LOD>)group.GetLODs()).ToArray();
			Character component = ((Component)group).GetComponent<Character>();
			bool flag = (Object)(object)component != (Object)null && (Object)(object)component.LODGroup == (Object)(object)group;
			if (!flag && array.Any((LOD l) => ((IEnumerable<Renderer>)l.renderers).Any((Renderer r) => (Object)(object)r == (Object)null || (Object)(object)((Il2CppObjectBase)r).TryCast<MeshRenderer>() == (Object)null)))
			{
				return;
			}
			Vector3 lossyScale = ((Component)group).transform.lossyScale;
			float worldSize = group.size * Math.Max(Math.Abs(lossyScale.x), Math.Max(Math.Abs(lossyScale.y), Math.Abs(lossyScale.z)));
			float[] heights = BalancedDetailPolicy.Heights(((Object)((Component)group).gameObject).name, worldSize, array.Select((LOD l) => l.screenRelativeTransitionHeight).ToArray(), flag, RenderingOptions.AppliedDetailStrength);
			if (heights != null)
			{
				LOD[] array2 = ((IEnumerable<LOD>)array).Select((Func<LOD, int, LOD>)((LOD l, int i) => new LOD(heights[i], Il2CppReferenceArray<Renderer>.op_Implicit(((IEnumerable<Renderer>)l.renderers).ToArray()))
				{
					fadeTransitionWidth = l.fadeTransitionWidth
				})).ToArray();
				lods.Add(((Object)group).GetInstanceID(), new ChangedLod
				{
					Group = group,
					Original = array
				});
				group.SetLODs(Il2CppReferenceArray<LOD>.op_Implicit(array2));
			}
		}

		internal static void Inspect(Character character)
		{
			if (!RenderingOptions.BalancedDetailEnabled || (Object)(object)character == (Object)null || character.magicaCloth == null)
			{
				return;
			}
			Enumerator<BaseCloth> enumerator = character.magicaCloth.GetEnumerator();
			while (enumerator.MoveNext())
			{
				BaseCloth current = enumerator.Current;
				if (!((Object)(object)current == (Object)null) && !cloth.ContainsKey(((Object)current).GetInstanceID()) && BalancedDetailPolicy.MissingClothLimit(((Object)((Component)character).gameObject).name, ((Object)((Component)current).gameObject).name, current.DistanceDisable_Active, current.DistanceDisable_Distance, current.DistanceDisable_FadeDistance))
				{
					cloth.Add(((Object)current).GetInstanceID(), current);
					current.DistanceDisable_Active = true;
				}
			}
		}

		internal static void Prune()
		{
			retired.Clear();
			foreach (KeyValuePair<int, ChangedLod> lod in lods)
			{
				if ((Object)(object)lod.Value.Group == (Object)null)
				{
					retired.Add(lod.Key);
				}
			}
			foreach (int item in retired)
			{
				lods.Remove(item);
			}
			retired.Clear();
			foreach (KeyValuePair<int, BaseCloth> item2 in cloth)
			{
				if ((Object)(object)item2.Value == (Object)null)
				{
					retired.Add(item2.Key);
				}
			}
			foreach (int item3 in retired)
			{
				cloth.Remove(item3);
			}
			retired.Clear();
		}

		internal static bool OwnsLod(int id)
		{
			return lods.ContainsKey(id);
		}

		internal static void Stop()
		{
			KeyValuePair<int, ChangedLod>[] array = lods.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, ChangedLod> entry = array[i];
				if (!DistantCharacterMeshes.OwnsLod(entry.Key) && RenderingOptimizations.TryRestore($"balanced LOD {entry.Key}", delegate
				{
					if ((Object)(object)entry.Value.Group != (Object)null)
					{
						entry.Value.Group.SetLODs(Il2CppReferenceArray<LOD>.op_Implicit(entry.Value.Original));
					}
				}))
				{
					lods.Remove(entry.Key);
				}
			}
			KeyValuePair<int, BaseCloth>[] array2 = cloth.ToArray();
			for (int i = 0; i < array2.Length; i++)
			{
				KeyValuePair<int, BaseCloth> entry2 = array2[i];
				if (RenderingOptimizations.TryRestore($"cloth {entry2.Key}", delegate
				{
					if ((Object)(object)entry2.Value != (Object)null)
					{
						entry2.Value.DistanceDisable_Active = false;
					}
				}))
				{
					cloth.Remove(entry2.Key);
				}
			}
		}
	}
	internal static class BusinessReminders
	{
		internal static ConfigEntry<bool> Hide;

		internal static void Bind(ConfigFile config)
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Expected O, but got Unknown
			bool flag = true;
			string text = Path.Combine(Paths.ConfigPath, "hvizeu.nivalis.trackedquestshud.cfg");
			try
			{
				if (File.Exists(text) && new FileInfo(text).Length <= 65536)
				{
					string text2 = "";
					foreach (string item in File.ReadLines(text))
					{
						string text3 = item.Trim();
						if (text3.StartsWith('[') && text3.EndsWith(']'))
						{
							string text4 = text3;
							text2 = text4.Substring(1, text4.Length - 1 - 1);
						}
						if (!(text2 != "HUD"))
						{
							string[] array = text3.Split('=', 2);
							if (array.Length == 2 && array[0].Trim() == "HideBusinessReminders" && bool.TryParse(array[1].Trim(), out var result))
							{
								flag = result;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = Plugin.ModLog;
				bool flag2 = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(53, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not read retired HUD preference; default used: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				modLog.LogWarning(val);
			}
			Hide = config.Bind<bool>("HUD", "HideBusinessReminders", flag, "Hide automatic business reminders on the HUD. Native quest filtering remains authoritative.");
		}
	}
	[HarmonyPatch(typeof(ActiveJournalEntriesUi), "Refresh")]
	internal static class BusinessReminderRefresh
	{
		private sealed class HiddenState
		{
			internal readonly List<GameObject> Rows = new List<GameObject>();

			internal float? Alpha;
		}

		private static readonly Dictionary<int, HiddenState> hidden = new Dictionary<int, HiddenState>();

		internal static void RefreshVisible()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			if (ApplicationState.IsQuitting)
			{
				return;
			}
			try
			{
				foreach (ActiveJournalEntriesUi item in Object.FindObjectsOfType<ActiveJournalEntriesUi>(true))
				{
					if ((Object)(object)item != (Object)null)
					{
						item.Refresh();
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = Plugin.ModLog;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(34, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Business reminder refresh failed: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				modLog.LogError(val);
			}
		}

		internal static void RestoreVisible()
		{
			foreach (ActiveJournalEntriesUi item in Object.FindObjectsOfType<ActiveJournalEntriesUi>(true))
			{
				if ((Object)(object)item != (Object)null)
				{
					Prefix(item, __runOriginal: true);
				}
			}
			hidden.Clear();
		}

		internal static void Forget(ActiveJournalEntriesUi ui)
		{
			hidden.Remove(((Object)ui).GetInstanceID());
		}

		[HarmonyPrefix]
		internal static void Prefix(ActiveJournalEntriesUi __instance, bool __runOriginal)
		{
			if (!__runOriginal || !hidden.Remove(((Object)__instance).GetInstanceID(), out HiddenState value))
			{
				return;
			}
			foreach (GameObject row in value.Rows)
			{
				if ((Object)(object)row != (Object)null)
				{
					row.SetActive(true);
				}
			}
			float? alpha = value.Alpha;
			if (alpha.HasValue)
			{
				float valueOrDefault = alpha.GetValueOrDefault();
				if ((Object)(object)__instance.entriesGroup != (Object)null && __instance.entriesGroup.alpha == 0f)
				{
					__instance.entriesGroup.alpha = valueOrDefault;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		internal static void Postfix(ActiveJournalEntriesUi __instance, bool __runOriginal)
		{
			if (!__runOriginal || ApplicationState.IsQuitting || !((UIPanel)__instance).IsVisible || !BusinessReminders.Hide.Value || (Object)(object)__instance.entriesGroup == (Object)null || (Object)(object)__instance.questList == (Object)null || (Object)(object)__instance.venueQuestList == (Object)null)
			{
				return;
			}
			HiddenState hiddenState = new HiddenState();
			ItemListUI venueQuestList = __instance.venueQuestList;
			for (int i = 0; i < venueQuestList.DisplayedCount; i++)
			{
				GameObject gameObject = venueQuestList.GetItem(i).GameObject;
				if (gameObject.activeSelf)
				{
					hiddenState.Rows.Add(gameObject);
					gameObject.SetActive(false);
				}
			}
			bool flag = false;
			for (int j = 0; j < __instance.questList.DisplayedCount; j++)
			{
				flag |= __instance.questList.GetItem(j).GameObject.activeSelf;
			}
			if (!flag && __instance.entriesGroup.alpha != 0f)
			{
				hiddenState.Alpha = __instance.entriesGroup.alpha;
				__instance.entriesGroup.alpha = 0f;
			}
			if (hiddenState.Rows.Count != 0 || hiddenState.Alpha.HasValue)
			{
				hidden[((Object)__instance).GetInstanceID()] = hiddenState;
				if (hiddenState.Rows.Count != 0)
				{
					LayoutRebuilder.ForceRebuildLayoutImmediate(__instance.entryParent);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ActiveJournalEntriesUi), "ShowAnimated")]
	internal static class BusinessReminderShow
	{
		private static void Postfix(ActiveJournalEntriesUi __instance)
		{
			if (!ApplicationState.IsQuitting && ((UIPanel)__instance).IsVisible)
			{
				__instance.Refresh();
			}
		}
	}
	[HarmonyPatch(typeof(ActiveJournalEntriesUi), "OnDestroy")]
	internal static class BusinessReminderDestroy
	{
		private static void Prefix(ActiveJournalEntriesUi __instance)
		{
			BusinessReminderRefresh.Forget(__instance);
		}
	}
	[HarmonyPatch(typeof(CharacterMovement), "Side")]
	internal static class ChairExitPatch
	{
		internal static long Recovered;

		private static int unresolvedReports;

		private static bool Prefix(CharacterMovement __instance, TransitionType transition, ref float __result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return ChooseExit(__instance, transition, ref __result);
			}
			catch (Exception error)
			{
				ModFaults.Report("Chair exit selection", error);
				return true;
			}
		}

		private static bool ChooseExit(CharacterMovement __instance, TransitionType transition, ref float __result)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Expected O, but got Unknown
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			if ((int)transition != 1)
			{
				return true;
			}
			Character character = __instance.character;
			if ((Object)(object)character == (Object)null)
			{
				return true;
			}
			AISpot previousSpot = character.previousSpot;
			Il2CppArrayBase<AISlot> val = ((Spot<AISlot>)(object)previousSpot)?.points;
			NavMeshAgent agent = __instance.Agent;
			if ((Object)(object)previousSpot == (Object)null || val == null || (Object)(object)agent == (Object)null || !Singleton<CharacterManager>.InstanceExist())
			{
				return true;
			}
			Vector3 origin = ((Component)__instance).transform.position;
			int environment = LayerMask.op_Implicit(Singleton<CharacterManager>.Instance.EnvironmentLayer);
			string blocker = "unknown";
			NavMeshHit val3 = default(NavMeshHit);
			foreach (AISlot item in val)
			{
				if (item == null)
				{
					return true;
				}
				Vector3 val2 = CharacterUtils.TransformPointUnscaled(((Component)previousSpot).transform, ((Slot)item).position);
				if (NavMesh.SamplePosition(val2, ref val3, 0.2f, -1) && NativeClear(val2))
				{
					return true;
				}
			}
			string text = "no authored exit slots";
			NavMeshHit val5 = default(NavMeshHit);
			bool flag = default(bool);
			foreach (AISlot item2 in val)
			{
				Vector3 val4 = CharacterUtils.TransformPointUnscaled(((Component)previousSpot).transform, ((Slot)item2).position);
				if (!NavMesh.SamplePositionFilter(val4, ref val5, 0.45f, agent.agentTypeID, agent.areaMask))
				{
					text = "no matching NavMesh near authored exit";
					continue;
				}
				if (Mathf.Abs(((NavMeshHit)(ref val5)).position.y - val4.y) > 0.2f)
				{
					text = "authored exit projects to a different height";
					continue;
				}
				if (!NativeClear(val4))
				{
					text = "native exit sweep blocked by environment";
					continue;
				}
				if (((Component)previousSpot).transform.InverseTransformPoint(((NavMeshHit)(ref val5)).position).x <= 0f != ((Slot)item2).position.x <= 0f)
				{
					text = "NavMesh projects across the chair center";
					continue;
				}
				string text2 = SceneLifecyclePatches.ProjectionObstruction(__instance, origin, val4) ?? SceneLifecyclePatches.ProjectionObstruction(__instance, origin, ((NavMeshHit)(ref val5)).position);
				if (text2 != null)
				{
					text = text2;
					continue;
				}
				__result = ((((Slot)item2).position.x <= 0f) ? 1f : (-1f));
				Recovered++;
				if (Recovered <= 8)
				{
					ManualLogSource modLog = Plugin.ModLog;
					BepInExInfoLogInterpolatedStringHandler val6 = new BepInExInfoLogInterpolatedStringHandler(57, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Chair exit recovered: character=");
						((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(((Object)character).name);
						((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("; spot=");
						((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(((Object)previousSpot).name);
						((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("; navmeshOffset=");
						((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<float>(Vector3.Distance(val4, ((NavMeshHit)(ref val5)).position), "F3");
						((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("m.");
					}
					modLog.LogInfo(val6);
				}
				return false;
			}
			if (unresolvedReports++ < 16)
			{
				ManualLogSource modLog2 = Plugin.ModLog;
				BepInExWarningLogInterpolatedStringHandler val7 = new BepInExWarningLogInterpolatedStringHandler(112, 6, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral("Chair exit unresolved: character=");
					((BepInExLogInterpolatedStringHandler)val7).AppendFormatted<string>(((Object)character).name);
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral("; spot=");
					((BepInExLogInterpolatedStringHandler)val7).AppendFormatted<string>(((Object)previousSpot).name);
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral("; slots=");
					((BepInExLogInterpolatedStringHandler)val7).AppendFormatted<int>(val.Length);
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral("; position=");
					((BepInExLogInterpolatedStringHandler)val7).AppendFormatted<Vector3>(origin);
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral("; reason=");
					((BepInExLogInterpolatedStringHandler)val7).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral("; sweepBlocker=");
					((BepInExLogInterpolatedStringHandler)val7).AppendFormatted<string>(blocker);
					((BepInExLogInterpolatedStringHandler)val7).AppendLiteral(". Native transition retained.");
				}
				modLog2.LogWarning(val7);
			}
			return true;
			bool NativeClear(Vector3 point)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: 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_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val8 = origin + Vector3.up * 0.75f;
				Vector3 val9 = point - origin;
				RaycastHit val10 = default(RaycastHit);
				bool num = Physics.SphereCast(val8, 0.15f, ((Vector3)(ref val9)).normalized, ref val10, 0.6f, environment, (QueryTriggerInteraction)0);
				if (num)
				{
					blocker = (((Object)(object)((RaycastHit)(ref val10)).collider == (Object)null) ? "unknown" : $"{((Object)((RaycastHit)(ref val10)).collider).name}, layer={((Component)((RaycastHit)(ref val10)).collider).gameObject.layer}");
				}
				return !num;
			}
		}
	}
	internal sealed class CleanupWork
	{
		private readonly List<(string Name, Action Action)> steps = new List<(string, Action)>();

		internal int Remaining => steps.Count;

		internal void Add(string name, Action action)
		{
			steps.Add((name, action));
		}

		internal bool Run()
		{
			int num = 0;
			while (num < steps.Count)
			{
				(string, Action) tuple = steps[num];
				try
				{
					tuple.Item2();
					steps.RemoveAt(num);
				}
				catch (Exception error)
				{
					ModFaults.Report(tuple.Item1, error);
					num++;
				}
			}
			return steps.Count == 0;
		}
	}
	internal static class CleanupRetries
	{
		private sealed class Pending
		{
			internal CleanupWork Work;

			internal int Left = 3;

			internal long Due;
		}

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

		internal static bool HasPending => pending.Count != 0;

		internal static string Status
		{
			get
			{
				if (pending.Count != 0)
				{
					return "Some cleanup could not finish. See the log for the affected controls or resources. Restart the game before unloading the patch.";
				}
				return "";
			}
		}

		internal static bool CanCreate => pending.Count < 256;

		internal static void Submit(CleanupWork work)
		{
			if (!work.Run())
			{
				Retry(work);
			}
		}

		internal static void Retry(CleanupWork work)
		{
			pending.Add(new Pending
			{
				Work = work,
				Due = Stopwatch.GetTimestamp() + Stopwatch.Frequency
			});
		}

		internal static void RetireCompleted(CleanupWork work)
		{
			if (work.Remaining != 0)
			{
				return;
			}
			for (int num = pending.Count - 1; num >= 0; num--)
			{
				if (pending[num].Work == work)
				{
					pending.RemoveAt(num);
				}
			}
		}

		internal static void Tick()
		{
			if (CleanupRetries.pending.Count == 0)
			{
				return;
			}
			long timestamp = Stopwatch.GetTimestamp();
			for (int num = CleanupRetries.pending.Count - 1; num >= 0; num--)
			{
				Pending pending = CleanupRetries.pending[num];
				if (pending.Left != 0 && timestamp >= pending.Due)
				{
					pending.Left--;
					pending.Due = timestamp + Stopwatch.Frequency;
					if (pending.Work.Run())
					{
						CleanupRetries.pending.RemoveAt(num);
					}
					else if (pending.Left == 0)
					{
						ModFaults.Report("Cleanup retry exhaustion", new InvalidOperationException("Cleanup stopped after three retries; unresolved native state retained. Restart is required before creating more affected controls."));
					}
				}
			}
		}
	}
	internal static class DistantCharacterDetails
	{
		private sealed class State
		{
			internal Character Character;

			internal GameObject Object;

			internal Transform Transform;

			internal CharacterCommunication? Communication;

			internal Salsa? Salsa;

			internal IKSolverLookAt? Look;

			internal bool Far;
		}

		private static readonly Dictionary<nint, State> characters = new Dictionary<IntPtr, State>();

		private static readonly Dictionary<nint, State> lips = new Dictionary<IntPtr, State>();

		private static readonly Dictionary<nint, State> looks = new Dictionary<IntPtr, State>();

		private static readonly List<nint> retired = new List<IntPtr>();

		private static readonly Harmony harmony = new Harmony("hvizeu.nivalis.unofficialpatch.distant-details");

		private static bool hooks;

		private static bool running;

		private static bool failed;

		private static float nextCheck;

		internal static bool HooksPending => hooks;

		internal static int Count => characters.Count;

		internal static void Start()
		{
			if (failed || hooks || !PerformanceCompatibility.Owns(PerformanceFeature.DistantCharacterDetails))
			{
				return;
			}
			hooks = true;
			try
			{
				Patch(typeof(Salsa), "LateUpdate", "LipPrefix");
				Patch(typeof(IKSolverLookAt), "SolveHead", "LookPrefix");
				Patch(typeof(IKSolverLookAt), "SolveEyes", "LookPrefix");
				Patch(typeof(Character), "OnPoolingDisable", "RetirePrefix");
				Patch(typeof(CharacterCommunication), "StartDialogue", "DialoguePrefix");
				Patch(typeof(CharacterCommunication), "StartTalk", "DialoguePrefix");
				running = true;
				nextCheck = 0f;
				PerformanceCompatibility.Health(PerformanceFeature.DistantCharacterDetails, null);
			}
			catch
			{
				failed = true;
				PerformanceCompatibility.Health(PerformanceFeature.DistantCharacterDetails, "Presentation hooks failed; disabled for this session");
				Stop();
				throw;
			}
		}

		private static void Patch(Type type, string target, string prefix)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			harmony.Patch((MethodBase)(AccessTools.Method(type, target, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, target)), new HarmonyMethod(typeof(DistantCharacterDetails), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void Inspect(Character character)
		{
			if (running && !((Object)(object)character == (Object)null) && !characters.ContainsKey(((Il2CppObjectBase)character).Pointer))
			{
				if (characters.Count >= 1024)
				{
					throw new InvalidOperationException("Distant character presentation inventory exceeded its limit.");
				}
				CharacterCommunication communication = character.Communication;
				CharacterIK iK = character.IK;
				LookAtIK val = (((Object)(object)iK == (Object)null) ? null : iK.lookIK);
				State state = new State
				{
					Character = character,
					Object = ((Component)character).gameObject,
					Transform = ((BaseCharacter)character).ThisTransform,
					Communication = communication,
					Salsa = (((Object)(object)communication == (Object)null) ? null : communication.Salsa),
					Look = (((Object)(object)val == (Object)null) ? null : val.solver)
				};
				if (((Object)(object)state.Salsa != (Object)null && lips.ContainsKey(((Il2CppObjectBase)state.Salsa).Pointer)) || (state.Look != null && looks.ContainsKey(((Il2CppObjectBase)state.Look).Pointer)))
				{
					throw new InvalidOperationException("Characters share a presentation component; distance ownership is ambiguous.");
				}
				characters.Add(((Il2CppObjectBase)character).Pointer, state);
				if ((Object)(object)state.Salsa != (Object)null)
				{
					lips[((Il2CppObjectBase)state.Salsa).Pointer] = state;
				}
				if (state.Look != null)
				{
					looks[((Il2CppObjectBase)state.Look).Pointer] = state;
				}
			}
		}

		internal static bool WantsTick(float now)
		{
			if (running && characters.Count > 0)
			{
				return now >= nextCheck;
			}
			return false;
		}

		internal static void Tick()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			float unscaledTime = Time.unscaledTime;
			if (WantsTick(unscaledTime))
			{
				Camera main = Camera.main;
				Tick(unscaledTime, ((Object)(object)main != (Object)null) ? new Vector3?(((Component)main).transform.position) : ((Vector3?)null));
			}
		}

		internal static void Tick(float now, Vector3? cameraPosition)
		{
			//IL_001f: 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)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			if (!WantsTick(now))
			{
				return;
			}
			nextCheck = now + 0.25f;
			try
			{
				bool hasValue = cameraPosition.HasValue;
				Vector3 valueOrDefault = cameraPosition.GetValueOrDefault();
				retired.Clear();
				foreach (KeyValuePair<IntPtr, State> character in characters)
				{
					State value = character.Value;
					if ((Object)(object)value.Character == (Object)null || (Object)(object)value.Transform == (Object)null || (Object)(object)value.Object == (Object)null || !value.Object.activeInHierarchy)
					{
						retired.Add(character.Key);
						continue;
					}
					bool flag = (Object)(object)value.Communication != (Object)null && value.Communication.IsPlayerDialogue;
					bool far = false;
					if (hasValue && !flag)
					{
						Vector3 position = value.Transform.position;
						far = DistantPresentationPolicy.Far(DistantPresentationPolicy.SquaredDistance(position.x, position.y, position.z, valueOrDefault.x, valueOrDefault.y, valueOrDefault.z), value.Far, 25f, 22f);
					}
					value.Far = far;
				}
				foreach (IntPtr item in retired)
				{
					Retire(item);
				}
				retired.Clear();
			}
			catch (Exception ex)
			{
				failed = true;
				Plugin.ModLog.LogError((object)("Distant character presentation stopped for this session. " + ex));
				PerformanceCompatibility.Health(PerformanceFeature.DistantCharacterDetails, "Presentation check failed; disabled for this session");
				RenderingOptimizations.Stop();
			}
		}

		internal static bool LipPrefix(Salsa __instance)
		{
			if (running && lips.TryGetValue(((Il2CppObjectBase)__instance).Pointer, out State value))
			{
				return !value.Far;
			}
			return true;
		}

		internal static bool LookPrefix(IKSolverLookAt __instance)
		{
			if (running && looks.TryGetValue(((Il2CppObjectBase)__instance).Pointer, out State value))
			{
				return !value.Far;
			}
			return true;
		}

		private static void RetirePrefix(Character __instance)
		{
			Retire(((Il2CppObjectBase)__instance).Pointer);
		}

		private static void DialoguePrefix(CharacterCommunication __instance)
		{
			foreach (State value in characters.Values)
			{
				CharacterCommunication? communication = value.Communication;
				if (((communication != null) ? new IntPtr?(((Il2CppObjectBase)communication).Pointer) : ((IntPtr?)null)) == ((Il2CppObjectBase)__instance).Pointer)
				{
					value.Far = false;
					break;
				}
			}
		}

		internal static void Retire(nint id)
		{
			if (characters.Remove(id, out State value))
			{
				if (value.Salsa != null)
				{
					lips.Remove(((Il2CppObjectBase)value.Salsa).Pointer);
				}
				if (value.Look != null)
				{
					looks.Remove(((Il2CppObjectBase)value.Look).Pointer);
				}
			}
		}

		internal static bool Stop()
		{
			if (!failed && (running || hooks))
			{
				PerformanceCompatibility.Health(PerformanceFeature.DistantCharacterDetails, "Stopped; waiting for rendering owner");
			}
			running = false;
			characters.Clear();
			lips.Clear();
			looks.Clear();
			retired.Clear();
			if (!hooks)
			{
				return true;
			}
			if (!RenderingOptimizations.TryRestore("distant presentation hooks", (Action)harmony.UnpatchSelf))
			{
				return false;
			}
			hooks = false;
			return true;
		}
	}
	internal static class DistantCharacterMeshes
	{
		private sealed class State
		{
			internal LODGroup Group;

			internal LOD[] Original;

			internal bool ChangedLods;

			internal readonly List<(Renderer Renderer, bool Original)> Retired = new List<(Renderer, bool)>();
		}

		private static readonly Dictionary<int, State> states = new Dictionary<int, State>();

		private static readonly List<int> retired = new List<int>();

		internal static int Count => states.Count;

		internal static bool OwnsLod(int id)
		{
			if (states.TryGetValue(id, out State value))
			{
				return value.ChangedLods;
			}
			return false;
		}

		internal static bool SmallGlasses(string character, string renderer, int triangles, int bones, int slots)
		{
			if (bones != 1)
			{
				return false;
			}
			switch (BalancedDetailPolicy.ObjectName(character))
			{
			case "Ceres Coilson":
				if (!(renderer == "Glasses_LOD_04") || triangles != 96 || slots != 2)
				{
					break;
				}
				return true;
			case "Steven McFellow":
				if (!(renderer == "Glasses_LOD_04") || triangles != 30 || slots != 2)
				{
					break;
				}
				return true;
			case "Mizzy Weiss":
				if (!(renderer == "Glasses_LOD_04") || triangles != 32 || slots != 1)
				{
					break;
				}
				return true;
			case "Roxi Fynx":
				if (!(renderer == "Glasses_LOD_04") || triangles != 32 || slots != 1)
				{
					break;
				}
				return true;
			case "Alexandria":
				if (!(renderer == "Glasses_LOD_04") || triangles != 48 || slots != 2)
				{
					break;
				}
				return true;
			case "Rice Walket":
				if (!(renderer == "Sunglasses_LOD_04") || triangles != 7 || slots != 1)
				{
					break;
				}
				return true;
			case "Male007":
				if (!(renderer == "GLASSES_LOD_004") || triangles != 90 || slots != 1)
				{
					break;
				}
				return true;
			case "Lynnphora Adams":
				if (!(renderer == "Glasses_LOD_04") || triangles != 20 || slots != 1)
				{
					break;
				}
				return true;
			case "Male008":
				if (!(renderer == "Garret_Glasses1_LOD_04") || triangles != 28 || slots != 1)
				{
					break;
				}
				return true;
			case "Milo":
				if (!(renderer == "Glasses_LOD_04") || triangles != 32 || slots != 1)
				{
					break;
				}
				return true;
			case "Random Male 03":
				if (!(renderer == "Glasses _LOD_004") || triangles != 27 || slots != 1)
				{
					break;
				}
				return true;
			case "Random Male 03_2":
				if (!(renderer == "Glasses _LOD_004") || triangles != 27 || slots != 1)
				{
					break;
				}
				return true;
			case "Dagmar Fitz":
				if (!(renderer == "Glasses_LOD_004") || triangles != 31 || slots != 2)
				{
					break;
				}
				return true;
			case "Mila Kalcifer":
				if (!(renderer == "Glasses_LOD_04") || triangles != 5 || slots != 1)
				{
					break;
				}
				return true;
			}
			return false;
		}

		internal static void Inspect(LODGroup group)
		{
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Expected O, but got Unknown
			if (!RenderingOptions.DistantCharacterMeshesEnabled || (Object)(object)group == (Object)null || states.ContainsKey(((Object)group).GetInstanceID()))
			{
				return;
			}
			Character component = ((Component)group).GetComponent<Character>();
			if ((Object)(object)component == (Object)null || (Object)(object)component.LODGroup != (Object)(object)group)
			{
				return;
			}
			string name = BalancedDetailPolicy.ObjectName(((Object)((Component)component).gameObject).name);
			bool flag;
			switch (name)
			{
			case "Ceres Coilson":
			case "Mila Kalcifer":
			case "Lynnphora Adams":
			case "Steven McFellow":
			case "Dagmar Fitz":
			case "Mizzy Weiss":
			case "Rice Walket":
			case "Male007":
			case "Male008":
			case "Roxi Fynx":
			case "Alexandria":
			case "Milo":
			case "Random Male 03":
			case "Random Male 03_2":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (!flag)
			{
				return;
			}
			LOD[] array = ((IEnumerable<LOD>)group.GetLODs()).ToArray();
			if (array.Length != 5 || array[0].screenRelativeTransitionHeight != 0.5f || array[4].screenRelativeTransitionHeight != 0.02f)
			{
				return;
			}
			State state = new State
			{
				Group = group,
				Original = array
			};
			Renderer[] array2 = ((IEnumerable<Renderer>)array[4].renderers).Where((Renderer r) => !Omit(name, r)).ToArray();
			state.ChangedLods = array2.Length != ((Il2CppArrayBase<Renderer>)(object)array[4].renderers).Length && array2.Length != 0;
			if (!state.ChangedLods)
			{
				return;
			}
			if (states.Count >= 1024)
			{
				throw new InvalidOperationException("Distant character mesh inventory exceeded its limit.");
			}
			states.Add(((Object)group).GetInstanceID(), state);
			if (!state.ChangedLods)
			{
				return;
			}
			LOD[] array3 = ((IEnumerable<LOD>)array).Select((Func<LOD, LOD>)((LOD l) => new LOD(l.screenRelativeTransitionHeight, l.renderers)
			{
				fadeTransitionWidth = l.fadeTransitionWidth
			})).ToArray();
			array3[4] = new LOD(array[4].screenRelativeTransitionHeight, Il2CppReferenceArray<Renderer>.op_Implicit(array2))
			{
				fadeTransitionWidth = array[4].fadeTransitionWidth
			};
			HashSet<IntPtr> hashSet = (from r in array3.SelectMany((LOD l) => (IEnumerable<Renderer>)l.renderers)
				where (Object)(object)r != (Object)null
				select ((Il2CppObjectBase)r).Pointer).ToHashSet();
			foreach (Renderer item in (Il2CppArrayBase<Renderer>)(object)array[4].renderers)
			{
				if ((Object)(object)item != (Object)null && !hashSet.Contains(((Il2CppObjectBase)item).Pointer))
				{
					state.Retired.Add((item, item.forceRenderingOff));
				}
			}
			group.SetLODs(Il2CppReferenceArray<LOD>.op_Implicit(array3));
			foreach (var item2 in state.Retired)
			{
				item2.Renderer.forceRenderingOff = true;
			}
		}

		private static bool Omit(string character, Renderer renderer)
		{
			//IL_000a: 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)
			if ((Object)(object)renderer == (Object)null || (int)renderer.shadowCastingMode != 0)
			{
				return false;
			}
			SkinnedMeshRenderer val = ((Il2CppObjectBase)renderer).TryCast<SkinnedMeshRenderer>();
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Mesh sharedMesh = val.sharedMesh;
			if ((Object)(object)sharedMesh == (Object)null || sharedMesh.subMeshCount > 2)
			{
				return false;
			}
			int num = 0;
			for (int i = 0; i < sharedMesh.subMeshCount; i++)
			{
				if ((int)sharedMesh.GetTopology(i) != 0)
				{
					return false;
				}
				num += checked((int)sharedMesh.GetIndexCount(i)) / 3;
			}
			return SmallGlasses(character, ((Object)((Component)renderer).gameObject).name, num, ((Il2CppArrayBase<Transform>)(object)val.bones).Length, ((Il2CppArrayBase<Material>)(object)renderer.sharedMaterials).Length);
		}

		internal static void Prune()
		{
			retired.Clear();
			foreach (KeyValuePair<int, State> state in states)
			{
				if ((Object)(object)state.Value.Group == (Object)null)
				{
					retired.Add(state.Key);
				}
			}
			foreach (int item in retired)
			{
				if (!Restore(states[item]))
				{
					throw new InvalidOperationException("A removed LODGroup still has unrestored distant mesh state.");
				}
				states.Remove(item);
			}
			retired.Clear();
		}

		internal static void Stop()
		{
			KeyValuePair<int, State>[] array = states.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, State> keyValuePair = array[i];
				if (Restore(keyValuePair.Value))
				{
					states.Remove(keyValuePair.Key);
				}
			}
		}

		private static bool Restore(State state)
		{
			bool flag;
			if (flag = !state.ChangedLods || RenderingOptimizations.TryRestore("distant character LOD", delegate
			{
				if ((Object)(object)state.Group != (Object)null)
				{
					state.Group.SetLODs(Il2CppReferenceArray<LOD>.op_Implicit(state.Original));
				}
			}))
			{
				foreach (var item in state.Retired)
				{
					flag &= RenderingOptimizations.TryRestore("distant accessory visibility", delegate
					{
						if ((Object)(object)item.Renderer != (Object)null)
						{
							item.Renderer.forceRenderingOff = item.Original;
						}
					});
				}
			}
			return flag;
		}
	}
	internal static class DistantWorldPanels
	{
		private sealed class State
		{
			internal MeshRenderer Renderer;

			internal bool Hidden;
		}

		private static readonly Dictionary<int, State> states = new Dictionary<int, State>();

		private static readonly List<int> retired = new List<int>();

		private static float nextCheck;

		internal static int Count => states.Count;

		internal static void Inspect(Transform node)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			if (!RenderingOptions.DistantWorldPanelsEnabled)
			{
				return;
			}
			string text = BalancedDetailPolicy.ObjectName(((Object)((Component)node).gameObject).name);
			bool flag;
			switch (text)
			{
			case "Animated_Billboard_1x1":
			case "Animated_Billboard_1x2":
			case "Animated_Billboard_2x1":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (!flag)
			{
				return;
			}
			MeshRenderer component = ((Component)node).GetComponent<MeshRenderer>();
			if ((Object)(object)component == (Object)null || states.ContainsKey(((Object)component).GetInstanceID()) || ((Renderer)component).forceRenderingOff || (int)((Renderer)component).shadowCastingMode != 0)
			{
				return;
			}
			MeshFilter component2 = ((Component)node).GetComponent<MeshFilter>();
			Mesh val = ((component2 != null) ? component2.sharedMesh : null);
			if ((Object)(object)val == (Object)null || val.subMeshCount != 1 || (int)val.GetTopology(0) != 0)
			{
				return;
			}
			Il2CppReferenceArray<Material> sharedMaterials = ((Renderer)component).sharedMaterials;
			if (((Il2CppArrayBase<Material>)(object)sharedMaterials).Length != 1 || (Object)(object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[0] == (Object)null)
			{
				return;
			}
			Material val2 = ((Il2CppArrayBase<Material>)(object)sharedMaterials)[0];
			Shader shader = val2.shader;
			if ((Object)(object)shader == (Object)null)
			{
				return;
			}
			Bounds bounds = val.bounds;
			Vector3 size = ((Bounds)(ref bounds)).size;
			Vector3 lossyScale = node.lossyScale;
			if (DistantPresentationPolicy.SmallPanel(text, ((Object)val).name, val.GetIndexCount(0), ((Object)val2).name, ((Object)shader).name, Math.Abs(size.x * lossyScale.x), Math.Abs(size.y * lossyScale.y)))
			{
				if (states.Count >= 256)
				{
					throw new InvalidOperationException("Small world-panel inventory exceeded its limit.");
				}
				states.Add(((Object)component).GetInstanceID(), new State
				{
					Renderer = component
				});
			}
		}

		internal static bool WantsTick(float now)
		{
			if (states.Count > 0)
			{
				return now >= nextCheck;
			}
			return false;
		}

		internal static void Tick()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			float unscaledTime = Time.unscaledTime;
			if (WantsTick(unscaledTime))
			{
				Camera main = Camera.main;
				Tick(unscaledTime, ((Object)(object)main != (Object)null) ? new Vector3?(((Component)main).transform.position) : ((Vector3?)null));
			}
		}

		internal static void Tick(float now, Vector3? cameraPosition)
		{
			//IL_001f: 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)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: 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)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			if (!WantsTick(now))
			{
				return;
			}
			nextCheck = now + 0.25f;
			bool hasValue = cameraPosition.HasValue;
			Vector3 valueOrDefault = cameraPosition.GetValueOrDefault();
			retired.Clear();
			foreach (KeyValuePair<int, State> state in states)
			{
				State value = state.Value;
				if ((Object)(object)value.Renderer == (Object)null)
				{
					retired.Add(state.Key);
					continue;
				}
				bool flag = false;
				if (hasValue && ((Component)value.Renderer).gameObject.activeInHierarchy)
				{
					Vector3 center = ((Renderer)value.Renderer).bounds.m_Center;
					flag = DistantPresentationPolicy.Far(DistantPresentationPolicy.SquaredDistance(center.x, center.y, center.z, valueOrDefault.x, valueOrDefault.y, valueOrDefault.z), value.Hidden, 40f, 35f);
				}
				if (flag != value.Hidden)
				{
					if (flag)
					{
						value.Hidden = true;
						((Renderer)value.Renderer).forceRenderingOff = true;
					}
					else
					{
						((Renderer)value.Renderer).forceRenderingOff = false;
						value.Hidden = false;
					}
				}
			}
			foreach (int item in retired)
			{
				states.Remove(item);
			}
			retired.Clear();
		}

		internal static void Stop()
		{
			KeyValuePair<int, State>[] array = states.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, State> keyValuePair = array[i];
				State state = keyValuePair.Value;
				if (!state.Hidden || RenderingOptimizations.TryRestore("small world panel", delegate
				{
					if ((Object)(object)state.Renderer != (Object)null)
					{
						((Renderer)state.Renderer).forceRenderingOff = false;
					}
				}))
				{
					states.Remove(keyValuePair.Key);
				}
			}
			nextCheck = 0f;
		}
	}
	internal static class LightingPatches
	{
		private sealed class LightingState
		{
			internal readonly LightingClockGate Clock = new LightingClockGate();

			internal readonly ExactCache Snapshot = new ExactCache();
		}

		[HarmonyPatch(typeof(LightCycleManager), "UpdateLightingInternal")]
		private static class Refresh
		{
			private static bool Prefix(LightCycleManager __instance, bool updateProbesIntensity, bool reuseUnchanged, out bool __state)
			{
				__state = false;
				if (!Plugin.Lighting || failed.Contains(((Il2CppObjectBase)__instance).Pointer))
				{
					return true;
				}
				bool flag;
				try
				{
					if (LightCycleManager.APPLY_FIXES)
					{
						Invalidate();
						return true;
					}
					LightingState lightingState = Cache(((Il2CppObjectBase)__instance).Pointer);
					if (!reuseUnchanged || __instance.inTransition || !updateProbesIntensity)
					{
						lightingState.Snapshot.Invalidate();
						lightingState.Clock.Reset();
						lastOwner = 0;
						return true;
					}
					if (!lightingState.Clock.Stable(__instance.currentTime, __instance.currentTimeRemapped))
					{
						lightingState.Snapshot.Invalidate();
						lastOwner = 0;
						return true;
					}
					Span<byte> buffer = stackalloc byte[1024];
					SnapshotWriter key = new SnapshotWriter(buffer);
					Capture(__instance, re