Decompiled source of All Shop Items In Level Plus v1.1.0

REPO_All_Shop_Items_in_Level.dll

Decompiled a month 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 System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace REPO_All_Shop_Items_in_Level
{
	[BepInPlugin("REPO_All_Shop_Items_in_Level", "ALL Shop Items spawn in Level", "1.1.0")]
	[BepInProcess("REPO.exe")]
	public class Plugin : BaseUnityPlugin
	{
		private class SpawnRecord
		{
			public GameObject Obj;

			public string Name;

			public Vector3 Pos;
		}

		private class CategorySettings
		{
			public int TypeId;

			public List<int> TypeIds = new List<int>();

			public string Name;

			public ConfigEntry<bool> Enabled;

			public ConfigEntry<bool> ShowOnMap;

			public ConfigEntry<float> Chance;

			public ConfigEntry<bool> UsePrice;
		}

		private class OldConfigData
		{
			public Dictionary<string, KeyValuePair<string, string>> Values = new Dictionary<string, KeyValuePair<string, string>>();

			public bool IsOldLayout;
		}

		private class HiddenIcon
		{
			public Map MapInstance;

			public MapCustom MapCustom;

			public object[] Args;

			public GameObject Item;

			public ItemAttributes Attributes;

			public PhysGrabObject Grab;

			public Component Icon;

			public string Name;
		}

		private class LootEntry
		{
			public string Token;

			public bool IsCategory;

			public float Chance;
		}

		private class LootRule
		{
			public List<string> Mobs = new List<string>();

			public List<LootEntry> Entries = new List<LootEntry>();
		}

		[HarmonyPatch(typeof(EnemyParent), "Despawn")]
		private class DespawnPatch
		{
			private class DropState
			{
				public bool Valid;

				public int Valuables;

				public bool HasPosition;

				public Vector3 Position;
			}

			private static bool _fieldsLooked;

			private static FieldInfo _enemyField;

			private static FieldInfo _healthField;

			private static FieldInfo _valuableField;

			private static bool TryGetSpawnValuableCurrent(EnemyParent ep, out int value)
			{
				value = 0;
				try
				{
					if (!_fieldsLooked)
					{
						_fieldsLooked = true;
						_enemyField = AccessTools.Field(typeof(EnemyParent), "Enemy");
						_healthField = AccessTools.Field(typeof(Enemy), "Health");
						_valuableField = AccessTools.Field(typeof(EnemyHealth), "spawnValuableCurrent");
					}
					if (_enemyField == null || _healthField == null || _valuableField == null)
					{
						return false;
					}
					object value2 = _enemyField.GetValue(ep);
					if (value2 == null)
					{
						return false;
					}
					object value3 = _healthField.GetValue(value2);
					if (value3 == null)
					{
						return false;
					}
					object value4 = _valuableField.GetValue(value3);
					if (value4 == null)
					{
						return false;
					}
					value = (int)value4;
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}

			private static bool TryGetDropPosition(EnemyParent ep, out Vector3 position)
			{
				//IL_0002: 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_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//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)
				position = Vector3.zero;
				try
				{
					object? obj = AccessTools.Field(typeof(EnemyParent), "Enemy")?.GetValue(ep);
					Enemy val = (Enemy)((obj is Enemy) ? obj : null);
					if ((Object)(object)val == (Object)null)
					{
						return false;
					}
					Transform val2 = (((Object)(object)val.CustomValuableSpawnTransform != (Object)null) ? val.CustomValuableSpawnTransform : val.CenterTransform);
					if ((Object)(object)val2 == (Object)null)
					{
						return false;
					}
					position = val2.position + Vector3.up;
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}

			private static void Prefix(EnemyParent __instance, out DropState __state)
			{
				//IL_005d: 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)
				__state = new DropState();
				if (SemiFunc.IsMasterClientOrSingleplayer() && EnemyLootEnabled != null && EnemyLootEnabled.Value)
				{
					__state.Valid = TryGetSpawnValuableCurrent(__instance, out var value);
					__state.Valuables = value;
					if (TryGetDropPosition(__instance, out var position))
					{
						__state.HasPosition = true;
						__state.Position = position;
					}
					if (!__state.Valid && DebugMode.Value && _lootWarned.Add("nohealth:" + ((Object)__instance).name))
					{
						DebugLog("[DROP] " + ((Object)__instance).name + ": its loot counter cannot be read right now (no health component yet), no drop check for it");
					}
				}
			}

			private static void Postfix(EnemyParent __instance, DropState __state)
			{
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_0398: Unknown result type (might be due to invalid IL or missing references)
				//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_03ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_042d: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0164: Unknown result type (might be due to invalid IL or missing references)
				//IL_0112: Unknown result type (might be due to invalid IL or missing references)
				//IL_0114: Unknown result type (might be due to invalid IL or missing references)
				//IL_0115: Unknown result type (might be due to invalid IL or missing references)
				//IL_011a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0489: Unknown result type (might be due to invalid IL or missing references)
				//IL_048a: Unknown result type (might be due to invalid IL or missing references)
				//IL_013f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0141: Unknown result type (might be due to invalid IL or missing references)
				if (__state == null || !__state.Valid || !SemiFunc.IsMasterClientOrSingleplayer() || !EnemyLootEnabled.Value || !TryGetSpawnValuableCurrent(__instance, out var value) || value <= __state.Valuables)
				{
					return;
				}
				string name = ((Object)__instance).name;
				LootRule lootRule = null;
				foreach (LootRule lootRule2 in GetLootRules())
				{
					if (MobMatches(lootRule2, name))
					{
						lootRule = lootRule2;
						break;
					}
				}
				if (lootRule == null)
				{
					DebugLog("[DROP] " + name + ": no rule in EnemyLootRules matches this enemy");
					return;
				}
				Vector3 val = __state.Position;
				bool flag = __state.HasPosition;
				if (TryGetDropPosition(__instance, out var position))
				{
					if (flag)
					{
						Vector3 val2 = position - val;
						if (((Vector3)(ref val2)).magnitude > 1f)
						{
							val2 = position - val;
							DebugLog($"[DROP] {name} moved {((Vector3)(ref val2)).magnitude:F1}m during despawn; using its position from before despawning");
						}
					}
					if (!flag)
					{
						val = position;
						flag = true;
					}
				}
				if (!flag || !IsPositionValid(val))
				{
					DebugLog($"[DROP] {name}: no valid drop position ({val}), skipping");
					return;
				}
				int num = 0;
				int value2 = MaxDropsPerEnemy.Value;
				List<LootEntry> list = new List<LootEntry>(lootRule.Entries);
				Shuffle(list);
				foreach (LootEntry item2 in list)
				{
					if (num >= value2)
					{
						DebugLog($"[DROP] {name}: maximum of {value2} drop(s) reached, the rest of the rule is skipped");
						break;
					}
					if ((double)item2.Chance <= 0.0)
					{
						continue;
					}
					float num2 = Random.Range(0f, 100f);
					if ((double)num2 > (double)item2.Chance)
					{
						DebugLog($"[DROP] {name}: {item2.Token} roll failed ({num2:F1} > {item2.Chance:F1}%)");
						continue;
					}
					Item item = null;
					if (item2.IsCategory)
					{
						if (!_categoryLookup.TryGetValue(item2.Token, out var value3))
						{
							LootWarnOnce("EnemyLootRules: unknown category '@" + item2.Token + "' (use the names of the 'Category: ...' sections)");
							continue;
						}
						if (!GetRandomItemOfCategory(value3, out item, ignoreSpawnRules: true) || (Object)(object)item == (Object)null)
						{
							DebugLog("[DROP] " + name + ": @" + item2.Token + " has nothing to drop (" + _lastPoolFailReason + ")");
							continue;
						}
					}
					else if (!_itemLookup.TryGetValue(item2.Token, out item) || (Object)(object)item == (Object)null)
					{
						LootWarnOnce("EnemyLootRules: unknown item '" + item2.Token + "' (write it as shown in the category sections)");
						continue;
					}
					try
					{
						Vector3 val3 = new Vector3(Random.Range(-0.3f, 0.3f), 0f, Random.Range(-0.3f, 0.3f)) * (float)num;
						GameObject val4 = SpawnItem(item, val + val3, Quaternion.identity, enemyDrop: true);
						if ((Object)(object)val4 == (Object)null)
						{
							DebugLog("[DROP FAIL] " + ((Object)item).name + " from " + name + ": " + (_lastSpawnFailReason ?? "unknown reason"));
							continue;
						}
						num++;
						DebugLog($"[DROP] {((Object)item).name} from {name} at {val}");
						if (DebugMode.Value && (Object)(object)Instance != (Object)null)
						{
							((MonoBehaviour)Instance).StartCoroutine(Instance.VerifySpawnedItems(new List<SpawnRecord>
							{
								new SpawnRecord
								{
									Obj = val4,
									Name = ((Object)item).name,
									Pos = val
								}
							}));
						}
					}
					catch (Exception ex)
					{
						DebugLog("Error spawning enemy loot: " + ex.Message);
					}
				}
			}
		}

		[HarmonyPatch]
		private class ValuableDirector_Spawn_Patch
		{
			private static MethodBase TargetMethod()
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(ValuableDirector), "Spawn", (Type[])null, (Type[])null);
				return ((object)methodInfo != null) ? methodInfo : AccessTools.Method(typeof(ValuableDirector), "SpawnValuable", (Type[])null, (Type[])null);
			}

			[HarmonyPrefix]
			private static void Prefix(object[] __args)
			{
				ValuableVolume val = __args.OfType<ValuableVolume>().FirstOrDefault();
				if ((Object)(object)val != (Object)null)
				{
					((Component)val).gameObject.AddComponent<UsedVolumeTracker>();
				}
			}
		}

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> DebugMode;

		internal static ConfigEntry<bool> ExtractionSavesItems;

		internal static ConfigEntry<bool> RevealHiddenOnMap;

		internal static ConfigEntry<float> RevealDistance;

		private const string ExtraMarker = "SIIL_EXTRA";

		private const string DropMarker = "SIIL_DROP";

		internal static ConfigEntry<bool> EnemyLootEnabled;

		internal static ConfigEntry<string> EnemyLootRules;

		internal static ConfigEntry<int> MaxDropsPerEnemy;

		internal static ConfigEntry<bool> SaveInventoryItems;

		internal static ConfigEntry<bool> RespectMaxAmount;

		internal static ConfigEntry<bool> InventoryMarker;

		internal static ConfigEntry<string> MarkerKeptText;

		internal static ConfigEntry<string> MarkerLostText;

		internal static ConfigEntry<float> MinItemValue;

		internal static ConfigEntry<float> MaxItemValue;

		internal static ConfigEntry<int> MaxItemsPerLevel;

		internal static ConfigEntry<int> MinItemsPerLevel;

		internal static ConfigEntry<bool> EnableLevelScaling;

		internal static ConfigEntry<float> LevelScalingMultiplier;

		internal static ConfigEntry<bool> AnnounceRareItems;

		internal static ConfigEntry<float> AnnounceValueThreshold;

		internal static readonly Dictionary<string, ConfigEntry<bool>> ItemSpawnEntries = new Dictionary<string, ConfigEntry<bool>>();

		internal static readonly Dictionary<string, ConfigEntry<bool>> ItemMapEntries = new Dictionary<string, ConfigEntry<bool>>();

		private static string _lastSpawnFailReason;

		private static string _lastPoolFailReason;

		private static string _lastSkipReason;

		private static int _dbgTried;

		private static int _dbgSkipped;

		private static int _dbgNoItem;

		private static int _dbgSpawnFailed;

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

		private static readonly List<string> _dbgFailures = new List<string>();

		private static readonly List<SpawnRecord> _dbgSpawned = new List<SpawnRecord>();

		private static readonly Dictionary<int, CategorySettings> CategorySettingsById = new Dictionary<int, CategorySettings>();

		private static readonly List<CategorySettings> CategoryList = new List<CategorySettings>();

		private static readonly Dictionary<string, CategorySettings> _categoryLookup = new Dictionary<string, CategorySettings>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Item> _itemLookup = new Dictionary<string, Item>(StringComparer.OrdinalIgnoreCase);

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

		private static OldConfigData _oldConfig;

		private static Dictionary<string, Item> _cachedItemDictionary;

		private static Dictionary<int, List<Item>> _cachedByType = new Dictionary<int, List<Item>>();

		private static float _lastItemRefreshTime;

		private static bool _isSpawning = false;

		private static bool _categoriesInitialized;

		private float _nextInitCheck;

		private static bool _mapEntityLookupDone;

		private static FieldInfo _mapEntityField;

		private static bool _mapWarned;

		private static readonly List<HiddenIcon> _hiddenIcons = new List<HiddenIcon>();

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

		private static Coroutine _revealLoop;

		private static FieldInfo _purchasedField;

		private static bool _inventoryExtrasSaved;

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

		private static readonly Dictionary<int, TextMeshProUGUI> _spotMarkers = new Dictionary<int, TextMeshProUGUI>();

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

		private static FieldInfo _spotIconField;

		private static bool _markerWarned;

		private static List<LootRule> _lootRules = new List<LootRule>();

		private static string _lootRulesSource;

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

		public static Plugin Instance { get; private set; }

		private static string CategoryName(int typeId)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return ((object)(itemType)typeId/*cast due to .constrained prefix*/).ToString();
		}

		private static string SanitizeConfigText(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return "";
			}
			char[] array = new char[9] { '=', '\n', '\r', '\t', '\\', '"', '\'', '[', ']' };
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char value in text)
			{
				if (Array.IndexOf(array, value) < 0)
				{
					stringBuilder.Append(value);
				}
			}
			return stringBuilder.ToString().Trim();
		}

		private static void DebugResetCounters()
		{
			_dbgTried = 0;
			_dbgSkipped = 0;
			_dbgNoItem = 0;
			_dbgSpawnFailed = 0;
			_dbgSpawnedByItem.Clear();
			_dbgFailures.Clear();
			_dbgSpawned.Clear();
		}

		private static string SafeName(Object o)
		{
			return (o != (Object)null) ? o.name : "<destroyed/null>";
		}

		private static void RecordSpawnFailure(Item item, ValuableVolume volume)
		{
			_dbgSpawnFailed++;
			string text = "'" + SafeName((Object)(object)item) + "' at volume '" + SafeName((Object)(object)volume) + "': " + (_lastSpawnFailReason ?? "unknown reason");
			_dbgFailures.Add(text);
			DebugLog("[SPAWN FAIL] " + text);
		}

		private static void LogSpawnSummary(int spawned, int min, int cap)
		{
			if (DebugMode == null || !DebugMode.Value)
			{
				return;
			}
			DebugLog($"[SUMMARY] volumes tried={_dbgTried} | spawned={spawned} | skipped (chance/disabled/invalid)={_dbgSkipped} | no item available={_dbgNoItem} | spawn failed={_dbgSpawnFailed} | min={min} cap={cap}");
			if (_dbgSpawnedByItem.Count > 0)
			{
				DebugLog("[SUMMARY] spawned by item: " + string.Join(", ", (from kv in _dbgSpawnedByItem
					orderby kv.Value descending
					select $"{kv.Key} x{kv.Value}").ToArray()));
			}
			foreach (string dbgFailure in _dbgFailures)
			{
				DebugLog("[SUMMARY] failure: " + dbgFailure);
			}
			if ((Object)(object)Instance != (Object)null && _dbgSpawned.Count > 0)
			{
				((MonoBehaviour)Instance).StartCoroutine(Instance.VerifySpawnedItems(new List<SpawnRecord>(_dbgSpawned)));
			}
		}

		private IEnumerator VerifySpawnedItems(List<SpawnRecord> snapshot)
		{
			yield return (object)new WaitForSecondsRealtime(3f);
			if (!SemiFunc.RunIsLevel())
			{
				DebugLog("[VERIFY] skipped: level changed before verification");
				yield break;
			}
			int ok = 0;
			foreach (SpawnRecord r in snapshot)
			{
				if ((Object)(object)r.Obj == (Object)null)
				{
					DebugLog($"[VERIFY] MISSING: '{r.Name}' spawned at {r.Pos} no longer exists (destroyed after spawning)");
				}
				else if (!r.Obj.activeInHierarchy)
				{
					DebugLog($"[VERIFY] INACTIVE: '{r.Name}' spawned at {r.Pos} is not active in the scene");
				}
				else if (r.Pos.y - r.Obj.transform.position.y > 50f)
				{
					DebugLog($"[VERIFY] FELL: '{r.Name}' spawned at {r.Pos} is now at {r.Obj.transform.position} (fell out of the map?)");
				}
				else
				{
					ok++;
				}
			}
			DebugLog($"[VERIFY] {ok}/{snapshot.Count} spawned items are still present and active 3s after spawning");
		}

		private static void LoadOldConfig(string path)
		{
			_oldConfig = null;
			try
			{
				if (string.IsNullOrEmpty(path) || !File.Exists(path))
				{
					return;
				}
				OldConfigData oldConfigData = new OldConfigData();
				string text = "";
				string value = null;
				string[] array = File.ReadAllLines(path);
				foreach (string text2 in array)
				{
					string text3 = text2.Trim();
					if (text3.Length == 0)
					{
						continue;
					}
					if (text3.StartsWith("[") && text3.EndsWith("]"))
					{
						text = text3.Substring(1, text3.Length - 2);
						value = null;
					}
					else if (text3.StartsWith("# Default value:"))
					{
						value = text3.Substring("# Default value:".Length).Trim();
					}
					else if (!text3.StartsWith("#"))
					{
						int num = text3.IndexOf(" = ", StringComparison.Ordinal);
						if (num > 0)
						{
							oldConfigData.Values[text + "\n" + text3.Substring(0, num).Trim()] = new KeyValuePair<string, string>(text3.Substring(num + 3).Trim(), value);
							value = null;
						}
					}
				}
				oldConfigData.IsOldLayout = oldConfigData.Values.Keys.Any((string k) => k.StartsWith("1_Debug\n") || k.StartsWith("5_EnemyLoot\n"));
				_oldConfig = oldConfigData;
				if (oldConfigData.IsOldLayout)
				{
					Logger.LogInfo((object)"Settings from the previous version found: they will be moved to the new layout.");
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Could not read the previous config for migration: " + ex.Message));
			}
		}

		private static bool TryGetOld(string[] sections, string key, out string value, out string oldDefault)
		{
			value = null;
			oldDefault = null;
			if (_oldConfig == null || !_oldConfig.IsOldLayout)
			{
				return false;
			}
			foreach (string text in sections)
			{
				if (_oldConfig.Values.TryGetValue(text + "\n" + key, out var value2))
				{
					value = value2.Key;
					oldDefault = value2.Value;
					return true;
				}
			}
			return false;
		}

		private static bool SameValue(string a, string b)
		{
			if (a == null || b == null)
			{
				return false;
			}
			if (double.TryParse(a, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && double.TryParse(b, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2))
			{
				return Math.Abs(result - result2) < 1E-06;
			}
			return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
		}

		private static void MigrateEntry(ConfigEntryBase entry, string[] oldSections, string oldKey)
		{
			if (entry == null || !TryGetOld(oldSections, oldKey, out var value, out var oldDefault))
			{
				return;
			}
			try
			{
				if (oldDefault != null && SameValue(value, oldDefault))
				{
					entry.BoxedValue = entry.DefaultValue;
				}
				else
				{
					entry.SetSerializedValue(value);
				}
			}
			catch (Exception ex)
			{
				DebugLog("Could not migrate '" + oldKey + "': " + ex.Message);
			}
		}

		private static void MigrateEnemyLootRules()
		{
			string[] sections = new string[1] { "5_EnemyLoot" };
			string value;
			string oldDefault;
			bool flag = TryGetOld(sections, "HealthPackDropChance", out value, out oldDefault);
			string value2;
			string oldDefault2;
			bool flag2 = TryGetOld(sections, "EnableEnemyLootTables", out value2, out oldDefault2);
			if (flag || flag2)
			{
				float result = 100f;
				bool result2 = true;
				if (flag)
				{
					float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
				}
				if (flag2)
				{
					bool.TryParse(value2, out result2);
				}
				if (!(Math.Abs(result - 100f) < 0.001f && result2))
				{
					string text = result.ToString("0.###", CultureInfo.InvariantCulture);
					EnemyLootRules.Value = (result2 ? ("gnome|small: @item_upgrade=" + text + "; large|boss: @drone=" + text + "; *: @healthPack=" + text) : ("*: @healthPack=" + text));
				}
			}
		}

		private static string[] OldSectionsFor(string categoryName)
		{
			return (!(categoryName == "carts")) ? new string[1] { "Category: " + categoryName } : new string[2] { "Category: cart", "Category: pocket_cart" };
		}

		private static string CategoryKeyOf(int typeId)
		{
			string text = CategoryName(typeId);
			return (text == "cart" || text == "pocket_cart") ? "carts" : text;
		}

		private static int VolumeClassOf(int typeId)
		{
			return typeId switch
			{
				0 => 1, 
				3 => 0, 
				_ => 2, 
			};
		}

		private static void Shuffle<T>(List<T> list)
		{
			for (int num = list.Count - 1; num > 0; num--)
			{
				int index = Random.Range(0, num + 1);
				T value = list[num];
				list[num] = list[index];
				list[index] = value;
			}
		}

		private CategorySettings RegisterCategorySettings(List<int> typeIds, string name, string section)
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			CategorySettings categorySettings = new CategorySettings
			{
				TypeId = typeIds[0],
				Name = name
			};
			categorySettings.TypeIds.AddRange(typeIds);
			bool flag = !(name == "carts") && !(name == "vehicle");
			categorySettings.Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>(section, "Category enabled", flag, "MASTER SWITCH for spawning. If OFF: no item of this category spawns as an extra in the level, whatever the individual 'Spawn in level' toggles say. If ON: the individual toggles apply. (Items you buy, the ones the game places and enemy drops are never affected.)");
			categorySettings.ShowOnMap = ((BaseUnityPlugin)this).Config.Bind<bool>(section, "Category show on map", false, "(Client) MASTER SWITCH for the map (OFF by default: extras stay off your map until you see them). If OFF: every extra of this category spawned in the level is hidden from your map, whatever the individual 'Show on map' toggles say. If ON: the individual toggles apply.");
			float num = 0.5f;
			categorySettings.Chance = ((BaseUnityPlugin)this).Config.Bind<float>(section, "SpawnChance", num, new ConfigDescription("% chance for a '" + name + "' item to spawn in a level spawn spot (0 = never)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			categorySettings.UsePrice = ((BaseUnityPlugin)this).Config.Bind<bool>(section, "UseShopPriceForItemSelection", true, "If ON: cheaper items of this category appear more often.");
			string[] oldSections = OldSectionsFor(name);
			MigrateEntry((ConfigEntryBase)(object)categorySettings.Enabled, oldSections, "Category enabled");
			MigrateEntry((ConfigEntryBase)(object)categorySettings.ShowOnMap, oldSections, "Category show on map");
			MigrateEntry((ConfigEntryBase)(object)categorySettings.Chance, oldSections, "SpawnChance");
			MigrateEntry((ConfigEntryBase)(object)categorySettings.UsePrice, oldSections, "UseShopPriceForItemSelection");
			foreach (int typeId in typeIds)
			{
				CategorySettingsById[typeId] = categorySettings;
			}
			CategoryList.Add(categorySettings);
			return categorySettings;
		}

		internal static void DebugLog(string message)
		{
			if (DebugMode != null && DebugMode.Value)
			{
				Logger.LogInfo((object)("[DEBUG] " + message));
			}
		}

		private void Awake()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Expected O, but got Unknown
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Expected O, but got Unknown
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Expected O, but got Unknown
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Expected O, but got Unknown
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Expected O, but got Unknown
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0367: Expected O, but got Unknown
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Instance = this;
			Logger = ((BaseUnityPlugin)this).Logger;
			Logger.LogInfo((object)"Plugin REPO_All_Shop_Items_in_Level is loaded!");
			Harmony val = new Harmony("REPO_All_Shop_Items_in_Level");
			val.PatchAll(typeof(Plugin));
			val.PatchAll(typeof(DespawnPatch));
			val.PatchAll(typeof(ValuableDirector_Spawn_Patch));
			Logger.LogInfo((object)"Harmony patches applied!");
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			LoadOldConfig(((BaseUnityPlugin)this).Config.ConfigFilePath);
			DebugMode = ((BaseUnityPlugin)this).Config.Bind<bool>("0_General", "DebugMode", false, "Enable verbose debug logging (every spawn decision, drop, map icon and extraction is written to the BepInEx log).");
			ExtractionSavesItems = ((BaseUnityPlugin)this).Config.Bind<bool>("0_General", "ExtractionSavesItems", true, "If ON: extra items spawned by this mod become permanent only if you bring them into the extraction point (like selling them). They vanish for the rest of the round and come back in the truck next level. Extras you leave behind are lost.");
			RevealHiddenOnMap = ((BaseUnityPlugin)this).Config.Bind<bool>("0_General", "RevealHiddenOnMap", true, "(Client) Extras hidden from the map by the 'Show on map' options appear on it once you see them nearby or pick them up / equip them. Turn OFF to keep them hidden for good.");
			RevealDistance = ((BaseUnityPlugin)this).Config.Bind<float>("0_General", "RevealDistance", 8f, new ConfigDescription("(Client) How close (in meters) a hidden extra must be, and in view, to be revealed on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), Array.Empty<object>()));
			MinItemValue = ((BaseUnityPlugin)this).Config.Bind<float>("1_Filters", "MinItemValue", 0f, new ConfigDescription("Minimum item value for spawning (0 = disabled)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 999999f), Array.Empty<object>()));
			MaxItemValue = ((BaseUnityPlugin)this).Config.Bind<float>("1_Filters", "MaxItemValue", 0f, new ConfigDescription("Maximum item value for spawning (0 = disabled)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 999999f), Array.Empty<object>()));
			MaxItemsPerLevel = ((BaseUnityPlugin)this).Config.Bind<int>("1_Filters", "MaxItemsPerLevel", 0, new ConfigDescription("Maximum items to spawn per level (0 = unlimited)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 999), Array.Empty<object>()));
			MinItemsPerLevel = ((BaseUnityPlugin)this).Config.Bind<int>("1_Filters", "MinItemsPerLevel", 0, new ConfigDescription("Minimum items guaranteed to spawn per level (0 = disabled)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 999), Array.Empty<object>()));
			EnableLevelScaling = ((BaseUnityPlugin)this).Config.Bind<bool>("2_LevelScaling", "EnableLevelScaling", false, "Spawn chances scale up as you progress through floors");
			LevelScalingMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("2_LevelScaling", "LevelScalingMultiplier", 0.05f, new ConfigDescription("Bonus multiplier per floor completed (0.05 = +5% per floor)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			AnnounceRareItems = ((BaseUnityPlugin)this).Config.Bind<bool>("3_Announce", "AnnounceRareItems", false, "Log to console when an expensive item spawns");
			AnnounceValueThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("3_Announce", "AnnounceValueThreshold", 5000f, new ConfigDescription("Min item value to trigger announce", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 999999f), Array.Empty<object>()));
			EnemyLootEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("4_EnemyLoot", "EnemyLootEnabled", true, "If ON: when an enemy dies and drops valuables, it can also drop shop items following the rules below. Enemy drops are normal items: they ignore 'Category enabled', 'Spawn in level' and 'Show on map' (they always show on the map like a bought item).");
			EnemyLootRules = ((BaseUnityPlugin)this).Config.Bind<string>("4_EnemyLoot", "EnemyLootRules", "*: @healthPack=30", "WHAT EACH ENEMY DROPS. Rules are separated by ';' and the FIRST rule whose enemy matches is used. Format: enemy words : item=chance, item=chance ... \n- Enemy words: parts of the enemy's name (not case sensitive), separated by '|'. '*' matches every enemy. \n- item: an item name exactly as shown in the category sections (e.g. Small Health Pack (25)), or @category to drop one random item of that category (e.g. @drone, @healthPack, @item_upgrade, @gun, @carts). \n- chance: 0-100 (%), written with a dot (0.5). Every item rolls its own chance, so one enemy can drop several. Without '=chance' it is 100. \nExample: gnome: Health Upgrade=25, @healthPack=50; *: Small Health Pack (25)=20");
			MaxDropsPerEnemy = ((BaseUnityPlugin)this).Config.Bind<int>("4_EnemyLoot", "MaxDropsPerEnemy", 1, new ConfigDescription("Maximum number of items ONE enemy can drop when it dies. If its rule could drop more than this, the extra drops are skipped (the items that drop are picked at random).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), Array.Empty<object>()));
			SaveInventoryItems = ((BaseUnityPlugin)this).Config.Bind<bool>("0_General", "SaveInventoryItems", true, "If ON: extras you carry in your inventory when a level is completed are kept (registered) and come back in the truck. If OFF: only the extras you bring to the extraction point are kept.");
			RespectMaxAmount = ((BaseUnityPlugin)this).Config.Bind<bool>("0_General", "RespectMaxAmount", true, "If ON: the number of copies the game can bring back in the truck is respected (the item's own limit and the free truck slots of its size). An extra that would not come back is NOT consumed by the extraction (you can keep using it this round) and you get a message. If OFF: the item limit is raised so every registered copy can come back (the truck slots still apply).");
			InventoryMarker = ((BaseUnityPlugin)this).Config.Bind<bool>("0_General", "InventoryMarker", true, "(Client) Shows a small label under the inventory slots that hold extras of this mod: green if the item will be kept when the level ends, red if it will not.");
			MarkerKeptText = ((BaseUnityPlugin)this).Config.Bind<string>("0_General", "InventoryMarkerKeptText", "REGISTERED", "(Client) Label shown (in green) under an inventory slot whose extra will be kept.");
			MarkerLostText = ((BaseUnityPlugin)this).Config.Bind<string>("0_General", "InventoryMarkerLostText", "CONTRABAND", "(Client) Label shown (in red) under an inventory slot whose extra will NOT be kept.");
			MigrateEntry((ConfigEntryBase)(object)ExtractionSavesItems, new string[1] { "0_General" }, "ExtractionSavesItems");
			MigrateEntry((ConfigEntryBase)(object)RevealHiddenOnMap, new string[1] { "0_General" }, "RevealHiddenOnMap");
			MigrateEntry((ConfigEntryBase)(object)RevealDistance, new string[1] { "0_General" }, "RevealDistance");
			MigrateEntry((ConfigEntryBase)(object)DebugMode, new string[1] { "1_Debug" }, "DebugMode");
			MigrateEntry((ConfigEntryBase)(object)MinItemValue, new string[1] { "2_Filters" }, "MinItemValue");
			MigrateEntry((ConfigEntryBase)(object)MaxItemValue, new string[1] { "2_Filters" }, "MaxItemValue");
			MigrateEntry((ConfigEntryBase)(object)MaxItemsPerLevel, new string[1] { "2_Filters" }, "MaxItemsPerLevel");
			MigrateEntry((ConfigEntryBase)(object)MinItemsPerLevel, new string[1] { "2_Filters" }, "MinItemsPerLevel");
			MigrateEntry((ConfigEntryBase)(object)EnableLevelScaling, new string[1] { "3_LevelScaling" }, "EnableLevelScaling");
			MigrateEntry((ConfigEntryBase)(object)LevelScalingMultiplier, new string[1] { "3_LevelScaling" }, "LevelScalingMultiplier");
			MigrateEntry((ConfigEntryBase)(object)AnnounceRareItems, new string[1] { "4_Announce" }, "AnnounceRareItems");
			MigrateEntry((ConfigEntryBase)(object)AnnounceValueThreshold, new string[1] { "4_Announce" }, "AnnounceValueThreshold");
			MigrateEntry((ConfigEntryBase)(object)EnemyLootEnabled, new string[1] { "5_EnemyLoot" }, "SpawnHealthPacksFromEnemies");
			MigrateEnemyLootRules();
			((MonoBehaviour)this).StartCoroutine(InventoryMarkerLoop());
			((MonoBehaviour)this).StartCoroutine(InitializeItemListsWhenReady());
		}

		private static bool ItemListIsReady()
		{
			return (Object)(object)StatsManager.instance != (Object)null && StatsManager.instance.itemDictionary != null && StatsManager.instance.itemDictionary.Count > 0;
		}

		internal static void EnsureInitialized()
		{
			if (!_categoriesInitialized && Instance != null)
			{
				Instance.TryInitializeCategories();
			}
		}

		private void TryInitializeCategories()
		{
			if (_categoriesInitialized || !ItemListIsReady())
			{
				return;
			}
			_categoriesInitialized = true;
			try
			{
				CreateCategoryConfig();
			}
			catch (Exception ex)
			{
				Logger.LogError((object)("Could not create the category config: " + ex));
			}
		}

		private void Update()
		{
			if (!_categoriesInitialized && !((double)Time.realtimeSinceStartup < (double)_nextInitCheck))
			{
				_nextInitCheck = Time.realtimeSinceStartup + 0.5f;
				TryInitializeCategories();
			}
		}

		private IEnumerator InitializeItemListsWhenReady()
		{
			Logger.LogInfo((object)"Waiting for the game's item list to create the category config...");
			float startTime = Time.realtimeSinceStartup;
			bool warned = false;
			while (!_categoriesInitialized)
			{
				TryInitializeCategories();
				if (_categoriesInitialized)
				{
					break;
				}
				if (!warned && (double)Time.realtimeSinceStartup - (double)startTime > 30.0)
				{
					Logger.LogWarning((object)"The game's item list is not ready yet - still waiting (no timeout)");
					warned = true;
				}
				yield return (object)new WaitForSecondsRealtime(0.5f);
			}
		}

		private void CreateCategoryConfig()
		{
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Expected O, but got Unknown
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Expected O, but got Unknown
			Logger.LogInfo((object)"Creating the category config sections from the game item list");
			_cachedItemDictionary = StatsManager.instance.itemDictionary;
			SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>();
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			CategoryList.Clear();
			CategorySettingsById.Clear();
			_categoryLookup.Clear();
			_itemLookup.Clear();
			foreach (IGrouping<string, Item> item in from i in _cachedItemDictionary.Values
				where (Object)(object)i != (Object)null
				group i by CategoryKeyOf((int)i.itemType) into g
				orderby g.Key
				select g)
			{
				string key = item.Key;
				List<int> list = item.Select((Item i) => (int)i.itemType).Distinct().ToList();
				string text = "Category: " + key;
				CategorySettings value = RegisterCategorySettings(list, key, text);
				_categoryLookup[key] = value;
				foreach (int item2 in list)
				{
					_categoryLookup[CategoryName(item2)] = value;
				}
				HashSet<string> hashSet = new HashSet<string>();
				List<KeyValuePair<string, Item>> list2 = new List<KeyValuePair<string, Item>>();
				foreach (Item item3 in item.OrderBy((Item i) => ((Object)i).name))
				{
					string name = ((Object)item3).name;
					string text2 = SanitizeConfigText(item3.itemName);
					if (text2.Length == 0)
					{
						text2 = SanitizeConfigText(name);
					}
					if (!hashSet.Add(text2))
					{
						text2 = SanitizeConfigText(text2 + " (" + name + ")");
						hashSet.Add(text2);
					}
					list2.Add(new KeyValuePair<string, Item>(text2, item3));
				}
				list2.Sort((KeyValuePair<string, Item> a, KeyValuePair<string, Item> b) => string.Compare(a.Key, b.Key, StringComparison.OrdinalIgnoreCase));
				string[] oldSections = OldSectionsFor(key);
				foreach (KeyValuePair<string, Item> item4 in list2)
				{
					ItemSpawnEntries[((Object)item4.Value).name] = ((BaseUnityPlugin)this).Config.Bind<bool>(text, "Spawn in level | " + item4.Key, true, new ConfigDescription("If OFF, '" + item4.Key + "' will not spawn as an extra in levels (only used when 'Category enabled' is ON)", (AcceptableValueBase)null, Array.Empty<object>()));
				}
				foreach (KeyValuePair<string, Item> item5 in list2)
				{
					ItemMapEntries[((Object)item5.Value).name] = ((BaseUnityPlugin)this).Config.Bind<bool>(text, "Show on map | " + item5.Key, true, new ConfigDescription("(Client) If OFF, '" + item5.Key + "' is hidden from your map (only used when 'Category enabled' is ON)", (AcceptableValueBase)null, Array.Empty<object>()));
				}
				foreach (KeyValuePair<string, Item> item6 in list2)
				{
					string name2 = ((Object)item6.Value).name;
					MigrateEntry((ConfigEntryBase)(object)ItemSpawnEntries[name2], oldSections, "Spawn in level | " + item6.Key);
					MigrateEntry((ConfigEntryBase)(object)ItemMapEntries[name2], oldSections, "Show on map | " + item6.Key);
				}
				foreach (KeyValuePair<string, Item> item7 in list2)
				{
					_itemLookup[item7.Key] = item7.Value;
					_itemLookup[((Object)item7.Value).name] = item7.Value;
				}
				sortedDictionary[key] = list2.Count;
			}
			((BaseUnityPlugin)this).Config.Save();
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			Logger.LogInfo((object)("Category sections created: " + string.Join(", ", sortedDictionary.Select((KeyValuePair<string, int> kv) => $"{kv.Key}={kv.Value}").ToArray())));
			Logger.LogInfo((object)$"Items with spawn disabled: {ItemSpawnEntries.Values.Count((ConfigEntry<bool> en) => !en.Value)} | hidden from map: {ItemMapEntries.Values.Count((ConfigEntry<bool> en) => !en.Value)}");
			RefreshCachedItemLists();
		}

		private static void RefreshCachedItemLists()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected I4, but got Unknown
			if (StatsManager.instance?.itemDictionary == null)
			{
				return;
			}
			_cachedItemDictionary = StatsManager.instance.itemDictionary;
			Dictionary<int, List<Item>> dictionary = new Dictionary<int, List<Item>>();
			foreach (Item candidate in GetCandidates((Item i) => true))
			{
				int key = (int)candidate.itemType;
				if (!dictionary.TryGetValue(key, out var value))
				{
					value = (dictionary[key] = new List<Item>());
				}
				value.Add(candidate);
			}
			_cachedByType = dictionary;
			_lastItemRefreshTime = Time.time;
			DebugLog("Cache refreshed: " + string.Join(", ", (from kv in dictionary
				orderby kv.Key
				select $"{CategoryName(kv.Key)}={kv.Value.Count}").ToArray()));
		}

		private static bool PassesValueFilter(Item item)
		{
			float num = (((Object)(object)item.value != (Object)null) ? item.value.valueMin : 0f);
			return ((double)MinItemValue.Value <= 0.0 || (double)num >= (double)MinItemValue.Value) && ((double)MaxItemValue.Value <= 0.0 || (double)num <= (double)MaxItemValue.Value);
		}

		private static bool IsItemAllowed(Item item)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected I4, but got Unknown
			if (CategorySettingsById.TryGetValue((int)item.itemType, out var value) && !value.Enabled.Value)
			{
				return false;
			}
			ConfigEntry<bool> value2;
			return !ItemSpawnEntries.TryGetValue(((Object)item).name, out value2) || value2.Value;
		}

		private static string ChanceLabel(CategorySettings c)
		{
			if (!c.Enabled.Value)
			{
				return "off";
			}
			return GetScaledChance(c.Chance.Value).ToString("F2") + "%";
		}

		private static List<Item> GetCandidates(Func<Item, bool> typeFilter)
		{
			if (StatsManager.instance?.itemDictionary == null)
			{
				return new List<Item>();
			}
			return (from i in StatsManager.instance.itemDictionary.Values.Where(typeFilter)
				where (Object)(object)i.value != (Object)null && (double)i.value.valueMin > 0.0
				select i).Where(PassesValueFilter).ToList();
		}

		private static Item WeightedOrRandom(List<Item> list, bool usePrice)
		{
			if (list == null || list.Count == 0)
			{
				return null;
			}
			float[] array = new float[list.Count];
			float num = 0f;
			for (int i = 0; i < list.Count; i++)
			{
				float num2 = (usePrice ? (1f / Mathf.Max(0.01f, list[i].value.valueMin)) : 1f);
				array[i] = num2;
				num += array[i];
			}
			if (float.IsNaN(num) || float.IsInfinity(num))
			{
				return list[Random.Range(0, list.Count)];
			}
			if (num <= 0f)
			{
				return null;
			}
			float num3 = Random.Range(0f, num);
			for (int j = 0; j < list.Count; j++)
			{
				num3 -= array[j];
				if (num3 <= 0f)
				{
					return list[j];
				}
			}
			return list[list.Count - 1];
		}

		private static float GetScaledChance(float baseChance)
		{
			if (!EnableLevelScaling.Value || (Object)(object)RunManager.instance == (Object)null)
			{
				return baseChance;
			}
			int levelsCompleted = RunManager.instance.levelsCompleted;
			return Mathf.Min(baseChance * (float)(1.0 + (double)levelsCompleted * (double)LevelScalingMultiplier.Value), 100f);
		}

		private static bool IsPositionValid(Vector3 pos)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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)
			return !float.IsNaN(pos.x) && !float.IsNaN(pos.y) && !float.IsNaN(pos.z) && pos != Vector3.zero;
		}

		private static bool IsVolumeStillValid(ValuableVolume volume)
		{
			if ((Object)(object)volume == (Object)null)
			{
				return false;
			}
			return !((Object)(object)volume == (Object)null) && !((Object)(object)((Component)volume).gameObject == (Object)null) && ((Component)volume).gameObject.activeInHierarchy;
		}

		private static void AnnounceItem(Item item, Vector3 position)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if (AnnounceRareItems.Value && !((Object)(object)item?.value == (Object)null) && !((double)item.value.valueMin < (double)AnnounceValueThreshold.Value))
			{
				Logger.LogInfo((object)$"[RARE SPAWN] {((Object)item).name} (value ~{item.value.valueMin}) at {position}");
			}
		}

		private static bool GetRandomItemOfType(int typeId, out Item item, bool ignoreSpawnRules = false)
		{
			if (CategorySettingsById.TryGetValue(typeId, out var value))
			{
				return GetRandomItemOfCategory(value, out item, ignoreSpawnRules);
			}
			item = null;
			_lastPoolFailReason = "no category settings for '" + CategoryName(typeId) + "' yet (config not created yet?)";
			return false;
		}

		private static bool GetRandomItemOfCategory(CategorySettings category, out Item item, bool ignoreSpawnRules)
		{
			item = null;
			_lastPoolFailReason = null;
			if ((double)Time.time - (double)_lastItemRefreshTime > 60.0)
			{
				RefreshCachedItemLists();
			}
			if (!ignoreSpawnRules && !category.Enabled.Value)
			{
				_lastPoolFailReason = "the '" + category.Name + "' category is turned off (master switch 'Category enabled')";
				return false;
			}
			List<Item> list = new List<Item>();
			foreach (int typeId in category.TypeIds)
			{
				if (_cachedByType.TryGetValue(typeId, out var value) && value != null)
				{
					list.AddRange(value);
				}
			}
			if (list.Count == 0)
			{
				_lastPoolFailReason = "the '" + category.Name + "' item pool is empty (cache not ready, or every item was removed by MinItemValue/MaxItemValue)";
				return false;
			}
			if (!ignoreSpawnRules && ItemSpawnEntries.Count > 0)
			{
				list = list.Where((Item i) => IsItemAllowed(i)).ToList();
				if (list.Count == 0)
				{
					_lastPoolFailReason = "every '" + category.Name + "' item has 'Spawn in level' turned off in the [Category: " + category.Name + "] config section";
					return false;
				}
			}
			item = WeightedOrRandom(list, category.UsePrice.Value);
			if ((Object)(object)item == (Object)null)
			{
				_lastPoolFailReason = "weighted pick from the '" + category.Name + "' pool returned null";
			}
			return (Object)(object)item != (Object)null;
		}

		private static bool GetRandomShopItem(out Item item)
		{
			item = null;
			List<CategorySettings> list = CategoryList.Where((CategorySettings c) => c.Enabled.Value && (!c.TypeIds.Contains(8) || (double)c.Chance.Value > 0.0)).ToList();
			Shuffle(list);
			foreach (CategorySettings item3 in list)
			{
				if (GetRandomItemOfCategory(item3, out var item2, ignoreSpawnRules: false) && (Object)(object)item2 != (Object)null)
				{
					item = item2;
					return true;
				}
			}
			return false;
		}

		private static GameObject SpawnItem(Item item, Vector3 position, Quaternion rotation, bool enemyDrop = false)
		{
			//IL_0044: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected I4, but got Unknown
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			_lastSpawnFailReason = null;
			if ((Object)(object)item == (Object)null || item.prefab == null)
			{
				_lastSpawnFailReason = "null item or null prefab reference";
				DebugLog("Spawn failed: null item or prefab");
				return null;
			}
			string name = ((Object)item).name;
			if (!IsPositionValid(position))
			{
				_lastSpawnFailReason = $"bad spawn position {position} (NaN or zero)";
				DebugLog($"Spawn of {name} rejected: bad position {position}");
				return null;
			}
			if (_isSpawning)
			{
				_lastSpawnFailReason = "re-entrant spawn call blocked (another spawn was in progress)";
				DebugLog("Spawn of " + name + " blocked: already inside a spawn call");
				return null;
			}
			_isSpawning = true;
			try
			{
				string text = "Items/" + name;
				GameObject val;
				if (SemiFunc.IsMultiplayer())
				{
					if (!PhotonNetwork.IsConnected || !PhotonNetwork.InRoom)
					{
						_lastSpawnFailReason = $"multiplayer run but not in a Photon room (connected={PhotonNetwork.IsConnected}, inRoom={PhotonNetwork.InRoom})";
						DebugLog("Spawn of " + name + " blocked: not in a Photon room");
						return null;
					}
					val = PhotonNetwork.InstantiateRoomObject(text, position, rotation, (byte)0, new object[1] { enemyDrop ? "SIIL_DROP" : "SIIL_EXTRA" });
				}
				else
				{
					val = Object.Instantiate<GameObject>(((PrefabRef<GameObject>)(object)item.prefab).Prefab, position, rotation);
				}
				if ((Object)(object)val != (Object)null)
				{
					val.AddComponent<SpawnedItemTracker>();
					if (enemyDrop)
					{
						_enemyDropIds.Add(((Object)val).GetInstanceID());
					}
					AnnounceItem(item, position);
					_dbgSpawnedByItem.TryGetValue(name, out var value);
					_dbgSpawnedByItem[name] = value + 1;
					_dbgSpawned.Add(new SpawnRecord
					{
						Obj = val,
						Name = name,
						Pos = position
					});
					DebugLog($"[SPAWN OK] {name} ({CategoryName((int)item.itemType)}) at {position}");
				}
				else
				{
					_lastSpawnFailReason = "instantiate returned null (resource path '" + text + "' missing, or the prefab could not be created)";
				}
				return val;
			}
			catch (Exception ex)
			{
				_lastSpawnFailReason = "exception " + ex.GetType().Name + ": " + ex.Message;
				DebugLog($"Spawn of {name} threw: {ex}");
				return null;
			}
			finally
			{
				_isSpawning = false;
			}
		}

		private static bool HasValuablePropSwitch(ValuableVolume volume)
		{
			return (Object)(object)((Component)volume).GetComponentInParent<ValuablePropSwitch>() != (Object)null;
		}

		private static bool ChooseCategoryForVolume(ValuableVolume volume, out CategorySettings category)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected I4, but got Unknown
			category = null;
			_lastSkipReason = null;
			if (HasValuablePropSwitch(volume))
			{
				_lastSkipReason = "volume belongs to a ValuablePropSwitch";
				return false;
			}
			int num = (int)volume.VolumeType;
			int volumeClass = num switch
			{
				1 => 1, 
				0 => 0, 
				_ => 2, 
			};
			List<CategorySettings> list = CategoryList.Where((CategorySettings c) => c.Chance != null && VolumeClassOf(c.TypeId) == volumeClass).ToList();
			if (list.Count == 0)
			{
				_lastSkipReason = $"no item category is configured for volume type {num} (config not initialized yet?)";
				return false;
			}
			List<CategorySettings> list2 = list.Where((CategorySettings c) => c.Enabled.Value).ToList();
			if (list2.Count == 0)
			{
				_lastSkipReason = "every category for this volume type is turned off (master switch)";
				return false;
			}
			Shuffle(list2);
			foreach (CategorySettings item in list2)
			{
				float scaledChance = GetScaledChance(item.Chance.Value);
				if ((double)scaledChance <= 0.0 || !((double)Random.Range(0f, 100f) <= (double)scaledChance))
				{
					continue;
				}
				category = item;
				return true;
			}
			_lastSkipReason = "chance rolls failed (" + string.Join(", ", list2.Select((CategorySettings c) => $"{c.Name} {GetScaledChance(c.Chance.Value):F2}%").ToArray()) + ")";
			return false;
		}

		private static bool RandomItemSpawn(ValuableVolume volume)
		{
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			string text = SafeName((Object)(object)volume);
			_dbgTried++;
			if (!IsVolumeStillValid(volume))
			{
				_dbgSkipped++;
				DebugLog("[SKIP] volume '" + text + "': no longer valid or not active");
				return false;
			}
			if (!ChooseCategoryForVolume(volume, out var category))
			{
				_dbgSkipped++;
				DebugLog("[SKIP] volume '" + text + "': " + _lastSkipReason);
				return false;
			}
			string name = category.Name;
			if (!GetRandomItemOfCategory(category, out var item, ignoreSpawnRules: false) || (Object)(object)item == (Object)null)
			{
				_dbgNoItem++;
				string text2 = "volume '" + text + "' (" + name + "): " + (_lastPoolFailReason ?? "no item available");
				_dbgFailures.Add("no item - " + text2);
				DebugLog("[NO ITEM] " + text2);
				return false;
			}
			if ((Object)(object)SpawnItem(item, ((Component)volume).transform.position, ((Component)volume).transform.rotation) == (Object)null)
			{
				RecordSpawnFailure(item, volume);
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
		[HarmonyPostfix]
		public static void RunManager_ChangeLevel_Postfix()
		{
			EnsureInitialized();
		}

		[HarmonyPatch(typeof(ValuableDirector), "VolumesAndSwitchSetup")]
		[HarmonyPostfix]
		public static void ValuableDirector_VolumesAndSwitchSetup_Postfix()
		{
			//IL_037a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.RunIsLevel() || !SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			EnsureInitialized();
			_inventoryExtrasSaved = false;
			LogPurchasedItems("level start");
			DebugResetCounters();
			RefreshCachedItemLists();
			List<ValuableVolume> list = (from v in Object.FindObjectsOfType<ValuableVolume>(false)
				where (Object)(object)((Component)v).gameObject.GetComponent<UsedVolumeTracker>() == (Object)null
				where !HasValuablePropSwitch(v)
				select v).ToList();
			Logger.LogInfo((object)($"Found {list.Count} volumes | spawn chances: " + string.Join(", ", (from c in CategoryList
				where c.Chance != null
				orderby c.Name
				select c.Name + ":" + ChanceLabel(c)).ToArray())));
			Logger.LogInfo((object)("Item pool: " + string.Join(" | ", (from kv in _cachedByType
				orderby kv.Key
				select $"{CategoryName(kv.Key)}={kv.Value.Count}").ToArray())));
			int value = MaxItemsPerLevel.Value;
			int value2 = MinItemsPerLevel.Value;
			int num = 0;
			foreach (ValuableVolume item2 in list)
			{
				if (value <= 0 || num < value)
				{
					if (RandomItemSpawn(item2))
					{
						num++;
					}
					continue;
				}
				DebugLog($"[CAP] reached MaxItemsPerLevel={value}, remaining volumes were not tried");
				break;
			}
			if (value2 > 0 && num < value2)
			{
				DebugLog($"[MIN] only {num} spawned, below MinItemsPerLevel={value2}; filling from unused volumes");
				List<ValuableVolume> list2 = list.Where((ValuableVolume v) => (Object)(object)((Component)v).gameObject.GetComponent<UsedVolumeTracker>() == (Object)null).ToList();
				for (int num2 = list2.Count - 1; num2 > 0; num2--)
				{
					int num3 = Random.Range(0, num2 + 1);
					List<ValuableVolume> list3 = list2;
					int index = num2;
					List<ValuableVolume> list4 = list2;
					int num4 = num3;
					ValuableVolume value3 = list2[num3];
					ValuableVolume val = list2[num2];
					list3[index] = value3;
					int index2 = num4;
					ValuableVolume value4 = val;
					list4[index2] = value4;
				}
				foreach (ValuableVolume item3 in list2)
				{
					if (num >= value2 || (value > 0 && num >= value))
					{
						break;
					}
					if (IsVolumeStillValid(item3) && GetRandomShopItem(out var item) && !((Object)(object)item == (Object)null))
					{
						Component val2 = (Component)(object)item3;
						_dbgTried++;
						if ((Object)(object)SpawnItem(item, val2.transform.position, val2.transform.rotation) != (Object)null)
						{
							num++;
						}
						else
						{
							RecordSpawnFailure(item, item3);
						}
					}
				}
			}
			Logger.LogInfo((object)$"Spawned {num} items (min={value2} cap={value})");
			LogSpawnSummary(num, value2, value);
		}

		private static Component GetMapIcon(MapCustom mapCustom)
		{
			if (!_mapEntityLookupDone)
			{
				_mapEntityLookupDone = true;
				_mapEntityField = AccessTools.Field(typeof(MapCustom), "mapCustomEntity");
				if (_mapEntityField == null)
				{
					_mapEntityField = typeof(MapCustom).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((FieldInfo f) => f.FieldType.Name == "MapCustomEntity");
				}
				if (_mapEntityField == null)
				{
					Logger.LogWarning((object)"Could not find the map icon field on MapCustom - 'Show on map' hiding is disabled (items are never deactivated).");
				}
			}
			return (Component)((_mapEntityField != null) ? /*isinst with value type is only supported in some contexts*/: null);
		}

		private static bool IsModExtra(GameObject go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return false;
			}
			SpawnedItemTracker componentInParent = go.GetComponentInParent<SpawnedItemTracker>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return !_enemyDropIds.Contains(((Object)((Component)componentInParent).gameObject).GetInstanceID());
			}
			PhotonView componentInParent2 = go.GetComponentInParent<PhotonView>();
			object[] array = (((Object)(object)componentInParent2 != (Object)null) ? componentInParent2.InstantiationData : null);
			return array != null && array.Length != 0 && array[0] is string && (string)array[0] == "SIIL_EXTRA";
		}

		private static bool IsModItem(GameObject go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return false;
			}
			if ((Object)(object)go.GetComponentInParent<SpawnedItemTracker>() != (Object)null)
			{
				return true;
			}
			PhotonView componentInParent = go.GetComponentInParent<PhotonView>();
			object[] array = (((Object)(object)componentInParent != (Object)null) ? componentInParent.InstantiationData : null);
			return array != null && array.Length != 0 && array[0] is string && ((string)array[0] == "SIIL_EXTRA" || (string)array[0] == "SIIL_DROP");
		}

		private static bool IsSeenByCamera(Camera cam, HiddenIcon hidden)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_004c: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = hidden.Item.transform.position;
			Vector3 position2 = ((Component)cam).transform.position;
			Vector3 val = position - position2;
			float magnitude = ((Vector3)(ref val)).magnitude;
			if ((double)magnitude > (double)RevealDistance.Value)
			{
				return false;
			}
			Vector3 val2 = cam.WorldToViewportPoint(position);
			if ((double)val2.z <= 0.0 || (double)val2.x < 0.0 || (double)val2.x > 1.0 || (double)val2.y < 0.0 || (double)val2.y > 1.0)
			{
				return false;
			}
			RaycastHit[] array = Physics.RaycastAll(position2, val / Mathf.Max(magnitude, 0.001f), magnitude, -1, (QueryTriggerInteraction)1);
			Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
			RaycastHit[] array2 = array;
			for (int num = 0; num < array2.Length; num++)
			{
				RaycastHit val3 = array2[num];
				if (!((double)((RaycastHit)(ref val3)).distance < 1.0))
				{
					return (Object)(object)((Component)((RaycastHit)(ref val3)).collider).GetComponentInParent<ItemAttributes>() == (Object)(object)hidden.Attributes;
				}
			}
			return true;
		}

		private static void RevealMapIcon(HiddenIcon hidden)
		{
			_revealedItems.Add(((Object)hidden.Item).GetInstanceID());
			try
			{
				MethodInfo methodInfo = null;
				if ((Object)(object)hidden.MapInstance != (Object)null && (Object)(object)hidden.MapCustom != (Object)null && hidden.Args != null)
				{
					methodInfo = typeof(Map).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "AddCustom" && m.GetParameters().Length == hidden.Args.Length);
				}
				if (methodInfo != null && (Object)(object)hidden.Icon != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)hidden.Icon.gameObject);
					if (_mapEntityField != null)
					{
						_mapEntityField.SetValue(hidden.MapCustom, null);
					}
					methodInfo.Invoke(hidden.MapInstance, hidden.Args);
					return;
				}
			}
			catch (Exception ex)
			{
				DebugLog("[MAP] could not recreate the icon of " + hidden.Name + ": " + ex.Message);
			}
			if ((Object)(object)hidden.Icon != (Object)null)
			{
				hidden.Icon.gameObject.SetActive(true);
			}
		}

		private IEnumerator RevealLoop()
		{
			WaitForSeconds wait = new WaitForSeconds(0.5f);
			while (_hiddenIcons.Count > 0 && RevealHiddenOnMap.Value)
			{
				yield return wait;
				Camera cam = Camera.main;
				int i = _hiddenIcons.Count - 1;
				while (i >= 0)
				{
					HiddenIcon hidden = _hiddenIcons[i];
					if ((Object)(object)hidden.Item == (Object)null)
					{
						_hiddenIcons.RemoveAt(i);
					}
					else
					{
						string reason = null;
						if (!hidden.Item.activeInHierarchy)
						{
							reason = "equipped or picked up";
						}
						else if ((Object)(object)hidden.Grab != (Object)null && hidden.Grab.grabbed)
						{
							reason = "picked up";
						}
						else if ((Object)(object)cam != (Object)null && IsSeenByCamera(cam, hidden))
						{
							reason = "seen";
						}
						if (reason != null)
						{
							if (!hidden.Item.activeInHierarchy)
							{
								_revealedItems.Add(((Object)hidden.Item).GetInstanceID());
								if ((Object)(object)hidden.Icon != (Object)null)
								{
									Object.Destroy((Object)(object)hidden.Icon.gameObject);
								}
							}
							else
							{
								RevealMapIcon(hidden);
							}
							_hiddenIcons.RemoveAt(i);
							DebugLog("[MAP] revealed the map icon of " + hidden.Name + " (" + reason + ")");
						}
					}
					int num = i - 1;
					i = num;
				}
			}
			_revealLoop = null;
		}

		private IEnumerator HideMapIconIfExtra(Map map, MapCustom mapCustom, object[] args, ItemAttributes attributes, string itemName)
		{
			yield return null;
			if ((Object)(object)mapCustom == (Object)null || (Object)(object)attributes == (Object)null)
			{
				yield break;
			}
			GameObject item = ((Component)attributes).gameObject;
			if (!IsModExtra(item))
			{
				DebugLog("[MAP] " + itemName + " was not spawned by this mod, so its map icon is left alone");
				yield break;
			}
			int attempt = 0;
			while (attempt < 30)
			{
				if ((Object)(object)mapCustom == (Object)null || (Object)(object)item == (Object)null)
				{
					yield break;
				}
				Component icon = GetMapIcon(mapCustom);
				if ((Object)(object)icon != (Object)null)
				{
					icon.gameObject.SetActive(false);
					DebugLog("[MAP] hid the map icon of " + itemName + " (the item itself was not touched)");
					if (RevealHiddenOnMap.Value)
					{
						_hiddenIcons.Add(new HiddenIcon
						{
							MapInstance = map,
							MapCustom = mapCustom,
							Args = args,
							Item = item,
							Attributes = attributes,
							Grab = FindOnItem<PhysGrabObject>(item),
							Icon = icon,
							Name = itemName
						});
						if (_revealLoop == null)
						{
							_revealLoop = ((MonoBehaviour)this).StartCoroutine(RevealLoop());
						}
					}
					yield break;
				}
				if (_mapEntityField == null)
				{
					yield break;
				}
				yield return null;
				int num = attempt + 1;
				attempt = num;
			}
			if (!_mapWarned)
			{
				_mapWarned = true;
				Logger.LogWarning((object)("Map icon for " + itemName + " never appeared, so it could not be hidden (the item itself was left untouched)."));
			}
		}

		[HarmonyPatch(typeof(Map), "AddCustom")]
		[HarmonyPostfix]
		public static void Map_AddCustom_Postfix(Map __instance, MapCustom mapCustom, object[] __args)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected I4, but got Unknown
			ItemAttributes val = default(ItemAttributes);
			if (SemiFunc.RunIsLevel() && !((Object)(object)mapCustom == (Object)null) && !((Object)(object)((Component)mapCustom).gameObject == (Object)null) && ((Component)mapCustom).gameObject.TryGetComponent<ItemAttributes>(ref val) && !((Object)(object)val?.item == (Object)null))
			{
				string name = ((Object)val.item).name;
				ConfigEntry<bool> value;
				bool flag = ItemMapEntries.TryGetValue(name, out value) && !value.Value;
				CategorySettings value2;
				bool flag2 = CategorySettingsById.TryGetValue((int)val.item.itemType, out value2) && !value2.ShowOnMap.Value;
				if ((flag || flag2) && !_revealedItems.Contains(((Object)((Component)val).gameObject).GetInstanceID()) && (Object)(object)Instance != (Object)null)
				{
					((MonoBehaviour)Instance).StartCoroutine(Instance.HideMapIconIfExtra(__instance, mapCustom, __args, val, name));
				}
			}
		}

		private static IDictionary<string, int> GetPurchasedDict()
		{
			try
			{
				if (_purchasedField == null)
				{
					_purchasedField = AccessTools.Field(typeof(StatsManager), "itemsPurchased");
				}
				if (_purchasedField == null || (Object)(object)StatsManager.instance == (Object)null)
				{
					return null;
				}
				return _purchasedField.GetValue(StatsManager.instance) as IDictionary<string, int>;
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static string ItemLimitInfo(Item item)
		{
			List<string> list = new List<string>();
			string[] array = new string[4] { "maxAmount", "maxAmountInShop", "maxPurchase", "maxPurchaseAmount" };
			foreach (string text in array)
			{
				try
				{
					FieldInfo fieldInfo = AccessTools.Field(typeof(Item), text);
					if (fieldInfo != null)
					{
						list.Add($"{text}={fieldInfo.GetValue(item)}");
					}
				}
				catch (Exception)
				{
				}
			}
			return (list.Count > 0) ? string.Join(" ", list.ToArray()) : "no limit fields found";
		}

		private static void PurchaseExtractedItem(Item item, string name)
		{
			IDictionary<string, int> purchasedDict = GetPurchasedDict();
			int value = 0;
			purchasedDict?.TryGetValue(name, out value);
			StatsManager.instance.ItemPurchase(name);
			int value2 = value;
			if (purchasedDict != null)
			{
				purchasedDict.TryGetValue(name, out value2);
				if (value2 <= value)
				{
					purchasedDict[name] = value + 1;
					Logger.LogInfo((object)$"The game did not raise the purchased count of {name} ({value} -> {value2}); it was raised to {value + 1}");
					value2 = value + 1;
				}
			}
			DebugLog($"[EXTRACT] {name}: purchased count {value} -> {value2} | {ItemLimitInfo(item)} | {LimitSummary(item)}");
		}

		private static string GetInstanceName(ItemAttributes attributes)
		{
			try
			{
				FieldInfo fieldInfo = AccessTools.Field(typeof(ItemAttributes), "instanceName");
				return (fieldInfo != null) ? (((string)fieldInfo.GetValue(attributes)) ?? "?") : "?";
			}
			catch (Exception)
			{
				return "?";
			}
		}

		private static void CountAsPurchased(string name)
		{
			StatsManager instance = StatsManager.instance;
			instance.itemsPurchased.TryGetValue(name, out var value);
			instance.itemsPurchased[name] = value + 1;
			instance.itemsPurchasedTotal.TryGetValue(name, out var value2);
			instance.itemsPurchasedTotal[name] = value2 + 1;
		}

		private static void SaveInventoryExtras()
		{
			if ((Object)(object)StatsManager.instance == (Object)null)
			{
				return;
			}
			if (!SaveInventoryItems.Value)
			{
				DebugLog("[SAVE] SaveInventoryItems is OFF: extras held in inventories are not kept");
				return;
			}
			int num = 0;
			ItemEquippable[] array = Object.FindObjectsOfType<ItemEquippable>(true);
			foreach (ItemEquippable val in array)
			{
				if ((Object)(object)val == (Object)null || !val.IsEquipped() || (Object)(object)((Component)val).GetComponentInParent<SpawnedItemTracker>() == (Object)null)
				{
					continue;
				}
				ItemAttributes component = ((Component)val).GetComponent<ItemAttributes>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)component.item == (Object)null))
				{
					string name = ((Object)component.item).name;
					if (RespectMaxAmount.Value && IsAtLimit(component.item))
					{
						Notify(component.item.itemName + ": no more copies fit in the truck, the extra in your inventory is not registered");
						DebugLog("[SAVE] " + name + " not registered (" + LimitSummary(component.item) + ")");
					}
					else
					{
						CountAsPurchased(name);
						num++;
						StatsManager.instance.itemsPurchased.TryGetValue(name, out var value);
						DebugLog($"[SAVE] {name} ({GetInstanceName(component)}) was in an inventory at the end of the level: purchased count is now {value} ({LimitSummary(component.item)})");
					}
				}
			}
			if (num > 0)
			{
				Logger.LogInfo((object)$"{num} extra(s) held in inventories were kept: they come back in the truck");
			}
		}

		[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
		[HarmonyPrefix]
		public static void RunManager_ChangeLevel_Prefix(bool _completedLevel, bool _levelFailed)
		{
			try
			{
				if (!(!_completedLevel || _levelFailed) && !_inventoryExtrasSaved && SemiFunc.IsMasterClientOrSingleplayer() && SemiFunc.RunIsLevel())
				{
					_inventoryExtrasSaved = true;
					SaveInventoryExtras();
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Could not keep the inventory extras: " + ex.Message));
			}
		}

		[HarmonyPatch(typeof(ItemManager), "GetAllItemVolumesInScene")]
		[HarmonyPostfix]
		public static void ItemManager_GetAllItemVolumesInScene_Postfix(ItemManager __instance)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected I4, but got Unknown
			try
			{
				if ((Object)(object)__instance == (Object)null || __instance.itemVolumes == null || __instance.itemVolumes.Count == 0)
				{
					return;
				}
				_truckSlots.Clear();
				foreach (ItemVolume itemVolume in __instance.itemVolumes)
				{
					if (!((Object)(object)itemVolume == (Object)null))
					{
						int key = (int)itemVolume.itemVolume;
						_truckSlots.TryGetValue(key, out var value);
						_truckSlots[key] = value + 1;
					}
				}
				DebugLog("[SAVE] truck slots by item size: " + string.Join(", ", _truckSlots.Select((KeyValuePair<int, int> kv) => $"{(object)(itemVolume)kv.Key}={kv.Value}").ToArray()));
			}
			catch (Exception ex)
			{
				DebugLog("Could not read the truck slots: " + ex.Message);
			}
		}

		private static int RoomLeft(Item item)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected I4, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)item == (Object)null || !item.physicalItem || (Object)(object)StatsManager.instance == (Object)null)
			{
				return int.MaxValue;
			}
			StatsManager.instance.itemsPurchased.TryGetValue(((Object)item).name, out var value);
			int num = item.maxAmount - Mathf.Clamp(value, 0, item.maxAmount);
			if (_truckSlots.TryGetValue((int)item.itemVolume, out var value2))
			{
				int num2 = 0;
				foreach (KeyValuePair<string, int> item2 in StatsManager.instance.itemsPurchased)
				{
					if (StatsManager.instance.itemDictionary.TryGetValue(item2.Key, out var value3) && (Object)(object)value3 != (Object)null && value3.physicalItem && !value3.disabled && value3.itemVolume == item.itemVolume)
					{
						num2 += Mathf.Clamp(item2.Value, 0, value3.maxAmount);
					}
				}
				num = Math.Min(num, value2 - num2);
			}
			return num;
		}

		private static bool IsAtLimit(Item item)
		{
			return RoomLeft(item) <= 0;
		}

		private static string LimitSummary(Item item)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected I4, but got Unknown
			if ((Object)(object)item == (Object)null || (Object)(object)StatsManager.instance == (Object)null)
			{
				return "?";
			}
			StatsManager.instance.itemsPurchased.TryGetValue(((Object)item).name, out var value);
			int value2;
			string text = (_truckSlots.TryGetValue((int)item.itemVolume, out value2) ? value2.ToString() : "unknown");
			return string.Format("owned={0} maxAmount={1} truck slots of its size={2} room left={3}", value, item.maxAmount, text, (RoomLeft(item) == int.MaxValue) ? "no limit" : RoomLeft(item).ToString());
		}

		private static void Notify(string message)
		{
			//IL_0037: 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)
			Logger.LogInfo((object)message);
			try
			{
				if ((Object)(object)BigMessageUI.instance != (Object)null)
				{
					SemiFunc.UIBigMessage(message, "{!}", 20f, new Color(1f, 0.6f, 0.1f), Color.white);
				}
			}
			catch (Exception)
			{
			}
		}

		[HarmonyPatch(typeof(ItemManager), "GetPurchasedItems")]
		[HarmonyPrefix]
		public static void ItemManager_GetPurchasedItems_Prefix()
		{
			if (RespectMaxAmount == null || RespectMaxAmount.Value || (Object)(object)StatsManager.instance == (Object)null)
			{
				return;
			}
			foreach (KeyValuePair<string, int> item in StatsManager.instance.itemsPurchased)
			{
				if (StatsManager.instance.itemDictionary.TryGetValue(item.Key, out var value) && (Object)(object)value != (Object)null && value.physicalItem && item.Value > value.maxAmount)
				{
					DebugLog($"[SAVE] raising the truck limit of {item.Key}: {value.maxAmount} -> {item.Value}");
					value.maxAmount = item.Value;
				}
			}
		}

		private static Image GetSpotIcon(InventorySpot spot)
		{
			try
			{
				if (_spotIconField == null)
				{
					_spotIconField = AccessTools.Field(typeof(InventorySpot), "inventoryIcon");
				}
				return (Image)((_spotIconField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static TextMeshProUGUI GetMarker(InventorySpot spot)
		{
			//IL_00d5: 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_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			if (_spotMarkers.TryGetValue(((Object)spot).GetInstanceID(), out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if ((Object)(object)spot.noItem == (Object)null)
			{
				return null;
			}
			value = Object.Instantiate<TextMeshProUGUI>(spot.noItem, ((Component)spot).transform);
			((Object)value).name = "SIIL_Marker";
			((Behaviour)value).enabled = true;
			((Graphic)value).raycastTarget = false;
			((TMP_Text)value).alignment = (TextAlignmentOptions)514;
			((TMP_Text)value).overflowMode = (TextOverflowModes)0;
			((TMP_Text)value).fontStyle = (FontStyles)1;
			((TMP_Text)value).enableAutoSizing = true;
			((TMP_Text)value).fontSizeMin = 3f;
			((TMP_Text)value).fontSizeMax = 9f;
			RectTransform rectTransform = ((TMP_Text)value).rectTransform;
			Transform transform = ((Component)spot).transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			float num;
			if (!((Object)(object)val != (Object)null))
			{
				num = 0f;
			}
			else
			{
				Rect rect = val.rect;
				num = ((Rect)(ref rect)).width;
			}
			float num2 = num;
			if ((double)num2 >= 12.0)
			{
				rectTransform.anchorMin = new Vector2(0f, 0f);
				rectTransform.anchorMax = new Vector2(1f, 0f);
				rectTransform.pivot = new Vector2(0.5f, 0f);
				rectTransform.offsetMin = new Vector2(0f, 0f);
				rectTransform.offsetMax = new Vector2(0f, 14f);
			}
			else
			{
				rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
				rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
				rectTransform.pivot = new Vector2(0.5f, 0.5f);
				rectTransform.anchoredPosition = Vector2.zero;
				rectTransform.sizeDelta = new Vector2(70f, 14f);
			}
			((Component)value).gameObject.SetActive(false);
			_spotMarkers[((Object)spot).GetInstanceID()] = value;
			DebugLog($"[MARKER] label created for slot '{((Object)spot).name}' (slot width {num2:F0})");
			return value;
		}

		private static bool WillBeKept(ItemEquippable equippable, Dictionary<string, int> alreadyCounted)
		{
			if (!SaveInventoryItems.Value)
			{
				return false;
			}
			ItemAttributes component = ((Component)equippable).GetComponent<ItemAttributes>();
			if ((Object)(object)component == (Object)null || (Object)(object)component.item == (Object)null || !RespectMaxAmount.Value || !component.item.physicalItem)
			{
				return true;
			}
			if (!SemiFunc.IsMasterClientOrSingleplayer() || (Object)(object)StatsManager.instance == (Object)null)
			{
				return true;
			}
			string name = ((Object)component.item).name;
			alreadyCounted.TryGetValue(name, out var value);
			if (RoomLeft(component.item) - value <= 0)
			{
				return false;
			}
			alreadyCounted[name] = value + 1;
			return true;
		}

		private static void SetSlotLook(InventorySpot spot, TextMeshProUGUI marker, bool? kept, string text)
		{
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			Image spotIcon = GetSpotIcon(spot);
			if (kept.HasValue)
			{
				if ((Object)(object)marker != (Object)null)
				{
					if (((TMP_Text)marker).text != text)
					{
						((TMP_Text)marker).text = text;
					}
					((Graphic)marker).color = (kept.Value ? new Color(0.35f, 1f, 0.35f) : new Color(1f, 0.3f, 0.3f));
					if (!((Component)marker).gameObject.activeSelf)
					{
						((Component)marker).gameObject.SetActive(true);
					}
				}
				if ((Object)(object)spotIcon != (Object)null)
				{
					((Graphic)spotIcon).color = (kept.Value ? new Color(0.7f, 1f, 0.7f) : new Color(1f, 0.55f, 0.55f));
				}
			}
			else
			{
				if ((Object)(object)marker != (Object)null && ((Component)marker).gameObject.activeSelf)
				{
					((Component)marker).gameObject.SetActive(false);
				}
				if ((Object)(object)spotIcon != (Object)null && ((Graphic)spotIcon).color != Color.white)
				{
					((Graphic)spotIcon).color = Color.white;
				}
			}
		}

		private static void UpdateInventoryMarkers()
		{
			Inventory instance = Inventory.instance;
			if ((Object)(object)instance == (Object)null || !InventoryMarker.Value)
			{
				foreach (KeyValuePair<int, TextMeshProUGUI> item in _spotMarkers.ToList())
				{
					if ((Object)(object)item.Value != (Object)null && ((Component)item.Value).gameObject.activeSelf)
					{
						((Component)item.Value).gameObject.SetActive(false);
					}
				}
				return;
			}
			Dictionary<string, int> alreadyCounted = new Dictionary<string, int>();
			foreach (InventorySpot allSpot in instance.GetAllSpots())
			{
				if ((Object)(object)allSpot == (Object)null)
				{
					continue;
				}
				TextMeshProUGUI marker = GetMarker(allSpot);
				ItemEquippable currentItem = allSpot.CurrentItem;
				string text = "empty";
				bool? kept = null;
				string text2 = null;
				if ((Object)(object)currentItem != (Object)null)
				{
					string name = ((Object)currentItem).name;
					if (IsModItem(((Component)currentItem).gameObject))
					{
						kept = WillBeKept(currentItem, alreadyCounted);
						text2 = (kept.Value ? MarkerKeptText.Value : MarkerLostText.Value);
						text = (kept.Value ? "kept " : "lost ") + name;
					}
					else
					{
						text = "not an extra: " + name;
					}
				}
				if (!_spotState.TryGetValue(((Object)allSpot).GetInstanceID(), out var value) || value != text)
				{
					_spotState[((Object)allSpot).GetInstanceID()] = text;
					DebugLog("[MARKER] slot '" + ((Object)allSpot).name + "': " + text);
				}
				SetSlotLook(allSpot, marker, kept, text2);
			}
		}

		private IEnumerator InventoryMarkerLoop()
		{
			WaitForSeconds wait = new WaitForSeconds(0.25f);
			while (true)
			{
				yield return wait;
				try
				{
					UpdateInventoryMarkers();
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					if (!_markerWarned)
					{
						_markerWarned = true;
						Logger.LogWarning((object)("Inventory label error (it keeps trying): " + ex2.Message));
					}
				}
			}
		}

		private static void LogPurchasedItems(string when)
		{
			if (DebugMode == null || !DebugMode.Value)
			{
				return;
			}
			IDictionary<string, int> purchasedDict = GetPurchasedDict();
			if (purchasedDict == null)
			{
				DebugLog("[SAVE] (" + when + ") could not read the game's purchased items");
				return;
			}
			DebugLog("[SAVE] (" + when + ") purchased items: " + string.Join(", ", (from kv in purchasedDict
				where kv.Value > 0
				select $"{kv.Key}={kv.Value}").ToArray()));
		}

		private static T FindOnItem<T>(GameObject root) where T : Component
		{
			T component = root.GetComponent<T>();
			if ((Object)(object)component != (Object)null)
			{
				return component;
			}
			component = root.GetComponentInChildren<T>(true);
			return ((Object)(object)component != (Object)null) ? component : root.GetComponentInParent<T>();
		}

		[HarmonyPatch(typeof(ExtractionPoint), "DestroyAllPhysObjectsInHaulList")]
		[HarmonyPostfix]
		public static void ExtractionPoint_DestroyAllPhysObjectsInHaulList_Postfix(ExtractionPoint __instance)
		{
			//IL_00e2: 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_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMasterClientOrSingleplayer() || !ExtractionSavesItems.Value)
			{
				return;
			}
			SpawnedItemTracker[] array = Object.FindObjectsOfType<SpawnedItemTracker>(false);
			if (array.Length == 0)
			{
				return;
			}
			ExtractionPoint[] source = Object.FindObjectsOfType<ExtractionPoint>(false);
			HashSet<string> hashSet = new HashSet<string>();
			int num = 0;
			SpawnedItemTracker[] array2 = array;
			foreach (SpawnedItemTracker spawnedItemTracker in array2)
			{
				GameObject gameObject = ((Component)spawnedItemTracker).gameObject;
				if ((Object)(object)gameObject == (Object)null)
				{
					continue;
				}
				ItemAttributes val = FindOnItem<ItemAttributes>(gameObject);
				if ((Object)(object)val == (Object)null || (Object)(object)val.item == (Object)null)
				{
					DebugLog("[EXTRACT] " + ((Object)gameObject).name + ": no ItemAttributes found, skipped");
					continue;
				}
				string name = ((Object)val.item).name;
				Vector3 itemPos = gameObject.transform.position;
				ExtractionPoint val2 = source.OrderBy(delegate(ExtractionPoint pt)
				{
					//IL_0006: 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_0011: 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)
					Vector3 val6 = ((Component)pt).transform.position - itemPos;
					return ((Vector3)(ref val6)).sqrMagnitude;
				}).FirstOrDefault();
				RoomVolumeCheck val3 = FindOnItem<RoomVolumeCheck>(gameObject);
				bool flag;
				if ((Object)(object)val3 != (Object)null)
				{
					flag = val3.CurrentRooms != null && val3.CurrentRooms.Any((RoomVolume r) => (Object)(object)r != (Object)null && r.Extraction);
				}
				else
				{
					int num2;
					if ((Object)(object)__instance != (Object)null)
					{
						Vector3 val4 = ((Component)__instance).transform.position - itemPos;
						num2 = ((((Vector3)(ref val4)).magnitude <= 5f) ? 1 : 0);
					}
					else
					{
						num2 = 0;
					}
					flag = (byte)num2 != 0;
					DebugLog($"[EXTRACT] {name}: no RoomVolumeCheck found, using distance to the extraction point -> {flag}");
				}
				if (!flag)
				{
					DebugLog("[EXTRACT] " + name + ": not inside an extraction zone, left alone");
				}
				else if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)__instance)
				{
					DebugLog("[EXTRACT] " + name + ": belongs to another extraction point, left alone");
				}
				else if ((Object)(object)StatsManager.instance == (Object)null)
				{
					DebugLog("[EXTRACT] StatsManager is null, skipping " + name);
				}
				else if (RespectMaxAmount.Value && IsAtLimit(val.item))
				{
					if (hashSet.Add(name))
					{
						Notify(val.item.itemName + ": no more copies fit in the truck, the extra stays in the level so you can still use it");
					}
					DebugLog("[EXTRACT] " + name + ": limit reached, left in the level (" + LimitSummary(val.item) + ")");
				}
				else
				{
					PurchaseExtractedItem(val.item, name);
					Logger.LogInfo((object)("Extracted item saved as permanent: " + name));
					PhysGrabObject val5 = FindOnItem<PhysGrabObject>(gameObject);
					if ((Object)(object)val5 != (Object)null)
					{
						val5.DestroyPhysGrabObject();
					}
					else
					{
						Object.Destroy((Object)(object)gameObject);
					}
					num++;
				}
			}
			Logger.LogInfo((object)$"Extraction completed: {array.Length} extras in the level, {num} saved (they return in the truck next level)");
			LogPurchasedItems("after extraction");
		}

		private static void LootWarnOnce(string message)
		{
			if (_lootWarned.Add(message))
			{
				Logger.LogWarning((object)message);
			}
		}

		private static List<LootRule> GetLootRules()
		{
			string text = EnemyLootRules.Value ?? "";
			if (text == _lootRulesSource)
			{
				return _lootRules;
			}
			_lootRulesSource = text;
			List<LootRule> list = new List<LootRule>();
			string[] array = text.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text2 in array)
			{
				int num = text2.IndexOf(':');
				if (num <= 0)
				{
					if (text2.Trim().Length > 0)
					{
						LootWarnOnce("EnemyLootRules: rule ignored because it has no ':' -> " + text2.Trim());
					}
					continue;
				}
				LootRule lootRule = new LootRule();
				string[] array2 = text2.Substring(0, num).Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string text3 in array2)
				{
					string text4 = text3.Trim();
					if (text4.Length > 0)
					{
						lootRule.Mobs.Add(text4);
					}
				}
				string[] array3 = text2.Substring(num + 1).Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string text5 in array3)
				{
					string text6 = text5.Trim();
					if (text6.Length == 0)
					{
						continue;
					}
					string text7 = text6;
					float chance = 100f;
					int num2 = text6.LastIndexOf('=');
					if (num2 > 0)
					{
						text7 = text6.Substring(0, num2).Trim();
						if (float.TryParse(text6.Substring(num2 + 1).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
						{
							chance = Mathf.Clamp(result, 0f, 100f);
						}
						else
						{
							LootWarnOnce("EnemyLootRules: the chance of '" + text7 + "' is not a number (use a dot, like 0.5), 100 is used");
						}
					}
					bool flag = text7.StartsWith("@");
					if (flag)
					{
						text7 = text7.Substring(1).Trim();
					}
					if (text7.Length > 0)
					{
						lootRule.Entries.Add(new LootEntry
						{
							Token = text7,
							IsCategory = flag,
							Chance = chance
						});
					}
				}
				if (lootRule.Mobs.Count > 0 && lootRule.Entries.Count > 0)
				{
					list.Add(lootRule);
				}
			}
			_lootRules = list;
			Logger.LogInfo((object)$"Enemy loot rules loaded: {list.Count} rule(s)");
			return list;
		}

		private static bool MobMatches(LootRule rule, string enemyName)
		{
			foreach (string mob in rule.Mobs)
			{
				if (mob == "*" || enemyName.IndexOf(mob, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
			return false;
		}
	}
	public class SpawnedItemTracker : MonoBehaviour
	{
	}
	public class UsedVolumeTracker : MonoBehaviour
	{
	}
}