Decompiled source of Aqueduct Bands to Random Greens v1.0.0

plugins/AqueductGreens/AqueductGreens.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HG.Reflection;
using On.RoR2;
using RiskOfOptions;
using RiskOfOptions.Components.Options;
using RiskOfOptions.OptionConfigs;
using RiskOfOptions.Options;
using RoR2;
using RoR2.CharacterAI;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.ResourceManagement.AsyncOperations;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: OptIn]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AqueductGreens")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.8.0")]
[assembly: AssemblyInformationalVersion("1.0.8")]
[assembly: AssemblyProduct("AqueductGreens")]
[assembly: AssemblyTitle("AqueductGreens")]
[assembly: AssemblyVersion("1.0.8.0")]
namespace AqueductGreens;

[BepInPlugin("com.AqueductGreens", "Aqueduct Greens", "1.0.8")]
[BepInDependency("___riskofthunder.RoR2BepInExPack", "1.49.0")]
[BepInDependency("com.rune580.riskofoptions", "2.8.6")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class AqueductGreensPlugin : BaseUnityPlugin
{
	private sealed class ItemOption
	{
		internal ItemDef Item;

		internal ConfigEntry<bool> Allowed;

		internal CheckBoxOption MenuOption;
	}

	[Serializable]
	private sealed class MenuPresentation
	{
		public string name = "Aqueduct Greens";

		public string description = "";
	}

	public const string PluginGuid = "com.AqueductGreens";

	public const string PluginName = "Aqueduct Greens";

	public const string PluginVersion = "1.0.8";

	internal static AqueductGreensPlugin Instance;

	private readonly List<ItemOption> _items = new List<ItemOption>();

	private readonly UnlockVisit _visit = new UnlockVisit();

	private readonly QualityCompatibility _quality = new QualityCompatibility();

	private ConfigEntry<bool> _enabled;

	private ConfigEntry<bool> _testCommands;

	private ConfigEntry<bool> _logRolls;

	private GreenDropTable _replaceableTable;

	private GreenDropTable _fixedTable;

	private bool _ready;

	private bool _initializationFailed;

	private bool _inTestDrop;

	private string _menuName = "Aqueduct Greens";

	private Texture2D _menuIconTexture;

	private Sprite _menuIcon;

	private readonly TestRandomStream<Xoroshiro128Plus> _naturalRewardRandom = new TestRandomStream<Xoroshiro128Plus>((ulong runSeed) => new Xoroshiro128Plus(runSeed ^ 0x639CFA27D45B18E3L));

	private string _activeNaturalGuardianLabel;

	private int _matchedNaturalRngCalls;

	private int _mismatchedNaturalRngCalls;

	private const string KjaroGuid = "2ea73dc7dd4e1fc4b8a127f7fcf4f193";

	private const string RunaldGuid = "59807e19f1b695749b9846a2d4770da4";

	private readonly List<CharacterMaster> _testMasters = new List<CharacterMaster>();

	private int _nextTestGuardianId;

	private TestMode _testMode;

	private GameObject _kjaroPrefab;

	private GameObject _runaldPrefab;

	private bool _testCycleRunning;

	private readonly List<AsyncOperationHandle<GameObject>> _guardianAssetHandles = new List<AsyncOperationHandle<GameObject>>();

	private readonly List<GameObject> _testLootTrays = new List<GameObject>();

	private TestGuardian _activeTestLoot;

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

	private static readonly FieldInfo TestDropRngField = typeof(MasterDropDroplet).GetField("rng", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private readonly TestRandomStream<Xoroshiro128Plus> _testRewardRandom = new TestRandomStream<Xoroshiro128Plus>((ulong runSeed) => new Xoroshiro128Plus(runSeed ^ 0xA9D3E571BD7F4C20uL));

	private int _matchedTestRngCalls;

	private int _mismatchedTestRngCalls;

	private void Awake()
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Expected O, but got Unknown
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Expected O, but got Unknown
		Instance = this;
		_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Replace the Aqueduct guardians' band rewards after the bands are unlocked.");
		_testCommands = ((BaseUnityPlugin)this).Config.Bind<bool>("Testing", "Enable test commands", false, "Allow host-only ag_test_* console commands. Use in a separate test run. No restart required.");
		_logRolls = ((BaseUnityPlugin)this).Config.Bind<bool>("Testing", "Log base item rolls", false, "Log the base item selected before Quality's native upgrade roll. No restart required.");
		LoadMenuPresentation();
		AddToggle(_enabled);
		MasterDropDroplet.DropItems += new hook_DropItems(DropGuardianItems);
		PickupDropletController.CreatePickupDroplet_CreatePickupInfo_Vector3_Vector3 += new hook_CreatePickupDroplet_CreatePickupInfo_Vector3_Vector3(RedirectTestLoot);
		SceneDirector.onPrePopulateSceneServer += BeginScene;
		Run.onRunStartGlobal += RunStarted;
		Run.onRunDestroyGlobal += RunEnded;
		NetworkUser.onNetworkUserUnlockablesUpdated += new NetworkUserGenericDelegate(UserUnlockablesUpdated);
		_replaceableTable = ScriptableObject.CreateInstance<GreenDropTable>();
		((Object)_replaceableTable).name = "AqueductGreensReplaceable";
		((PickupDropTable)_replaceableTable).canDropBeReplaced = true;
		_fixedTable = ScriptableObject.CreateInstance<GreenDropTable>();
		((Object)_fixedTable).name = "AqueductGreensFixed";
		((PickupDropTable)_fixedTable).canDropBeReplaced = false;
	}

	private IEnumerator Start()
	{
		while (!RoR2Application.loadFinished)
		{
			yield return null;
		}
		InitializeItems();
	}

	private CheckBoxOption AddToggle(ConfigEntry<bool> entry, string displayName = null)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Expected O, but got Unknown
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		//IL_003a: Expected O, but got Unknown
		CheckBoxOption val = new CheckBoxOption(entry, new CheckBoxConfig
		{
			name = (displayName ?? ((ConfigEntryBase)entry).Definition.Key),
			restartRequired = false
		});
		ModSettingsManager.AddOption((BaseOption)val, "com.AqueductGreens", _menuName);
		return val;
	}

	private void InitializeItems()
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Expected O, but got Unknown
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Expected O, but got Unknown
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Expected O, but got Unknown
		if (_ready || _initializationFailed)
		{
			return;
		}
		try
		{
			_quality.Initialize();
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			ModSettingsManager.AddOption((BaseOption)new GenericButtonOption("Allow all greens", "Allowed green items", "Check every green item. This replaces your current guardian-item blacklist.", "Allow all", (UnityAction)delegate
			{
				SetAllItems(allowed: true);
			}), "com.AqueductGreens", _menuName);
			ModSettingsManager.AddOption((BaseOption)new GenericButtonOption("Blacklist all greens", "Allowed green items", "Uncheck every green item. Randomized guardians drop nothing until at least one item is allowed. First-unlock bands stay protected.", "Blacklist all", (UnityAction)delegate
			{
				SetAllItems(allowed: false);
			}), "com.AqueductGreens", _menuName);
			RegisterNewGreenItems();
			_ready = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("Version {0}: registered {1} base green items. Both ScrapGreen and ScrapGreenSuppressed are excluded; Regenerating Scrap is allowed. Quality detected: {2}.", "1.0.8", _items.Count, _quality.Installed));
		}
		catch (Exception arg)
		{
			_initializationFailed = true;
			((BaseUnityPlugin)this).Logger.LogError((object)$"Item catalog could not be validated; keeping original rewards. {arg}");
		}
		finally
		{
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			((BaseUnityPlugin)this).Config.Save();
		}
	}

	private void RegisterNewGreenItems()
	{
		//IL_004a: 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)
		HashSet<ItemIndex> hashSet = new HashSet<ItemIndex>(_items.Select((ItemOption entry) => entry.Item.itemIndex));
		bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
		int num = 0;
		try
		{
			foreach (ItemDef item in ((IEnumerable<ItemDef>)(object)ItemCatalog.allItemDefs).Where((ItemDef item) => Object.op_Implicit((Object)(object)item) && (int)item.tier == 1).OrderBy<ItemDef, string>((ItemDef item) => Language.GetString(item.nameToken), StringComparer.OrdinalIgnoreCase).ThenBy<ItemDef, string>((ItemDef item) => ((Object)item).name, StringComparer.Ordinal))
			{
				if (Exclusion(item) == null && hashSet.Add(item.itemIndex))
				{
					string text = Language.GetString(item.nameToken);
					ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Allowed green items", ((Object)item).name, true, "Allow " + text + " as a guardian reward. Checked means allowed; unchecked means blacklisted. All qualities of this item follow this setting. The item must be available in the current run.");
					CheckBoxOption menuOption = AddToggle(val, text);
					_items.Add(new ItemOption
					{
						Item = item,
						Allowed = val,
						MenuOption = menuOption
					});
					num++;
				}
			}
		}
		finally
		{
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			if (num > 0 && saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.Save();
			}
		}
		if (num > 0 && _ready)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Registered {num} additional green item(s) after catalog initialization.");
		}
	}

	private void SetAllItems(bool allowed)
	{
		ModSettingsBool[] source = (from control in Object.FindObjectsOfType<ModSettingsBool>()
			where Object.op_Implicit((Object)(object)control) && ((Component)control).gameObject.activeInHierarchy
			select control).ToArray();
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
		try
		{
			foreach (ItemOption item in _items)
			{
				foreach (ModSettingsBool item2 in source.Where((ModSettingsBool control) => ((ModSetting)control).settingToken == ((BaseOption)item.MenuOption).Identifier))
				{
					try
					{
						((ModSettingsControl<bool, BaseOptionConfig>)(object)item2).SubmitValue(allowed);
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not refresh a visible item checkbox: " + ex.Message));
					}
				}
				item.Allowed.Value = allowed;
			}
		}
		finally
		{
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			((BaseUnityPlugin)this).Config.Save();
		}
	}

	private string Exclusion(ItemDef item)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Invalid comparison between Unknown and I4
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		return GreenPolicy.Exclusion((int)item.tier == 1, item.hidden, (Object)(object)item == (Object)(object)Items.ScrapGreen || GreenPolicy.IsGreenScrapName(((Object)item).name), _quality.IsVariant(item.itemIndex));
	}

	private List<PickupIndex> CurrentPool()
	{
		if (!_ready || !Object.op_Implicit((Object)(object)Run.instance))
		{
			return new List<PickupIndex>();
		}
		RegisterNewGreenItems();
		return (from entry in GreenPolicy.EnabledAvailable(_items.Where((ItemOption entry) => Exclusion(entry.Item) == null), (ItemOption entry) => entry.Allowed.Value, (ItemOption entry) => Run.instance.IsItemAvailable(entry.Item.itemIndex) && !Run.instance.IsItemExpansionLocked(entry.Item.itemIndex))
			select PickupCatalog.FindPickupIndex(entry.Item.itemIndex) into pickup
			where pickup != PickupIndex.none
			select pickup).Distinct().ToList();
	}

	private static bool IsAqueduct()
	{
		if (Object.op_Implicit((Object)(object)SceneCatalog.mostRecentSceneDef))
		{
			return SceneCatalog.mostRecentSceneDef.baseSceneName == "goolake";
		}
		return false;
	}

	private static bool SomeoneNeedsBands()
	{
		ItemDef fireRing = Items.FireRing;
		ItemDef iceRing = Items.IceRing;
		if (!Object.op_Implicit((Object)(object)fireRing) || !Object.op_Implicit((Object)(object)iceRing) || !Object.op_Implicit((Object)(object)Run.instance))
		{
			return true;
		}
		UnlockableDef unlockableDef = UnlockableCatalog.GetUnlockableDef("Items.ElementalRings");
		ReadOnlyCollection<NetworkUser> readOnlyInstancesList = NetworkUser.readOnlyInstancesList;
		if (readOnlyInstancesList.Count == 0)
		{
			return true;
		}
		foreach (NetworkUser item in readOnlyInstancesList)
		{
			if (!Object.op_Implicit((Object)(object)item) || item.unlockables == null)
			{
				return true;
			}
			if (Object.op_Implicit((Object)(object)fireRing.unlockableDef) && !item.unlockables.Contains(fireRing.unlockableDef))
			{
				return true;
			}
			if (Object.op_Implicit((Object)(object)iceRing.unlockableDef) && !item.unlockables.Contains(iceRing.unlockableDef))
			{
				return true;
			}
			if (Object.op_Implicit((Object)(object)unlockableDef) && !item.unlockables.Contains(unlockableDef))
			{
				return true;
			}
		}
		if (!Object.op_Implicit((Object)(object)fireRing.unlockableDef) && !Object.op_Implicit((Object)(object)iceRing.unlockableDef))
		{
			return !Object.op_Implicit((Object)(object)unlockableDef);
		}
		return false;
	}

	private void RunStarted(Run run)
	{
		_testRewardRandom.Reset();
		ResetNaturalRewardRandomness();
		_nextTestGuardianId = 0;
		_matchedTestRngCalls = (_mismatchedTestRngCalls = 0);
		_testQualityTotals.Clear();
		if (NetworkServer.active)
		{
			_visit.Begin(SomeoneNeedsBands());
		}
	}

	private void RunEnded(Run run)
	{
		_visit.Clear();
		ClearTestLootTrays();
		_testMasters.Clear();
		_testQualityTotals.Clear();
		_testMode = TestMode.Normal;
		_testRewardRandom.Reset();
		_matchedTestRngCalls = (_mismatchedTestRngCalls = 0);
		ResetNaturalRewardRandomness();
	}

	private void BeginScene(SceneDirector director)
	{
		_testMasters.Clear();
		ClearTestLootTrays();
		_visit.Begin(SomeoneNeedsBands());
	}

	private void UserUnlockablesUpdated(NetworkUser user)
	{
		if (NetworkServer.active && IsAqueduct())
		{
			_visit.Observe(SomeoneNeedsBands());
		}
	}

	private static bool IsBand(PickupIndex pickup)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: 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_0027: Unknown result type (might be due to invalid IL or missing references)
		PickupDef pickupDef = PickupCatalog.GetPickupDef(pickup);
		if (pickupDef != null)
		{
			if (pickupDef.itemIndex != Items.FireRing.itemIndex)
			{
				return pickupDef.itemIndex == Items.IceRing.itemIndex;
			}
			return true;
		}
		return false;
	}

	private static bool IsBandTable(PickupDropTable table)
	{
		if (Object.op_Implicit((Object)(object)table))
		{
			if (!(((Object)table).name.Replace("(Clone)", "").Trim() == "dtFireRing"))
			{
				return ((Object)table).name.Replace("(Clone)", "").Trim() == "dtIceRing";
			}
			return true;
		}
		return false;
	}

	private static CharacterMaster DropMaster(MasterDropDroplet drop)
	{
		return ((Component)drop).GetComponent<CharacterMaster>();
	}

	private static bool IsGuardian(MasterDropDroplet drop)
	{
		CharacterMaster val = DropMaster(drop);
		if (!Object.op_Implicit((Object)(object)val))
		{
			return false;
		}
		if (GreenPolicy.IsNativeGuardianName(((Object)val).name))
		{
			return true;
		}
		CharacterBody body = val.GetBody();
		if (!Object.op_Implicit((Object)(object)body) || !((Object)body).name.StartsWith("LemurianBruiserBody", StringComparison.Ordinal))
		{
			return false;
		}
		if (drop.pickupsToDrop == null || !drop.pickupsToDrop.Any((SerializablePickupIndex p) => !string.IsNullOrEmpty(p.pickupName) && IsBand((PickupIndex)p)))
		{
			if (drop.dropTables != null)
			{
				return drop.dropTables.Any(IsBandTable);
			}
			return false;
		}
		return true;
	}

	private void DropGuardianItems(orig_DropItems orig, MasterDropDroplet self)
	{
		TestGuardian component = ((Component)self).GetComponent<TestGuardian>();
		TestGuardian activeTestLoot = _activeTestLoot;
		_activeTestLoot = ((Object.op_Implicit((Object)(object)component) && _testCommands.Value && IsGuardian(self)) ? component : null);
		try
		{
			using ((NetworkServer.active && Object.op_Implicit((Object)(object)_activeTestLoot)) ? new ScopedFieldOverride<Xoroshiro128Plus>(self, TestDropRngField, _testRewardRandom.Get(Run.instance.seed)) : null)
			{
				DropGuardianItemsCore(orig, self, component);
			}
		}
		finally
		{
			_activeTestLoot = activeTestLoot;
		}
	}

	private void DropGuardianItemsCore(orig_DropItems orig, MasterDropDroplet self, TestGuardian marker)
	{
		if (Object.op_Implicit((Object)(object)marker))
		{
			marker.DropHandlerObserved = true;
		}
		bool flag = Object.op_Implicit((Object)(object)marker) && _testCommands.Value;
		if (!NetworkServer.active || !_enabled.Value || !_ready || (!IsAqueduct() && !flag) || !IsGuardian(self))
		{
			orig.Invoke(self);
			return;
		}
		_visit.Observe(SomeoneNeedsBands());
		bool flag2 = _visit.PreserveBands;
		if (flag && marker.Mode != TestMode.Normal)
		{
			flag2 = marker.Mode == TestMode.Locked;
		}
		if (flag2)
		{
			if (flag)
			{
				Say("First-unlock protection: keeping this test guardian's native band reward.");
			}
			orig.Invoke(self);
			return;
		}
		SerializablePickupIndex[] pickupsToDrop = self.pickupsToDrop;
		PickupDropTable[] dropTables = self.dropTables;
		List<PickupIndex> list = CurrentPool();
		List<SerializablePickupIndex> list2 = new List<SerializablePickupIndex>();
		_replaceableTable.Choices = list;
		_fixedTable.Choices = list;
		List<PickupDropTable> list3 = new List<PickupDropTable>();
		RewardRouting.MoveFixedRewardsToTables(pickupsToDrop, (SerializablePickupIndex original) => !string.IsNullOrEmpty(original.pickupName) && IsBand((PickupIndex)original), list2, list3, (PickupDropTable)(object)_fixedTable, list.Count > 0);
		bool flag3 = GreenPolicy.IsNativeGuardianName(((Object)DropMaster(self)).name) && dropTables != null && dropTables.Length == 1;
		if (dropTables != null)
		{
			PickupDropTable[] array = dropTables;
			foreach (PickupDropTable val in array)
			{
				if (!IsBandTable(val) && (!flag3 || !Object.op_Implicit((Object)(object)val)))
				{
					list3.Add(val);
				}
				else if (list.Count > 0)
				{
					list3.Add((PickupDropTable)(object)(val.canDropBeReplaced ? _replaceableTable : _fixedTable));
				}
			}
		}
		if (list.Count == 0)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"No allowed, available greens: suppressing randomized guardian rewards. Enable at least one green item.");
		}
		string activeNaturalGuardianLabel = _activeNaturalGuardianLabel;
		try
		{
			_inTestDrop = flag;
			self.pickupsToDrop = ((pickupsToDrop == null) ? null : list2.ToArray());
			self.dropTables = ((dropTables == null && list3.Count == 0) ? null : list3.ToArray());
			if (!flag)
			{
				_activeNaturalGuardianLabel = NaturalGuardianLabel(DropMaster(self));
			}
			using (flag ? null : new ScopedFieldOverride<Xoroshiro128Plus>(self, TestDropRngField, _naturalRewardRandom.Get(Run.instance.seed)))
			{
				orig.Invoke(self);
			}
		}
		finally
		{
			self.pickupsToDrop = pickupsToDrop;
			self.dropTables = dropTables;
			_inTestDrop = false;
			_activeNaturalGuardianLabel = activeNaturalGuardianLabel;
		}
	}

	internal void ReportBaseRoll(PickupIndex pickup)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		if (_inTestDrop || _logRolls.Value)
		{
			Say("Base item roll: " + ItemName(pickup) + " (Quality rolls afterward)." + (Object.op_Implicit((Object)(object)_activeTestLoot) ? (" Guardian=" + _activeTestLoot.Label + ".") : ((_activeNaturalGuardianLabel != null) ? (" Guardian=" + _activeNaturalGuardianLabel + ".") : "")));
		}
	}

	internal unsafe static string ItemName(PickupIndex pickup)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		PickupDef pickupDef = PickupCatalog.GetPickupDef(pickup);
		if (pickupDef != null)
		{
			return Language.GetString(pickupDef.nameToken) + " [" + pickupDef.internalName + "]";
		}
		return ((object)(*(PickupIndex*)(&pickup))/*cast due to .constrained prefix*/).ToString();
	}

	internal static void Say(string message)
	{
		Debug.Log((object)("[Aqueduct Greens] " + message));
	}

	private void OnDestroy()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Expected O, but got Unknown
		MasterDropDroplet.DropItems -= new hook_DropItems(DropGuardianItems);
		PickupDropletController.CreatePickupDroplet_CreatePickupInfo_Vector3_Vector3 -= new hook_CreatePickupDroplet_CreatePickupInfo_Vector3_Vector3(RedirectTestLoot);
		SceneDirector.onPrePopulateSceneServer -= BeginScene;
		Run.onRunStartGlobal -= RunStarted;
		Run.onRunDestroyGlobal -= RunEnded;
		NetworkUser.onNetworkUserUnlockablesUpdated -= new NetworkUserGenericDelegate(UserUnlockablesUpdated);
		ReleaseGuardianAssetHandles();
		ClearTestLootTrays();
		if (Object.op_Implicit((Object)(object)_replaceableTable))
		{
			Object.Destroy((Object)(object)_replaceableTable);
		}
		if (Object.op_Implicit((Object)(object)_fixedTable))
		{
			Object.Destroy((Object)(object)_fixedTable);
		}
		if (Object.op_Implicit((Object)(object)_menuIcon))
		{
			Object.Destroy((Object)(object)_menuIcon);
		}
		if (Object.op_Implicit((Object)(object)_menuIconTexture))
		{
			Object.Destroy((Object)(object)_menuIconTexture);
		}
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}

	private void LoadMenuPresentation()
	{
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Expected O, but got Unknown
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		string directoryName = Path.GetDirectoryName(typeof(AqueductGreensPlugin).Assembly.Location);
		MenuPresentation menuPresentation = new MenuPresentation();
		try
		{
			string path = Path.Combine(directoryName, "mod-options.json");
			if (File.Exists(path))
			{
				JsonUtility.FromJsonOverwrite(File.ReadAllText(path), (object)menuPresentation);
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not read mod-options.json; using default menu presentation. " + ex.Message));
		}
		_menuName = (string.IsNullOrWhiteSpace(menuPresentation.name) ? "Aqueduct Greens" : menuPresentation.name.Trim());
		ModSettingsManager.SetModDescription(menuPresentation.description ?? "", "com.AqueductGreens", _menuName);
		try
		{
			string path2 = Path.Combine(directoryName, "options-icon.png");
			if (File.Exists(path2))
			{
				_menuIconTexture = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(_menuIconTexture, File.ReadAllBytes(path2), true))
				{
					throw new InvalidDataException("options-icon.png is not a supported image.");
				}
				_menuIcon = Sprite.Create(_menuIconTexture, new Rect(0f, 0f, (float)((Texture)_menuIconTexture).width, (float)((Texture)_menuIconTexture).height), new Vector2(0.5f, 0.5f));
				ModSettingsManager.SetModIcon(_menuIcon, "com.AqueductGreens", _menuName);
			}
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not load the optional options-icon.png; gameplay settings are still available. " + ex2.Message));
		}
	}

	private void ResetNaturalRewardRandomness()
	{
		_naturalRewardRandom.Reset();
		_activeNaturalGuardianLabel = null;
		_matchedNaturalRngCalls = (_mismatchedNaturalRngCalls = 0);
	}

	private static string NaturalGuardianLabel(CharacterMaster master)
	{
		string text = ((Object)master).name.Replace("(Clone)", "").Trim();
		if (string.Equals(text, "LemurianBruiserMasterFire", StringComparison.OrdinalIgnoreCase))
		{
			return "Kjaro (natural)";
		}
		if (string.Equals(text, "LemurianBruiserMasterIce", StringComparison.OrdinalIgnoreCase))
		{
			return "Runald (natural)";
		}
		return text + " (natural guardian reward)";
	}

	private void VerifyNaturalRewardRng(Xoroshiro128Plus actual)
	{
		if (_activeNaturalGuardianLabel != null)
		{
			bool flag = actual == _naturalRewardRandom.Get(Run.instance.seed);
			if (flag)
			{
				_matchedNaturalRngCalls++;
			}
			else
			{
				_mismatchedNaturalRngCalls++;
			}
			if (_logRolls.Value || !flag)
			{
				Say("NATURAL RNG CHECK: Guardian=" + _activeNaturalGuardianLabel + "; " + (flag ? "matched advancing natural stream" : "MISMATCH — unexpected native RNG") + ".");
			}
		}
	}

	private void ReportNaturalRngTotals()
	{
		Say($"NATURAL RNG CHECKS (this run): matched={_matchedNaturalRngCalls}, mismatched={_mismatchedNaturalRngCalls}. First-unlock rewards use their original path; command tests use a separate stream.");
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void QualityCommand(ConCommandArgs args)
	{
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)Instance) || !Instance._ready)
		{
			Say("The mod is not ready.");
			return;
		}
		AqueductGreensPlugin instance = Instance;
		Say(instance._quality.Summary);
		if (!instance._quality.Installed)
		{
			return;
		}
		if (!instance._quality.CanInspectVariants)
		{
			Say("This Quality version does not expose the variant/rule inspection API. Native drops still use its normal hooks.");
			return;
		}
		bool flag = ((ConCommandArgs)(ref args)).Count > 0 && string.Equals(((ConCommandArgs)(ref args))[0], "full", StringComparison.OrdinalIgnoreCase);
		instance.RegisterNewGreenItems();
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		foreach (ItemOption item in instance._items)
		{
			(string, bool, bool)[] array = instance._quality.InspectVariants(item.Item.itemIndex).ToArray();
			num += array.Count(((string Tier, bool Registered, bool Enabled) status) => status.Registered);
			num2 += array.Count(((string Tier, bool Registered, bool Enabled) status) => status.Registered && !status.Enabled);
			num3 += 4 - array.Count(((string Tier, bool Registered, bool Enabled) status) => status.Registered);
			if (flag || array.Length != 4 || array.Any(((string Tier, bool Registered, bool Enabled) status) => !status.Registered || !status.Enabled))
			{
				Say("QUALITY VARIANTS: " + Language.GetString(item.Item.nameToken) + ": " + string.Join(", ", array.Select(((string Tier, bool Registered, bool Enabled) status) => status.Tier + "=" + ((!status.Registered) ? "not registered" : (status.Enabled ? "enabled" : "disabled by run rules")))));
			}
		}
		Say($"QUALITY AUDIT: {num} registered green variants, {num2} disabled by current run rules, {num3} missing. Base-item blacklists still apply to all qualities. ag_quality full lists every item.");
		instance.ReportTestQualityTotals();
	}

	private static bool CheckTestCommand(ConCommandArgs args)
	{
		if (!Object.op_Implicit((Object)(object)Instance) || !Instance._ready)
		{
			Say("The mod has not finished loading its item catalog.");
			return false;
		}
		if (!NetworkServer.active || !Object.op_Implicit((Object)(object)Run.instance))
		{
			Say("Start a run as the host first.");
			return false;
		}
		if (!Instance._testCommands.Value)
		{
			Say("Enable Testing > Enable test commands in Aqueduct Greens' Mod Options first.");
			return false;
		}
		return true;
	}

	private static int PairCount(ConCommandArgs args)
	{
		if (((ConCommandArgs)(ref args)).Count != 0)
		{
			return Math.Max(1, Math.Min(10, ((ConCommandArgs)(ref args)).GetArgInt(0)));
		}
		return 1;
	}

	private static CharacterBody ResolvePlayer(ConCommandArgs args)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		CharacterBody senderBody = ((ConCommandArgs)(ref args)).senderBody;
		if (Object.op_Implicit((Object)(object)senderBody))
		{
			return senderBody;
		}
		if (args.localUserSender != null && Object.op_Implicit((Object)(object)args.localUserSender.cachedBody))
		{
			return args.localUserSender.cachedBody;
		}
		LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser();
		if (firstLocalUser == null)
		{
			return null;
		}
		return firstLocalUser.cachedBody;
	}

	private static bool ApplyOptionalMode(ConCommandArgs args)
	{
		if (((ConCommandArgs)(ref args)).Count < 2)
		{
			return true;
		}
		if (!Enum.TryParse<TestMode>(((ConCommandArgs)(ref args))[1], ignoreCase: true, out var result) || !Enum.IsDefined(typeof(TestMode), result))
		{
			Say("Mode must be normal, random, or locked.");
			return false;
		}
		Instance._testMode = result;
		return true;
	}

	private static bool HasLiveBody(CharacterMaster master)
	{
		if (!Object.op_Implicit((Object)(object)master))
		{
			return false;
		}
		CharacterBody body = master.GetBody();
		if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.healthComponent))
		{
			return body.healthComponent.alive;
		}
		return false;
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void TestModeCommand(ConCommandArgs args)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if (CheckTestCommand(args))
		{
			if (((ConCommandArgs)(ref args)).Count != 1 || !Enum.TryParse<TestMode>(((ConCommandArgs)(ref args))[0], ignoreCase: true, out var result) || !Enum.IsDefined(typeof(TestMode), result))
			{
				Say("Usage: ag_test_mode normal|random|locked");
				return;
			}
			Instance._testMode = result;
			Say($"New test guardians use {result} mode. Normal uses actual unlock state; Random simulates unlocked; Locked simulates first-unlock protection. Natural guardians and profile unlocks are unchanged.");
		}
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void TestSpawnCommand(ConCommandArgs args)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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)
		if (CheckTestCommand(args) && ApplyOptionalMode(args))
		{
			CharacterBody val = ResolvePlayer(args);
			if (!Object.op_Implicit((Object)(object)val))
			{
				Say("You need a living player body.");
				return;
			}
			if (Instance._testCycleRunning)
			{
				Say("A guardian test is already running.");
				return;
			}
			Instance._testCycleRunning = true;
			Say("Version 1.0.8: loading native guardians for a spawn-only test.");
			((MonoBehaviour)Instance).StartCoroutine(Instance.GuardTest(Instance.SpawnAfterLoading(val, PairCount(args))));
		}
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void TestKillCommand(ConCommandArgs args)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if (CheckTestCommand(args))
		{
			Instance.KillTestGuardians();
		}
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void TestCycleCommand(ConCommandArgs args)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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_0080: Unknown result type (might be due to invalid IL or missing references)
		if (CheckTestCommand(args) && ApplyOptionalMode(args))
		{
			CharacterBody val = ResolvePlayer(args);
			if (!Object.op_Implicit((Object)(object)val))
			{
				Say("TEST STOPPED: no living host player body was found. Spawn your survivor and resume gameplay first.");
				return;
			}
			if (Instance._testCycleRunning)
			{
				Say("A test cycle is already running.");
				return;
			}
			Say(string.Format("Version {0}: starting test with {1} pair(s), mode {2}. Let gameplay run briefly while their bodies initialize.", "1.0.8", PairCount(args), Instance._testMode));
			((MonoBehaviour)Instance).StartCoroutine(Instance.GuardTest(Instance.TestCycle(val, PairCount(args))));
		}
	}

	private IEnumerator GuardTest(IEnumerator steps)
	{
		try
		{
			while (true)
			{
				bool flag = false;
				object obj = null;
				Exception ex = null;
				try
				{
					flag = steps.MoveNext();
					if (flag)
					{
						obj = steps.Current;
					}
				}
				catch (Exception ex2)
				{
					ex = ex2;
				}
				if (ex != null)
				{
					Say("TEST FAILED: " + ex.GetType().Name + ": " + ex.Message + ". See LogOutput.log for the stack trace.");
					((BaseUnityPlugin)this).Logger.LogError((object)ex);
					break;
				}
				if (!flag)
				{
					break;
				}
				yield return obj;
			}
		}
		finally
		{
			AqueductGreensPlugin aqueductGreensPlugin = this;
			(steps as IDisposable)?.Dispose();
			aqueductGreensPlugin._testCycleRunning = false;
		}
	}

	private IEnumerator TestCycle(CharacterBody player, int pairs)
	{
		_testCycleRunning = true;
		try
		{
			IEnumerator loading = LoadGuardianPrefabs();
			while (loading.MoveNext())
			{
				yield return loading.Current;
			}
			if (!Object.op_Implicit((Object)(object)player))
			{
				Say("TEST STOPPED: host player body disappeared while loading assets.");
				yield break;
			}
			List<CharacterMaster> spawned = SpawnTestGuardians(player, pairs);
			if (spawned.Count == 0)
			{
				Say("TEST FAILED: no native guardian masters were summoned. See the preceding failure line or run ag_test_info.");
				yield break;
			}
			yield return null;
			yield return null;
			float deadline = Time.realtimeSinceStartup + 15f;
			while (spawned.Any((CharacterMaster master) => !HasLiveBody(master)) && Time.realtimeSinceStartup < deadline)
			{
				yield return null;
			}
			yield return null;
			List<CharacterMaster> ready = spawned.Where(HasLiveBody).ToList();
			foreach (CharacterMaster item in ready)
			{
				Say("READY: " + ((Object)item).name + "; " + DescribeDropHandler(((Component)item).GetComponent<MasterDropDroplet>()));
			}
			if (ready.Count < spawned.Count)
			{
				Say($"BODY TIMEOUT: {ready.Count}/{spawned.Count} guardians have living bodies. Pending masters are retained for ag_test_kill; unpause gameplay and retry that command.");
			}
			KillTestGuardians(ready);
			yield return null;
			yield return null;
			int num = ready.Count((CharacterMaster master) => Object.op_Implicit((Object)(object)master) && Object.op_Implicit((Object)(object)((Component)master).GetComponent<TestGuardian>()) && ((Component)master).GetComponent<TestGuardian>().DropHandlerObserved);
			Say($"TEST RESULT: {ready.Count} living guardian(s) were targeted; native drop callbacks observed for {num}. ag_pool only audits items; it never spawns enemies.");
		}
		finally
		{
			_testCycleRunning = false;
		}
	}

	private IEnumerator SpawnAfterLoading(CharacterBody player, int pairs)
	{
		IEnumerator loading = LoadGuardianPrefabs();
		while (loading.MoveNext())
		{
			yield return loading.Current;
		}
		if (!Object.op_Implicit((Object)(object)player))
		{
			Say("TEST STOPPED: host player body disappeared while loading assets.");
		}
		else
		{
			SpawnTestGuardians(player, pairs);
		}
	}

	private IEnumerator LoadGuardianPrefabs()
	{
		string[] names = new string[2] { "LemurianBruiserMasterFire", "LemurianBruiserMasterIce" };
		string[] guids = new string[2] { "2ea73dc7dd4e1fc4b8a127f7fcf4f193", "59807e19f1b695749b9846a2d4770da4" };
		GameObject[] prefabs = (GameObject[])(object)new GameObject[2] { _kjaroPrefab, _runaldPrefab };
		for (int index = 0; index < prefabs.Length; index++)
		{
			if (!Object.op_Implicit((Object)(object)prefabs[index]))
			{
				prefabs[index] = MasterCatalog.FindMasterPrefab(names[index]);
			}
			if (!Object.op_Implicit((Object)(object)prefabs[index]))
			{
				Say("Loading native asset " + names[index] + " asynchronously; it was not found in MasterCatalog.");
				AsyncOperationHandle<GameObject> handle = Addressables.LoadAssetAsync<GameObject>((object)guids[index]);
				_guardianAssetHandles.Add(handle);
				float deadline = Time.realtimeSinceStartup + 15f;
				while (!handle.IsDone && Time.realtimeSinceStartup < deadline)
				{
					yield return null;
				}
				if (!handle.IsDone)
				{
					throw new TimeoutException("Native guardian asset " + names[index] + " did not load in 15 seconds.");
				}
				if ((int)handle.Status != 1 || !Object.op_Implicit((Object)(object)handle.Result))
				{
					throw new InvalidOperationException("Native guardian asset " + names[index] + " could not be loaded.", handle.OperationException);
				}
				prefabs[index] = handle.Result;
			}
		}
		_kjaroPrefab = prefabs[0];
		_runaldPrefab = prefabs[1];
	}

	private void ReleaseGuardianAssetHandles()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		foreach (AsyncOperationHandle<GameObject> guardianAssetHandle in _guardianAssetHandles)
		{
			if (guardianAssetHandle.IsValid())
			{
				Addressables.Release<GameObject>(guardianAssetHandle);
			}
		}
		_guardianAssetHandles.Clear();
	}

	private List<CharacterMaster> SpawnTestGuardians(CharacterBody player, int pairs)
	{
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: 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_0158: 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)
		//IL_0173: 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_017d: Unknown result type (might be due to invalid IL or missing references)
		//IL_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		List<CharacterMaster> spawned = new List<CharacterMaster>();
		if (!Object.op_Implicit((Object)(object)_kjaroPrefab) || !Object.op_Implicit((Object)(object)_runaldPrefab) || !Object.op_Implicit((Object)(object)_kjaroPrefab.GetComponent<CharacterMaster>()) || !Object.op_Implicit((Object)(object)_runaldPrefab.GetComponent<CharacterMaster>()))
		{
			Say("SPAWN FAILED: could not load both native guardian CharacterMaster prefabs. No ordinary Elder Lemurian was substituted.");
			return spawned;
		}
		Say("Native prefab " + ((Object)_kjaroPrefab).name + ": " + DescribeDropHandler(_kjaroPrefab.GetComponent<MasterDropDroplet>()));
		Say("Native prefab " + ((Object)_runaldPrefab).name + ": " + DescribeDropHandler(_runaldPrefab.GetComponent<MasterDropDroplet>()));
		Transform transform = ((Component)player).transform;
		Vector3 forward = (Object.op_Implicit((Object)(object)player.inputBank) ? player.inputBank.aimDirection : transform.forward);
		forward.y = 0f;
		if (((Vector3)(ref forward)).sqrMagnitude < 0.01f)
		{
			forward = Vector3.forward;
		}
		((Vector3)(ref forward)).Normalize();
		Vector3 val = Vector3.Cross(Vector3.up, forward);
		Vector3 lootAnchor = CreateTestLootTray(player.footPosition, forward);
		for (int i = 0; i < pairs; i++)
		{
			Vector3 val2 = player.footPosition + forward * (10f + (float)(i / 3) * 4f) + val * ((float)(i % 3 - 1) * 7f);
			Spawn(_kjaroPrefab, val2 - val * 2f);
			Spawn(_runaldPrefab, val2 + val * 2f);
		}
		Say($"Spawned {spawned.Count} native test guardians in {_testMode} mode. AI disabled. ag_test_kill kills only these marked test spawns.");
		return spawned;
		void Spawn(GameObject prefab, Vector3 position)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val3 = default(RaycastHit);
			if (Physics.Raycast(position + Vector3.up * 20f, Vector3.down, ref val3, 80f, LayerMask.op_Implicit(((LayerIndex)(ref LayerIndex.world)).mask)))
			{
				position = ((RaycastHit)(ref val3)).point + Vector3.up;
			}
			CharacterMaster val4 = new MasterSummon
			{
				masterPrefab = prefab,
				position = position,
				rotation = Quaternion.LookRotation(-forward),
				teamIndexOverride = (TeamIndex)2,
				ignoreTeamMemberLimit = true,
				preSpawnSetupCallback = delegate(CharacterMaster summoned)
				{
					//IL_0028: Unknown result type (might be due to invalid IL or missing references)
					//IL_002d: Unknown result type (might be due to invalid IL or missing references)
					TestGuardian testGuardian2 = ((Component)summoned).gameObject.AddComponent<TestGuardian>();
					testGuardian2.Mode = _testMode;
					testGuardian2.LootAnchor = lootAnchor;
					testGuardian2.Label = string.Format("{0} #{1}", ((Object)(object)prefab == (Object)(object)_kjaroPrefab) ? "Kjaro" : "Runald", ++_nextTestGuardianId);
					BaseAI[] components = ((Component)summoned).GetComponents<BaseAI>();
					for (int j = 0; j < components.Length; j++)
					{
						((Behaviour)components[j]).enabled = false;
					}
				}
			}.Perform();
			if (Object.op_Implicit((Object)(object)val4))
			{
				TestGuardian testGuardian = ((Component)val4).GetComponent<TestGuardian>();
				if (!Object.op_Implicit((Object)(object)testGuardian))
				{
					testGuardian = ((Component)val4).gameObject.AddComponent<TestGuardian>();
				}
				testGuardian.Mode = _testMode;
				testGuardian.LootAnchor = lootAnchor;
				if (string.IsNullOrEmpty(testGuardian.Label))
				{
					testGuardian.Label = string.Format("{0} #{1}", ((Object)(object)prefab == (Object)(object)_kjaroPrefab) ? "Kjaro" : "Runald", ++_nextTestGuardianId);
				}
				spawned.Add(val4);
				_testMasters.Add(val4);
			}
			else
			{
				Say("SPAWN FAILED: MasterSummon returned no master for " + ((Object)prefab).name + ".");
			}
		}
	}

	private void KillTestGuardians(List<CharacterMaster> selected = null)
	{
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		CharacterMaster[] array = (selected ?? _testMasters).ToArray();
		foreach (CharacterMaster val in array)
		{
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)((Component)val).GetComponent<TestGuardian>()))
			{
				CharacterBody body = val.GetBody();
				if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.healthComponent) && body.healthComponent.alive)
				{
					body.healthComponent.Suicide((GameObject)null, (GameObject)null, default(DamageTypeCombo));
					num++;
				}
			}
		}
		_testMasters.RemoveAll((CharacterMaster master) => !Object.op_Implicit((Object)(object)master) || (Object.op_Implicit((Object)(object)master.GetBody()) && Object.op_Implicit((Object)(object)master.GetBody().healthComponent) && !master.GetBody().healthComponent.alive));
		Say($"Instantly killed {num} test guardians through their normal death/drop handlers.");
		ReportTestQualityTotals();
	}

	private static string DescribeDropHandler(MasterDropDroplet drop)
	{
		if (!Object.op_Implicit((Object)(object)drop))
		{
			return "NO MasterDropDroplet component";
		}
		string arg = ((drop.dropTables == null) ? "null" : string.Join(", ", drop.dropTables.Select((PickupDropTable table) => (!Object.op_Implicit((Object)(object)table)) ? "null" : ((Object)table).name)));
		string arg2 = ((drop.pickupsToDrop == null) ? "null" : string.Join(", ", drop.pickupsToDrop.Select((SerializablePickupIndex pickup) => pickup.pickupName ?? "null")));
		return $"tables=[{arg}], legacy=[{arg2}], recognized={IsGuardian(drop)}";
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void TestInfoCommand(ConCommandArgs args)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)Instance))
		{
			return;
		}
		CharacterBody val = ResolvePlayer(args);
		Say(string.Format("Version {0}; ready={1}; enabled={2}; testCommands={3}; server={4}; playerBody={5}; testRunning={6}.", "1.0.8", Instance._ready, Instance._enabled.Value, Instance._testCommands.Value, NetworkServer.active, Object.op_Implicit((Object)(object)val) ? ((Object)val).name : "none", Instance._testCycleRunning));
		Say("Marked test guardians share one advancing native reward RNG for this run. Each base/final drop log names its guardian.");
		Instance.ReportNaturalRngTotals();
		string[] array = new string[2] { "LemurianBruiserMasterFire", "LemurianBruiserMasterIce" };
		foreach (string text in array)
		{
			GameObject val2 = MasterCatalog.FindMasterPrefab(text);
			Say("Catalog " + text + ": " + (Object.op_Implicit((Object)(object)val2) ? DescribeDropHandler(val2.GetComponent<MasterDropDroplet>()) : "not registered"));
		}
		foreach (CharacterMaster item in Instance._testMasters.Where((CharacterMaster master) => Object.op_Implicit((Object)(object)master)))
		{
			Say($"Tracked {((Object)item).name}: liveBody={HasLiveBody(item)}; {DescribeDropHandler(((Component)item).GetComponent<MasterDropDroplet>())}");
		}
	}

	[ConCommand(/*Could not decode attribute arguments.*/)]
	private static void PoolCommand(ConCommandArgs args)
	{
		//IL_008d: 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_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_023a: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)Instance) || !Instance._ready)
		{
			Say("Item catalog is not ready.");
			return;
		}
		bool flag = ((ConCommandArgs)(ref args)).Count > 0 && string.Equals(((ConCommandArgs)(ref args))[0], "full", StringComparison.OrdinalIgnoreCase);
		AqueductGreensPlugin instance = Instance;
		List<PickupIndex> list = instance.CurrentPool();
		HashSet<ItemIndex> hashSet = new HashSet<ItemIndex>(instance._items.Select((ItemOption entry) => entry.Item.itemIndex));
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		foreach (ItemDef item in ((IEnumerable<ItemDef>)(object)ItemCatalog.allItemDefs).Where((ItemDef val) => Object.op_Implicit((Object)(object)val) && (int)val.tier == 1).OrderBy<ItemDef, string>((ItemDef val) => Language.GetString(val.nameToken), StringComparer.OrdinalIgnoreCase))
		{
			string text = instance.Exclusion(item);
			if (text != null)
			{
				if (instance._quality.IsVariant(item.itemIndex))
				{
					num2++;
					continue;
				}
				if ((Object)(object)item == (Object)(object)Items.ScrapGreen || GreenPolicy.IsGreenScrapName(((Object)item).name))
				{
					num4++;
				}
				if (item.hidden)
				{
					num3++;
				}
				if (flag)
				{
					Say("EXCLUDED: " + Language.GetString(item.nameToken) + " [" + ((Object)item).name + "] — " + text);
				}
			}
			else if (!hashSet.Contains(item.itemIndex))
			{
				num++;
				Say("ERROR missing checkbox: " + ((Object)item).name);
			}
			else if (flag)
			{
				ItemOption itemOption = instance._items.First((ItemOption entry) => (Object)(object)entry.Item == (Object)(object)item);
				bool flag2 = list.Contains(PickupCatalog.FindPickupIndex(item.itemIndex));
				string text2 = ((!itemOption.Allowed.Value) ? "BLACKLISTED" : ((!Object.op_Implicit((Object)(object)Run.instance)) ? "NO RUN" : (flag2 ? "IN POOL" : "LOCKED/DISABLED IN RUN")));
				Say(text2 + ": " + Language.GetString(item.nameToken) + " [" + ((Object)item).name + "]");
			}
		}
		int num5 = ((IEnumerable<ItemDef>)(object)ItemCatalog.allItemDefs).Count((ItemDef val) => Object.op_Implicit((Object)(object)val) && (int)val.tier == 13);
		Say(string.Format("Version {0} AUDIT {1}: {2} eligible base greens registered, {3} currently in pool, {4} missing. Excluded: {5} green scrap definitions, {6} hidden/internal greens, {7} Quality aliases. {8} hexes are a separate tier. Regenerating Scrap stays eligible.", "1.0.8", (num == 0) ? "PASS" : "FAIL", hashSet.Count, list.Count, num, num4, num3, num2, num5));
		Say($"Quality installed: {instance._quality.Installed}. First-unlock protection this visit: {instance._visit.PreserveBands}. Test mode: {instance._testMode}. ag_pool full lists every item; ag_test_cycle 1 random spawns and kills one pair.");
	}

	private Vector3 CreateTestLootTray(Vector3 playerFeet, Vector3 forward)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: 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_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_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: 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_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: 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_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: 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)
		Vector3 val = playerFeet + forward * 6f;
		foreach (GameObject testLootTray in _testLootTrays)
		{
			if (Object.op_Implicit((Object)(object)testLootTray))
			{
				Vector3 result = testLootTray.transform.position - val;
				if (((Vector3)(ref result)).sqrMagnitude < 400f)
				{
					result = testLootTray.transform.position + Vector3.up * 2.75f;
					return result;
				}
			}
		}
		float y = playerFeet.y;
		RaycastHit val2 = default(RaycastHit);
		if (Physics.Raycast(val + Vector3.up * 20f, Vector3.down, ref val2, 80f, LayerMask.op_Implicit(((LayerIndex)(ref LayerIndex.world)).mask), (QueryTriggerInteraction)1))
		{
			y = ((RaycastHit)(ref val2)).point.y;
		}
		GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)3);
		((Object)val3).name = "Aqueduct Greens test loot tray";
		int num = LayerMask.NameToLayer("World");
		if (num >= 0)
		{
			val3.layer = num;
		}
		val3.transform.position = new Vector3(val.x, y, val.z);
		val3.transform.localScale = new Vector3(8f, 0.5f, 8f);
		_testLootTrays.Add(val3);
		Say("A small test loot tray is placed nearby. Test drops are moved above it after their native Quality roll.");
		return val3.transform.position + Vector3.up * 2.75f;
	}

	private void RedirectTestLoot(orig_CreatePickupDroplet_CreatePickupInfo_Vector3_Vector3 orig, CreatePickupInfo pickupInfo, Vector3 position, Vector3 velocity)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: 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_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		if (!NetworkServer.active || !Object.op_Implicit((Object)(object)_activeTestLoot))
		{
			orig.Invoke(pickupInfo, position, velocity);
			if (NetworkServer.active && _activeNaturalGuardianLabel != null && _logRolls.Value)
			{
				PickupIndex pickupIndex = ((CreatePickupInfo)(ref pickupInfo)).pickup.pickupIndex;
				Say("FINAL GUARDIAN DROP: " + ItemName(pickupIndex) + " — " + _quality.GetQualityName(pickupIndex) + ". Guardian=" + _activeNaturalGuardianLabel + ". Native drop position preserved.");
			}
			return;
		}
		HashSet<int> hashSet = new HashSet<int>(from drop in Object.FindObjectsOfType<PickupDropletController>()
			select ((Object)drop).GetInstanceID());
		Vector2 insideUnitCircle = Random.insideUnitCircle;
		position = _activeTestLoot.LootAnchor + new Vector3(insideUnitCircle.x, 0f, insideUnitCircle.y);
		velocity = Vector3.up * 7f;
		orig.Invoke(pickupInfo, position, velocity);
		PickupDropletController[] array = Object.FindObjectsOfType<PickupDropletController>();
		foreach (PickupDropletController val in array)
		{
			if (!hashSet.Contains(((Object)val).GetInstanceID()))
			{
				Rigidbody component = ((Component)val).GetComponent<Rigidbody>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.collisionDetectionMode = (CollisionDetectionMode)(component.isKinematic ? 3 : 2);
				}
			}
		}
		PickupIndex pickupIndex2 = ((CreatePickupInfo)(ref pickupInfo)).pickup.pickupIndex;
		string qualityName = _quality.GetQualityName(pickupIndex2);
		_testQualityTotals.TryGetValue(qualityName, out var value);
		_testQualityTotals[qualityName] = value + 1;
		Say("FINAL TEST DROP: " + ItemName(pickupIndex2) + " — " + qualityName + ". Guardian=" + _activeTestLoot.Label + ". Native Quality roll preserved.");
	}

	private void ReportTestQualityTotals()
	{
		string[] source = new string[5] { "base quality", "Uncommon", "Rare", "Epic", "Legendary" };
		Say("TEST QUALITY TOTALS (this run): " + string.Join(", ", source.Select((string tier) => $"{tier}={(_testQualityTotals.TryGetValue(tier, out var value) ? value : 0)}")));
		Say($"TEST RNG CHECKS (this run): matched={_matchedTestRngCalls}, mismatched={_mismatchedTestRngCalls}. Counts reflect actual RNG arguments received by the native table path.");
	}

	private void ClearTestLootTrays()
	{
		foreach (GameObject testLootTray in _testLootTrays)
		{
			if (Object.op_Implicit((Object)(object)testLootTray))
			{
				Object.Destroy((Object)(object)testLootTray);
			}
		}
		_testLootTrays.Clear();
	}

	internal void VerifyTestRewardRng(Xoroshiro128Plus actual)
	{
		if (!Object.op_Implicit((Object)(object)_activeTestLoot))
		{
			VerifyNaturalRewardRng(actual);
			return;
		}
		if (actual == _testRewardRandom.Get(Run.instance.seed))
		{
			_matchedTestRngCalls++;
			return;
		}
		_mismatchedTestRngCalls++;
		Say("TEST RNG MISMATCH: Guardian=" + _activeTestLoot.Label + ". The native table received a different RNG; retain this log for diagnosis.");
	}
}
public sealed class GreenDropTable : PickupDropTable
{
	internal List<PickupIndex> Choices = new List<PickupIndex>();

	public override int GetPickupCount()
	{
		return Choices.Count;
	}

	public override UniquePickup GeneratePickupPreReplacement(Xoroshiro128Plus rng)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: 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_0053: 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)
		if (Choices.Count == 0)
		{
			return UniquePickup.none;
		}
		AqueductGreensPlugin.Instance?.VerifyTestRewardRng(rng);
		PickupIndex val = Choices[rng.RangeInt(0, Choices.Count)];
		AqueductGreensPlugin.Instance?.ReportBaseRoll(val);
		return new UniquePickup(val);
	}

	public override void GenerateDistinctPickupsPreReplacement(List<UniquePickup> dest, int desiredCount, Xoroshiro128Plus rng)
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		AqueductGreensPlugin.Instance?.VerifyTestRewardRng(rng);
		List<PickupIndex> list = new List<PickupIndex>(Choices);
		while (list.Count > 0 && desiredCount-- > 0)
		{
			int index = rng.RangeInt(0, list.Count);
			dest.Add(new UniquePickup(list[index]));
			list.RemoveAt(index);
		}
	}
}
internal static class GreenPolicy
{
	internal static bool IsGreenScrapName(string name)
	{
		if (!string.Equals(name, "ScrapGreen", StringComparison.OrdinalIgnoreCase))
		{
			return string.Equals(name, "ScrapGreenSuppressed", StringComparison.OrdinalIgnoreCase);
		}
		return true;
	}

	internal static bool IsNativeGuardianName(string name)
	{
		if (name == null)
		{
			return false;
		}
		name = name.Replace("(Clone)", "").Trim();
		if (!string.Equals(name, "LemurianBruiserMasterFire", StringComparison.OrdinalIgnoreCase))
		{
			return string.Equals(name, "LemurianBruiserMasterIce", StringComparison.OrdinalIgnoreCase);
		}
		return true;
	}

	internal static string Exclusion(bool isTier2, bool hidden, bool isGreenScrap, bool isQualityVariant)
	{
		if (!isTier2)
		{
			return "not Tier 2";
		}
		if (isGreenScrap)
		{
			return "green scrap";
		}
		if (isQualityVariant)
		{
			return "Quality variant (rolled by Quality instead)";
		}
		if (hidden)
		{
			return "hidden/internal item";
		}
		return null;
	}

	internal static List<T> EnabledAvailable<T>(IEnumerable<T> catalog, Func<T, bool> enabled, Func<T, bool> available)
	{
		List<T> list = new List<T>();
		foreach (T item in catalog)
		{
			if (enabled(item) && available(item))
			{
				list.Add(item);
			}
		}
		return list;
	}
}
internal sealed class UnlockVisit
{
	internal bool PreserveBands { get; private set; } = true;

	internal bool Captured { get; private set; }

	internal void Begin(bool someoneNeedsBands)
	{
		PreserveBands = someoneNeedsBands;
		Captured = true;
	}

	internal void Observe(bool someoneNeedsBands)
	{
		if (!Captured)
		{
			Begin(someoneNeedsBands);
		}
		else
		{
			PreserveBands |= someoneNeedsBands;
		}
	}

	internal void Clear()
	{
		Captured = false;
		PreserveBands = true;
	}
}
internal sealed class QualityCompatibility
{
	internal const string PluginGuid = "com.Gorakh.ItemQualities";

	private MethodInfo _getQualityTier;

	private object _baseQuality;

	private MethodInfo _getItemIndexOfQuality;

	private MethodInfo _isPickupRuleEnabled;

	private Type _tierType;

	private ConfigEntry<float> _globalChance;

	internal bool Installed { get; private set; }

	internal string Version { get; private set; }

	internal bool CanInspectVariants
	{
		get
		{
			if (_getItemIndexOfQuality != null)
			{
				return _isPickupRuleEnabled != null;
			}
			return false;
		}
	}

	internal string Summary
	{
		get
		{
			if (!Installed)
			{
				return "Quality is not installed.";
			}
			return "Quality " + Version + "; Global Quality Chance=" + ((_globalChance == null) ? "unknown" : (_globalChance.Value.ToString("0.##") + "%")) + ".";
		}
	}

	internal void Initialize()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Expected O, but got Unknown
		Installed = Chainloader.PluginInfos.TryGetValue("com.Gorakh.ItemQualities", out var value);
		if (Installed)
		{
			Version = value.Metadata.Version.ToString();
			value.Instance.Config.TryGetEntry<float>(new ConfigDefinition("General", "Global Quality Chance"), ref _globalChance);
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			Type type = assembly.GetType("ItemQualities.QualityCatalog", throwOnError: true);
			Type type2 = assembly.GetType("ItemQualities.QualityTier", throwOnError: true);
			_getQualityTier = type.GetMethod("GetQualityTier", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(ItemIndex) }, null);
			if (_getQualityTier == null)
			{
				throw new MissingMethodException(type.FullName, "GetQualityTier(ItemIndex)");
			}
			_baseQuality = Enum.Parse(type2, "None");
			_tierType = type2;
			_getItemIndexOfQuality = type.GetMethod("GetItemIndexOfQuality", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
			{
				typeof(ItemIndex),
				type2
			}, null);
			_isPickupRuleEnabled = assembly.GetType("ItemQualities.Utilities.Extensions.RuleExtensions")?.GetMethod("IsPickupRuleEnabled", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2]
			{
				typeof(RuleBook),
				typeof(PickupIndex)
			}, null);
		}
	}

	internal bool IsVariant(ItemIndex item)
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		if (!Installed)
		{
			return false;
		}
		if (_getQualityTier == null)
		{
			throw new InvalidOperationException("Quality's catalog could not be checked.");
		}
		return !object.Equals(_getQualityTier.Invoke(null, new object[1] { item }), _baseQuality);
	}

	internal string GetQualityName(PickupIndex pickup)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Invalid comparison between Unknown and I4
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		if (!Installed)
		{
			return "base quality";
		}
		PickupDef pickupDef = PickupCatalog.GetPickupDef(pickup);
		if (pickupDef == null || (int)pickupDef.itemIndex == -1)
		{
			return "not an item";
		}
		object obj = _getQualityTier.Invoke(null, new object[1] { pickupDef.itemIndex });
		if (!object.Equals(obj, _baseQuality))
		{
			return obj.ToString();
		}
		return "base quality";
	}

	internal IEnumerable<(string Tier, bool Registered, bool Enabled)> InspectVariants(ItemIndex baseItem)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		if (Installed && CanInspectVariants)
		{
			string[] array = new string[4] { "Uncommon", "Rare", "Epic", "Legendary" };
			foreach (string text in array)
			{
				object obj = Enum.Parse(_tierType, text);
				ItemIndex val = (ItemIndex)_getItemIndexOfQuality.Invoke(null, new object[2] { baseItem, obj });
				PickupIndex val2 = PickupCatalog.FindPickupIndex(val);
				bool flag = val != baseItem && (int)val != -1 && val2 != PickupIndex.none && object.Equals(_getQualityTier.Invoke(null, new object[1] { val }), obj);
				bool item = flag && (!Object.op_Implicit((Object)(object)Run.instance) || Run.instance.ruleBook == null || (bool)_isPickupRuleEnabled.Invoke(null, new object[2]
				{
					Run.instance.ruleBook,
					val2
				}));
				yield return (Tier: text, Registered: flag, Enabled: item);
			}
		}
	}
}
internal static class RewardRouting
{
	internal static void MoveFixedRewardsToTables<TPickup, TTable>(IEnumerable<TPickup> originals, Func<TPickup, bool> isReplacedReward, List<TPickup> retainedPickups, List<TTable> tables, TTable rewardTable, bool hasAllowedChoices)
	{
		if (originals == null)
		{
			return;
		}
		foreach (TPickup original in originals)
		{
			if (!isReplacedReward(original))
			{
				retainedPickups.Add(original);
			}
			else if (hasAllowedChoices)
			{
				tables.Add(rewardTable);
			}
		}
	}
}
internal sealed class ScopedFieldOverride<T> : IDisposable where T : class
{
	private object _target;

	private readonly FieldInfo _field;

	private readonly object _original;

	internal ScopedFieldOverride(object target, FieldInfo field, T replacement)
	{
		if (target == null)
		{
			throw new ArgumentNullException("target");
		}
		if (field == null)
		{
			throw new MissingFieldException("The native test-drop RNG field was not found.");
		}
		if (replacement == null)
		{
			throw new ArgumentNullException("replacement");
		}
		if (field.IsStatic || field.FieldType != typeof(T) || !field.DeclaringType.IsInstanceOfType(target))
		{
			throw new ArgumentException("The native test-drop RNG field has an incompatible type or owner.", "field");
		}
		_field = field;
		_original = field.GetValue(target);
		field.SetValue(target, replacement);
		_target = target;
	}

	public void Dispose()
	{
		if (_target != null)
		{
			_field.SetValue(_target, _original);
			_target = null;
		}
	}
}
internal enum TestMode
{
	Normal,
	Random,
	Locked
}
public sealed class TestGuardian : MonoBehaviour
{
	internal TestMode Mode;

	internal bool DropHandlerObserved;

	internal Vector3 LootAnchor;

	internal string Label;
}
internal sealed class TestRandomStream<T> where T : class
{
	private readonly Func<ulong, T> _create;

	private T _current;

	private ulong _runSeed;

	internal TestRandomStream(Func<ulong, T> create)
	{
		_create = create;
	}

	internal T Get(ulong runSeed)
	{
		if (_current == null || _runSeed != runSeed)
		{
			_current = _create(runSeed);
			_runSeed = runSeed;
		}
		return _current;
	}

	internal void Reset()
	{
		_current = null;
	}
}