Decompiled source of SnaddysToolkit v1.0.1

SnaddysToolkit.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("s.naddy")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © 2026 s.naddy")]
[assembly: AssemblyDescription("Host-authoritative gameplay customization toolkit for R.E.P.O.")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("Snaddy's Toolkit")]
[assembly: AssemblyTitle("Snaddy's Toolkit")]
[assembly: AssemblyMetadata("Website", "https://snaddy.dev")]
[assembly: AssemblyMetadata("AuthorWebsite", "https://guns.lol/snaddy")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Snaddy.Toolkit
{
	[BepInPlugin("dev.snaddy.toolkit", "Snaddy's Toolkit", "1.0.1")]
	[BepInIncompatibility("nl.solveonstudios.repo.hostgamemanager")]
	[DefaultExecutionOrder(-10000)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class QaResult
		{
			public string Status;

			public string Name;

			public string Detail;
		}

		private sealed class SpawnProbe
		{
			public int Id;

			public int Before;

			public int OtherCalls;

			public bool InCall;

			public bool Seen;

			public bool Allowed;

			public bool Passed;

			public string Reason = "not reached";
		}

		private sealed class CreditProbe
		{
			public int Currency;

			public int Haul;

			public int Point;
		}

		private sealed class SettlementPlan
		{
			public int OpeningCurrencyK;

			public int OpeningHaulK;

			public int ExtractionK;

			public int BonusDollars;

			public int BonusK;

			public int MissingHeads;

			public int Rate;

			public int RequestedPenaltyK;

			public int AppliedPenaltyK;

			public int CurrencyBeforeK;

			public int HaulBeforeK;

			public int CurrencyAfterK;

			public int HaulAfterK;

			public int HeadMode;

			public bool FixedPenalty;

			public bool CurrencyWritten;

			public bool HaulWritten;

			public string[] Credits;

			public string[] Orbs;

			public string[] Missing;

			public List<HeadObservation> HeadAudit;
		}

		private sealed class HeadObservation
		{
			public int AvatarId;

			public int HeadId;

			public int Actor;

			public string Player;

			public string Reason;

			public bool AvatarActive;

			public bool Dead;

			public bool Connected;

			public bool HeadActive;

			public bool Triggered;

			public bool TruckFlag;

			public bool RoomTruckFlag;

			public bool Exempt;

			[JsonIgnore]
			public object Head;
		}

		private sealed class EconomyView
		{
			public int Sequence;

			public int Level;

			public int ExtractionK;

			public int BonusK;

			public int PenaltyK;

			public int RequestedK;

			public int Missing;

			public int Rate;

			public int BalanceK;

			public int Mode;

			public int OrbCount;

			public bool Final;

			public bool LedgerValid;

			public bool FixedPenalty;
		}

		private sealed class ExternalReservation
		{
			public object Parent;

			public string Name;

			public float Until;
		}

		private sealed class RemovalProbe
		{
			public int Id;

			public object Grab;

			public object Value;

			public bool Orb;

			public bool Extracted;
		}

		private sealed class WireRules
		{
			public int Level;

			public Dictionary<string, int> Rules;
		}

		private sealed class PhysicalOriginal
		{
			public object Value;

			public object Grab;

			public object Impact;

			public Rigidbody Body;

			public float Mass;

			public float GrabMass;

			public float Durability;

			public float Fragility;

			public int LastMass = -1;

			public bool Indestructible;

			public bool MassChanged;

			public bool DurabilityChanged;

			public bool FragilityChanged;

			public bool UnbreakableChanged;
		}

		private sealed class NetObservation
		{
			public string Nonce;

			public int Level;

			public int CurrencyK;

			public int HaulK;

			public int Actor;

			public bool MenuOpen;

			public Dictionary<int, int> Orbs;

			public Dictionary<int, int> Valuables;

			public Dictionary<int, bool> Enemies;
		}

		private sealed class BaseIdentity
		{
			public object Parent;

			public string Name;
		}

		private sealed class MutantReservation
		{
			public object Parent;

			public string Name;

			public float Until;
		}

		private sealed class Life
		{
			public string Name;

			public string Variant = "";

			public int Spawns;

			public int Drops;

			public int VariantCountedAt;

			public float DespawnedAt = -1f;

			public float RandomDelay = -1f;

			public bool DeathHandled;
		}

		private sealed class OrbRule
		{
			public int Index;

			public int Value;

			public int Multiplier;

			public int Reduction;

			public int Scale;

			public int Mode;

			public int Cap;

			public int SourceId;

			public string Name;
		}

		private sealed class DropContext
		{
			public object Health;

			public bool Flag;

			public bool Active;

			public bool Changed;

			public bool WasDead;

			public int Max;

			public int Before;

			public int Id;

			public OrbRule Rule;

			public OrbRule Previous;

			public DropContext PriorMutantContext;

			public bool ManagedMutantDrop;

			public bool MutantOrbDenied;
		}

		private readonly List<QaResult> qaResults = new List<QaResult>();

		private Dictionary<string, int> qaOverrides;

		private bool qaBusy;

		private bool qaConfirmed;

		private bool qaCancel;

		private int qaGeneration;

		private string qaFile = "";

		private int capParentsFrame = -1;

		private object[] capParents = Array.Empty<object>();

		private static Func<bool> qaMultiplayerCheck;

		private SpawnProbe qaProbe;

		private string qaSuite = "diagnostics";

		internal const string LegacyGuid = "nl.solveonstudios.repo.hostgamemanager";

		private const string LegacyDirectory = "HostGameManager";

		private const string MigrationMarker = ".migration-v1-complete";

		private int openingCurrencyK = -1;

		private int openingHaulK = -1;

		private int creditedCurrencyK;

		private int creditedHaulK;

		private bool ledgerValid = true;

		private readonly List<string> extractionLedger = new List<string>();

		private object blockedRunManager;

		private float retryDepartureAt;

		private SettlementPlan departurePlan;

		private const string EconomyDisplayMagic = "s.naddy.toolkit.economy.display/1";

		private EconomyView liveEconomy;

		private EconomyView lastEconomy;

		private EconomyView demoEconomy;

		private int economySequence;

		private int receivedEconomySequence;

		private float liveEconomyUntil;

		private float finalEconomyUntil;

		private float demoEconomyUntil;

		private float finalVisibleSeconds;

		private int lastEconomyPaintFrame = -1;

		private GUIStyle economyTitle;

		private GUIStyle economyLabel;

		private GUIStyle economyAmount;

		private GUIStyle economySmall;

		private GUIStyle economyTotal;

		private static readonly Color EconomyGreen = Color32.op_Implicit(new Color32((byte)112, (byte)217, (byte)148, byte.MaxValue));

		private static readonly Color EconomyRed = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)114, (byte)114, byte.MaxValue));

		private readonly Dictionary<int, ExternalReservation> externalPending = new Dictionary<int, ExternalReservation>();

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

		private long generatedLootDollars;

		private int destroyedLoot;

		private int destroyedOrbs;

		private int extractedLoot;

		private int extractedOrbs;

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

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

		private bool generationAuditDone;

		[ThreadStatic]
		private static int nativeLootDepth;

		private bool inputReleasePending;

		private int inputReleaseAfterFrame;

		private static MethodInfo resetUiPointers;

		private bool pointerResetFailed;

		private string qaProgress = "";

		private GUISkin menuSkin;

		private Texture2D menuPointer;

		private GUIStyle windowStyle;

		private GUIStyle heading;

		private GUIStyle subtitle;

		private GUIStyle sectionStyle;

		private GUIStyle navActive;

		private GUIStyle navNormal;

		private GUIStyle cardStyle;

		private GUIStyle statusStyle;

		private GUIStyle titleStyle;

		private GUIStyle fieldLabel;

		private GUIStyle tinyButton;

		private GUIStyle selectedButton;

		private readonly List<Texture2D> menuTextures = new List<Texture2D>();

		private Vector2 navScroll;

		private Vector2 pickerScroll;

		private string enemySearch = "";

		private string lootSearch = "";

		private int enemyPage;

		private int lootPage;

		private float uiSnapshotAt;

		private string[] dashboardLines = Array.Empty<string>();

		private string[] profileFiles = Array.Empty<string>();

		private object[] headSnapshot = Array.Empty<object>();

		private string snapshotSummary = "No active level";

		private int snapshotBonus;

		private int snapshotHeads;

		private static readonly string[] MenuTitles = new string[9] { "Overview", "Monsters", "Valuables", "Escape & recovery", "Live dashboard", "Profiles", "Diagnostics", "Developer tools", "Mutations" };

		private static readonly string[] MenuDescriptions = new string[9] { "General rules, controls and overall limits.", "Choose a monster or global rules. Configure spawning, respawns and Soul Orb rewards together.", "Choose which valuables may spawn and their value.", "Truck rewards and consequences for leaving friends behind.", "Live information about this level.", "Save and reuse your permanent rules.", "Compatibility, registered content and recent events.", "Run tests in a disposable save.", "Optional RepoMutantEnemies integration and variant rules." };

		private static readonly Vector2[] PointerShape = (Vector2[])(object)new Vector2[7]
		{
			new Vector2(2f, 1f),
			new Vector2(2f, 26f),
			new Vector2(9f, 20f),
			new Vector2(14f, 30f),
			new Vector2(19f, 27f),
			new Vector2(14f, 17f),
			new Vector2(26f, 17f)
		};

		private const byte RulesEvent = 173;

		private const string WireMagic = "s.naddy.toolkit.rules/1";

		private Room authorityRoom;

		private int initialMaster;

		private int remoteMaster;

		private int remoteLevel;

		private bool migrated;

		private bool networkStarted;

		private bool clientNotice;

		private float networkAt;

		private float remoteReceivedAt = -1000f;

		private string previousWire = "";

		private readonly Dictionary<int, float> acknowledgedClients = new Dictionary<int, float>();

		private const string WireAck = "s.naddy.toolkit.ack/1";

		private float ackAt;

		private Dictionary<string, int> remoteRules = new Dictionary<string, int>();

		private static readonly string[] SharedLootFields = new string[3] { "mass percent", "durability percent", "fragility percent" };

		private static readonly string[] SharedEnemyFields = new string[1] { "damage percent" };

		private float sharedDiscoverAt;

		[ThreadStatic]
		private static int damageDepth;

		private readonly Dictionary<int, PhysicalOriginal> physical = new Dictionary<int, PhysicalOriginal>();

		private const string AuditRequestMagic = "s.naddy.toolkit.audit.request/1";

		private const string AuditReplyMagic = "s.naddy.toolkit.audit.reply/1";

		private string auditNonce = "";

		private string auditStatus = "No multiplayer audit run";

		private float auditDeadline;

		private int[] auditActors = Array.Empty<int>();

		private NetObservation auditHost;

		private Room auditRoom;

		private readonly Dictionary<int, NetObservation> auditResponses = new Dictionary<int, NetObservation>();

		private const string MutantGuid = "com.matsu.repomutations";

		private const string MutantPrefix = "Mutant: ";

		private Type mutantSelectionType;

		private Type mutantCatalogType;

		private bool mutantAdapter;

		private readonly SortedDictionary<int, string> mutantCatalog = new SortedDictionary<int, string>();

		private readonly Dictionary<string, int> mutantSpawns = new Dictionary<string, int>();

		private readonly Dictionary<int, BaseIdentity> mutantBaseNames = new Dictionary<int, BaseIdentity>();

		private readonly Dictionary<int, MutantReservation> mutantPending = new Dictionary<int, MutantReservation>();

		private string selectedMutant = "";

		private string mutantSearch = "";

		private int mutantPage;

		private static DropContext mutantDeathContext;

		public const string ProjectWebsite = "https://snaddy.dev";

		public const string AuthorWebsite = "https://guns.lol/snaddy";

		public const string CopyrightNotice = "Copyright © 2026 s.naddy";

		public const string Guid = "dev.snaddy.toolkit";

		public const string Version = "1.0.1";

		private static Plugin P;

		private Harmony harmony;

		private ConfigEntry<KeyCode> hotkey;

		private ConfigEntry<bool> modEnabled;

		private ConfigEntry<bool> developer;

		private ConfigEntry<bool> advancedMode;

		private string root;

		private string settingsFile;

		private readonly Dictionary<string, int> permanent = new Dictionary<string, int>();

		private readonly Dictionary<string, int> run = new Dictionary<string, int>();

		private readonly Dictionary<string, int> level = new Dictionary<string, int>();

		private readonly Dictionary<string, int> pending = new Dictionary<string, int>();

		private readonly Dictionary<string, int> drafts = new Dictionary<string, int>();

		private readonly Dictionary<string, string> inputText = new Dictionary<string, string>();

		private readonly Dictionary<string, object> enemySetups = new Dictionary<string, object>();

		private readonly Dictionary<string, object> lootRefs = new Dictionary<string, object>();

		private readonly SortedSet<string> enemyNames = new SortedSet<string>();

		private readonly SortedSet<string> lootNames = new SortedSet<string>();

		private readonly Dictionary<int, Life> lives = new Dictionary<int, Life>();

		private readonly Dictionary<string, int> spawnCounts = new Dictionary<string, int>();

		private readonly Dictionary<string, int> lootCounts = new Dictionary<string, int>();

		private readonly Dictionary<int, OrbRule> orbRules = new Dictionary<int, OrbRule>();

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

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

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

		private readonly List<string> logs = new List<string>();

		private readonly List<string> patches = new List<string>();

		private int totalSpawns;

		private int totalDrops;

		private int totalLoot;

		private int scope;

		private int tab;

		private int levelNumber = 1;

		private int selectedLevel = 1;

		private int earnedK;

		private bool open;

		private bool bypass;

		private bool developerBypass;

		private bool paused;

		private bool forceDeparture;

		private bool settled;

		private bool wasRun;

		private int forcedDropSuppression;

		private float scanAt;

		private int debugAmount = 1;

		private string selectedEnemy = "";

		private string selectedLoot = "";

		private string search = "";

		private string profile = "default";

		private string message = "";

		private Rect window = new Rect(30f, 40f, 850f, 650f);

		private Vector2 scroll;

		private Vector2 listScroll;

		private CursorLockMode oldLock;

		private bool oldVisible;

		private static readonly string[] tiers = new string[3] { "enemiesDifficulty1", "enemiesDifficulty2", "enemiesDifficulty3" };

		private static readonly string[] lootLists = new string[7] { "tinyValuables", "smallValuables", "mediumValuables", "bigValuables", "wideValuables", "tallValuables", "veryTallValuables" };

		private static OrbRule currentOrb;

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

		private static Func<bool> hostCheck;

		private static Func<bool> levelCheck;

		private static Func<bool> lobbyCheck;

		private static Func<bool> lobbyMenuCheck;

		private const BindingFlags MemberFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

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

		private static readonly Dictionary<(Type, string), PropertyInfo> propertyCache = new Dictionary<(Type, string), PropertyInfo>();

		private readonly Dictionary<string, float> logTimes = new Dictionary<string, float>();

		private object blockedDeparture;

		private bool debugConfirm;

		private bool confirmReset;

		private int simRevenue = 100000;

		private int simHeads = 1;

		private int simBonus;

		private Color Ink => Color32.op_Implicit(new Color32((byte)232, (byte)237, (byte)239, byte.MaxValue));

		private Color Muted => Color32.op_Implicit(new Color32((byte)158, (byte)174, (byte)183, byte.MaxValue));

		private Color Accent => Color32.op_Implicit(new Color32(byte.MaxValue, (byte)176, (byte)73, byte.MaxValue));

		private bool Advanced => advancedMode.Value;

		private object[] CapParents()
		{
			if (capParentsFrame != Time.frameCount)
			{
				capParents = Parents().ToArray();
				capParentsFrame = Time.frameCount;
			}
			return capParents.Where(Exists).ToArray();
		}

		private static double CalculateOrb(double vanilla, OrbRule r, int map)
		{
			double num = ((r.Value >= 0) ? ((double)r.Value) : vanilla);
			if (r.Multiplier >= 0)
			{
				num *= (double)r.Multiplier / 100.0;
			}
			num = Scale(num, r.Scale, r.Mode, map);
			if (r.Reduction >= 0)
			{
				num *= Math.Pow(1.0 - (double)Math.Min(100, r.Reduction) / 100.0, Math.Max(0, r.Index));
			}
			if (r.Cap >= 0)
			{
				num = Math.Min(num, r.Cap);
			}
			return ClampMoney(num);
		}

		private static int CalculatePenalty(int gross, int pct, int heads)
		{
			return Math.Min(Math.Max(0, gross), ClampMoney((double)Math.Max(0, gross) * Math.Min(100.0, (double)Math.Max(0, pct) * (double)Math.Max(0, heads)) / 100.0));
		}

		private void Qa(string status, string name, string detail)
		{
			qaResults.Add(new QaResult
			{
				Status = status,
				Name = name,
				Detail = detail
			});
			Log("[QA " + status + "] " + name + ": " + detail);
		}

		private void AssertQa(string name, bool ok, string detail)
		{
			Qa(ok ? "PASS" : "FAIL", name, detail);
		}

		private void Case(string name, Func<bool> test)
		{
			try
			{
				AssertQa(name, test(), "Rule engine assertion");
			}
			catch (Exception ex)
			{
				Qa("FAIL", name, (ex.InnerException ?? ex).Message);
			}
		}

		private void RunQuickDiagnostics()
		{
			RunQuickDiagnostics(export: true);
		}

		private void RunQuickDiagnostics(bool export)
		{
			if (qaBusy)
			{
				message = "Live QA in progress";
				return;
			}
			qaResults.Clear();
			qaSuite = "diagnostics";
			foreach (string patch in patches)
			{
				if (patch.EndsWith(" : installed", StringComparison.Ordinal))
				{
					int num = patch.LastIndexOf('.');
					string text = patch.Substring(0, num);
					string m = patch.Substring(num + 1).Split(' ')[0];
					try
					{
						Type type = T(text);
						bool flag = type != null && (from x in AccessTools.GetDeclaredMethods(type)
							where x.Name == m
							select x).Any(delegate(MethodInfo x)
						{
							Patches patchInfo = Harmony.GetPatchInfo((MethodBase)x);
							return patchInfo != null && patchInfo.Owners.Contains("dev.snaddy.toolkit");
						});
						AssertQa("Hook " + text + "." + m, flag, flag ? "Harmony owner present" : "Patch not found");
					}
					catch (Exception ex)
					{
						Qa("FAIL", patch, ex.Message);
					}
				}
				else if (patch.Contains("FAILED"))
				{
					Qa("FAIL", "Hook registration", patch);
				}
				else
				{
					Qa("SKIP", "Optional integration", patch);
				}
			}
			Case("Spawn cap boundary", () => !Limit(1, 2) && Limit(2, 2) && !Limit(100, -1) && Limit(0, 0));
			Case("Group capacity", () => !WouldExceed(1, 1, 2) && WouldExceed(1, 2, 2) && !WouldExceed(100, 50, -1));
			Case("Orb decay 10000 / 7500 / 5625", delegate
			{
				OrbRule orbRule = new OrbRule
				{
					Value = 10000,
					Reduction = 25,
					Multiplier = -1,
					Scale = -1,
					Mode = -1,
					Cap = -1
				};
				for (int i = 0; i < 3; i++)
				{
					orbRule.Index = i;
					if (CalculateOrb(1.0, orbRule, 1) != (double)(new int[3] { 10000, 7500, 5625 })[i])
					{
						return false;
					}
				}
				return true;
			});
			Case("Explicit value scaling Off", () => Scale(10000.0, 25, 0, 5) == 10000.0 && Scale(10000.0, 25, 1, 5) == 20000.0 && Scale(10000.0, -1, 2, 5) == 10000.0 && CalculateOrb(0.0, new OrbRule
			{
				Value = 10000,
				Multiplier = -1,
				Reduction = -1,
				Scale = 25,
				Mode = 0,
				Cap = -1
			}, 5) == 10000.0);
			Case("Orb scaling and value cap", delegate
			{
				OrbRule r = new OrbRule
				{
					Value = 10000,
					Reduction = 25,
					Multiplier = 100,
					Scale = 10,
					Mode = 1,
					Cap = 12000,
					Index = 0
				};
				return CalculateOrb(0.0, r, 3) == 12000.0 && Scale(10000.0, 10, 2, 3) > 12099.0 && Scale(10000.0, 10, 2, 3) < 12101.0;
			});
			Case("Head penalty 20 percent per head", () => CalculatePenalty(100000, 20, 1) == 20000 && CalculatePenalty(100000, 20, 2) == 40000 && CalculatePenalty(100000, 20, 8) == 100000);
			Case("Truck reward included before penalty", () => CalculatePenalty(120000, 20, 1) == 24000);
			EconomyQa();
			MutantDiagnostics();
			try
			{
				Discover();
				Qa((enemyNames.Count > 0) ? "PASS" : "SKIP", "Enemy registry", enemyNames.Count + " detected types");
				Qa((lootNames.Count > 0) ? "PASS" : "SKIP", "Valuable registry", lootNames.Count + " detected types");
			}
			catch (Exception ex2)
			{
				Qa("FAIL", "Registry scan", ex2.Message);
			}
			if (InLevel())
			{
				try
				{
					AuditLive();
				}
				catch (Exception ex3)
				{
					Qa("FAIL", "Live map audit", ex3.Message);
				}
			}
			else
			{
				Qa("SKIP", "Live map audit", "Enter a gameplay map first");
			}
			if (drafts.Count > 0)
			{
				Qa("WARN", "Unapplied settings", drafts.Count + " draft changes are not active yet");
			}
			if (!modEnabled.Value)
			{
				Qa("WARN", "Mod disabled", "Enable it before gameplay tests");
			}
			string text2 = LiveBlockReason();
			Qa((text2 == null) ? "PASS" : "SKIP", "Live test readiness", text2 ?? "Offline gameplay map ready; confirm disposable save before live testing");
			Qa("SKIP", "Multiplayer / extraction settlement", "Requires real departure and comparison against a second player; same-version clients recommended");
			if (export)
			{
				ExportQa();
			}
		}

		private void AuditLive()
		{
			object[] array = Parents().Where(Active).ToArray();
			int num = R("enemy", "*", "max active");
			Qa((num < 0) ? "SKIP" : ((array.Length <= num) ? "PASS" : "WARN"), "Current global active limit", array.Length + " active / " + ((num < 0) ? "game default" : num.ToString()) + "; existing enemies are not removed automatically");
			foreach (IGrouping<string, object> item in array.GroupBy(EnemyName))
			{
				int num2 = R("enemy", item.Key, "max active");
				if (num2 >= 0)
				{
					Qa((item.Count() <= num2) ? "PASS" : "WARN", "Active " + item.Key, item.Count() + " / " + num2);
				}
				if (!EnemyAllowed(item.Key))
				{
					Qa("WARN", "Disabled enemy still active", item.Key + " (may predate rule)");
				}
			}
			foreach (KeyValuePair<string, int> spawnCount in spawnCounts)
			{
				int num3 = R("enemy", spawnCount.Key, "max spawns");
				if (num3 >= 0)
				{
					Qa((spawnCount.Value <= num3) ? "PASS" : "WARN", "Lifetime " + spawnCount.Key, spawnCount.Value + " / " + num3);
				}
			}
			int num4 = R("orb", "*", "max present");
			int num5 = PresentOrbs();
			Qa((num4 < 0) ? "SKIP" : ((num5 <= num4) ? "PASS" : "WARN"), "Orb presence", num5 + " / " + ((num4 < 0) ? "game default" : num4.ToString()));
		}

		private static bool QaMultiplayer()
		{
			if (qaMultiplayerCheck == null)
			{
				MethodInfo methodInfo = T("SemiFunc")?.GetMethod("IsMultiplayer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
				if (methodInfo == null || methodInfo.ReturnType != typeof(bool))
				{
					throw new MissingMethodException("SemiFunc.IsMultiplayer");
				}
				qaMultiplayerCheck = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo);
			}
			return qaMultiplayerCheck();
		}

		private string LiveBlockReason()
		{
			try
			{
				if (!Host())
				{
					return "You must be the host.";
				}
				if (!modEnabled.Value)
				{
					return "Enable Snaddy's Toolkit first.";
				}
				if (QaMultiplayer())
				{
					return "Multiplayer mode detected. Start a new SINGLEPLAYER game from the main menu, not a private multiplayer lobby.";
				}
				if (!InLevel())
				{
					return "Enter an actual gameplay map (not the lobby, truck-only lobby or shop).";
				}
				if (!B(S("LevelGenerator"), "Generated"))
				{
					return "Wait for the map to finish generating.";
				}
				return null;
			}
			catch (Exception ex)
			{
				return "Unable to verify safe test context: " + (ex.InnerException ?? ex).Message;
			}
		}

		private bool LiveAllowed()
		{
			return LiveBlockReason() == null;
		}

		private string LiveTestBlockReason()
		{
			object obj = LiveBlockReason();
			if (obj == null)
			{
				if (qaConfirmed)
				{
					return null;
				}
				obj = "Confirm this is a disposable single-player test save.";
			}
			return (string)obj;
		}

		private object QaSubject(bool needHealth = false)
		{
			object[] source = (from x in Parents()
				where (!mutantAdapter || MutantKey(x) == "") && B(x, "SetupDone") && (!needHealth || Exists(Health(x))) && (selectedEnemy == "*" || string.IsNullOrEmpty(selectedEnemy) || EnemyName(x) == selectedEnemy)
				select x).ToArray();
			return source.Where((object x) => !Active(x)).FirstOrDefault() ?? source.FirstOrDefault();
		}

		private void Override(string cat, string name, string field, int value)
		{
			qaOverrides[Key(cat, name, field)] = value;
		}

		private void SetTestRules(string n)
		{
			qaOverrides = new Dictionary<string, int>();
			string[] array = new string[9] { "max active", "max spawns", "max assigned", "min level", "max level", "health", "respawn min seconds", "respawn max seconds", "respawn reduction percent per level" };
			foreach (string field in array)
			{
				Override("enemy", "*", field, -2);
				Override("enemy", n, field, -2);
			}
			Override("enemy", n, "allow", 1);
			Override("enemy", n, "respawn", 1);
			Override("enemy", n, "respawn seconds", 0);
			Override("enemy", n, "max respawns", -2);
			Override("enemy", n, "after extraction", 0);
			Override("orb", n, "allow", 0);
		}

		private void ObserveQaSpawn(object p, bool allowed, string reason)
		{
			SpawnProbe spawnProbe = qaProbe;
			if (spawnProbe != null && spawnProbe.Id == ID(p))
			{
				if (spawnProbe.InCall && !spawnProbe.Seen)
				{
					spawnProbe.Seen = true;
					spawnProbe.Allowed = allowed;
					spawnProbe.Reason = reason;
				}
				else
				{
					spawnProbe.OtherCalls++;
				}
			}
		}

		private string SpawnPatchOwners()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(T("EnemyParent"), "Spawn", Type.EmptyTypes, (Type[])null);
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
				return string.Join(", ", ((patchInfo != null) ? patchInfo.Owners.AsEnumerable() : null) ?? Enumerable.Empty<string>());
			}
			catch
			{
				return "unavailable";
			}
		}

		private IEnumerator QaAttempt(object p, string label, bool expected, string reason, SpawnProbe probe)
		{
			probe.Id = ID(p);
			probe.Before = State(p).Spawns;
			qaProbe = probe;
			try
			{
				if (Active(p))
				{
					Qa("FAIL", label, "Subject already active before attempt; id=" + probe.Id);
					yield break;
				}
				probe.InCall = true;
				try
				{
					Call(p, "Spawn");
				}
				finally
				{
					probe.InCall = false;
				}
				bool immediate = Active(p) && State(p).Spawns == probe.Before + 1;
				float deadline = Time.realtimeSinceStartup + (expected ? 3f : 0.25f);
				while (Exists(p) && Time.realtimeSinceStartup < deadline && (expected ? (!Active(p)) : (!Active(p) && State(p).Spawns == probe.Before)))
				{
					yield return null;
				}
				bool flag = Exists(p) && Active(p);
				int num = (Exists(p) ? (State(p).Spawns - probe.Before) : 0);
				probe.Passed = Exists(p) && probe.Seen && probe.Allowed == expected && flag == expected && num == (expected ? 1 : 0) && ((!expected) ? (probe.Reason == reason) : (probe.Reason == "allowed" && (immediate || probe.OtherCalls == 0)));
				AssertQa(label, probe.Passed, "id=" + probe.Id + "; guard=" + probe.Reason + "; expected " + (expected ? "active/+1" : ("inactive/+0, " + reason)) + "; observed " + (flag ? "active" : "inactive") + "/+" + num + "; immediate=" + immediate + "; additional spawn attempts=" + probe.OtherCalls + (probe.Passed ? "" : ("; Spawn patch owners: " + SpawnPatchOwners())));
			}
			finally
			{
				Plugin plugin = this;
				if (plugin.qaProbe == probe)
				{
					plugin.qaProbe = null;
				}
			}
		}

		private void RunLiveSpawnTests()
		{
			if (qaBusy)
			{
				return;
			}
			RunQuickDiagnostics(export: false);
			qaSuite = "native-spawn";
			string text = LiveTestBlockReason();
			if (text != null)
			{
				Qa("SKIP", "Native spawn suite", text);
				ExportQa();
				return;
			}
			object obj = QaSubject();
			if (!Exists(obj))
			{
				Qa("SKIP", "Native spawn suite", "No initialized instance of the selected monster. Choose All monsters or spawn one manually first.");
				ExportQa();
				return;
			}
			qaBusy = true;
			qaCancel = false;
			qaProgress = "Preparing native spawn tests";
			((MonoBehaviour)this).StartCoroutine(DriveSpawnQa(obj, qaGeneration));
		}

		private IEnumerator DriveSpawnQa(object p, int generation)
		{
			bool priorPause = paused;
			bool priorBypass = bypass;
			float timer = F(p, "DespawnedTimer");
			IEnumerator steps = null;
			try
			{
				yield return null;
				steps = SpawnSteps(p);
				while (true)
				{
					if (qaCancel || generation != qaGeneration || !LiveAllowed() || !Exists(p))
					{
						Qa("SKIP", "Native spawn suite interrupted", "Cancelled, host/map changed or subject unavailable");
						break;
					}
					bool flag;
					try
					{
						flag = steps.MoveNext();
					}
					catch (Exception ex)
					{
						Qa("FAIL", "Native spawn suite", (ex.InnerException ?? ex).Message);
						break;
					}
					if (flag)
					{
						yield return steps.Current;
						continue;
					}
					break;
				}
			}
			finally
			{
				Plugin plugin = this;
				(steps as IDisposable)?.Dispose();
				plugin.qaProbe = null;
				if (generation == plugin.qaGeneration && plugin.LiveAllowed())
				{
					try
					{
						if (Exists(p) && Active(p))
						{
							plugin.Despawn(p);
						}
						if (Exists(p))
						{
							Set(p, "DespawnedTimer", Math.Max(2f, timer));
						}
					}
					catch (Exception ex2)
					{
						plugin.Qa("WARN", "Test subject cleanup", ex2.Message);
					}
					plugin.paused = priorPause;
					plugin.bypass = priorBypass;
				}
				plugin.qaOverrides = null;
				plugin.qaBusy = false;
				plugin.qaCancel = false;
				plugin.capParentsFrame = -1;
				plugin.qaProgress = "Finished";
				plugin.ExportQa();
			}
		}

		private IEnumerator SpawnSteps(object p)
		{
			string n = EnemyName(p);
			paused = false;
			bypass = false;
			SetTestRules(n);
			if (Active(p))
			{
				Despawn(p);
			}
			if (Active(p))
			{
				throw new Exception("Native despawn did not deactivate test subject");
			}
			string[] labels = new string[9]
			{
				"Native disabled monster: " + n,
				"Native per-type concurrent cap",
				"Native global concurrent cap",
				"Native cumulative spawn cap",
				"Native global cumulative cap",
				"Native permitted spawn",
				"Native early respawn blocked",
				"Native respawn count cap",
				"Native respawn permitted after zero delay"
			};
			string[] reasons = new string[9] { "disabled or level restricted", "concurrent cap", "concurrent cap", "lifetime spawn cap", "lifetime spawn cap", null, "respawn timer", "respawn blocked", null };
			for (int i = 0; i < labels.Length; i++)
			{
				qaProgress = labels[i];
				switch (i)
				{
				case 0:
					Override("enemy", n, "allow", 0);
					break;
				case 1:
					Override("enemy", n, "allow", 1);
					Override("enemy", n, "max active", Parents().Count((object x) => Active(x) && EnemyName(x) == n));
					break;
				case 2:
					Override("enemy", n, "max active", -2);
					Override("enemy", "*", "max active", Parents().Count(Active));
					break;
				case 3:
					Override("enemy", "*", "max active", -2);
					Override("enemy", n, "max spawns", ReadCount(spawnCounts, n));
					break;
				case 4:
					Override("enemy", n, "max spawns", -2);
					Override("enemy", "*", "max spawns", totalSpawns);
					break;
				case 5:
					Override("enemy", "*", "max spawns", -2);
					break;
				case 6:
					Override("enemy", n, "respawn seconds", 60);
					break;
				case 7:
					Override("enemy", n, "respawn seconds", 0);
					Override("enemy", n, "max respawns", Math.Max(0, State(p).Spawns - 1));
					break;
				case 8:
					Override("enemy", n, "max respawns", -2);
					break;
				}
				SpawnProbe probe = new SpawnProbe();
				{
					IEnumerator step = QaAttempt(p, labels[i], reasons[i] == null, reasons[i], probe);
					try
					{
						while (step.MoveNext())
						{
							yield return step.Current;
						}
					}
					finally
					{
						IDisposable disposable = step as IDisposable;
						if (disposable != null)
						{
							disposable.Dispose();
						}
					}
				}
				if (!probe.Passed)
				{
					Qa("SKIP", "Remaining native spawn checks", "Stopped at failed prerequisite: " + labels[i]);
					yield break;
				}
				if (Active(p))
				{
					Despawn(p);
				}
				if (Active(p))
				{
					throw new Exception("Native despawn did not deactivate test subject");
				}
			}
			Qa("SKIP", "Real multiplayer, orb creation and extraction", "Not exercised by the native spawn suite");
		}

		private void ExportQa()
		{
			try
			{
				string text = Path.Combine(root, "QA");
				Directory.CreateDirectory(text);
				qaFile = Path.Combine(text, "qa-" + DateTime.Now.ToString("yyyyMMdd-HHmmssfff") + ".txt");
				List<string> list = new List<string>();
				list.Add("SNADDY'S TOOLKIT v1.0.1 | s.naddy");
				list.Add(DateTime.Now.ToString("O"));
				list.Add("Host=" + Host() + " | Level=" + levelNumber + " | Game enabled=" + modEnabled.Value);
				list.Add("Live test readiness: " + (LiveBlockReason() ?? "Ready") + " | Confirmed disposable save: " + qaConfirmed);
				list.Add("Suite: " + qaSuite);
				list.Add("Network: " + NetworkSummary());
				list.Add("Economy: opening $" + (long)openingCurrencyK * 1000L + " / credited $" + (long)earnedK * 1000L + " / ledger valid=" + ledgerValid + " / settled=" + settled);
				list.Add("Reflection metadata cache: " + fieldCache.Count + " field entries / " + propertyCache.Count + " property entries");
				list.Add("PASS=" + qaResults.Count((QaResult x) => x.Status == "PASS") + " FAIL=" + qaResults.Count((QaResult x) => x.Status == "FAIL") + " WARN=" + qaResults.Count((QaResult x) => x.Status == "WARN") + " SKIP=" + qaResults.Count((QaResult x) => x.Status == "SKIP"));
				list.Add("PASS means this particular assertion passed, not overall multiplayer certification.");
				list.Add("");
				List<string> list2 = list;
				list2.AddRange(qaResults.Select((QaResult x) => "[" + x.Status + "] " + x.Name + " | " + x.Detail));
				list2.AddRange(new string[2] { "", "-- Installed hooks --" });
				list2.AddRange(patches);
				list2.AddRange(new string[7]
				{
					"",
					"-- Effective rules (stored scopes) --",
					"Permanent: " + JsonConvert.SerializeObject((object)permanent),
					"Run: " + JsonConvert.SerializeObject((object)run),
					"Level: " + JsonConvert.SerializeObject((object)level),
					"",
					"-- Recent events --"
				});
				list2.AddRange(logs);
				File.WriteAllLines(qaFile, list2);
				File.Copy(qaFile, Path.Combine(root, "qa-latest.txt"), overwrite: true);
				File.Copy(qaFile, Path.Combine(text, "qa-latest.txt"), overwrite: true);
				File.Copy(qaFile, Path.Combine(text, "qa-" + qaSuite + "-latest.txt"), overwrite: true);
				message = "QA report saved to qa-latest.txt";
			}
			catch (Exception e)
			{
				Error("QA export", e);
			}
		}

		private void DrawQaSummary()
		{
			if (qaResults.Count == 0)
			{
				return;
			}
			Section("Latest automatic test results");
			GUILayout.Label(qaResults.Count((QaResult x) => x.Status == "PASS") + " passed  |  " + qaResults.Count((QaResult x) => x.Status == "FAIL") + " failed  |  " + qaResults.Count((QaResult x) => x.Status == "WARN") + " warnings  |  " + qaResults.Count((QaResult x) => x.Status == "SKIP") + " skipped", heading, Array.Empty<GUILayoutOption>());
			foreach (QaResult item in qaResults.Where((QaResult x) => x.Status != "PASS" || Advanced).Take(120))
			{
				GUILayout.Label("[" + item.Status + "] " + item.Name + ": " + item.Detail, Array.Empty<GUILayoutOption>());
			}
			if (!Advanced)
			{
				Hint("Advanced shows successful assertions too. Export includes everything.");
			}
			if (GUILayout.Button("Export latest QA report", Array.Empty<GUILayoutOption>()))
			{
				ExportQa();
			}
			Hint(string.IsNullOrEmpty(qaFile) ? "No report exported yet." : "Report: BepInEx/config/SnaddysToolkit/qa-latest.txt");
		}

		private void SafeQaAction(Action a)
		{
			try
			{
				a();
			}
			catch (Exception ex)
			{
				Qa("FAIL", "QA action", (ex.InnerException ?? ex).Message);
				if (!qaBusy)
				{
					qaOverrides = null;
				}
				ExportQa();
			}
		}

		private void AutomatedTestsMenu()
		{
			Section("Automatic tests");
			Hint("Quick diagnostics checks the installed hooks, rule calculations, registry and current limits without changing the map.");
			GUI.enabled = !qaBusy;
			if (GUILayout.Button("Run quick diagnostics", selectedButton, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(48f) }))
			{
				SafeQaAction(RunQuickDiagnostics);
			}
			GUI.enabled = true;
			Hint("Selected monster: " + ((string.IsNullOrEmpty(selectedEnemy) || selectedEnemy == "*") ? "automatic" : selectedEnemy) + ". Select another monster under Monsters, or use the manual picker below.");
			if (GUILayout.Button("Use any initialized monster", Array.Empty<GUILayoutOption>()))
			{
				selectedEnemy = "*";
			}
			Hint("Native spawn suite exercises real Spawn and Despawn calls. It uses the selected initialized monster, or picks one if All monsters is selected. Temporary rules are restored; actual spawn counters and the test monster are changed. Only use a disposable single-player save.");
			string text = LiveBlockReason();
			Hint((text == null) ? "READY: Offline gameplay map detected." : ("NOT READY: " + text));
			GUI.enabled = text == null && !qaBusy;
			qaConfirmed = GUILayout.Toggle(qaConfirmed, "I am in a disposable single-player test save", Array.Empty<GUILayoutOption>());
			GUI.enabled = text == null && qaConfirmed && !qaBusy;
			if (GUILayout.Button("Run automatic native spawn tests", selectedButton, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(48f) }))
			{
				SafeQaAction(RunLiveSpawnTests);
			}
			Hint("Orb sequence: real kill and orb creation on the same monster. Checks three real drops ($10,000 / $7,500 / $5,625), concurrent capacity, personal and global lifetime limits. Other orbs are left alone. May take several seconds.");
			if (GUILayout.Button("Run automatic live orb tests", selectedButton, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(48f) }))
			{
				SafeQaAction(StartOrbQa);
			}
			Hint("Valuable suite: checks blocked external spawn requests, allowed spawn and the actual initialized value using REPOLib. Selected valuable: " + (string.IsNullOrEmpty(selectedLoot) ? "automatic" : selectedLoot));
			if (GUILayout.Button("Run automatic valuable tests", selectedButton, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(48f) }))
			{
				SafeQaAction(RunLiveLootTests);
			}
			Hint("Native stat roundtrip uses synthetic revenue in a disposable offline save and restores original balances. It does not test actual departure.");
			if (GUILayout.Button("Run automatic economy stat tests", selectedButton, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(48f) }))
			{
				SafeQaAction(RunEconomyStatQa);
			}
			GUI.enabled = true;
			MultiplayerAuditMenu();
			if (qaBusy)
			{
				Hint("Test running: " + qaProgress);
				if (GUILayout.Button("Cancel live test", Array.Empty<GUILayoutOption>()))
				{
					qaCancel = true;
				}
			}
			DrawQaSummary();
			if (!qaBusy)
			{
				Section("Manual test controls");
			}
		}

		private bool PrepareConfiguration()
		{
			try
			{
				if (Chainloader.PluginInfos.ContainsKey("nl.solveonstudios.repo.hostgamemanager"))
				{
					((BaseUnityPlugin)this).Logger.LogError((object)"An older Toolkit plugin is loaded. Remove the duplicate DLL and restart R.E.P.O.");
					return false;
				}
				root = Path.Combine(Paths.ConfigPath, "SnaddysToolkit");
				settingsFile = Path.Combine(root, "settings.json");
				Directory.CreateDirectory(root);
				string path = Path.Combine(root, ".migration-v1-complete");
				if (File.Exists(path))
				{
					return true;
				}
				string path2 = Path.Combine(Paths.ConfigPath, "HostGameManager");
				bool flag = CopyIfMissing(Path.Combine(Paths.ConfigPath, "nl.solveonstudios.repo.hostgamemanager.cfg"), ((BaseUnityPlugin)this).Config.ConfigFilePath);
				if (flag || File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
				{
					((BaseUnityPlugin)this).Config.Reload();
				}
				int num = 0;
				if (Directory.Exists(path2))
				{
					foreach (string item in Directory.EnumerateFiles(path2, "*", SearchOption.TopDirectoryOnly))
					{
						string fileName = Path.GetFileName(item);
						if ((!(fileName != "settings.json") || !(fileName != "settings.json.bak") || (fileName.StartsWith("profile_", StringComparison.Ordinal) && fileName.EndsWith(".json", StringComparison.Ordinal))) && CopyIfMissing(item, Path.Combine(root, fileName)))
						{
							num++;
						}
					}
				}
				File.WriteAllText(path, "Configuration migration completed. Original files retained.\n");
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Configuration migration complete: " + num + " rule/profile file(s), preferences copied=" + flag + ". Existing Toolkit settings take precedence."));
				return true;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Configuration migration failed; Toolkit disabled to avoid losing settings. " + ex));
				return false;
			}
		}

		private static bool CopyIfMissing(string source, string destination)
		{
			if (!File.Exists(source) || File.Exists(destination))
			{
				return false;
			}
			string text = destination + ".migration-" + System.Guid.NewGuid().ToString("N") + ".tmp";
			try
			{
				File.Copy(source, text, overwrite: false);
				if (File.Exists(destination))
				{
					return false;
				}
				File.Move(text, destination);
				return true;
			}
			finally
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
		}

		private void ResetEconomy()
		{
			openingCurrencyK = (openingHaulK = -1);
			creditedCurrencyK = (creditedHaulK = (earnedK = 0));
			ledgerValid = true;
			extractionLedger.Clear();
			exemptHeads.Clear();
			departurePlan = null;
			settled = false;
			forceDeparture = false;
			blockedDeparture = null;
			blockedRunManager = null;
			retryDepartureAt = 0f;
		}

		private bool CaptureOpening()
		{
			if (openingCurrencyK >= 0 && openingHaulK >= 0)
			{
				return true;
			}
			try
			{
				if (!Exists(S("StatsManager")) || !Exists(S("PunManager")))
				{
					return false;
				}
				int num = Currency();
				int num2 = Haul();
				if (num < 0 || num2 < 0)
				{
					return false;
				}
				openingCurrencyK = num;
				openingHaulK = num2;
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static void BeforeExtraction(object __instance, out CreditProbe __state)
		{
			__state = null;
			if (!Host() || !InLevel() || !B(__instance, "stateStart") || B(__instance, "isShop"))
			{
				return;
			}
			try
			{
				if (!P.CaptureOpening())
				{
					P.ledgerValid = false;
					return;
				}
				__state = new CreditProbe
				{
					Currency = Currency(),
					Haul = Haul(),
					Point = ID(__instance)
				};
			}
			catch (Exception e)
			{
				P.ledgerValid = false;
				P.Error("Extraction ledger capture", e);
			}
		}

		private static void AfterExtraction(CreditProbe __state)
		{
			if (__state == null || !Host())
			{
				return;
			}
			try
			{
				int num = Currency() - __state.Currency;
				int num2 = Haul() - __state.Haul;
				if (num != 0 || num2 != 0)
				{
					if (num < 0 || num2 < 0 || num != num2)
					{
						P.ledgerValid = false;
						P.Log("Extraction ledger mismatch; departure penalty will be suspended: currency delta " + num + " / haul delta " + num2);
						return;
					}
					P.creditedCurrencyK = ClampMoney((double)P.creditedCurrencyK + (double)num);
					P.creditedHaulK = ClampMoney((double)P.creditedHaulK + (double)num2);
					P.earnedK = Math.Min(P.creditedCurrencyK, P.creditedHaulK);
					string text = "Extraction " + __state.Point + ": $" + (long)num * 1000L + " credited; level $" + (long)P.earnedK * 1000L;
					P.extractionLedger.Add(text);
					P.Log(text);
				}
			}
			catch (Exception e)
			{
				P.ledgerValid = false;
				P.Error("Extraction ledger accounting", e);
			}
		}

		private IEnumerable<object> TruckOrbs()
		{
			return (from g in (from x in ((IEnumerable<object>)Find("EnemyValuable")).Select((Func<object, Component>)delegate(object x)
					{
						Component val = (Component)((x is Component) ? x : null);
						object obj = ((val != null) ? val.GetComponentInParent(T("ValuableObject")) : null);
						if (obj == null)
						{
							if (val == null)
							{
								return (Component)null;
							}
							obj = val.GetComponentInChildren(T("ValuableObject"), true);
						}
						return (Component)obj;
					})
					where Exists(x) && B(Get(x, "roomVolumeCheck"), "inTruck") && !B(x, "committedToExtraction") && B(x, "dollarValueSet") && F(x, "dollarValueCurrent") > 0f
					select x).GroupBy(ID)
				select g.First()).OrderBy(ID);
		}

		private bool ConnectedAvatar(object avatar)
		{
			if (!QaMultiplayer())
			{
				return true;
			}
			try
			{
				object obj = Get(avatar, "photonView");
				PhotonView val = (PhotonView)((obj is PhotonView) ? obj : null);
				return (Object)(object)val != (Object)null && val.Owner != null && PhotonNetwork.CurrentRoom != null && PhotonNetwork.CurrentRoom.Players.ContainsKey(val.Owner.ActorNumber) && !val.Owner.IsInactive;
			}
			catch
			{
				return false;
			}
		}

		private List<HeadObservation> ObserveHeads()
		{
			object[] source = Find("PlayerDeathHead").Where(Exists).ToArray();
			IEnumerable<object> enumerable = from g in Items(Get(S("GameDirector"), "PlayerList")).Concat(Find("PlayerAvatar")).Concat(source.Select((object h) => Get(h, "playerAvatar"))).Where(Exists)
					.GroupBy(ID)
				select g.First();
			List<HeadObservation> list = new List<HeadObservation>();
			using IEnumerator<object> enumerator = enumerable.GetEnumerator();
			object obj;
			HeadObservation obj4;
			int headActive;
			HeadObservation headObservation;
			for (; enumerator.MoveNext(); obj4.HeadActive = (byte)headActive != 0, obj4.Triggered = B(obj, "triggered"), obj4.TruckFlag = B(obj, "inTruck"), obj4.RoomTruckFlag = B(Get(obj, "roomVolumeCheck"), "inTruck"), obj4.Exempt = exemptHeads.Contains(ID(obj)), headObservation = obj4, headObservation.Reason = ((!headObservation.Connected) ? "Disconnected" : ((!headObservation.Dead) ? "Alive" : ((!Exists(obj) || !headObservation.HeadActive) ? "Head absent or inactive" : ((!headObservation.Triggered) ? "Head not triggered" : ((headObservation.TruckFlag || headObservation.RoomTruckFlag) ? "Recovered in truck" : (headObservation.Exempt ? "Host exempted" : "Missing recoverable head")))))), list.Add(headObservation))
			{
				object avatar = enumerator.Current;
				obj = Get(avatar, "playerDeathHead");
				object obj2 = source.FirstOrDefault((object h) => ID(Get(h, "playerAvatar")) == ID(avatar) && B(h, "triggered"));
				if (Exists(obj2))
				{
					if (Exists(obj) && B(obj, "triggered"))
					{
						Component val = (Component)((obj is Component) ? obj : null);
						if (val != null && val.gameObject.activeInHierarchy)
						{
							goto IL_016e;
						}
					}
					obj = obj2;
				}
				goto IL_016e;
				IL_016e:
				object obj3 = Get(avatar, "photonView");
				PhotonView val2 = (PhotonView)((obj3 is PhotonView) ? obj3 : null);
				obj4 = new HeadObservation
				{
					AvatarId = ID(avatar),
					HeadId = ID(obj),
					Actor = (((Object)(object)val2 != (Object)null && val2.Owner != null) ? val2.Owner.ActorNumber : 0),
					Player = ((Get(avatar, "playerName") as string) ?? "Unknown player"),
					Head = obj
				};
				object obj5 = avatar;
				Component val3 = (Component)((obj5 is Component) ? obj5 : null);
				obj4.AvatarActive = val3 != null && val3.gameObject.activeInHierarchy;
				obj4.Dead = B(avatar, "isDisabled");
				obj4.Connected = ConnectedAvatar(avatar);
				if (Exists(obj))
				{
					Component val4 = (Component)((obj is Component) ? obj : null);
					if (val4 != null)
					{
						headActive = (val4.gameObject.activeInHierarchy ? 1 : 0);
						continue;
					}
				}
				headActive = 0;
			}
			return list;
		}

		private IEnumerable<object> MissingHeads()
		{
			return from g in (from x in ObserveHeads()
					where x.Reason == "Missing recoverable head"
					select x.Head).Where(Exists).GroupBy(ID)
				select g.First();
		}

		private void ExportHeadDiagnostics()
		{
			if (!Host() || !InLevel())
			{
				throw new InvalidOperationException("Enter a gameplay map as host first");
			}
			List<HeadObservation> list = ObserveHeads();
			string text = Path.Combine(root, "QA");
			Directory.CreateDirectory(text);
			File.WriteAllText(contents: JsonConvert.SerializeObject((object)new
			{
				Version = "1.0.1",
				Level = levelNumber,
				Timestamp = DateTime.Now.ToString("O"),
				HeadMode = R("escape", "*", "head mode"),
				Rate = R("escape", "*", "penalty percent"),
				FixedPenalty = R("escape", "*", "fixed penalty"),
				LedgerValid = ledgerValid,
				EarnedK = earnedK,
				OpeningCurrencyK = openingCurrencyK,
				CurrentCurrencyK = Currency(),
				Heads = list
			}, (Formatting)1), path: Path.Combine(text, "head-recovery-latest.json"));
			Log("Head recovery diagnostic: " + list.Count + " roster entries; " + list.Count((HeadObservation x) => x.Reason == "Missing recoverable head") + " missing. Exported QA/head-recovery-latest.json");
		}

		private object[] EligibleTruckOrbs()
		{
			if (R("escape", "*", "truck orbs") != 1)
			{
				return Array.Empty<object>();
			}
			int num = R("escape", "*", "max truck orbs");
			object[] array = TruckOrbs().ToArray();
			return array.Take((num < 0) ? array.Length : num).ToArray();
		}

		private int BonusFor(object[] orbs)
		{
			int num = R("escape", "*", "max bonus");
			int num2 = R("escape", "*", "bonus percent");
			double num3 = ((IEnumerable<object>)orbs).Sum((Func<object, double>)((object x) => F(x, "dollarValueCurrent")));
			if (num2 >= 0)
			{
				num3 *= (double)num2 / 100.0;
			}
			if (num >= 0)
			{
				num3 = Math.Min(num3, num);
			}
			return ClampMoney(num3);
		}

		private int BonusDollars()
		{
			return BonusFor(EligibleTruckOrbs());
		}

		private static SettlementPlan PlanSettlement(int openingCurrency, int openingHaul, int currentCurrency, int currentHaul, int earned, int bonusDollars, int rate, int missing, bool valid, int fixedPenaltyDollars = -1, int maxPenaltyPercent = 100)
		{
			int num = Math.Max(0, bonusDollars) / 1000;
			int num2 = ClampMoney((double)Math.Max(0, earned) + (double)num);
			int val = (valid ? ((fixedPenaltyDollars >= 0) ? Math.Min(num2, ClampMoney((double)fixedPenaltyDollars * (double)Math.Max(0, missing) / 1000.0)) : CalculatePenalty(num2, rate, missing)) : 0);
			val = Math.Min(val, CalculatePenalty(num2, Mathf.Clamp(maxPenaltyPercent, 0, 100), 1));
			int val2 = ClampMoney(Math.Max(0.0, (double)currentCurrency - (double)openingCurrency) + (double)num);
			int val3 = ClampMoney(Math.Max(0.0, (double)currentHaul - (double)openingHaul) + (double)num);
			int num3 = Math.Min(val, Math.Min(val2, val3));
			return new SettlementPlan
			{
				OpeningCurrencyK = openingCurrency,
				OpeningHaulK = openingHaul,
				ExtractionK = earned,
				BonusDollars = bonusDollars,
				BonusK = num,
				MissingHeads = missing,
				Rate = rate,
				RequestedPenaltyK = val,
				AppliedPenaltyK = num3,
				CurrencyBeforeK = currentCurrency,
				HaulBeforeK = currentHaul,
				CurrencyAfterK = ClampMoney((double)currentCurrency + (double)num - (double)num3),
				HaulAfterK = ClampMoney((double)currentHaul + (double)num - (double)num3)
			};
		}

		private SettlementPlan BuildDeparturePlan(object[] heads, bool includeAudit = false)
		{
			if (!CaptureOpening())
			{
				ledgerValid = false;
				throw new InvalidOperationException("Native run stats not ready");
			}
			object[] array = EligibleTruckOrbs();
			int num = R("escape", "*", "head mode");
			int num2 = ((num == 1) ? Math.Max(0, R("escape", "*", "penalty percent")) : 0);
			int num3 = ((num == 1) ? R("escape", "*", "fixed penalty") : (-1));
			int num4 = R("escape", "*", "max penalty percent");
			if (num != 1)
			{
				num4 = 0;
			}
			else if (num4 < 0)
			{
				num4 = 100;
			}
			int num5 = R("escape", "*", "penalty growth percent");
			if (num == 1 && num5 >= 0)
			{
				num2 = ClampMoney(Scale(num2, num5, 1, levelNumber));
				if (num3 >= 0)
				{
					num3 = ClampMoney(Scale(num3, num5, 1, levelNumber));
				}
			}
			SettlementPlan settlementPlan = PlanSettlement(openingCurrencyK, openingHaulK, Currency(), Haul(), earnedK, BonusFor(array), num2, heads.Length, ledgerValid, num3, num4);
			settlementPlan.HeadMode = Math.Max(0, num);
			settlementPlan.FixedPenalty = num3 >= 0;
			settlementPlan.Credits = extractionLedger.ToArray();
			settlementPlan.Orbs = array.Select((object x) => ID(x) + ": $" + F(x, "dollarValueCurrent").ToString("0")).ToArray();
			if (includeAudit)
			{
				settlementPlan.HeadAudit = ObserveHeads();
			}
			settlementPlan.Missing = heads.Select((object x) => ID(x) + ": " + ((Get(Get(x, "playerAvatar"), "playerName") as string) ?? "Unknown player")).ToArray();
			return settlementPlan;
		}

		private bool SettleDeparture()
		{
			if (settled)
			{
				return true;
			}
			if (departurePlan == null)
			{
				object[] array = MissingHeads().ToArray();
				if (R("escape", "*", "head mode") == 2 && array.Length != 0 && !forceDeparture)
				{
					Block("Departure denied: " + array.Length + " recoverable heads missing. Recover, exempt or use host override.");
					return false;
				}
				departurePlan = BuildDeparturePlan(array, includeAudit: true);
			}
			SettlementPlan settlementPlan = departurePlan;
			if (!settlementPlan.CurrencyWritten)
			{
				int num = Currency();
				if (num != settlementPlan.CurrencyBeforeK && num != settlementPlan.CurrencyAfterK)
				{
					throw new InvalidOperationException("Currency changed during settlement; refusing stale write");
				}
				if (num != settlementPlan.CurrencyAfterK)
				{
					Call(T("SemiFunc"), "StatSetRunCurrency", settlementPlan.CurrencyAfterK);
				}
				if (Currency() != settlementPlan.CurrencyAfterK)
				{
					throw new InvalidOperationException("Currency settlement did not commit");
				}
				settlementPlan.CurrencyWritten = true;
			}
			if (!settlementPlan.HaulWritten)
			{
				int num2 = Haul();
				if (num2 != settlementPlan.HaulBeforeK && num2 != settlementPlan.HaulAfterK)
				{
					throw new InvalidOperationException("Haul changed during settlement; refusing stale write");
				}
				if (num2 != settlementPlan.HaulAfterK)
				{
					Call(T("SemiFunc"), "StatSetRunTotalHaul", settlementPlan.HaulAfterK);
				}
				if (Haul() != settlementPlan.HaulAfterK)
				{
					throw new InvalidOperationException("Haul settlement did not commit");
				}
				settlementPlan.HaulWritten = true;
			}
			settled = true;
			blockedDeparture = null;
			blockedRunManager = null;
			forceDeparture = false;
			try
			{
				if (PhotonNetwork.InRoom)
				{
					PhotonNetwork.SendAllOutgoingCommands();
				}
				object o = S("CurrencyUI");
				if (Exists(o))
				{
					Call(o, "FetchCurrency");
				}
			}
			catch (Exception e)
			{
				Error("Settlement display/flush", e);
			}
			Log("Departure settlement: extraction $" + (long)settlementPlan.ExtractionK * 1000L + " / truck bonus $" + (long)settlementPlan.BonusK * 1000L + " / penalty $" + (long)settlementPlan.AppliedPenaltyK * 1000L + " / missing " + settlementPlan.MissingHeads + " / balance $" + (long)settlementPlan.CurrencyAfterK * 1000L);
			if (!ledgerValid || settlementPlan.AppliedPenaltyK < settlementPlan.RequestedPenaltyK)
			{
				Log("Settlement warning: incomplete ledger or protected opening funds; full requested penalty not charged.");
			}
			ExportSettlement();
			ShowCommittedEconomy(settlementPlan);
			return true;
		}

		private void ExportSettlement()
		{
			try
			{
				string text = Path.Combine(root, "QA");
				Directory.CreateDirectory(text);
				string contents = JsonConvert.SerializeObject((object)new
				{
					Version = "1.0.1",
					Level = levelNumber,
					Timestamp = DateTime.Now.ToString("O"),
					Multiplayer = QaMultiplayer(),
					LedgerValid = ledgerValid,
					Settled = settled,
					Plan = departurePlan
				}, (Formatting)1);
				File.WriteAllText(Path.Combine(text, "settlement-" + DateTime.Now.ToString("yyyyMMdd-HHmmssfff") + ".json"), contents);
				File.WriteAllText(Path.Combine(text, "settlement-latest.json"), contents);
			}
			catch (Exception e)
			{
				Error("Settlement export", e);
			}
		}

		private bool EscapeActive()
		{
			if (Host() && InLevel())
			{
				if (!modEnabled.Value || !HasCategory("escape"))
				{
					return departurePlan != null;
				}
				return true;
			}
			return false;
		}

		private bool SuccessfulDepartureReady()
		{
			if (B(S("RoundDirector"), "allExtractionPointsCompleted"))
			{
				return !B(S("RunManager"), "restarting");
			}
			return false;
		}

		private static bool BeforeDeparture(object __instance)
		{
			if ((Object)(object)P == (Object)null || !P.EscapeActive() || !P.SuccessfulDepartureReady() || P.settled)
			{
				return true;
			}
			try
			{
				if (P.departurePlan == null && P.R("escape", "*", "head mode") == 2 && !P.forceDeparture)
				{
					int num = P.MissingHeads().Count();
					if (num > 0)
					{
						P.blockedDeparture = __instance;
						P.Block("Departure denied: " + num + " recoverable heads missing. Recover, exempt or use host override.");
						return false;
					}
				}
				return true;
			}
			catch (Exception e)
			{
				P.blockedDeparture = __instance;
				P.Error("Departure eligibility", e);
				return false;
			}
		}

		private static bool BeforeChangeLevel(object __instance, object[] __args)
		{
			bool flag = default(bool);
			int num2;
			if (!((Object)(object)P == (Object)null) && P.EscapeActive() && __args.Length == 3)
			{
				object obj = __args[0];
				if (obj is bool && (bool)obj)
				{
					obj = __args[1];
					int num;
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
					num2 = ((num == 0) ? 1 : 0);
					goto IL_0052;
				}
			}
			num2 = 1;
			goto IL_0052;
			IL_0052:
			if (((uint)num2 | (flag ? 1u : 0u)) != 0 || Convert.ToInt32(__args[2]) != 0 || !P.SuccessfulDepartureReady())
			{
				return true;
			}
			try
			{
				if (P.SettleDeparture())
				{
					return true;
				}
				P.blockedRunManager = __instance;
				return false;
			}
			catch (Exception e)
			{
				P.blockedRunManager = __instance;
				P.Error("Level transition settlement blocked; see Diagnostics", e);
				P.ExportSettlement();
				return false;
			}
		}

		private bool HasBlockedDeparture()
		{
			if (!Exists(blockedDeparture))
			{
				return Exists(blockedRunManager);
			}
			return true;
		}

		private void RetryDeparture()
		{
			if (!Host() || !SuccessfulDepartureReady())
			{
				return;
			}
			object o = blockedDeparture;
			object obj = blockedRunManager;
			if (Exists(o))
			{
				Call(o, "GotoNextLevel");
			}
			else if (Exists(obj))
			{
				MethodInfo methodInfo = obj.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Single((MethodInfo x) => x.Name == "ChangeLevel" && x.GetParameters().Length == 3);
				Call(obj, "ChangeLevel", true, false, Enum.ToObject(methodInfo.GetParameters()[2].ParameterType, 0));
			}
		}

		private void EconomyTick()
		{
			if (!InLevel())
			{
				return;
			}
			if (openingCurrencyK < 0)
			{
				CaptureOpening();
			}
			if (!HasBlockedDeparture() || !SuccessfulDepartureReady() || Time.unscaledTime < retryDepartureAt || departurePlan != null)
			{
				return;
			}
			retryDepartureAt = Time.unscaledTime + 1f;
			try
			{
				if (!modEnabled.Value || R("escape", "*", "head mode") != 2 || forceDeparture || !MissingHeads().Any())
				{
					RetryDeparture();
				}
			}
			catch (Exception e)
			{
				Error("Retry departure", e);
			}
		}

		private void EconomyQa()
		{
			Case("Economy preserves opening funds", delegate
			{
				SettlementPlan settlementPlan = PlanSettlement(50, 90, 150, 190, 100, 0, 20, 2, valid: true);
				return settlementPlan.AppliedPenaltyK == 40 && settlementPlan.CurrencyAfterK == 110 && settlementPlan.HaulAfterK == 150;
			});
			Case("Economy includes truck bonus", delegate
			{
				SettlementPlan settlementPlan = PlanSettlement(50, 90, 150, 190, 100, 20000, 20, 1, valid: true);
				return settlementPlan.BonusK == 20 && settlementPlan.AppliedPenaltyK == 24 && settlementPlan.CurrencyAfterK == 146;
			});
			Case("Economy 100% maximum and spent funds", delegate
			{
				SettlementPlan settlementPlan = PlanSettlement(50, 90, 70, 190, 100, 5000, 50, 5, valid: true);
				return settlementPlan.RequestedPenaltyK == 105 && settlementPlan.AppliedPenaltyK == 25 && settlementPlan.CurrencyAfterK == 50;
			});
			Case("Economy native precision", delegate
			{
				SettlementPlan settlementPlan = PlanSettlement(50, 90, 150, 190, 100, 1999, 0, 0, valid: true);
				return settlementPlan.BonusK == 1 && settlementPlan.CurrencyAfterK == 151;
			});
			Case("Economy invalid ledger does not debit", () => PlanSettlement(50, 90, 150, 190, 100, 10000, 20, 1, valid: false).AppliedPenaltyK == 0);
			Case("Fixed penalty and percentage ceiling", () => PlanSettlement(50, 90, 150, 190, 100, 0, 20, 2, valid: true, 40000, 30).AppliedPenaltyK == 30);
		}

		private static string Cash(long k)
		{
			return "$" + (k * 1000).ToString("N0", CultureInfo.InvariantCulture);
		}

		private static long Net(EconomyView v)
		{
			return (long)v.ExtractionK + (long)v.BonusK - v.PenaltyK;
		}

		private bool FinancialDisplayEnabled()
		{
			if (R("escape", "*", "truck orbs") != 1)
			{
				return R("escape", "*", "head mode") > 0;
			}
			return true;
		}

		private EconomyView ToEconomyView(SettlementPlan p, bool final)
		{
			return new EconomyView
			{
				Level = levelNumber,
				ExtractionK = p.ExtractionK,
				BonusK = p.BonusK,
				PenaltyK = p.AppliedPenaltyK,
				RequestedK = p.RequestedPenaltyK,
				Missing = p.MissingHeads,
				Rate = p.Rate,
				BalanceK = p.CurrencyAfterK,
				Mode = p.HeadMode,
				OrbCount = ((p.Orbs != null) ? p.Orbs.Length : 0),
				LedgerValid = ledgerValid,
				FixedPenalty = p.FixedPenalty,
				Final = final
			};
		}

		private void ClearEconomyDisplayRoom()
		{
			liveEconomy = (lastEconomy = (demoEconomy = null));
			liveEconomyUntil = (finalEconomyUntil = (demoEconomyUntil = 0f));
			economySequence = (receivedEconomySequence = 0);
		}

		private void PublishEconomyView(EconomyView view)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			if (!Host())
			{
				return;
			}
			view.Sequence = ++economySequence;
			AcceptEconomyView(view);
			if (authorityRoom != null && !migrated && PhotonNetwork.IsMasterClient)
			{
				PhotonNetwork.RaiseEvent((byte)173, (object)new object[2]
				{
					"s.naddy.toolkit.economy.display/1",
					JsonConvert.SerializeObject((object)view)
				}, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				}, SendOptions.SendReliable);
				if (view.Final)
				{
					PhotonNetwork.SendAllOutgoingCommands();
				}
			}
		}

		private void AcceptEconomyView(EconomyView v)
		{
			if (v.Final)
			{
				lastEconomy = v;
				finalEconomyUntil = Time.unscaledTime + 90f;
				finalVisibleSeconds = 14f;
				lastEconomyPaintFrame = -1;
				liveEconomy = null;
				liveEconomyUntil = 0f;
			}
			else
			{
				liveEconomy = v;
				liveEconomyUntil = Time.unscaledTime + 5f;
			}
		}

		private void ReceiveEconomyDisplay(EventData ev, string json)
		{
			if (authorityRoom != null && !migrated && !PhotonNetwork.IsMasterClient && ev.Sender == initialMaster && ev.Sender == authorityRoom.MasterClientId && json.Length <= 2048)
			{
				EconomyView economyView = JsonConvert.DeserializeObject<EconomyView>(json);
				if (economyView != null && economyView.Sequence > receivedEconomySequence && economyView.Level >= 1 && economyView.ExtractionK >= 0 && economyView.BonusK >= 0 && economyView.PenaltyK >= 0 && economyView.RequestedK >= economyView.PenaltyK && economyView.PenaltyK <= (long)economyView.ExtractionK + (long)economyView.BonusK && economyView.BalanceK >= 0 && economyView.Missing >= 0 && economyView.Rate >= 0 && economyView.Mode >= 0 && economyView.Mode <= 2 && economyView.OrbCount >= 0)
				{
					receivedEconomySequence = economyView.Sequence;
					AcceptEconomyView(economyView);
				}
			}
		}

		private void EconomyDisplayTick()
		{
			if (!Host() || qaBusy || !modEnabled.Value || !InLevel() || !SuccessfulDepartureReady() || settled || departurePlan != null || !FinancialDisplayEnabled())
			{
				liveEconomy = null;
				return;
			}
			try
			{
				if (openingCurrencyK >= 0 && openingHaulK >= 0)
				{
					PublishEconomyView(ToEconomyView(BuildDeparturePlan(MissingHeads().ToArray()), final: false));
				}
			}
			catch (Exception ex)
			{
				Block("Economy preview unavailable: " + ex.Message);
			}
		}

		private void ShowCommittedEconomy(SettlementPlan p)
		{
			if (!FinancialDisplayEnabled() && p.BonusK == 0 && p.AppliedPenaltyK == 0)
			{
				return;
			}
			try
			{
				PublishEconomyView(ToEconomyView(p, final: true));
			}
			catch (Exception e)
			{
				Error("Economy display broadcast", e);
			}
		}

		private void DemoEconomyDisplay()
		{
			if (Host())
			{
				demoEconomy = new EconomyView
				{
					Final = true,
					Level = levelNumber,
					ExtractionK = 100,
					BonusK = 20,
					PenaltyK = 48,
					RequestedK = 48,
					Missing = 2,
					Rate = 20,
					BalanceK = 122,
					Mode = 1,
					OrbCount = 2,
					LedgerValid = true
				};
				demoEconomyUntil = Time.unscaledTime + 14f;
				Close();
			}
		}

		private void EnsureEconomyStyles()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//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_00b1: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			if (economyTitle == null)
			{
				economyTitle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 26,
					fontStyle = (FontStyle)1,
					alignment = (TextAnchor)4,
					wordWrap = false
				};
				economyLabel = new GUIStyle(GUI.skin.label)
				{
					fontSize = 21,
					alignment = (TextAnchor)3,
					wordWrap = false
				};
				economyAmount = new GUIStyle(GUI.skin.label)
				{
					fontSize = 31,
					fontStyle = (FontStyle)1,
					alignment = (TextAnchor)5,
					wordWrap = false
				};
				economyTotal = new GUIStyle(economyTitle)
				{
					fontSize = 43
				};
				economySmall = new GUIStyle(GUI.skin.label)
				{
					fontSize = 15,
					alignment = (TextAnchor)4,
					wordWrap = false
				};
			}
		}

		private void EconomyText(Rect rect, string text, GUIStyle style, Color color)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			style.normal.textColor = color;
			GUI.Label(rect, text, style);
		}

		private void EconomyRect(Rect rect, Color color)
		{
			//IL_0000: 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_0011: Unknown result type (might be due to invalid IL or missing references)
			GUI.color = color;
			GUI.DrawTexture(rect, (Texture)(object)Texture2D.whiteTexture);
			GUI.color = Color.white;
		}

		private void EconomyRow(float x, float y, float w, string label, string amount, Color c)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			EconomyText(new Rect(x, y, w * 0.55f, 40f), label, economyLabel, Ink);
			EconomyText(new Rect(x + w * 0.48f, y, w * 0.52f, 40f), amount, economyAmount, c);
		}

		private string EconomyHeads(EconomyView v)
		{
			if (v.Mode != 2)
			{
				if (v.Mode != 1)
				{
					return "Head penalty disabled";
				}
				return v.Missing + " missing heads" + (v.FixedPenalty ? " | fixed penalty" : (" | " + v.Rate + "% each"));
			}
			return v.Missing + " missing heads | recovery required";
		}

		private void DrawEconomyOverlay()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			//IL_0652: Unknown result type (might be due to invalid IL or missing references)
			//IL_0658: Unknown result type (might be due to invalid IL or missing references)
			//IL_065f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0666: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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_00db: 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_00f9: 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_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: 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)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0507: Unknown result type (might be due to invalid IL or missing references)
			//IL_050c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			//IL_0528: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_063f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0646: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0420: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Unknown result type (might be due to invalid IL or missing references)
			//IL_0483: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a3: Unknown result type (might be due to invalid IL or missing references)
			if ((int)Event.current.type != 7 || migrated)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			bool flag = demoEconomy != null && unscaledTime < demoEconomyUntil;
			EconomyView economyView = (flag ? demoEconomy : ((lastEconomy != null && unscaledTime < finalEconomyUntil && finalVisibleSeconds > 0f) ? lastEconomy : ((liveEconomy != null && unscaledTime < liveEconomyUntil && InLevel()) ? liveEconomy : null)));
			if (economyView == null)
			{
				return;
			}
			if (economyView.Final && !flag && lastEconomyPaintFrame != Time.frameCount)
			{
				lastEconomyPaintFrame = Time.frameCount;
				finalVisibleSeconds -= Mathf.Min(0.1f, Time.unscaledDeltaTime);
			}
			Matrix4x4 matrix = GUI.matrix;
			Color color = GUI.color;
			Color contentColor = GUI.contentColor;
			Color backgroundColor = GUI.backgroundColor;
			int depth = GUI.depth;
			try
			{
				EnsureEconomyStyles();
				GUI.depth = -9000;
				GUI.color = (GUI.contentColor = (GUI.backgroundColor = Color.white));
				float num = Mathf.Max(0.35f, Mathf.Min((float)Screen.width / 1440f, (float)Screen.height / 850f));
				GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(num, num, 1f));
				float num2 = (float)Screen.width / num;
				float num3 = (float)Screen.height / num;
				if (economyView.Final)
				{
					float num4 = Mathf.Min(690f, num2 - 32f);
					float num5 = 365f;
					float num6 = (num2 - num4) / 2f;
					float num7 = (num3 - num5) / 2f;
					EconomyRect(new Rect(num6, num7, num4, num5), Color32.op_Implicit(new Color32((byte)17, (byte)21, (byte)26, (byte)248)));
					EconomyRect(new Rect(num6, num7, num4, 4f), Accent);
					EconomyText(new Rect(num6 + 10f, num7 + 12f, num4 - 20f, 40f), flag ? "TEST DISPLAY | NO MONEY CHANGED" : ("LEVEL " + economyView.Level + " | FINAL SETTLEMENT"), economyTitle, Accent);
					EconomyRow(num6 + 24f, num7 + 61f, num4 - 48f, "Extraction revenue", Cash(economyView.ExtractionK), Ink);
					EconomyRow(num6 + 24f, num7 + 106f, num4 - 48f, "Truck Soul Orb bonus (" + economyView.OrbCount + ")", "+" + Cash(economyView.BonusK), EconomyGreen);
					EconomyRow(num6 + 24f, num7 + 151f, num4 - 48f, "Missing crew penalty", "-" + Cash(economyView.PenaltyK), EconomyRed);
					EconomyText(new Rect(num6 + 12f, num7 + 193f, num4 - 24f, 24f), EconomyHeads(economyView), economySmall, Muted);
					EconomyRect(new Rect(num6 + 24f, num7 + 224f, num4 - 48f, 1f), Muted);
					EconomyText(new Rect(num6 + 10f, num7 + 232f, num4 - 20f, 26f), economyView.LedgerValid ? "FINAL LEVEL REVENUE" : "TRACKED LEVEL REVENUE", economySmall, Accent);
					EconomyText(new Rect(num6 + 10f, num7 + 258f, num4 - 20f, 45f), Cash(Net(economyView)), economyTotal, Accent);
					EconomyText(new Rect(num6 + 10f, num7 + 306f, num4 - 20f, 24f), "New bank balance: " + Cash(economyView.BalanceK), economySmall, Ink);
					if (!economyView.LedgerValid || economyView.RequestedK > economyView.PenaltyK)
					{
						EconomyText(new Rect(num6 + 10f, num7 + 332f, num4 - 20f, 24f), (!economyView.LedgerValid) ? "Ledger incomplete: tracked income may be incomplete" : "Penalty limited to protect opening funds", economySmall, Accent);
					}
				}
				else
				{
					float num8 = Mathf.Min(465f, num2 - 24f);
					float num9 = 162f;
					float num10 = num2 - num8 - 18f;
					float num11 = Mathf.Max(105f, num3 * 0.2f);
					EconomyRect(new Rect(num10, num11, num8, num9), Color32.op_Implicit(new Color32((byte)17, (byte)21, (byte)26, (byte)235)));
					EconomyRect(new Rect(num10, num11, num8, 3f), Accent);
					EconomyText(new Rect(num10 + 10f, num11 + 5f, num8 - 20f, 28f), "ESCAPE | ESTIMATED REWARDS", economySmall, Accent);
					EconomyRow(num10 + 14f, num11 + 35f, num8 - 28f, "Truck orbs (" + economyView.OrbCount + ")", "+" + Cash(economyView.BonusK), EconomyGreen);
					EconomyRow(num10 + 14f, num11 + 76f, num8 - 28f, "Crew penalty", "-" + Cash(economyView.PenaltyK), EconomyRed);
					EconomyText(new Rect(num10 + 8f, num11 + 119f, num8 - 16f, 32f), EconomyHeads(economyView), economySmall, (economyView.Mode == 2 && economyView.Missing > 0) ? EconomyRed : Muted);
				}
			}
			finally
			{
				GUI.matrix = matrix;
				GUI.color = color;
				GUI.contentColor = contentColor;
				GUI.backgroundColor = backgroundColor;
				GUI.depth = depth;
			}
		}

		private void DrawEconomyMenuSummary()
		{
			EconomyView economyView = lastEconomy;
			if (economyView != null)
			{
				Section("Last completed settlement | Level " + economyView.Level);
				GUILayout.Label("Extraction revenue: " + Cash(economyView.ExtractionK), fieldLabel, Array.Empty<GUILayoutOption>());
				GUILayout.Label("Truck Soul Orb bonus: +" + Cash(economyView.BonusK), fieldLabel, Array.Empty<GUILayoutOption>());
				GUILayout.Label("Missing crew penalty: -" + Cash(economyView.PenaltyK), fieldLabel, Array.Empty<GUILayoutOption>());
				Hint(EconomyHeads(economyView));
				GUILayout.Label((economyView.LedgerValid ? "Final level revenue: " : "Tracked level revenue: ") + Cash(Net(economyView)), heading, Array.Empty<GUILayoutOption>());
				Hint("Bank balance after departure: " + Cash(economyView.BalanceK));
				if (!economyView.LedgerValid || economyView.RequestedK > economyView.PenaltyK)
				{
					Hint("Penalty limited to protect opening funds or because the ledger was incomplete.");
				}
			}
		}

		private void PruneReservations()
		{
			KeyValuePair<int, ExternalReservation>[] array = externalPending.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, ExternalReservation> keyValuePair = array[i];
				if (!Exists(keyValuePair.Value.Parent) || Active(keyValuePair.Value.Parent) || Time.unscaledTime >= keyValuePair.Value.Until || ReadLifeSpawns(keyValuePair.Key) > 0)
				{
					externalPending.Remove(keyValuePair.Key);
				}
			}
		}

		private int ReadLifeSpawns(int id)
		{
			if (!lives.TryGetValue(id, out var value))
			{
				return 0;
			}
			return value.Spawns;
		}

		private void ReserveExternal(object parent)
		{
			if (Exists(parent) && !Active(parent) && ReadLifeSpawns(ID(parent)) <= 0)
			{
				externalPending[ID(parent)] = new ExternalReservation
				{
					Parent = parent,
					Name = EnemyName(parent),
					Until = Time.unscaledTime + 20f
				};
			}
		}

		private static bool WouldExceed(int current, int add, int cap)
		{
			if (cap >= 0)
			{
				return (long)current + (long)add > cap;
			}
			return false;
		}

		private bool AllowExternalGroup(string[] members, out string reason)
		{
			reason = "";
			if (!Rules() || !HasCategory("enemy"))
			{
				return true;
			}
			if (members.Length == 0)
			{
				return true;
			}
			PruneReservations();
			object[] array = Parents().Where(Active).ToArray();
			int count = externalPending.Count;
			if (WouldExceed(array.Length + count, members.Length, R("enemy", "*", "max active")) || WouldExceed(totalSpawns + count, members.Length, R("enemy", "*", "max spawns")))
			{
				reason = "global active or lifetime cap";
				return false;
			}
			foreach (IGrouping<string, string> g in from x in members
				group x by x)
			{
				int num = externalPending.Values.Count((ExternalReservation x) => x.Name == g.Key);
				if (!EnemyAllowed(g.Key))
				{
					reason = g.Key + " disabled or level restricted";
					return false;
				}
				if (WouldExceed(array.Count((object x) => EnemyName(x) == g.Key) + num, g.Count(), R("enemy", g.Key, "max active")) || WouldExceed(ReadCount(spawnCounts, g.Key) + num, g.Count(), R("enemy", g.Key, "max spawns")))
				{
					reason = g.Key + " active or lifetime cap";
					return false;
				}
			}
			return true;
		}

		private void InstallExternalGuards()
		{
			if (T("LobbyWarden.Spawner") != null)
			{
				Hook("LobbyWarden.Spawner", "Make", 4, "WardenSpawnGuard", "WardenSpawnResult");
			}
			else
			{
				patches.Add("Lobby Warden integration: not installed");
			}
			if (T("REPOLib.Modules.Valuables") != null)
			{
				Hook("REPOLib.Modules.Valuables", "SpawnValuable", 3, "LibLootGuard", "LibLootResult");
			}
			else
			{
				patches.Add("REPOLib valuable integration: not installed");
			}
			if (T("REPOLib.Modules.Enemies") != null)
			{
				Hook("REPOLib.Modules.Enemies", "SpawnEnemy", 4, "LibSpawnGuard", "LibSpawnResult");
			}
			else
			{
				patches.Add("REPOLib enemy integration: not installed");
			}
		}

		private static object PrefabParent(object prefabRef)
		{
			object obj = Get(prefabRef, "Prefab");
			GameObject val = (GameObject)(((obj is GameObject) ? obj : null) ?? ((prefabRef is GameObject) ? prefabRef : null));
			Type type = T("EnemyParent");
			if (!((Object)(object)val != (Object)null) || !(type != null))
			{
				return null;
			}
			return val.GetComponentInChildren(type, true);
		}

		private static bool WardenSpawnGuard(object __0, ref GameObject __result)
		{
			if (!Rules() || (!P.HasCategory("enemy") && !P.HasCategory("loot")))
			{
				return true;
			}
			try
			{
				object o = PrefabParent(__0);
				if (Exists(o))
				{
					if (P.AllowExternalGroup(new string[1] { EnemyName(o) }, out var reason))
					{
						return true;
					}
					__result = null;
					P.Block("Lobby Warden spawn denied: " + reason);
					return false;
				}
				object obj = Get(__0, "Prefab");
				GameObject val = (GameObject)((obj is GameObject) ? obj : null);
				if ((Object)(object)val != (Object)null && P.HasCategory("loot") && IsRegularValuable(val) && !P.AllowExternalLoot(LootName(__0)))
				{
					__result = null;
					P.Block("Lobby Warden valuable denied: " + LootName(__0));
					return false;
				}
				return true;
			}
			catch (Exception e)
			{
				P.Error("Lobby Warden integration", e);
				return true;
			}
		}

		private static void WardenSpawnResult(object __0, GameObject __result)
		{
			if ((Object)(object)P == (Object)null || !Host() || !InLevel() || (Object)(object)__result == (Object)null)
			{
				return;
			}
			try
			{
				Component componentInChildren = __result.GetComponentInChildren(T("EnemyParent"), true);
				if (Exists(componentInChildren))
				{
					if (Rules() && P.HasCategory("enemy"))
					{
						P.ReserveExternal(componentInChildren);
					}
				}
				else if (IsRegularValuable(__result))
				{
					P.RecordExternalLoot(LootName(__0), __result);
				}
			}
			catch (Exception e)
			{
				P.Error("Lobby Warden result", e);
			}
		}

		private static bool IsRegularValuable(GameObject obj)
		{
			Type type = T("ValuableObject");
			Type type2 = T("EnemyValuable");
			if ((Object)(object)obj != (Object)null && type != null && (Object)(object)obj.GetComponentInChildren(type, true) != (Object)null)
			{
				if (!(type2 == null))
				{
					return (Object)(object)obj.GetComponentInChildren(type2, true) == (Object)null;
				}
				return true;
			}
			return false;
		}

		private bool AllowExternalLoot(string n)
		{
			if (LootAllowed(n) && !LootBudgetReached() && !Limit(totalLoot, R("loot", "*", "max count")))
			{
				if (R("loot", n, "spawn chance percent") >= 0)
				{
					return Random.Range(0, 100) < R("loot", n, "spawn chance percent");
				}
				return true;
			}
			return false;
		}

		private void RecordExternalLoot(string n, GameObject obj)
		{
			if (!((Object)(object)obj == (Object)null) && externalLootRecorded.Add(((Object)obj).GetInstanceID()))
			{
				Inc(lootCounts, n);
				totalLoot++;
				Log(n + " external valuable #" + ReadCount(lootCounts, n));
			}
		}

		private static bool LibLootGuard(object __0, ref GameObject __result)
		{
			if (!Rules() || !P.HasCategory("loot"))
			{
				return true;
			}
			try
			{
				string text = LootName(__0);
				if (P.AllowExternalLoot(text))
				{
					return true;
				}
				P.Block("REPOLib valuable denied: " + text);
				__result = null;
				return false;
			}
			catch (Exception e)
			{
				P.Error("REPOLib valuable gate", e);
				return true;
			}
		}

		private static void LibLootResult(object __0, GameObject __result)
		{
			if ((Object)(object)P == (Object)null || !InLevel() || !Host() || (Object)(object)__result == (Object)null)
			{
				return;
			}
			try
			{
				P.RecordExternalLoot(LootName(__0), __result);
			}
			catch (Exception e)
			{
				P.Error("REPOLib valuable accounting", e);
			}
		}

		private static bool LibSpawnGuard(object __0, ref List<EnemyParent> __result)
		{
			if (!Rules() || !P.HasCategory("enemy"))
			{
				return true;
			}
			try
			{
				if (P.AllowExternalGroup(Members(__0).ToArray(), out var reason))
				{
					return true;
				}
				__result = new List<EnemyParent>();
				P.Block("REPOLib spawn denied: " + reason);
				return false;
			}
			catch (Exception e)
			{
				P.Error("REPOLib integration", e);
				return true;
			}
		}

		private static void LibSpawnResult(List<EnemyParent> __result)
		{
			if (!Rules() || !P.HasCategory("enemy") || __result == null)
			{
				return;
			}
			try
			{
				foreach (EnemyParent item in __result)
				{
					P.ReserveExternal(item);
				}
			}
			catch (Exception e)
			{
				P.Error("REPOLib reservation", e);
			}
		}

		private void ResetGeneration()
		{
			generatedLootDollars = 0L;
			destroyedLoot = (destroyedOrbs = (extractedLoot = (extractedOrbs = 0)));
			valuedLoot.Clear();
			removedLoot.Clear();
			generationAuditDone = false;
		}

		private void InstallExtendedGeneration()
		{
			Hook("PhysGrabObjectImpactDetector", "DestroyObject", 2, "BeforeTrackedRemoval", "AfterTrackedRemoval");
		}

		private static Exception FinalLoot(Exception __exception)
		{
			nativeLootDepth = Math.Max(0, nativeLootDepth - 1);
			return __exception;
		}

		private void RecordInitialLootValue(object item)
		{
			if (valuedLoot.Add(ID(item)))
			{
				generatedLootDollars += Math.Max(0, ClampMoney(F(item, "dollarValueOriginal")));
			}
		}

		private bool LootBudgetReached()
		{
			int num = R("loot", "*", "max total value");
			if (num >= 0)
			{
				return generatedLootDollars >= num;
			}
			return false;
		}

		private double ApplyLootBudget(string name, double value, int fixedValue, int itemMax)
		{
			int num = R("loot", "*", "max total value");
			int num2 = R("loot", "*", "min total value");
			if (nativeLootDepth > 0 && num2 >= 0 && fixedValue < 0)
			{
				object o = S("ValuableDirector");
				int num3 = Math.Max(1, I(o, "totalMaxAmount") - I(o, "valuableTargetAmount"));
				double num4 = Math.Ceiling(Math.Max(0.0, (double)num2 - (double)generatedLootDollars) / (double)num3);
				if (itemMax >= 0)
				{
					num4 = Math.Min(num4, itemMax);
				}
				value = Math.Max(value, num4);
			}
			if (num >= 0)
			{
				value = Math.Min(value, Math.Max(0.0, (double)num - (double)generatedLootDollars));
			}
			return value;
		}

		private static TItem Weighted<TItem>(IEnumerable<TItem> source, Func<TItem, double> weight) where TItem : class
		{
			var array = (from x in source
				select new
				{
					Item = x,
					W = Math.Max(0.0, weight(x))
				} into x
				where x.W > 0.0
				select x).ToArray();
			double num = array.Sum(x => x.W);
			if (num <= 0.0)
			{
				return null;
			}
			double num2 = (double)Random.value * num;
			var array2 = array;
			foreach (var anon in array2)
			{
				num2 -= anon.W;
				if (num2 <= 0.0)
				{
					return anon.Item;
				}
			}
			return array.Last().Item;
		}

		private bool AnyField(string cat, string field)
		{
			return new Dictionary<string, int>[3] { permanent, run, level }.Any((Dictionary<string, int> d) => d.Any((KeyValuePair<string, int> k) => k.Value >= 0 && k.Key.Contains(cat + "/") && k.Key.EndsWith("/" + field, StringComparison.Ordinal)));
		}

		private bool AdjustEnemyPlan(object director, List<object> chosen, Dictionary<string, int> assigned, ref int count, int originalGroups)
		{
			bool result = false;
			int num = R("enemy", "*", "count percent");
			int num2 = R("enemy", "*", "count growth percent");
			bool flag = AnyField("enemy", "spawn weight");
			bool flag2 = AnyField("enemy", "min assigned");
			if (num < 0 && num2 < 0 && !flag && !flag2)
			{
				return false;
			}
			var array = (from x in tiers.SelectMany((string t) => Items(Get(director, t))).Distinct()
				select new
				{
					Setup = x,
					Names = Members(x).ToArray()
				} into x
				where x.Names.Length != 0
				select x).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			if (flag)
			{
				List<object> list = new List<object>();
				Dictionary<string, int> used = new Dictionary<string, int>();
				int total = 0;
				foreach (object old in chosen)
				{
					string tier = tiers.FirstOrDefault((string t) => Items(Get(director, t)).Contains(old));
					var anon = Weighted(((tier == null) ? ((IEnumerable<<>f__AnonymousType3<object, string[]>>)array) : ((IEnumerable<<>f__AnonymousType3<object, string[]>>)array.Where(x => Items(Get(director, tier)).Contains(x.Setup)).ToArray())).Where(x => GroupAllowed(x.Names, used, total) && x.Names.All((string n3) => R("enemy", n3, "spawn chance percent") != 0)), x => x.Names.Select(delegate(string n3)
					{
						int num7 = R("enemy", n3, "spawn weight");
						int num8 = R("enemy", n3, "spawn chance percent");
						return ((num7 < 0) ? 100.0 : ((double)num7)) * ((num8 < 0) ? 1.0 : ((double)num8 / 100.0));
					}).Min());
					if (anon != null)
					{
						list.Add(anon.Setup);
						string[] names = anon.Names;
						foreach (string n in names)
						{
							Inc(used, n);
						}
						total += anon.Names.Length;
					}
				}
				chosen.Clear();
				chosen.AddRange(list);
				assigned.Clear();
				foreach (KeyValuePair<string, int> item in used)
				{
					assigned[item.Key] = item.Value;
				}
				count = total;
				result = true;
			}
			int num4 = chosen.Count;
			if (num >= 0 || num2 >= 0)
			{
				double num5 = (double)originalGroups * ((num < 0) ? 1.0 : ((double)num / 100.0));
				if (num2 >= 0)
				{
					num5 *= 1.0 + (double)num2 / 100.0 * (double)Math.Max(0, levelNumber - 1);
				}
				num4 = Math.Min(500, ClampMoney(num5));
				while (chosen.Count > num4)
				{
					object setup = chosen[chosen.Count - 1];
					chosen.RemoveAt(chosen.Count - 1);
					foreach (string item2 in Members(setup))
					{
						assigned[item2] = Math.Max(0, ReadCount(assigned, item2) - 1);
						count--;
					}
					result = true;
				}
			}
			while (chosen.Count < 500)
			{
				int total2 = count;
				var array2 = array.Where(x => GroupAllowed(x.Names, assigned, total2) && x.Names.All((string n3) => R("enemy", n3, "spawn chance percent") != 0 && R("enemy", n3, "spawn weight") != 0)).ToArray();
				var array3 = (flag2 ? array2.Where(x => x.Names.Any((string n3) => R("enemy", n3, "min assigned") > ReadCount(assigned, n3))).ToArray() : array2.Take(0).ToArray());
				if (chosen.Count >= num4 && array3.Length == 0)
				{
					break;
				}
				var anon2 = Weighted((array3.Length != 0) ? array3 : array2, x => x.Names.Select(delegate(string n3)
				{
					int num7 = R("enemy", n3, "spawn weight");
					int num8 = R("enemy", n3, "spawn chance percent");
					return ((num7 < 0) ? 100.0 : ((double)num7)) * ((num8 < 0) ? 1.0 : ((double)num8 / 100.0));
				}).Min());
				if (anon2 == null)
				{
					break;
				}
				chosen.Add(anon2.Setup);
				string[] names = anon2.Names;
				foreach (string n2 in names)
				{
					Inc(assigned, n2);
				}
				count += anon2.Names.Length;
				result = true;
			}
			if (flag2)
			{
				foreach (string item3 in array.SelectMany(x => x.Names).Distinct())
				{
					int num6 = R("enemy", item3, "min assigned");
					if (num6 >= 0 && ReadCount(assigned, item3) < num6)
					{
						Log("Generation target not met for " + item3 + ": " + ReadCount(assigned, item3) + " / " + num6 + "; caps or available groups took precedence.");
					}
				}
			}
			return result;
		}

		private void AdjustLootSlot(object director, object[] args, string original)
		{
			bool flag = AnyField("loot", "min count");
			bool flag2 = AnyField("loot", "spawn weight");
			if (!flag && !flag2)
			{
				return;
			}
			string[] array = lootLists;
			foreach (string n in array)
			{
				object[] source = Items(Get(director, n)).ToArray();
				if (!source.Any((object x) => LootName(x) == original))
				{
					continue;
				}
				object[] array2 = source.Where((object x) => LootAllowed(LootName(x)) && R("loot", LootName(x), "spawn chance percent") != 0 && R("loot", LootName(x), "spawn weight") != 0).ToArray();
				if (array2.Length == 0)
				{
					break;
				}
				object[] array3 = (flag ? array2.Where((object x) => R("loot", LootName(x), "min count") > ReadCount(lootCounts, LootName(x))).ToArray() : Array.Empty<object>());
				if (array3.Length != 0 || flag2)
				{
					object obj = Weighted((array3.Length != 0) ? array3 : array2, delegate(object x)
					{
						int num = R("loot", LootName(x), "spawn weight");
						return (num < 0) ? 100 : num;
					});
					if (obj != null)
					{
						args[0] = obj;
					}
				}
				break;
			}
		}

		private void AuditGeneration()
		{
			if (generationAuditDone || !Host() || !InLevel() || !B(S("LevelGenerator"), "Generated"))
			{
				return;
			}
			generationAuditDone = true;
			int num = R("loot", "*", "min total value");
			if (num >= 0 && generatedLootDollars < num)
			{
				Log("Minimum loot target not met: $" + generatedLootDollars + " / $" + num + "; native slots or other caps took precedence.");
			}
			if (!AnyField("loot", "min count"))
			{
				return;
			}
			foreach (string lootName in lootNames)
			{
				int num2 = R("loot", lootName, "min count");
				if (num2 >= 0 && ReadCount(lootCounts, lootName) < num2)
				{
					Block("Minimum valuable count not met: " + lootName + " (" + ReadCount(lootCounts, lootName) + " / " + num2 + ")");
				}
			}
		}

		private static void BeforeTrackedRemoval(object __instance, bool __1, out RemovalProbe __state)
		{
			__state = null;
			if ((Object)(object)P == (Object)null || !Host() || !InLevel())
			{
				return;
			}
			try
			{
				if (!B(__instance, "destroyDisable") || __1)
				{
					object obj = Get(__instance, "valuableObject");
					object obj2 = Get(__instance, "physGrabObject");
					if (Exists(obj) && Exists(obj2) && !B(obj2, "dead"))
					{
						__state = new RemovalProbe
						{
							Id = ID(obj),
							Grab = obj2,
							Value = obj,
							Orb = IsOrb(obj),
							Extracted = B(obj, "committedToExtraction")
						};
					}
				}
			}
			catch (Exception e)
			{
				P.Error("Removal audit", e);
			}
		}

		private static void AfterTrackedRemoval(RemovalProbe __state)
		{
			if ((Object)(object)P == (Object)null || __state == null || !Host() || (Exists(__state.Grab) && !B(__state.Grab, "dead") && Exists(__state.Value)) || !P.removedLoot.Add(__state.Id))
			{
				return;
			}
			if (__state.Orb)
			{
				if (__state.Extracted)
				{
					P.extractedOrbs++;
				}
				else
				{
					P.destroyedOrbs++;
				}
			}
			else if (__state.Extracted)
			{
				P.extractedLoot++;
			}
			else
			{
				P.destroyedLoot++;
			}
		}

		private void RemoveValuables(bool excess)
		{
			if (!InLevel())
			{
				throw new Exception("Enter a gameplay map first");
			}
			object[] array = (from x in Find("ValuableObject")
				where !IsOrb(x) && !B(x, "committedToExtraction")
				select x).OrderBy(ID).ToArray();
			HashSet<object> hashSet = new HashSet<object>();
			if (!excess)
			{
				object[] array2 = array;
				foreach (object obj in array2)
				{
					string n = LootName(obj);
					int num2 = R("loot", n, "min level");
					int num3 = R("loot", n, "max level");
					if (R("loot", n, "allow") == 0 || (num2 >= 0 && levelNumber < num2) || (num3 >= 0 && levelNumber > num3))
					{
						hashSet.Add(obj);
					}
				}
			}
			else
			{
				int num4 = R("loot", "*", "max count");
				if (num4 >= 0)
				{
					foreach (object item in array.Skip(num4))
					{
						hashSet.Add(item);
					}
				}
				foreach (IGrouping<string, object> item2 in array.GroupBy(LootName))
				{
					int num5 = R("loot", item2.Key, "max count");
					if (num5 < 0)
					{
						continue;
					}
					foreach (object item3 in item2.Skip(num5))
					{
						hashSet.Add(item3);
					}
				}
			}
			int num6 = 0;
			foreach (object item4 in hashSet)
			{
				object o = QaImpactDetector(item4);
				if (Exists(o) && Exists(Get(o, "physGrabObject")))
				{
					Call(o, "DestroyObject", false, true);
					num6++;
				}
			}
			Log("Explicit valuable cleanup requested for " + num6 + " objects; generation counters were not refunded.");
		}

		private void BeginInputRelease()
		{
			inputReleasePending = true;
			inputReleaseAfterFrame = Time.frameCount + 2;
		}

		private void UpdateInputRelease()
		{
			if (inputReleasePending)
			{
				if (Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2))
				{
					inputReleaseAfterFrame = Time.frameCount + 2;
				}
				else if (Time.frameCount >