Decompiled source of ValuableTracker v1.2.1

BepInEx/plugins/MechGaming-ValuableTracker/ValuableTracker.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[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("MechGaming")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: AssemblyInformationalVersion("1.2.1")]
[assembly: AssemblyProduct("ValuableTracker")]
[assembly: AssemblyTitle("ValuableTracker")]
[assembly: AssemblyVersion("1.2.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MechGaming.REPO.ValuableTracker
{
	internal static class HotkeyInput
	{
		private const int KeyDownMask = 32768;

		private const float TextInputScanInterval = 0.15f;

		private static readonly Dictionary<KeyCode, bool> PreviousStates = new Dictionary<KeyCode, bool>();

		private static readonly Type? UnityInputFieldType = Type.GetType("UnityEngine.UI.InputField, UnityEngine.UI");

		private static readonly Type? TmpInputFieldType = Type.GetType("TMPro.TMP_InputField, Unity.TextMeshPro");

		private static int _currentProcessId;

		private static float _nextTextInputScanTime;

		private static bool _cachedNoTextInputActive = true;

		internal static bool LegacyInputDisabled { get; private set; }

		internal static int FailureCount { get; private set; }

		internal static string FailureReason { get; private set; } = string.Empty;

		private static int CurrentProcessId
		{
			get
			{
				if (_currentProcessId == 0)
				{
					_currentProcessId = Process.GetCurrentProcess().Id;
				}
				return _currentProcessId;
			}
		}

		internal static bool GetKeyDown(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			bool flag = GetUnityKeyDown(key) || GetWindowsKey(key);
			bool value;
			bool flag2 = PreviousStates.TryGetValue(key, out value) && value;
			PreviousStates[key] = flag;
			if (flag)
			{
				return !flag2;
			}
			return false;
		}

		internal static bool NoTextInputActive(Func<bool> gameCheck)
		{
			try
			{
				if (!gameCheck())
				{
					return false;
				}
			}
			catch
			{
			}
			if (Time.unscaledTime < _nextTextInputScanTime)
			{
				return _cachedNoTextInputActive;
			}
			_nextTextInputScanTime = Time.unscaledTime + 0.15f;
			_cachedNoTextInputActive = !AnyFocusedTextInput();
			return _cachedNoTextInputActive;
		}

		private static bool GetUnityKeyDown(KeyCode key)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (LegacyInputDisabled)
			{
				return false;
			}
			try
			{
				return Input.GetKeyDown(key);
			}
			catch (Exception error)
			{
				RecordLegacyInputFailure(error);
				return false;
			}
		}

		private static void RecordLegacyInputFailure(Exception error)
		{
			if (FailureCount < int.MaxValue)
			{
				FailureCount++;
			}
			FailureReason = error.GetType().FullName + ": " + error.Message;
			if (error is InvalidOperationException && error.Message.IndexOf("UnityEngine.Input", StringComparison.OrdinalIgnoreCase) >= 0 && error.Message.IndexOf("Input System", StringComparison.OrdinalIgnoreCase) >= 0 && (error.Message.IndexOf("active Input handling", StringComparison.OrdinalIgnoreCase) >= 0 || error.Message.IndexOf("Player Settings", StringComparison.OrdinalIgnoreCase) >= 0))
			{
				LegacyInputDisabled = true;
			}
		}

		private static bool GetWindowsKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			int num = ToVirtualKey(key);
			if (num != 0 && IsForegroundProcess())
			{
				return IsVirtualKeyDown(num);
			}
			return false;
		}

		private static bool IsVirtualKeyDown(int virtualKey)
		{
			try
			{
				return (GetAsyncKeyState(virtualKey) & 0x8000) != 0;
			}
			catch
			{
				return false;
			}
		}

		private static bool IsForegroundProcess()
		{
			try
			{
				IntPtr foregroundWindow = GetForegroundWindow();
				if (foregroundWindow == IntPtr.Zero)
				{
					return false;
				}
				GetWindowThreadProcessId(foregroundWindow, out var processId);
				return processId == CurrentProcessId;
			}
			catch
			{
				return false;
			}
		}

		private static int ToVirtualKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Invalid comparison between Unknown and I4
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_001e: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected I4, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected I4, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected I4, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Invalid comparison between Unknown and I4
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Invalid comparison between Unknown and I4
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Invalid comparison between Unknown and I4
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected I4, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Invalid comparison between Unknown and I4
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected I4, but got Unknown
			if ((int)key >= 97 && (int)key <= 122)
			{
				return 65 + (key - 97);
			}
			if ((int)key >= 48 && (int)key <= 57)
			{
				return 48 + (key - 48);
			}
			if ((int)key >= 282 && (int)key <= 678)
			{
				return 112 + (key - 282);
			}
			if ((int)key <= 27)
			{
				if ((int)key <= 9)
				{
					if ((int)key == 8)
					{
						return 8;
					}
					if ((int)key == 9)
					{
						return 9;
					}
				}
				else
				{
					if ((int)key == 13)
					{
						return 13;
					}
					if ((int)key == 27)
					{
						return 27;
					}
				}
			}
			else if ((int)key <= 127)
			{
				if ((int)key == 32)
				{
					return 32;
				}
				if ((int)key == 127)
				{
					return 46;
				}
			}
			else
			{
				switch (key - 273)
				{
				case 7:
					return 33;
				case 8:
					return 34;
				case 6:
					return 35;
				case 5:
					return 36;
				case 3:
					return 37;
				case 0:
					return 38;
				case 2:
					return 39;
				case 1:
					return 40;
				case 4:
					return 45;
				}
				switch (key - 303)
				{
				case 1:
					return 160;
				case 0:
					return 161;
				case 3:
					return 162;
				case 2:
					return 163;
				case 5:
					return 164;
				case 4:
					return 165;
				}
				switch (key - 323)
				{
				case 0:
					return 1;
				case 1:
					return 2;
				case 2:
					return 4;
				}
			}
			return 0;
		}

		private static bool AnyFocusedTextInput()
		{
			if (!TypeHasFocusedInput(UnityInputFieldType))
			{
				return TypeHasFocusedInput(TmpInputFieldType);
			}
			return true;
		}

		private static bool TypeHasFocusedInput(Type? inputType)
		{
			if (inputType == null)
			{
				return false;
			}
			try
			{
				Object[] array = Resources.FindObjectsOfTypeAll(inputType);
				for (int i = 0; i < array.Length; i++)
				{
					if (IsFocusedInput(array[i]))
					{
						return true;
					}
				}
			}
			catch
			{
				return false;
			}
			return false;
		}

		private static bool IsFocusedInput(Object input)
		{
			Component val = (Component)(object)((input is Component) ? input : null);
			if (val == null || !val.gameObject.activeInHierarchy)
			{
				return false;
			}
			Behaviour val2 = (Behaviour)(object)((val is Behaviour) ? val : null);
			if (val2 != null && !val2.enabled)
			{
				return false;
			}
			PropertyInfo property = ((object)input).GetType().GetProperty("isFocused", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null && property.PropertyType == typeof(bool))
			{
				try
				{
					object value = property.GetValue(input, null);
					return value is bool && (bool)value;
				}
				catch
				{
					return false;
				}
			}
			return false;
		}

		[DllImport("user32.dll")]
		private static extern short GetAsyncKeyState(int virtualKey);

		[DllImport("user32.dll")]
		private static extern IntPtr GetForegroundWindow();

		[DllImport("user32.dll")]
		private static extern uint GetWindowThreadProcessId(IntPtr windowHandle, out uint processId);
	}
	internal sealed class InitialInventoryReadiness
	{
		internal bool Captured { get; private set; }

		internal bool Complete { get; private set; }

		internal int Expected { get; private set; } = -1;

		internal int Started { get; private set; }

		internal int Registered { get; private set; }

		internal void Observe(bool generated, int expected, int started, int registered)
		{
			if (!Captured)
			{
				Expected = expected;
				Started = started;
				Registered = registered;
				if (generated && expected >= 0)
				{
					Captured = true;
					Complete = started >= expected && registered >= expected;
				}
			}
		}

		internal void Clear()
		{
			Captured = false;
			Complete = false;
			Expected = -1;
			Started = 0;
			Registered = 0;
		}
	}
	[BepInPlugin("MechGaming.REPO.ValuableTracker", "ValuableTracker", "1.2.1")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "MechGaming.REPO.ValuableTracker";

		public const string PluginName = "ValuableTracker";

		public const string PluginVersion = "1.2.1";

		private const float SnapshotInterval = 0.25f;

		private const int MenuWidth = 360;

		private const int MenuHeight = 350;

		private Harmony? _harmony;

		private ConfigEntry<KeyCode> _menuKey;

		private ConfigEntry<bool> _showHud;

		private ConfigEntry<bool> _showInCart;

		private ConfigEntry<bool> _showDestroyed;

		private ConfigEntry<float> _hudRightOffset;

		private ConfigEntry<float> _hudTopOffset;

		private ConfigEntry<bool> _showRoomCounters;

		private ConfigEntry<float> _roomCounterFontSize;

		private readonly RoomMapTracker _roomMapTracker = new RoomMapTracker();

		private readonly RoomMapOverlay _roomMapOverlay = new RoomMapOverlay();

		private readonly List<RoomValuableLocation> _roomLocations = new List<RoomValuableLocation>();

		private readonly List<RoomMapCounter> _roomCounters = new List<RoomMapCounter>();

		private TrackerSnapshot _snapshot;

		private Rect _menuRect = new Rect(30f, 30f, 360f, 350f);

		private float _nextSnapshotTime;

		private float _statusMessageUntil;

		private string _statusMessage = string.Empty;

		private bool _menuOpen;

		private bool _storedCursorVisible;

		private CursorLockMode _storedCursorLockMode;

		internal static Plugin? Instance { get; private set; }

		private void Awake()
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Expected O, but got Unknown
			Instance = this;
			_menuKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "MenuKey", (KeyCode)285, "Key used to open ValuableTracker settings.");
			_showHud = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD", "ShowHUD", true, "Show the valuable tracking HUD.");
			_showInCart = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD", "ShowInCart", true, "Show valuables that are currently in carts or Valuable Boxes.");
			_showDestroyed = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD", "ShowDestroyed", true, "Show valuables that were destroyed or removed before sale.");
			_hudRightOffset = ((BaseUnityPlugin)this).Config.Bind<float>("HUD", "RightOffset", 18f, "HUD distance from the right side of the screen.");
			_hudTopOffset = ((BaseUnityPlugin)this).Config.Bind<float>("HUD", "TopOffset", 275f, "HUD distance from the top of the screen.");
			_showRoomCounters = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "ShowRoomCounters", true, "Show discovered / total valuables for each whole room. A question mark means its total is unverified.");
			_roomCounterFontSize = ((BaseUnityPlugin)this).Config.Bind<float>("Map", "RoomCounterFontSize", 2f, new ConfigDescription("Size of the room counters on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.75f, 6f), Array.Empty<object>()));
			ValuableTrackerState.Init(((BaseUnityPlugin)this).Logger);
			_harmony = new Harmony("MechGaming.REPO.ValuableTracker");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"ValuableTracker 1.2.1 loaded.");
		}

		private void Update()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (HotkeyInput.GetKeyDown(_menuKey.Value) && (_menuOpen || NoTextInputActive()))
			{
				SetMenuOpen(!_menuOpen);
			}
			else if (_menuOpen && HotkeyInput.GetKeyDown((KeyCode)27))
			{
				SetMenuOpen(open: false);
			}
			if (_menuOpen && (Object)(object)InputManager.instance != (Object)null)
			{
				SemiFunc.InputDisableMovement();
				SemiFunc.InputDisableAiming();
			}
			if (Time.unscaledTime >= _nextSnapshotTime)
			{
				_snapshot = ValuableTrackerState.CreateSnapshot();
				Map instance = Map.Instance;
				if (!ValuableTrackerState.IsReady)
				{
					_roomMapTracker.Clear();
					_roomCounters.Clear();
				}
				else if (_showRoomCounters.Value && (Object)(object)instance != (Object)null && instance.Active)
				{
					ValuableTrackerState.FillRoomLocations(_roomLocations);
					_roomMapTracker.Refresh(instance, _roomLocations, _roomCounters, ValuableTrackerState.InventoryComplete);
				}
				_nextSnapshotTime = Time.unscaledTime + 0.25f;
			}
		}

		private void LateUpdate()
		{
			Map instance = Map.Instance;
			if ((Object)(object)instance != (Object)null && ValuableTrackerState.IsReady)
			{
				_roomMapOverlay.Refresh(instance, _roomCounters, _showRoomCounters.Value, _roomCounterFontSize.Value);
			}
			else
			{
				_roomMapOverlay.Clear();
			}
			if (_menuOpen)
			{
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)0;
			}
		}

		private void OnDestroy()
		{
			SetMenuOpen(open: false);
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_roomMapOverlay.Dispose();
			_roomMapTracker.Clear();
			ValuableTrackerState.Clear();
			Instance = null;
		}

		private void OnGUI()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (_showHud.Value && ShouldDrawHud())
			{
				DrawHud();
			}
			if (_menuOpen)
			{
				_menuRect = GUI.Window(((Object)this).GetInstanceID(), _menuRect, new WindowFunction(DrawMenuWindow), "ValuableTracker");
			}
		}

		private bool ShouldDrawHud()
		{
			if (ValuableTrackerState.IsReady && (_snapshot.Total > 0 || !ValuableTrackerState.InventoryComplete))
			{
				return SafeGameCheck((Func<bool>)SemiFunc.RunIsLevel);
			}
			return false;
		}

		private void DrawHud()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = BuildHudLines();
			if (list.Count == 0)
			{
				return;
			}
			float num = 14f + (float)list.Count * 23f;
			float num2 = Mathf.Max(8f, (float)Screen.width - 300f - _hudRightOffset.Value);
			float num3 = Mathf.Clamp(_hudTopOffset.Value, 8f, Mathf.Max(8f, (float)Screen.height - num - 8f));
			Rect val = new Rect(num2, num3, 300f, num);
			GUI.color = new Color(0f, 0f, 0f, 0.66f);
			GUI.Box(val, GUIContent.none);
			GUI.color = Color.white;
			GUIStyle val2 = new GUIStyle(GUI.skin.label)
			{
				fontSize = 18,
				fontStyle = (FontStyle)1,
				alignment = (TextAnchor)2,
				richText = true
			};
			val2.normal.textColor = new Color(0.78f, 0.91f, 0.9f, 1f);
			float num4 = num3 + 7f;
			foreach (string item in list)
			{
				GUI.Label(new Rect(num2 + 8f, num4, 284f, 24f), item, val2);
				num4 += 23f;
			}
		}

		private List<string> BuildHudLines()
		{
			List<string> list = new List<string>();
			int accountedFor = _snapshot.AccountedFor;
			string arg = (ValuableTrackerState.InventoryComplete ? _snapshot.Total.ToString() : "?");
			string item = ((ValuableTrackerState.InventoryComplete && accountedFor >= _snapshot.Total && _snapshot.Total > 0) ? $"<color=#58ff79>Accounted for: {accountedFor} / {_snapshot.Total}</color>" : $"Accounted for: {accountedFor} / {arg}");
			list.Add(item);
			list.Add($"Sold: {_snapshot.Sold}");
			if (_showInCart.Value && _snapshot.InCart > 0)
			{
				list.Add($"In Cart: {_snapshot.InCart}");
			}
			if (_showInCart.Value && _snapshot.InBox > 0)
			{
				list.Add($"In Box: {_snapshot.InBox}");
			}
			if (_showDestroyed.Value && _snapshot.Destroyed > 0)
			{
				list.Add($"<color=#ff5555>Destroyed: {_snapshot.Destroyed}</color>");
			}
			return list;
		}

		private void DrawMenuWindow(int windowId)
		{
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Space(8f);
			_showHud.Value = GUILayout.Toggle(_showHud.Value, "Show HUD", Array.Empty<GUILayoutOption>());
			_showInCart.Value = GUILayout.Toggle(_showInCart.Value, "Track Carts / Valuable Boxes", Array.Empty<GUILayoutOption>());
			_showDestroyed.Value = GUILayout.Toggle(_showDestroyed.Value, "Track Destroyed", Array.Empty<GUILayoutOption>());
			_showRoomCounters.Value = GUILayout.Toggle(_showRoomCounters.Value, "Show Room Counters on Map (discovered / total)", Array.Empty<GUILayoutOption>());
			GUILayout.Space(8f);
			GUILayout.Label($"Sold: {_snapshot.Sold}   In Cart: {_snapshot.InCart}   Destroyed: {_snapshot.Destroyed}", Array.Empty<GUILayoutOption>());
			GUILayout.Label($"In Valuable Boxes: {_snapshot.InBox}", Array.Empty<GUILayoutOption>());
			GUILayout.Label(string.Format("Accounted for: {0} / {1}", _snapshot.AccountedFor, ValuableTrackerState.InventoryComplete ? _snapshot.Total.ToString() : "?"), Array.Empty<GUILayoutOption>());
			GUILayout.Space(8f);
			GUI.enabled = ValuableTrackerState.IsReady;
			if (GUILayout.Button("Discover All Valuables", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(34f) }))
			{
				int num = ValuableTrackerState.DiscoverAll();
				_snapshot = ValuableTrackerState.CreateSnapshot();
				_statusMessage = ((num == 1) ? "Discovered 1 valuable." : $"Discovered {num} valuables.");
				_statusMessageUntil = Time.unscaledTime + 4f;
			}
			GUI.enabled = true;
			if (Time.unscaledTime < _statusMessageUntil)
			{
				GUILayout.Label(_statusMessage, Array.Empty<GUILayoutOption>());
			}
			GUILayout.FlexibleSpace();
			GUILayout.Label($"Press {_menuKey.Value} or Escape to close.", Array.Empty<GUILayoutOption>());
			GUI.DragWindow(new Rect(0f, 0f, 360f, 24f));
		}

		private void SetMenuOpen(bool open)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (_menuOpen != open)
			{
				_menuOpen = open;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("ValuableTracker menu " + (open ? "opened" : "closed") + "."));
				if (open)
				{
					_storedCursorVisible = Cursor.visible;
					_storedCursorLockMode = Cursor.lockState;
					Cursor.visible = true;
					Cursor.lockState = (CursorLockMode)0;
				}
				else
				{
					Cursor.visible = _storedCursorVisible;
					Cursor.lockState = _storedCursorLockMode;
				}
			}
		}

		private static bool NoTextInputActive()
		{
			return HotkeyInput.NoTextInputActive((Func<bool>)SemiFunc.NoTextInputsActive);
		}

		private static bool SafeGameCheck(Func<bool> check)
		{
			try
			{
				return check();
			}
			catch
			{
				return false;
			}
		}
	}
	internal readonly struct RoomValuableObservation
	{
		internal int ValuableId { get; }

		internal int RoomId { get; }

		internal bool Discovered { get; }

		internal RoomValuableObservation(int valuableId, int roomId, bool discovered)
		{
			ValuableId = valuableId;
			RoomId = roomId;
			Discovered = discovered;
		}
	}
	internal readonly struct RoomCounterSnapshot
	{
		internal int Discovered { get; }

		internal int Total { get; }

		internal RoomCounterSnapshot(int discovered, int total)
		{
			Discovered = discovered;
			Total = total;
		}
	}
	internal static class RoomCounterModel
	{
		internal static Dictionary<int, RoomCounterSnapshot> Count(IEnumerable<int> roomIds, IEnumerable<RoomValuableObservation> valuables)
		{
			Dictionary<int, RoomCounterSnapshot> dictionary = new Dictionary<int, RoomCounterSnapshot>();
			foreach (int roomId in roomIds)
			{
				dictionary[roomId] = new RoomCounterSnapshot(0, 0);
			}
			Dictionary<int, RoomValuableObservation> dictionary2 = new Dictionary<int, RoomValuableObservation>();
			foreach (RoomValuableObservation valuable in valuables)
			{
				dictionary2[valuable.ValuableId] = valuable;
			}
			foreach (RoomValuableObservation value2 in dictionary2.Values)
			{
				if (dictionary.TryGetValue(value2.RoomId, out var value))
				{
					dictionary[value2.RoomId] = new RoomCounterSnapshot(value.Discovered + (value2.Discovered ? 1 : 0), value.Total + 1);
				}
			}
			return dictionary;
		}
	}
	internal static class RoomCounterText
	{
		internal static string Format(int discovered, int total, bool totalKnown)
		{
			return discovered.ToString(CultureInfo.InvariantCulture) + "/" + (totalKnown ? total.ToString(CultureInfo.InvariantCulture) : "?");
		}

		internal static bool IsComplete(int discovered, int total, bool totalKnown)
		{
			if (totalKnown && total > 0)
			{
				return discovered >= total;
			}
			return false;
		}
	}
	internal readonly struct RoomMapCounter
	{
		internal int RoomId { get; }

		internal int Layer { get; }

		internal Vector3 WorldPosition { get; }

		internal int Discovered { get; }

		internal int Total { get; }

		internal bool TotalKnown { get; }

		internal RoomMapCounter(int roomId, int layer, Vector3 worldPosition, int discovered, int total, bool totalKnown = true)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			RoomId = roomId;
			Layer = layer;
			WorldPosition = worldPosition;
			Discovered = discovered;
			Total = total;
			TotalKnown = totalKnown;
		}
	}
	internal sealed class RoomMapOverlay : IDisposable
	{
		private sealed class Label
		{
			internal TextMeshPro Text { get; }

			internal int Discovered { get; set; } = -1;

			internal int Total { get; set; } = -1;

			internal bool TotalKnown { get; set; }

			internal float FontSize { get; set; } = -1f;

			internal Label(TextMeshPro text)
			{
				Text = text;
			}
		}

		private const float LabelHeight = 0.18f;

		private static readonly Color IncompleteColor = new Color(1f, 0.87f, 0.28f, 1f);

		private static readonly Color CompleteColor = new Color(0.45f, 1f, 0.58f, 1f);

		private static readonly Color EmptyColor = new Color(0.76f, 0.82f, 0.8f, 1f);

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

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

		private readonly List<int> _removedRooms = new List<int>();

		private Map? _map;

		private GameObject? _root;

		private TMP_FontAsset? _font;

		private Material? _material;

		private int _renderLayer;

		private int _sortingLayer;

		private int _sortingOrder;

		private bool _fontWarningLogged;

		internal void Refresh(Map map, IReadOnlyList<RoomMapCounter> counters, bool enabled, float fontSize)
		{
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)map == (Object)null || (Object)(object)map.OverLayerParent == (Object)null)
			{
				Clear();
				return;
			}
			if ((Object)(object)_map != (Object)(object)map)
			{
				Clear();
				_map = map;
			}
			if (!enabled || !map.Active)
			{
				if ((Object)(object)_root != (Object)null && _root.activeSelf)
				{
					_root.SetActive(false);
				}
			}
			else
			{
				if ((Object)(object)_root == (Object)null && !CreateRoot(map))
				{
					return;
				}
				if (!_root.activeSelf)
				{
					_root.SetActive(true);
				}
				Transform val = (((Object)(object)DirtFinderMapPlayer.Instance != (Object)null) ? ((Component)DirtFinderMapPlayer.Instance).transform : map.playerTransformSource);
				float num = (((Object)(object)val != (Object)null) ? val.eulerAngles.y : 0f);
				Quaternion rotation = Quaternion.Euler(90f, num, 0f);
				float num2 = Mathf.Clamp(fontSize, 0.5f, 8f);
				_seenRooms.Clear();
				for (int i = 0; i < counters.Count; i++)
				{
					RoomMapCounter roomMapCounter = counters[i];
					if (!_seenRooms.Add(roomMapCounter.RoomId))
					{
						continue;
					}
					if (!_labels.TryGetValue(roomMapCounter.RoomId, out Label value) || (Object)(object)value.Text == (Object)null)
					{
						value = CreateLabel(roomMapCounter.RoomId);
						_labels[roomMapCounter.RoomId] = value;
					}
					TextMeshPro text = value.Text;
					bool flag = roomMapCounter.Layer == map.PlayerLayer;
					if (((Component)text).gameObject.activeSelf != flag)
					{
						((Component)text).gameObject.SetActive(flag);
					}
					if (flag)
					{
						Transform transform = text.transform;
						transform.position = roomMapCounter.WorldPosition * map.Scale + map.OverLayerParent.position;
						Vector3 localPosition = transform.localPosition;
						localPosition.y = 0.18f;
						transform.localPosition = localPosition;
						transform.rotation = rotation;
						if (value.FontSize != num2)
						{
							((TMP_Text)text).fontSize = num2;
							value.FontSize = num2;
						}
						if (value.Discovered != roomMapCounter.Discovered || value.Total != roomMapCounter.Total || value.TotalKnown != roomMapCounter.TotalKnown)
						{
							((TMP_Text)text).text = RoomCounterText.Format(roomMapCounter.Discovered, roomMapCounter.Total, roomMapCounter.TotalKnown);
							((Graphic)text).color = ((roomMapCounter.TotalKnown && roomMapCounter.Total == 0) ? EmptyColor : (RoomCounterText.IsComplete(roomMapCounter.Discovered, roomMapCounter.Total, roomMapCounter.TotalKnown) ? CompleteColor : IncompleteColor));
							value.Discovered = roomMapCounter.Discovered;
							value.Total = roomMapCounter.Total;
							value.TotalKnown = roomMapCounter.TotalKnown;
						}
					}
				}
				_removedRooms.Clear();
				foreach (KeyValuePair<int, Label> label in _labels)
				{
					if (!_seenRooms.Contains(label.Key))
					{
						if ((Object)(object)label.Value.Text != (Object)null)
						{
							Object.Destroy((Object)(object)((Component)label.Value.Text).gameObject);
						}
						_removedRooms.Add(label.Key);
					}
				}
				foreach (int removedRoom in _removedRooms)
				{
					_labels.Remove(removedRoom);
				}
			}
		}

		private bool CreateRoot(Map map)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Expected O, but got Unknown
			if ((Object)(object)_material != (Object)null)
			{
				Object.Destroy((Object)(object)_material);
			}
			_material = null;
			_labels.Clear();
			TextMeshPro val = FindTemplate(map);
			_font = (((Object)(object)val != (Object)null) ? ((TMP_Text)val).font : TMP_Settings.defaultFontAsset);
			if ((Object)(object)_font == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val2 in array)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						_font = val2;
						break;
					}
				}
			}
			if ((Object)(object)_font == (Object)null)
			{
				if (!_fontWarningLogged)
				{
					Debug.LogWarning((object)"ValuableTracker: no loaded font is available for room map counters.");
					_fontWarningLogged = true;
				}
				return false;
			}
			Material val3 = (((Object)(object)val != (Object)null && (Object)(object)((TMP_Text)val).fontSharedMaterial != (Object)null) ? ((TMP_Text)val).fontSharedMaterial : ((TMP_Asset)_font).material);
			if ((Object)(object)val3 != (Object)null)
			{
				_material = new Material(val3)
				{
					name = "ValuableTracker Room Counter Material"
				};
				if (_material.HasProperty("_FaceColor"))
				{
					_material.SetColor("_FaceColor", Color.white);
				}
				if (_material.HasProperty("_OutlineColor"))
				{
					_material.SetColor("_OutlineColor", Color.black);
				}
				if (_material.HasProperty("_OutlineWidth"))
				{
					_material.SetFloat("_OutlineWidth", 0.16f);
				}
			}
			Renderer val4 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<Renderer>() : null);
			MapValuable val5 = (((Object)(object)map.ValuableObject != (Object)null) ? map.ValuableObject.GetComponent<MapValuable>() : null);
			if ((Object)(object)val5 != (Object)null && (Object)(object)val5.spriteRenderer != (Object)null)
			{
				val4 = (Renderer)(object)val5.spriteRenderer;
			}
			_renderLayer = (((Object)(object)val4 != (Object)null) ? ((Component)val4).gameObject.layer : ((Component)map.OverLayerParent).gameObject.layer);
			_sortingLayer = (((Object)(object)val4 != (Object)null) ? val4.sortingLayerID : 0);
			_sortingOrder = (((Object)(object)val4 != (Object)null) ? (val4.sortingOrder + 20) : 20);
			_root = new GameObject("ValuableTracker Room Counters")
			{
				layer = _renderLayer
			};
			_root.transform.SetParent(map.OverLayerParent, false);
			return true;
		}

		private static TextMeshPro? FindTemplate(Map map)
		{
			MapShopScreen componentInChildren = ((Component)map).GetComponentInChildren<MapShopScreen>(true);
			if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.text != (Object)null && (Object)(object)((TMP_Text)componentInChildren.text).font != (Object)null)
			{
				return componentInChildren.text;
			}
			DirtFinderMapComplete componentInChildren2 = ((Component)map).GetComponentInChildren<DirtFinderMapComplete>(true);
			if ((Object)(object)componentInChildren2 != (Object)null && (Object)(object)componentInChildren2.TextTop != (Object)null && (Object)(object)((TMP_Text)componentInChildren2.TextTop).font != (Object)null)
			{
				return componentInChildren2.TextTop;
			}
			return null;
		}

		private Label CreateLabel(int roomId)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Room " + roomId.ToString(CultureInfo.InvariantCulture) + " Valuable Counter")
			{
				layer = _renderLayer
			};
			val.SetActive(false);
			TextMeshPro val2 = val.AddComponent<TextMeshPro>();
			val2.transform.SetParent(_root.transform, false);
			val2.transform.localScale = Vector3.one;
			((TMP_Text)val2).font = _font;
			if ((Object)(object)_material != (Object)null)
			{
				((TMP_Text)val2).fontSharedMaterial = _material;
			}
			((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val2).enableAutoSizing = false;
			((TMP_Text)val2).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)val2).overflowMode = (TextOverflowModes)0;
			((TMP_Text)val2).richText = false;
			((Graphic)val2).raycastTarget = false;
			((TMP_Text)val2).rectTransform.sizeDelta = new Vector2(5f, 1f);
			MeshRenderer component = val.GetComponent<MeshRenderer>();
			((Renderer)component).sortingLayerID = _sortingLayer;
			((Renderer)component).sortingOrder = _sortingOrder;
			((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)component).receiveShadows = false;
			return new Label(val2);
		}

		internal void Clear()
		{
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)_root);
			}
			if ((Object)(object)_material != (Object)null)
			{
				Object.Destroy((Object)(object)_material);
			}
			_root = null;
			_material = null;
			_font = null;
			_map = null;
			_labels.Clear();
			_seenRooms.Clear();
			_removedRooms.Clear();
		}

		public void Dispose()
		{
			Clear();
		}
	}
	internal readonly struct RoomValuableLocation
	{
		internal int ValuableId { get; }

		internal Component Source { get; }

		internal bool Discovered { get; }

		internal RoomValuableLocation(int valuableId, Component source, bool discovered)
		{
			ValuableId = valuableId;
			Source = source;
			Discovered = discovered;
		}
	}
	internal sealed class RoomMapTracker
	{
		private sealed class RoomDefinition
		{
			internal readonly int Id;

			internal readonly RoomVolume Volume;

			internal Bounds Bounds;

			internal Vector3 LabelPosition;

			internal float InventoryBottom;

			internal float InventoryTop;

			internal RoomDefinition(int id, RoomVolume volume, Bounds bounds)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				Id = id;
				Volume = volume;
				Bounds = bounds;
				LabelPosition = ((Bounds)(ref bounds)).center;
			}
		}

		private readonly struct RoomRegion
		{
			internal readonly RoomVolume Volume;

			internal readonly Collider Collider;

			internal readonly Bounds Bounds;

			internal readonly RoomDefinition Room;

			internal RoomRegion(RoomVolume volume, Collider collider, Bounds bounds, RoomDefinition room)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				Volume = volume;
				Collider = collider;
				Bounds = bounds;
				Room = room;
			}
		}

		private static readonly FieldInfo LayerHeightField = AccessTools.Field(typeof(Map), "LayerHeight");

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

		private readonly List<RoomRegion> _regions = new List<RoomRegion>();

		private readonly List<RoomValuableObservation> _observations = new List<RoomValuableObservation>();

		private readonly List<int> _activeRoomIds = new List<int>();

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

		private Map? _map;

		private float _layerHeight = 4f;

		private float _nextGeometryRefresh;

		internal void Clear()
		{
			_rooms.Clear();
			_regions.Clear();
			_observations.Clear();
			_activeRoomIds.Clear();
			_uncertainRooms.Clear();
			_nextGeometryRefresh = 0f;
			_map = null;
		}

		internal void Refresh(Map map, IReadOnlyList<RoomValuableLocation> valuables, List<RoomMapCounter> counters, bool inventoryComplete = true)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_map != (Object)(object)map)
			{
				Clear();
				_map = map;
				if (LayerHeightField.GetValue(map) is float num && num > 0f)
				{
					_layerHeight = num;
				}
			}
			if (Time.unscaledTime >= _nextGeometryRefresh)
			{
				RefreshGeometry();
				_nextGeometryRefresh = Time.unscaledTime + 1f;
			}
			_observations.Clear();
			_uncertainRooms.Clear();
			foreach (RoomDefinition value in _rooms.Values)
			{
				value.InventoryBottom = ((Bounds)(ref value.Bounds)).min.y + 0.01f;
				value.InventoryTop = ((Bounds)(ref value.Bounds)).max.y - 0.11f;
			}
			bool flag = !inventoryComplete;
			foreach (RoomValuableLocation valuable in valuables)
			{
				if ((Object)(object)valuable.Source == (Object)null)
				{
					continue;
				}
				RoomDefinition roomDefinition = ResolveRoom(valuable.Source);
				if (roomDefinition != null)
				{
					roomDefinition.InventoryBottom = Math.Min(roomDefinition.InventoryBottom, valuable.Source.transform.position.y);
					roomDefinition.InventoryTop = Math.Max(roomDefinition.InventoryTop, valuable.Source.transform.position.y);
					_observations.Add(new RoomValuableObservation(valuable.ValuableId, roomDefinition.Id, valuable.Discovered));
					continue;
				}
				Module componentInParent = valuable.Source.GetComponentInParent<Module>();
				bool flag2 = false;
				if ((Object)(object)componentInParent != (Object)null)
				{
					foreach (RoomDefinition value2 in _rooms.Values)
					{
						if (!((Object)(object)value2.Volume.Module != (Object)(object)componentInParent) && FootprintContains(value2, valuable.Source.transform.position))
						{
							_uncertainRooms.Add(value2.Id);
							flag2 = true;
						}
					}
				}
				if (!flag2)
				{
					flag = true;
				}
			}
			Dictionary<int, RoomCounterSnapshot> dictionary = RoomCounterModel.Count(_activeRoomIds, _observations);
			counters.Clear();
			foreach (RoomDefinition value3 in _rooms.Values)
			{
				RoomCounterSnapshot roomCounterSnapshot = dictionary[value3.Id];
				int num2 = Floor(value3.InventoryBottom);
				int num3 = Mathf.Max(num2, Floor(value3.InventoryTop));
				int layer = ((map.PlayerLayer >= num2 && map.PlayerLayer <= num3) ? map.PlayerLayer : num2);
				counters.Add(new RoomMapCounter(value3.Id, layer, value3.LabelPosition, roomCounterSnapshot.Discovered, roomCounterSnapshot.Total, !flag && !_uncertainRooms.Contains(value3.Id)));
			}
		}

		private int Floor(float worldY)
		{
			return Mathf.FloorToInt((worldY + 0.1f) / _layerHeight);
		}

		private void RefreshGeometry()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			_rooms.Clear();
			_regions.Clear();
			_activeRoomIds.Clear();
			Transform val = (((Object)(object)LevelGenerator.Instance != (Object)null && (Object)(object)LevelGenerator.Instance.LevelParent != (Object)null) ? LevelGenerator.Instance.LevelParent.transform : null);
			RoomVolume[] array = Object.FindObjectsByType<RoomVolume>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (RoomVolume val2 in array)
			{
				if ((Object)(object)val2.Module == (Object)null)
				{
					continue;
				}
				Scene scene = ((Component)val2).gameObject.scene;
				if (!((Scene)(ref scene)).IsValid())
				{
					continue;
				}
				scene = ((Component)val2).gameObject.scene;
				if (!((Scene)(ref scene)).isLoaded || ((Object)(object)val != (Object)null && !((Component)val2.Module).transform.IsChildOf(val)))
				{
					continue;
				}
				int instanceID = ((Object)val2).GetInstanceID();
				Collider[] componentsInChildren = ((Component)val2).GetComponentsInChildren<Collider>(true);
				foreach (Collider val3 in componentsInChildren)
				{
					if ((val3 is BoxCollider || val3 is MeshCollider) && !((Object)(object)((Component)val3).GetComponentInParent<RoomVolume>() != (Object)(object)val2))
					{
						Bounds val4 = GeometryBounds(val3);
						if (!_rooms.TryGetValue(instanceID, out RoomDefinition value) || value == null)
						{
							value = new RoomDefinition(instanceID, val2, val4);
							_rooms.Add(instanceID, value);
							_activeRoomIds.Add(instanceID);
						}
						else
						{
							((Bounds)(ref value.Bounds)).Encapsulate(val4);
						}
						_regions.Add(new RoomRegion(val2, val3, val4, value));
					}
				}
			}
			foreach (RoomDefinition value2 in _rooms.Values)
			{
				float num = float.PositiveInfinity;
				foreach (RoomRegion region in _regions)
				{
					RoomRegion current2 = region;
					if (current2.Room == value2)
					{
						float num2 = HorizontalDistance(((Bounds)(ref current2.Bounds)).center, ((Bounds)(ref value2.Bounds)).center);
						if (!(num2 >= num))
						{
							num = num2;
							value2.LabelPosition = ((Bounds)(ref current2.Bounds)).center;
						}
					}
				}
			}
		}

		private static Bounds GeometryBounds(Collider collider)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			BoxCollider val = (BoxCollider)(object)((collider is BoxCollider) ? collider : null);
			Bounds bounds = default(Bounds);
			if (val != null)
			{
				((Bounds)(ref bounds))..ctor(val.center, val.size);
			}
			else
			{
				MeshCollider val2 = (MeshCollider)(object)((collider is MeshCollider) ? collider : null);
				if (val2 == null || !((Object)(object)val2.sharedMesh != (Object)null))
				{
					return collider.bounds;
				}
				bounds = val2.sharedMesh.bounds;
			}
			Bounds result = default(Bounds);
			((Bounds)(ref result))..ctor(((Component)collider).transform.TransformPoint(((Bounds)(ref bounds)).min), new Vector3(0f, 0f, 0f));
			for (int i = -1; i <= 1; i += 2)
			{
				for (int j = -1; j <= 1; j += 2)
				{
					for (int k = -1; k <= 1; k += 2)
					{
						Vector3 val3 = ((Bounds)(ref bounds)).center + new Vector3((float)i * ((Bounds)(ref bounds)).size.x * 0.5f, (float)j * ((Bounds)(ref bounds)).size.y * 0.5f, (float)k * ((Bounds)(ref bounds)).size.z * 0.5f);
						((Bounds)(ref result)).Encapsulate(new Bounds(((Component)collider).transform.TransformPoint(val3), new Vector3(0f, 0f, 0f)));
					}
				}
			}
			return result;
		}

		private RoomDefinition? ResolveRoom(Component source)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = source.transform.position;
			RoomVolumeCheck component = source.GetComponent<RoomVolumeCheck>();
			List<RoomVolume> list = (((Object)(object)component != (Object)null) ? component.CurrentRooms : null);
			RoomDefinition best = null;
			float bestDistance = float.PositiveInfinity;
			foreach (RoomRegion region in _regions)
			{
				RoomRegion current = region;
				if ((Object)(object)current.Collider == (Object)null)
				{
					continue;
				}
				Collider collider = current.Collider;
				BoxCollider val = (BoxCollider)(object)((collider is BoxCollider) ? collider : null);
				bool num;
				if (val == null)
				{
					if (list == null || !list.Contains(current.Volume))
					{
						continue;
					}
					num = ((Bounds)(ref current.Bounds)).Contains(position);
				}
				else
				{
					num = InsideBox(val, position, ignoreHeight: false);
				}
				if (num)
				{
					Select(current.Room, position, ref best, ref bestDistance);
				}
			}
			if (best != null)
			{
				return best;
			}
			if (list != null)
			{
				foreach (RoomVolume item in list)
				{
					if (!((Object)(object)item == (Object)null) && _rooms.TryGetValue(((Object)item).GetInstanceID(), out RoomDefinition value) && value != null && FootprintContains(value, position))
					{
						SelectShelf(value, position, ref best, ref bestDistance);
					}
				}
			}
			Module componentInParent = source.GetComponentInParent<Module>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				foreach (RoomDefinition value2 in _rooms.Values)
				{
					if (!((Object)(object)value2.Volume.Module != (Object)(object)componentInParent) && FootprintContains(value2, position, allowMeshBounds: false))
					{
						SelectShelf(value2, position, ref best, ref bestDistance);
					}
				}
			}
			return best;
		}

		private bool FootprintContains(RoomDefinition room, Vector3 position, bool allowMeshBounds = true)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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: Unknown result type (might be due to invalid IL or missing references)
			foreach (RoomRegion region in _regions)
			{
				RoomRegion current = region;
				if (current.Room != room || (Object)(object)current.Collider == (Object)null)
				{
					continue;
				}
				Collider collider = current.Collider;
				BoxCollider val = (BoxCollider)(object)((collider is BoxCollider) ? collider : null);
				if (val != null)
				{
					if (InsideBox(val, position, ignoreHeight: true))
					{
						return true;
					}
				}
				else if (allowMeshBounds && position.x >= ((Bounds)(ref current.Bounds)).min.x && position.x <= ((Bounds)(ref current.Bounds)).max.x && position.z >= ((Bounds)(ref current.Bounds)).min.z && position.z <= ((Bounds)(ref current.Bounds)).max.z)
				{
					return true;
				}
			}
			return false;
		}

		private static bool InsideBox(BoxCollider box, Vector3 position, bool ignoreHeight)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)box).transform.InverseTransformPoint(position) - box.center;
			Vector3 val2 = box.size * 0.5f;
			if (Mathf.Abs(val.x) <= val2.x + 0.01f && Mathf.Abs(val.z) <= val2.z + 0.01f)
			{
				if (!ignoreHeight)
				{
					return Mathf.Abs(val.y) <= val2.y + 0.01f;
				}
				return true;
			}
			return false;
		}

		private static void Select(RoomDefinition room, Vector3 position, ref RoomDefinition? best, ref float bestDistance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			float num = ((position.y < ((Bounds)(ref room.Bounds)).min.y) ? (((Bounds)(ref room.Bounds)).min.y - position.y) : ((position.y > ((Bounds)(ref room.Bounds)).max.y) ? (position.y - ((Bounds)(ref room.Bounds)).max.y) : 0f));
			float num2 = num * num + HorizontalDistance(position, room.LabelPosition);
			int num3 = (room.Volume.priorityVolume ? room.Volume.priority : int.MinValue);
			int num4 = ((best != null && best.Volume.priorityVolume) ? best.Volume.priority : int.MinValue);
			if (best == null || num3 > num4 || (num3 == num4 && (num2 < bestDistance || (Mathf.Approximately(num2, bestDistance) && room.Id < best.Id))))
			{
				best = room;
				bestDistance = num2;
			}
		}

		private static void SelectShelf(RoomDefinition room, Vector3 position, ref RoomDefinition? best, ref float bestDistance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			float num = VerticalGap(position.y, room.Bounds);
			float num2 = ((best != null) ? VerticalGap(position.y, best.Bounds) : float.PositiveInfinity);
			float num3 = HorizontalDistance(position, room.LabelPosition);
			int num4 = (room.Volume.priorityVolume ? room.Volume.priority : int.MinValue);
			int num5 = ((best != null && best.Volume.priorityVolume) ? best.Volume.priority : int.MinValue);
			if (best == null || num < num2 || (Mathf.Approximately(num, num2) && (num4 > num5 || (num4 == num5 && (num3 < bestDistance || (Mathf.Approximately(num3, bestDistance) && room.Id < best.Id))))))
			{
				best = room;
				bestDistance = num3;
			}
		}

		private static float VerticalGap(float y, Bounds bounds)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!(y < ((Bounds)(ref bounds)).min.y))
			{
				if (!(y > ((Bounds)(ref bounds)).max.y))
				{
					return 0f;
				}
				return y - ((Bounds)(ref bounds)).max.y;
			}
			return ((Bounds)(ref bounds)).min.y - y;
		}

		private static float HorizontalDistance(Vector3 a, Vector3 b)
		{
			//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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			return num * num + num2 * num2;
		}
	}
	internal enum ValuableStatus
	{
		Available,
		InCart,
		InBox,
		Sold,
		Destroyed
	}
	internal sealed class ValuableLedger
	{
		private readonly Dictionary<int, ValuableStatus> _valuables = new Dictionary<int, ValuableStatus>();

		internal void Register(int id)
		{
			if (!_valuables.ContainsKey(id))
			{
				_valuables.Add(id, ValuableStatus.Available);
			}
		}

		internal bool Contains(int id)
		{
			return _valuables.ContainsKey(id);
		}

		internal bool IsActive(int id)
		{
			if (_valuables.TryGetValue(id, out var value) && value != ValuableStatus.Sold)
			{
				return value != ValuableStatus.Destroyed;
			}
			return false;
		}

		internal void SetInCart(int id, bool inCart)
		{
			if (_valuables.TryGetValue(id, out var value) && value != ValuableStatus.Sold && value != ValuableStatus.Destroyed)
			{
				if (inCart)
				{
					_valuables[id] = ValuableStatus.InCart;
				}
				else if (value == ValuableStatus.InCart)
				{
					_valuables[id] = ValuableStatus.Available;
				}
			}
		}

		internal void SetInBox(int id, bool inBox)
		{
			if (_valuables.TryGetValue(id, out var value) && value != ValuableStatus.Sold && value != ValuableStatus.Destroyed)
			{
				if (inBox)
				{
					_valuables[id] = ValuableStatus.InBox;
				}
				else if (value == ValuableStatus.InBox)
				{
					_valuables[id] = ValuableStatus.Available;
				}
			}
		}

		internal void MarkSold(int id)
		{
			if (_valuables.ContainsKey(id))
			{
				_valuables[id] = ValuableStatus.Sold;
			}
		}

		internal void MarkDestroyed(int id)
		{
			if (_valuables.TryGetValue(id, out var value) && value != ValuableStatus.Sold)
			{
				_valuables[id] = ValuableStatus.Destroyed;
			}
		}

		internal void Clear()
		{
			_valuables.Clear();
		}

		internal TrackerSnapshot CreateSnapshot()
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			using (Dictionary<int, ValuableStatus>.ValueCollection.Enumerator enumerator = _valuables.Values.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					switch (enumerator.Current)
					{
					case ValuableStatus.Sold:
						num++;
						break;
					case ValuableStatus.InCart:
						num2++;
						break;
					case ValuableStatus.InBox:
						num3++;
						break;
					case ValuableStatus.Destroyed:
						num4++;
						break;
					}
				}
			}
			return new TrackerSnapshot(_valuables.Count, num, num2, num4, num3);
		}
	}
	internal readonly struct TrackerSnapshot
	{
		internal int Total { get; }

		internal int Sold { get; }

		internal int InCart { get; }

		internal int Destroyed { get; }

		internal int InBox { get; }

		internal int Collected => Sold + InCart + InBox;

		internal int AccountedFor => Sold + InCart + InBox + Destroyed;

		internal TrackerSnapshot(int total, int sold, int inCart, int destroyed, int inBox = 0)
		{
			Total = total;
			Sold = sold;
			InCart = inCart;
			Destroyed = destroyed;
			InBox = inBox;
		}
	}
	internal static class ValuableTrackerState
	{
		private static readonly ValuableLedger Ledger = new ValuableLedger();

		private static readonly Dictionary<int, ValuableObject> Items = new Dictionary<int, ValuableObject>();

		private static readonly Dictionary<int, ItemValuableBox> StoredInBoxes = new Dictionary<int, ItemValuableBox>();

		private static readonly Dictionary<int, bool> BoxedDiscovery = new Dictionary<int, bool>();

		private static readonly InitialInventoryReadiness InitialInventory = new InitialInventoryReadiness();

		private static readonly FieldInfo DiscoveredField = AccessTools.Field(typeof(ValuableObject), "discovered");

		private static readonly FieldInfo CommittedField = AccessTools.Field(typeof(ValuableObject), "committedToExtraction");

		private static readonly FieldInfo InCartField = AccessTools.Field(typeof(PhysGrabObjectImpactDetector), "inCart");

		private static readonly FieldInfo DeadField = AccessTools.Field(typeof(PhysGrabObject), "dead");

		private static readonly FieldInfo BoxStateField = AccessTools.Field(typeof(ItemValuableBox), "currentState");

		private static readonly FieldInfo SpawnAmountField = AccessTools.Field(typeof(ValuableDirector), "valuableSpawnAmount");

		private static readonly FieldInfo TargetAmountField = AccessTools.Field(typeof(ValuableDirector), "valuableTargetAmount");

		private static ManualLogSource? _logger;

		private static float _nextRescan;

		private static int _lastLoggedCount = -1;

		private static bool _loggedInitialInventory;

		internal static bool IsReady
		{
			get
			{
				if ((Object)(object)RunManager.instance != (Object)null && (Object)(object)LevelGenerator.Instance != (Object)null && SemiFunc.RunIsLevel())
				{
					return SemiFunc.LevelGenDone();
				}
				return false;
			}
		}

		internal static bool InventoryComplete
		{
			get
			{
				if (IsReady)
				{
					return InitialInventory.Complete;
				}
				return false;
			}
		}

		internal static void Init(ManualLogSource logger)
		{
			_logger = logger;
		}

		internal static void Clear()
		{
			Ledger.Clear();
			Items.Clear();
			StoredInBoxes.Clear();
			BoxedDiscovery.Clear();
			InitialInventory.Clear();
			_nextRescan = 0f;
			_lastLoggedCount = -1;
			_loggedInitialInventory = false;
		}

		internal static void Rebuild()
		{
			if (!IsReady)
			{
				return;
			}
			ValuableDirector instance = ValuableDirector.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			foreach (ValuableObject valuable in instance.valuableList)
			{
				Register(valuable);
			}
			ObserveInitialInventory(instance);
			_nextRescan = Time.unscaledTime + 1f;
			int total = Ledger.CreateSnapshot().Total;
			if (total == _lastLoggedCount && (!InitialInventory.Captured || _loggedInitialInventory))
			{
				return;
			}
			int num = 0;
			foreach (ValuableObject value in Items.Values)
			{
				if ((Object)(object)value != (Object)null && !((Component)value).gameObject.activeInHierarchy)
				{
					num++;
				}
			}
			ManualLogSource? logger = _logger;
			if (logger != null)
			{
				logger.LogDebug((object)($"Tracking {total} valuables ({num} inactive). Initial inventory: " + $"expected={InitialInventory.Expected}, started={InitialInventory.Started}, " + $"registered={InitialInventory.Registered}, complete={InitialInventory.Complete}."));
			}
			_lastLoggedCount = total;
			_loggedInitialInventory = InitialInventory.Captured;
		}

		internal static void Register(ValuableObject? valuable)
		{
			if ((Object)(object)valuable == (Object)null || (Object)(object)RunManager.instance == (Object)null || (Object)(object)LevelGenerator.Instance == (Object)null || !SemiFunc.RunIsLevel())
			{
				return;
			}
			ValuableDirector instance = ValuableDirector.instance;
			if (!((Object)(object)instance == (Object)null) && instance.valuableList.Contains(valuable))
			{
				int instanceID = ((Object)valuable).GetInstanceID();
				Ledger.Register(instanceID);
				Items[instanceID] = valuable;
				if (!LevelGenerator.Instance.Generated)
				{
					ObserveInitialInventory(instance);
				}
			}
		}

		private static void ObserveInitialInventory(ValuableDirector director)
		{
			InitialInventory.Observe(LevelGenerator.Instance.Generated, (int)TargetAmountField.GetValue(director), (int)SpawnAmountField.GetValue(director), Items.Count);
		}

		internal static TrackerSnapshot CreateSnapshot()
		{
			if (!IsReady)
			{
				return default(TrackerSnapshot);
			}
			if (Time.unscaledTime >= _nextRescan)
			{
				Rebuild();
			}
			foreach (KeyValuePair<int, ValuableObject> item in Items)
			{
				int key = item.Key;
				if (StoredInBoxes.TryGetValue(key, out ItemValuableBox value))
				{
					if ((Object)(object)value == (Object)null)
					{
						Ledger.MarkDestroyed(key);
					}
					else
					{
						Ledger.SetInBox(key, inBox: true);
					}
					continue;
				}
				ValuableObject value2 = item.Value;
				if ((Object)(object)value2 == (Object)null)
				{
					Ledger.MarkDestroyed(key);
					continue;
				}
				if (IsBroken(((Component)value2).GetComponent<PhysGrabObject>()))
				{
					Ledger.MarkDestroyed(key);
					continue;
				}
				PhysGrabObjectImpactDetector component = ((Component)value2).GetComponent<PhysGrabObjectImpactDetector>();
				int num;
				if ((Object)(object)component != (Object)null)
				{
					object value3 = InCartField.GetValue(component);
					num = ((value3 is bool && (bool)value3) ? 1 : 0);
				}
				else
				{
					num = 0;
				}
				bool inCart = (byte)num != 0;
				Ledger.SetInCart(key, inCart);
			}
			return Ledger.CreateSnapshot();
		}

		internal static void MarkSold(PhysGrabObject target)
		{
			if (IsReady && !((Object)(object)target == (Object)null) && !IsBroken(target))
			{
				ValuableObject component = ((Component)target).GetComponent<ValuableObject>();
				if ((Object)(object)component != (Object)null)
				{
					Ledger.MarkSold(((Object)component).GetInstanceID());
				}
			}
		}

		internal static void ObjectDestroyed(PhysGrabObject target)
		{
			if (!IsReady)
			{
				return;
			}
			ValuableObject component = ((Component)target).GetComponent<ValuableObject>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)component).GetInstanceID();
			if (!Ledger.Contains(instanceID) || StoredInBoxes.ContainsKey(instanceID))
			{
				return;
			}
			if (!IsBroken(target))
			{
				object value = CommittedField.GetValue(component);
				if (value is bool && (bool)value)
				{
					Ledger.MarkSold(instanceID);
					return;
				}
			}
			Ledger.MarkDestroyed(instanceID);
		}

		internal static void Absorb(ItemValuableBox box, PhysGrabObject target)
		{
			if (IsReady && !((Object)(object)box == (Object)null) && !((Object)(object)target == (Object)null))
			{
				ValuableObject component = ((Component)target).GetComponent<ValuableObject>();
				if (!((Object)(object)component == (Object)null))
				{
					Register(component);
					int instanceID = ((Object)component).GetInstanceID();
					StoredInBoxes[instanceID] = box;
					Dictionary<int, bool> boxedDiscovery = BoxedDiscovery;
					object value = DiscoveredField.GetValue(component);
					boxedDiscovery[instanceID] = value is bool && (bool)value;
					Ledger.SetInBox(instanceID, inBox: true);
				}
			}
		}

		internal static void BoxValueUpdated(ItemValuableBox box)
		{
			if (box.CurrentValue <= 0f && BoxStateField.GetValue(box)?.ToString() == "Extracting")
			{
				FinishBox(box, sold: true);
			}
		}

		internal static void BoxDestroyed(ItemValuableBox box)
		{
			if (IsReady)
			{
				bool sold = !IsBroken(((Component)box).GetComponent<PhysGrabObject>()) && BoxStateField.GetValue(box)?.ToString() == "Extracting";
				FinishBox(box, sold);
			}
		}

		private static bool IsBroken(PhysGrabObject target)
		{
			if ((Object)(object)target != (Object)null)
			{
				object value = DeadField.GetValue(target);
				if (value is bool)
				{
					return (bool)value;
				}
				return false;
			}
			return false;
		}

		internal static void FinishBox(ItemValuableBox box, bool sold)
		{
			List<int> list = new List<int>();
			foreach (KeyValuePair<int, ItemValuableBox> storedInBox in StoredInBoxes)
			{
				if (!((Object)(object)storedInBox.Value != (Object)(object)box))
				{
					if (sold)
					{
						Ledger.MarkSold(storedInBox.Key);
					}
					else
					{
						Ledger.MarkDestroyed(storedInBox.Key);
					}
					list.Add(storedInBox.Key);
				}
			}
			foreach (int item in list)
			{
				StoredInBoxes.Remove(item);
				BoxedDiscovery.Remove(item);
			}
		}

		internal static void FillRoomLocations(List<RoomValuableLocation> locations)
		{
			locations.Clear();
			if (!IsReady)
			{
				return;
			}
			foreach (KeyValuePair<int, ValuableObject> item in Items)
			{
				if (!Ledger.IsActive(item.Key))
				{
					continue;
				}
				if (StoredInBoxes.TryGetValue(item.Key, out ItemValuableBox value))
				{
					if ((Object)(object)value != (Object)null && ((Component)value).gameObject.activeInHierarchy)
					{
						locations.Add(new RoomValuableLocation(item.Key, (Component)(object)value, BoxedDiscovery.TryGetValue(item.Key, out var value2) && value2));
					}
					continue;
				}
				ValuableObject value3 = item.Value;
				if (!((Object)(object)value3 == (Object)null) && !IsBroken(((Component)value3).GetComponent<PhysGrabObject>()))
				{
					int key = item.Key;
					object value4 = DiscoveredField.GetValue(value3);
					locations.Add(new RoomValuableLocation(key, (Component)(object)value3, value4 is bool && (bool)value4));
				}
			}
		}

		internal static int DiscoverAll()
		{
			if (!IsReady || (Object)(object)Map.Instance == (Object)null)
			{
				return 0;
			}
			Rebuild();
			HashSet<int> hashSet = new HashSet<int>();
			MapValuable[] array = Object.FindObjectsByType<MapValuable>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (MapValuable val in array)
			{
				if ((Object)(object)val.target != (Object)null)
				{
					hashSet.Add(((Object)val.target).GetInstanceID());
				}
			}
			int num = 0;
			foreach (KeyValuePair<int, ValuableObject> item in Items)
			{
				ValuableObject value = item.Value;
				if (!((Object)(object)value == (Object)null) && ((Component)value).gameObject.activeInHierarchy && !StoredInBoxes.ContainsKey(item.Key))
				{
					object value2 = DiscoveredField.GetValue(value);
					if (!(value2 is bool) || !(bool)value2)
					{
						DiscoveredField.SetValue(value, true);
						num++;
					}
					if (hashSet.Add(item.Key))
					{
						Map.Instance.AddValuable(value);
					}
				}
			}
			return num;
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "Awake")]
	internal static class LevelGeneratorAwakePatch
	{
		private static void Prefix()
		{
			ValuableTrackerState.Clear();
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "GenerateDoneApply")]
	internal static class LevelGeneratorGenerateDoneApplyPatch
	{
		private static void Postfix()
		{
			ValuableTrackerState.Rebuild();
		}
	}
	[HarmonyPatch(typeof(ValuableObject), "Start")]
	internal static class ValuableObjectStartPatch
	{
		private static void Postfix(ValuableObject __instance)
		{
			ValuableTrackerState.Register(__instance);
		}
	}
	[HarmonyPatch(typeof(PhysGrabObject), "OnDestroy")]
	internal static class PhysGrabObjectOnDestroyPatch
	{
		private static void Prefix(PhysGrabObject __instance)
		{
			ValuableTrackerState.ObjectDestroyed(__instance);
		}
	}
	[HarmonyPatch(typeof(ExtractionPoint), "SpawnExtractingVisuals")]
	internal static class ExtractionSalePatch
	{
		private static void Prefix(PhysGrabObject target)
		{
			ValuableTrackerState.MarkSold(target);
		}
	}
	[HarmonyPatch(typeof(ItemValuableBox), "StartAbsorbLocal")]
	internal static class ValuableBoxAbsorbPatch
	{
		private static void Prefix(ItemValuableBox __instance, PhysGrabObject __0)
		{
			ValuableTrackerState.Absorb(__instance, __0);
		}
	}
	[HarmonyPatch(typeof(ItemValuableBox), "UpdateValueRPC")]
	internal static class ValuableBoxValuePatch
	{
		private static void Postfix(ItemValuableBox __instance)
		{
			ValuableTrackerState.BoxValueUpdated(__instance);
		}
	}
	[HarmonyPatch(typeof(ItemValuableBox), "OnExtracted")]
	internal static class ValuableBoxExtractedPatch
	{
		private static void Prefix(ItemValuableBox __instance)
		{
			ValuableTrackerState.FinishBox(__instance, sold: true);
		}
	}
	[HarmonyPatch(typeof(ItemValuableBox), "ExplodeValuableBox")]
	internal static class ValuableBoxExplodePatch
	{
		private static void Prefix(ItemValuableBox __instance)
		{
			ValuableTrackerState.FinishBox(__instance, sold: false);
		}
	}
	[HarmonyPatch(typeof(ItemValuableBox), "OnDestroy")]
	internal static class ValuableBoxDestroyedPatch
	{
		private static void Prefix(ItemValuableBox __instance)
		{
			ValuableTrackerState.BoxDestroyed(__instance);
		}
	}
}