Decompiled source of GambleCartPack v1.1.1

BepInEx/plugins/GambleCartPack.dll

Decompiled 3 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Patpack;
using Patpack.MultiplierCart;
using Patpack.ShrinkCart;
using Photon.Pun;
using Photon.Realtime;
using REPOLib.Modules;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("1.1.1.0")]
namespace GambleCartPack;

[BepInPlugin("com.codex.gamblecart", "GambleCartPack", "1.1.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	public const string ModGuid = "com.codex.gamblecart";

	public const string ModName = "GambleCartPack";

	public const string ModVersion = "1.1.1";

	public const byte GambleValueEventCode = 178;

	public const byte GambleLuckEventCode = 179;

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> PatpackPresetApplied;

	internal static ConfigEntry<bool> ForceReapplyPreset;

	internal static ConfigEntry<bool> SacrificeDefaultOffApplied;

	internal static ConfigEntry<bool> EnableCartShrinking;

	internal static ConfigEntry<float> ShrinkSpeed;

	internal static ConfigEntry<bool> ScaleNonValuables;

	internal static ConfigEntry<bool> SilenceInCartBumpImpacts;

	internal static ConfigEntry<float> GamblePriceMultiplier;

	internal static ConfigEntry<float> GambleTierSfxVolumeDb;

	internal static ConfigEntry<float> JackpotSfxVolumeDb;

	internal static ConfigEntry<bool> EnablePastelRimEffect;

	internal static ConfigEntry<bool> EnablePastelScreenEffect;

	internal static ConfigEntry<float> RimGlowIntensity;

	internal static ConfigEntry<float> ScreenGlowIntensity;

	internal static ConfigEntry<float> RimAnimationFps;

	internal static ConfigEntry<float> GambleInnerZoneScale;

	internal static ConfigEntry<float> GambleDwellSeconds;

	internal static ConfigEntry<bool> RequireReleasedInCart;

	internal static ConfigEntry<bool> EnableLuckTokenSystem;

	internal static ConfigEntry<bool> ShowLuckHud;

	internal static ConfigEntry<int> ItemsPerBonusTokenRoll;

	internal static ConfigEntry<float> LuckHudOffsetX;

	internal static ConfigEntry<float> LuckHudOffsetY;

	internal static ConfigEntry<bool> EnableRollPopupsAndVfx;

	internal static ConfigEntry<bool> ShowExtractionSettlementBanner;

	internal static ConfigEntry<bool> BhEnabled;

	internal static ConfigEntry<float> BhHealthPackMultiplier;

	internal static ConfigEntry<bool> BhFullHealthAtStart;

	internal static ConfigEntry<bool> BhEnableHealthRegen;

	internal static ConfigEntry<int> BhHealthRegenAmount;

	internal static ConfigEntry<int> BhRegenIntervalSeconds;

	internal static ConfigEntry<bool> BhEnableExtractionHeal;

	internal static ConfigEntry<bool> BhExtractionFullHeal;

	internal static ConfigEntry<int> BhExtractionHealAmount;

	internal static ConfigEntry<bool> BhEnableTeamHealthPack;

	internal static ConfigEntry<bool> BhEqualSplitTeamHealth;

	internal static ConfigEntry<bool> BhEnableCustomReviveHealth;

	internal static ConfigEntry<bool> BhFullReviveHealth;

	internal static ConfigEntry<int> BhCustomReviveHealthAmount;

	internal static ConfigEntry<bool> AutoGrantTestCartOnce;

	internal static ConfigEntry<bool> EnableTestSpawnHotkey;

	internal static ConfigEntry<int> TestSaveUpgradeLevel;

	internal static readonly HashSet<int> RolledValuables = new HashSet<int>();

	internal static bool PendingTestCartSpawn;

	internal static int PendingTestUpgradeLevel;

	internal static readonly AudioClip[] TierClips = (AudioClip[])(object)new AudioClip[6];

	internal static readonly FieldInfo ValuableOrigField = AccessTools.Field(typeof(ValuableObject), "dollarValueOriginal");

	internal static readonly FieldInfo ValuableCurrField = AccessTools.Field(typeof(ValuableObject), "dollarValueCurrent");

	internal static readonly FieldInfo ValuableSetField = AccessTools.Field(typeof(ValuableObject), "dollarValueSet");

	internal static readonly FieldInfo PhysIsPlayerField = AccessTools.Field(typeof(PhysGrabObject), "isPlayer");

	internal static readonly FieldInfo PhysIsEnemyField = AccessTools.Field(typeof(PhysGrabObject), "isEnemy");

	internal static readonly FieldInfo ImpactPhysObjField = AccessTools.Field(typeof(PhysGrabObjectImpactDetector), "physGrabObject");

	internal static readonly FieldInfo RoundCosmeticListField = AccessTools.Field(typeof(RoundDirector), "cosmeticWorldObjectsExtracted");

	internal static readonly FieldInfo RunCosmeticCooldownField = AccessTools.Field(typeof(RunManager), "cosmeticWorldObjectCooldown");

	internal static readonly FieldInfo RunRestartingField = AccessTools.Field(typeof(RunManager), "restarting");

	internal static readonly FieldInfo ResultStateTimerField = AccessTools.Field(typeof(ResultScreenUI), "stateTimer");

	internal static readonly FieldInfo CartInCartField = AccessTools.Field(typeof(PhysGrabCart), "inCart");

	internal static readonly FieldInfo PatpackInstanceField = AccessTools.Field(typeof(PatpackPlugin), "Instance");

	internal static readonly FieldInfo PatpackModulesField = AccessTools.Field(typeof(PatpackPlugin), "Modules");

	private Harmony _harmony;

	private void Awake()
	{
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Expected O, but got Unknown
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Expected O, but got Unknown
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Expected O, but got Unknown
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Expected O, but got Unknown
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Expected O, but got Unknown
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Expected O, but got Unknown
		//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Expected O, but got Unknown
		//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fc: Expected O, but got Unknown
		//IL_0330: Unknown result type (might be due to invalid IL or missing references)
		//IL_033a: Expected O, but got Unknown
		//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ce: Expected O, but got Unknown
		//IL_0402: Unknown result type (might be due to invalid IL or missing references)
		//IL_040c: Expected O, but got Unknown
		//IL_0440: Unknown result type (might be due to invalid IL or missing references)
		//IL_044a: Expected O, but got Unknown
		//IL_04de: Unknown result type (might be due to invalid IL or missing references)
		//IL_04e8: Expected O, but got Unknown
		//IL_0552: Unknown result type (might be due to invalid IL or missing references)
		//IL_055c: Expected O, but got Unknown
		//IL_0586: Unknown result type (might be due to invalid IL or missing references)
		//IL_0590: Expected O, but got Unknown
		//IL_05fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0607: Expected O, but got Unknown
		//IL_06b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_06bb: Expected O, but got Unknown
		//IL_0732: Unknown result type (might be due to invalid IL or missing references)
		//IL_073c: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		PatpackPresetApplied = ((BaseUnityPlugin)this).Config.Bind<bool>("1_PatpackTakeover", "Preset Applied Once", false, "Internal flag: set to true after Patpack defaults were taken over on first install.");
		ForceReapplyPreset = ((BaseUnityPlugin)this).Config.Bind<bool>("1_PatpackTakeover", "Force Reapply Preset", false, "Set true and restart/reload to reapply the curated Patpack preset defaults.");
		SacrificeDefaultOffApplied = ((BaseUnityPlugin)this).Config.Bind<bool>("1_PatpackTakeover", "Sacrifice Bomb Default Off Applied", false, "Internal migration flag: set to true after Sacrifice Bomb was turned off by default.");
		EnableCartShrinking = ((BaseUnityPlugin)this).Config.Bind<bool>("2_ScaleInCart", "Enabled", true, "All carts shrink items placed inside them permanently using BULLETBOT-ScaleInCart mass ratios.");
		ShrinkSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("2_ScaleInCart", "Shrink Speed", 0.45f, new ConfigDescription("Scale interpolation speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 10f), new object[0]));
		ScaleNonValuables = ((BaseUnityPlugin)this).Config.Bind<bool>("2_ScaleInCart", "Scale Non-Valuable Items", false, "Also shrink loose non-valuable shop items placed in carts.");
		SilenceInCartBumpImpacts = ((BaseUnityPlugin)this).Config.Bind<bool>("2_ScaleInCart", "Silence In-Cart Bump Sounds", true, "Suppresses light/medium impact triggers (like HuhCat/FUMO talking) caused by cart pushing bumps while items ride inside a cart.");
		GamblePriceMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Shop Price Multiplier", 1.5f, new ConfigDescription("Price multiplier vs medium cart.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), new object[0]));
		GambleTierSfxVolumeDb = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Result SFX Trim (dB)", 0f, new ConfigDescription("Volume trim in dB for tiered gamble sound effects (already normalized to -25.5 dBFS).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-30f, 6f), new object[0]));
		JackpotSfxVolumeDb = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "100x Jackpot SFX Trim (dB)", 0f, new ConfigDescription("Volume trim in dB for the global 0.1% 100x jackpot sound.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-30f, 6f), new object[0]));
		EnablePastelRimEffect = ((BaseUnityPlugin)this).Config.Bind<bool>("3_GambleCart", "Animated Pastel Infinity Rim", true, "Apply animated pastel cosmic effect to only the Gamble Cart upper rim.");
		EnablePastelScreenEffect = ((BaseUnityPlugin)this).Config.Bind<bool>("3_GambleCart", "Animated Pastel Value Screen", true, "Apply animated pastel cosmic effect to the Gamble Cart blue value screen background.");
		RimGlowIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Rim Glow Intensity", 0.62f, new ConfigDescription("HDR emission brightness for the pastel infinity rim.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 6f), new object[0]));
		ScreenGlowIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Screen Glow Intensity", 0.35f, new ConfigDescription("HDR emission brightness for the pastel value screen.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 4f), new object[0]));
		RimAnimationFps = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Rim Animation FPS", 12f, new ConfigDescription("Frame rate of the animated upper rim.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), new object[0]));
		GambleInnerZoneScale = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Interior Center Zone Scale", 0.94f, new ConfigDescription("Requires the item centerPoint to be inside this fraction of the cart interior (prevents outer-wall brushing while catching tiny corner items).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.35f, 1f), new object[0]));
		GambleDwellSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("3_GambleCart", "Inside Dwell Time (Seconds)", 0.25f, new ConfigDescription("Minimum seconds an item must stay inside the cart before gambling triggers.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1.5f), new object[0]));
		RequireReleasedInCart = ((BaseUnityPlugin)this).Config.Bind<bool>("3_GambleCart", "Require Item Released", true, "Prevents triggering while you are still holding/waving an item near the cart; triggers once dropped inside.");
		EnableLuckTokenSystem = ((BaseUnityPlugin)this).Config.Bind<bool>("3_LuckAndTokens", "Enabled", true, "Tracks per-level luck weight from Gamble Cart rolls and awards cosmetic tokens on truck extraction.");
		ShowLuckHud = ((BaseUnityPlugin)this).Config.Bind<bool>("3_LuckAndTokens", "Show Luck HUD", true, "Displays rolled loot count and current luck weight at bottom-right in-game HUD during levels.");
		ItemsPerBonusTokenRoll = ((BaseUnityPlugin)this).Config.Bind<int>("3_LuckAndTokens", "Items Per Bonus Roll", 15, new ConfigDescription("Every N gambled items guarantees +1 bonus token roll (with smooth curve up to 50% between steps).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 50), new object[0]));
		LuckHudOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("3_LuckAndTokens", "Bottom-Right Margin X", -42f, new ConfigDescription("Horizontal margin from screen bottom-right (1920x1080 reference).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-600f, 600f), new object[0]));
		LuckHudOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("3_LuckAndTokens", "Bottom-Right Margin Y", 34f, new ConfigDescription("Vertical margin from screen bottom-right (1920x1080 reference).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-600f, 600f), new object[0]));
		EnableRollPopupsAndVfx = ((BaseUnityPlugin)this).Config.Bind<bool>("3_LuckAndTokens", "Enable Value Popups & Fireworks", true, "Shows floating +/- value popups and celebratory fireworks / bad-outcome effects when items enter the Gamble Cart.");
		ShowExtractionSettlementBanner = ((BaseUnityPlugin)this).Config.Bind<bool>("3_LuckAndTokens", "Show Extraction Settlement Banner", true, "Displays an animated luck & coin breakdown banner when extracting via the truck.");
		BhEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("5_BetterHeals_General", "Enabled", true, "Enables integrated BetterHeals (team health packs, extraction heal, custom revive health, optional regen).");
		BhHealthPackMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("5_BetterHeals_General", "HealthPackAmountMultiplier", 1f, new ConfigDescription("Multiplier applied to health pack healing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), new object[0]));
		BhFullHealthAtStart = ((BaseUnityPlugin)this).Config.Bind<bool>("5_BetterHeals_General", "EnableFullHealthAtStart", false, "If enabled, players start each match with full health.");
		BhEnableHealthRegen = ((BaseUnityPlugin)this).Config.Bind<bool>("5_BetterHeals_General", "EnableHealthRegen", false, "If enabled, players slowly regenerate health over time inside levels.");
		BhHealthRegenAmount = ((BaseUnityPlugin)this).Config.Bind<int>("5_BetterHeals_General", "HealthRegenAmount", 10, new ConfigDescription("HP regenerated per interval when EnableHealthRegen is true.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), new object[0]));
		BhRegenIntervalSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("5_BetterHeals_General", "CustomRegenIntervalAmount", 60, new ConfigDescription("Seconds between health regeneration ticks.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 120), new object[0]));
		BhEnableExtractionHeal = ((BaseUnityPlugin)this).Config.Bind<bool>("5_BetterHeals_General", "EnableExtractionHeal", true, "Heals alive players after an extraction point is completed.");
		BhExtractionFullHeal = ((BaseUnityPlugin)this).Config.Bind<bool>("5_BetterHeals_General", "ExtractionFullHeal", false, "If true, heals alive players to full health upon extraction.");
		BhExtractionHealAmount = ((BaseUnityPlugin)this).Config.Bind<int>("5_BetterHeals_General", "ExtractionHealAmount", 20, new ConfigDescription("HP restored to alive players after extraction.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), new object[0]));
		BhEnableTeamHealthPack = ((BaseUnityPlugin)this).Config.Bind<bool>("6_BetterHeals_Team", "EnableTeamHealthPack", true, "Allows health packs to heal all living teammates.");
		BhEqualSplitTeamHealth = ((BaseUnityPlugin)this).Config.Bind<bool>("6_BetterHeals_Team", "EnableEqualSplitTeamHealth", false, "If true, health pack healing is split equally among all teammates.");
		BhEnableCustomReviveHealth = ((BaseUnityPlugin)this).Config.Bind<bool>("6_BetterHeals_Team", "EnableCustomReviveHealth", true, "Applies custom revive HP when a player is revived.");
		BhFullReviveHealth = ((BaseUnityPlugin)this).Config.Bind<bool>("6_BetterHeals_Team", "FullReviveHealth", false, "If true, revived players receive full max health.");
		BhCustomReviveHealthAmount = ((BaseUnityPlugin)this).Config.Bind<int>("6_BetterHeals_Team", "CustomReviveHealthAmount", 20, new ConfigDescription("HP set upon player revival.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), new object[0]));
		AutoGrantTestCartOnce = ((BaseUnityPlugin)this).Config.Bind<bool>("4_Debug", "Auto Grant Test Cart Once", false, "If true, adds 1 Gamble Cart to the loaded save once and resets back to false.");
		EnableTestSpawnHotkey = ((BaseUnityPlugin)this).Config.Bind<bool>("4_Debug", "Enable F8 Test Spawn Hotkey", false, "If true (host/singleplayer), press F8 in-game to spawn 1 Gamble Cart in front of you.");
		TestSaveUpgradeLevel = ((BaseUnityPlugin)this).Config.Bind<int>("4_Debug", "Test Save Upgrade Level", 0, "If > 0, sets Stamina/Strength/Range/Speed upgrades to this level in the loaded save once and resets to 0.");
		TakeOverPatpack();
		ApplyGambleItemSettings();
		_harmony = new Harmony("com.codex.gamblecart");
		_harmony.PatchAll(typeof(Patches));
		InstallPatpackMenuPatch();
		if (BhEnabled.Value)
		{
			if (Chainloader.PluginInfos.ContainsKey("MrBytesized.REPO.BetterHeals"))
			{
				Log.LogWarning((object)"Standalone BetterHeals detected; skipping integrated BetterHeals patches to avoid conflicts.");
			}
			else
			{
				_harmony.PatchAll(typeof(BetterHealsPatches));
				Log.LogInfo((object)"Integrated BetterHeals module enabled (team packs, extraction heal, custom revive, ShopPopulateItemVolumes fix).");
			}
		}
		RegisterNetworkEvents();
		LoadAllEmbeddedAudioClips();
		GambleRimAnimator.PreloadStripFromResources();
		Log.LogInfo((object)"GambleCartPack 1.1.1 initialized cleanly.");
	}

	private void OnDestroy()
	{
		if (PhotonNetwork.NetworkingClient != null)
		{
			PhotonNetwork.NetworkingClient.EventReceived -= OnPhotonEvent;
		}
	}

	private void Update()
	{
		GambleLuckHudUI.TickHud();
		GambleSettlementBannerUI.Tick();
		if (EnableTestSpawnHotkey.Value && Input.GetKeyDown((KeyCode)289) && SemiFunc.IsMasterClientOrSingleplayer())
		{
			TrySpawnGambleCartNearPlayer();
		}
	}

	private void TakeOverPatpack()
	{
		try
		{
			IList list = ((PatpackModulesField != null) ? (PatpackModulesField.GetValue(null) as IList) : null);
			if (list == null)
			{
				return;
			}
			Type type = typeof(PatpackPlugin).Assembly.GetType("Patpack.PatModule");
			FieldInfo fieldInfo = ((type != null) ? type.GetField("Id", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : null);
			FieldInfo fieldInfo2 = ((type != null) ? type.GetField("Entries", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : null);
			FieldInfo sectionOfField = ((type != null) ? type.GetField("SectionOf", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : null);
			bool flag = !PatpackPresetApplied.Value || ForceReapplyPreset.Value;
			bool flag2 = false;
			if (flag)
			{
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "LastStand", "General", "Enabled", val: true);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "CartsCrushEnemies", "General", "Enabled", val: false);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "SacrificeBomb", "General", "Enabled", val: false);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "SacrificeBomb", "Explosion", "Hurt Teammates", val: false);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "FasterStaminaRegen", "General", "Enabled", val: true);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "ValuablesInEveryRoom", "General", "Enabled", val: false);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "ExtractionNoHeightLimit", "General", "Enabled", val: false);
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "MultiplierCart", "Shop", "Price Multiplier", GamblePriceMultiplier.Value);
				PatpackPresetApplied.Value = true;
				ForceReapplyPreset.Value = false;
				SacrificeDefaultOffApplied.Value = true;
				flag2 = true;
				Log.LogInfo((object)"Applied curated Patpack defaults (LastStand/Stamina ON, SacrificeBomb/CartCrush/Valuables/NoHeight OFF, Multiplier Price 1.5x).");
			}
			else if (!SacrificeDefaultOffApplied.Value)
			{
				SetPatpackEntry(list, fieldInfo, fieldInfo2, sectionOfField, "SacrificeBomb", "General", "Enabled", val: false);
				SacrificeDefaultOffApplied.Value = true;
				flag2 = true;
				Log.LogInfo((object)"Migrated Patpack SacrificeBomb default -> OFF.");
			}
			PatpackPlugin val = (PatpackPlugin)((PatpackInstanceField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if (flag2)
			{
				if ((Object)(object)val != (Object)null && ((BaseUnityPlugin)val).Config != null)
				{
					((BaseUnityPlugin)val).Config.Save();
				}
				((BaseUnityPlugin)this).Config.Save();
			}
			for (int num = list.Count - 1; num >= 0; num--)
			{
				object obj = list[num];
				string text = ((fieldInfo != null) ? (fieldInfo.GetValue(obj) as string) : null);
				if (text == "ShrinkCart")
				{
					list.RemoveAt(num);
				}
				else if (text == "MultiplierCart" && fieldInfo2 != null && fieldInfo2.GetValue(obj) is List<ConfigEntryBase> list2)
				{
					list2.RemoveAll((ConfigEntryBase e) => e.Definition.Key == "Value Multiplier" || e.Definition.Key == "Keep Bonus After Removal");
				}
			}
			ExposePatpackInRepoConfig(val);
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("TakeOverPatpack warning: " + ex));
		}
	}

	private static void ExposePatpackInRepoConfig(PatpackPlugin patInst)
	{
		if ((Object)(object)patInst == (Object)null || ((BaseUnityPlugin)patInst).Config == null)
		{
			return;
		}
		int num = 0;
		foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in ((BaseUnityPlugin)patInst).Config)
		{
			ConfigDefinition key = item.Key;
			ConfigEntryBase value = item.Value;
			if (key == (ConfigDefinition)null || value == null)
			{
				continue;
			}
			string text = key.Section ?? string.Empty;
			string text2 = key.Key ?? string.Empty;
			if (text.StartsWith("Shrink Cart", StringComparison.OrdinalIgnoreCase) || (text.StartsWith("Multiplier Cart", StringComparison.OrdinalIgnoreCase) && (text2 == "Value Multiplier" || text2 == "Keep Bonus After Removal")) || value.Description == null || value.Description.Tags == null)
			{
				continue;
			}
			object[] tags = value.Description.Tags;
			for (int i = 0; i < tags.Length; i++)
			{
				string text3 = tags[i] as string;
				if (text3 == "HideREPOConfig" || text3 == "HideFromREPOConfig")
				{
					tags[i] = string.Empty;
					num++;
				}
			}
		}
		if (num > 0)
		{
			Log.LogInfo((object)("Exposed " + num + " Patpack config entries inside REPOConfig (Mods menu)."));
		}
	}

	private static void SetPatpackEntry<T>(IList modules, FieldInfo idField, FieldInfo entriesField, FieldInfo sectionOfField, string moduleId, string section, string key, T val)
	{
		if (idField == null || entriesField == null || sectionOfField == null)
		{
			return;
		}
		for (int i = 0; i < modules.Count; i++)
		{
			object obj = modules[i];
			string text = idField.GetValue(obj) as string;
			if (text != moduleId)
			{
				continue;
			}
			List<ConfigEntryBase> list = entriesField.GetValue(obj) as List<ConfigEntryBase>;
			Dictionary<ConfigEntryBase, string> dictionary = sectionOfField.GetValue(obj) as Dictionary<ConfigEntryBase, string>;
			if (list == null || dictionary == null)
			{
				break;
			}
			foreach (ConfigEntryBase item in list)
			{
				if (dictionary.TryGetValue(item, out var value) && value == section && item.Definition.Key == key && item is ConfigEntry<T> val2)
				{
					val2.Value = val;
					return;
				}
			}
		}
	}

	private void ApplyGambleItemSettings()
	{
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(Items), "_itemsToRegister");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(Items), "_itemsRegistered");
			List<Item> list = ((fieldInfo != null) ? (fieldInfo.GetValue(null) as List<Item>) : null);
			List<Item> list2 = ((fieldInfo2 != null) ? (fieldInfo2.GetValue(null) as List<Item>) : null);
			list?.RemoveAll((Item it) => (Object)(object)it != (Object)null && ((Object)it).name == "Item Cart Shrink");
			if (list2 != null)
			{
				foreach (Item item in list2)
				{
					if ((Object)(object)item != (Object)null && ((Object)item).name == "Item Cart Shrink")
					{
						item.disabled = true;
						item.maxAmountInShop = 0;
					}
				}
				list2.RemoveAll((Item it) => (Object)(object)it != (Object)null && ((Object)it).name == "Item Cart Shrink");
			}
			Item val = FindRegisteredItem("Item Cart Multiplier");
			GameObject val2 = Resources.Load<GameObject>("Items/Item Cart Medium");
			if (!((Object)(object)val != (Object)null))
			{
				return;
			}
			val.itemName = "Gamble C.A.R.T.";
			val.description = "50/50 gamble cart! First entry rolls 0.001x to 100x value permanently (0.1% 100x jackpot). Items shrink permanently.";
			if ((Object)(object)val2 != (Object)null)
			{
				ItemAttributes component = val2.GetComponent<ItemAttributes>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.item != (Object)null && (Object)(object)component.item.value != (Object)null && (Object)(object)val.value != (Object)null)
				{
					float num = Mathf.Max(0.1f, GamblePriceMultiplier.Value);
					val.value.valueMin = Mathf.Round(component.item.value.valueMin * num);
					val.value.valueMax = Mathf.Round(component.item.value.valueMax * num);
				}
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("ApplyGambleItemSettings warning: " + ex));
		}
	}

	internal static Item FindRegisteredItem(string internalName)
	{
		if ((Object)(object)StatsManager.instance != (Object)null && StatsManager.instance.itemDictionary != null && StatsManager.instance.itemDictionary.TryGetValue(internalName, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		FieldInfo fieldInfo = AccessTools.Field(typeof(Items), "_itemsToRegister");
		List<Item> list = ((fieldInfo != null) ? (fieldInfo.GetValue(null) as List<Item>) : null);
		if (list != null)
		{
			foreach (Item item in list)
			{
				if ((Object)(object)item != (Object)null && ((Object)item).name == internalName)
				{
					return item;
				}
			}
		}
		foreach (Item registeredItem in Items.RegisteredItems)
		{
			if ((Object)(object)registeredItem != (Object)null && ((Object)registeredItem).name == internalName)
			{
				return registeredItem;
			}
		}
		return null;
	}

	private void RegisterNetworkEvents()
	{
		if (PhotonNetwork.NetworkingClient != null)
		{
			PhotonNetwork.NetworkingClient.EventReceived += OnPhotonEvent;
		}
	}

	private void InstallPatpackMenuPatch()
	{
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		try
		{
			Type type = typeof(PatpackPlugin).Assembly.GetType("Patpack.PatpackMenu");
			MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "AddOpenButton", (Type[])null, (Type[])null) : null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(Patches), "Prefix_SkipPatpackOpenButton", (Type[])null, (Type[])null);
			if (methodInfo != null && methodInfo2 != null)
			{
				_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Hid standalone Patpack menu button (Patpack configs now live in REPOConfig Mods menu).");
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("InstallPatpackMenuPatch warning: " + ex));
		}
	}

	private void LoadAllEmbeddedAudioClips()
	{
		string[] array = new string[6] { "sfx_tier0_adrenaline.wav.gz", "sfx_tier1_bust.wav.gz", "sfx_tier2_common.wav.gz", "sfx_tier3_rare.wav.gz", "sfx_tier4_ultrarare.wav.gz", "sfx_tier5_jackpot.wav.gz" };
		string[] array2 = new string[6] { "GambleCart_Tier0_Adrenaline", "GambleCart_Tier1_Bust", "GambleCart_Tier2_Common", "GambleCart_Tier3_Rare", "GambleCart_Tier4_UltraRare", "GambleCart_Tier5_Jackpot100x" };
		int num = 0;
		for (int i = 0; i < array.Length; i++)
		{
			try
			{
				byte[] array3 = ReadEmbeddedResource(array[i]);
				if (array3 == null || array3.Length == 0)
				{
					Log.LogWarning((object)("Embedded audio missing: " + array[i]));
					continue;
				}
				byte[] wav = DecompressGzip(array3);
				AudioClip val = DecodePcm16Wav(wav, array2[i]);
				if ((Object)(object)val != (Object)null)
				{
					TierClips[i] = val;
					num++;
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Failed loading audio " + array[i] + ": " + ex.Message));
			}
		}
		Log.LogInfo((object)("Loaded " + num + "/6 embedded Gamble Cart SFX clips cleanly in memory."));
	}

	private static byte[] DecompressGzip(byte[] gzBytes)
	{
		using MemoryStream stream = new MemoryStream(gzBytes);
		using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress);
		using MemoryStream memoryStream = new MemoryStream();
		byte[] array = new byte[16384];
		int count;
		while ((count = gZipStream.Read(array, 0, array.Length)) > 0)
		{
			memoryStream.Write(array, 0, count);
		}
		return memoryStream.ToArray();
	}

	private static AudioClip DecodePcm16Wav(byte[] wav, string clipName)
	{
		if (wav == null || wav.Length < 44)
		{
			return null;
		}
		int num = BitConverter.ToInt16(wav, 22);
		int num2 = BitConverter.ToInt32(wav, 24);
		if (num <= 0 || num2 <= 0)
		{
			return null;
		}
		int i = 12;
		int num3 = -1;
		int num4 = 0;
		int num6;
		for (; i + 8 <= wav.Length; i += 8 + num6 + (num6 & 1))
		{
			int num5 = BitConverter.ToInt32(wav, i);
			num6 = BitConverter.ToInt32(wav, i + 4);
			if (num5 == 1635017060)
			{
				num3 = i + 8;
				num4 = Math.Min(num6, wav.Length - num3);
				break;
			}
		}
		if (num3 < 0 || num4 <= 0)
		{
			return null;
		}
		int num7 = num4 / 2;
		int num8 = num7 / num;
		float[] array = new float[num7];
		for (int j = 0; j < num7; j++)
		{
			short num9 = BitConverter.ToInt16(wav, num3 + j * 2);
			array[j] = (float)num9 / 32768f;
		}
		AudioClip val = AudioClip.Create(clipName, num8, num, num2, false);
		val.SetData(array, 0);
		return val;
	}

	internal static byte[] ReadEmbeddedResource(string suffix)
	{
		Assembly executingAssembly = Assembly.GetExecutingAssembly();
		string[] manifestResourceNames = executingAssembly.GetManifestResourceNames();
		for (int i = 0; i < manifestResourceNames.Length; i++)
		{
			if (!manifestResourceNames[i].EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
			{
				continue;
			}
			using Stream stream = executingAssembly.GetManifestResourceStream(manifestResourceNames[i]);
			if (stream == null)
			{
				return null;
			}
			byte[] array = new byte[stream.Length];
			int num;
			for (int j = 0; j < array.Length; j += num)
			{
				num = stream.Read(array, j, array.Length - j);
				if (num <= 0)
				{
					break;
				}
			}
			return array;
		}
		return null;
	}

	internal static void ApplyAndBroadcastGambleRoll(ValuableObject valuable, float mult, float oldCurrent, float newOrig, float newCurrent, int tier, int luckDelta, Vector3 cartPos)
	{
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Expected O, but got Unknown
		//IL_00fe: 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)
		if (!((Object)(object)valuable == (Object)null))
		{
			RolledValuables.Add(((Object)valuable).GetInstanceID());
			GambleLuckManager.HostRecordRoll(tier, luckDelta, out var newLuck, out var newRolled, out var newJackpots);
			PhotonView component = ((Component)valuable).GetComponent<PhotonView>();
			if (SemiFunc.IsMultiplayer() && (Object)(object)component != (Object)null && component.ViewID > 0)
			{
				object[] array = new object[12]
				{
					component.ViewID, newOrig, newCurrent, mult, tier, cartPos.x, cartPos.y, cartPos.z, newLuck, newRolled,
					newJackpots, oldCurrent
				};
				RaiseEventOptions val = new RaiseEventOptions();
				val.Receivers = (ReceiverGroup)1;
				RaiseEventOptions val2 = val;
				PhotonNetwork.RaiseEvent((byte)178, (object)array, val2, SendOptions.SendReliable);
			}
			else
			{
				ApplyRollResultLocal(valuable, oldCurrent, newOrig, newCurrent, mult, tier, cartPos, newLuck, newRolled, newJackpots);
			}
		}
	}

	internal static void BroadcastLevelReset()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		if (SemiFunc.IsMultiplayer())
		{
			object[] array = new object[1] { (byte)0 };
			RaiseEventOptions val = new RaiseEventOptions();
			val.Receivers = (ReceiverGroup)1;
			RaiseEventOptions val2 = val;
			PhotonNetwork.RaiseEvent((byte)179, (object)array, val2, SendOptions.SendReliable);
		}
		else
		{
			GambleLuckManager.ResetLocal();
		}
	}

	internal static void BroadcastExtractedTokens(byte[] rarities, int finalLuck, int rolledCount, int fullChunks, int curveChancePct, int curveHit, int fixedGoldCount)
	{
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		//IL_0074: 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)
		byte[] array = rarities ?? new byte[0];
		if (SemiFunc.IsMultiplayer())
		{
			object[] array2 = new object[8]
			{
				(byte)1,
				array,
				finalLuck,
				rolledCount,
				fullChunks,
				curveChancePct,
				curveHit,
				fixedGoldCount
			};
			RaiseEventOptions val = new RaiseEventOptions();
			val.Receivers = (ReceiverGroup)1;
			RaiseEventOptions val2 = val;
			PhotonNetwork.RaiseEvent((byte)179, (object)array2, val2, SendOptions.SendReliable);
		}
		else
		{
			GambleLuckManager.ApplyExtractedTokensLocal(array, finalLuck, rolledCount, fullChunks, curveChancePct, curveHit, fixedGoldCount);
		}
	}

	private static void OnPhotonEvent(EventData evt)
	{
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		if (evt == null)
		{
			return;
		}
		if (evt.Code == 178)
		{
			try
			{
				if (evt.CustomData is object[] array && array.Length >= 11)
				{
					int num = (int)array[0];
					float newOrig = (float)array[1];
					float num2 = (float)array[2];
					float num3 = (float)array[3];
					int tier = (int)array[4];
					Vector3 cartPos = default(Vector3);
					((Vector3)(ref cartPos))..ctor((float)array[5], (float)array[6], (float)array[7]);
					int newLuck = (int)array[8];
					int newRolled = (int)array[9];
					int newJackpots = (int)array[10];
					float oldCurrent = ((array.Length >= 12) ? ((float)array[11]) : Mathf.Max(1f, Mathf.Round(num2 / Mathf.Max(0.001f, num3))));
					PhotonView val = PhotonView.Find(num);
					ValuableObject v = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<ValuableObject>() : null);
					ApplyRollResultLocal(v, oldCurrent, newOrig, num2, num3, tier, cartPos, newLuck, newRolled, newJackpots);
				}
				return;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("OnPhotonEvent (178) error: " + ex.Message));
				return;
			}
		}
		if (evt.Code != 179)
		{
			return;
		}
		try
		{
			if (!(evt.CustomData is object[] array2) || array2.Length < 1)
			{
				return;
			}
			switch ((byte)array2[0])
			{
			case 0:
				GambleLuckManager.ResetLocal();
				break;
			case 1:
				if (array2.Length >= 4)
				{
					byte[] rarities = (array2[1] as byte[]) ?? new byte[0];
					int finalLuck = (int)array2[2];
					int rolledCount = (int)array2[3];
					int fullChunks = ((array2.Length >= 8) ? ((int)array2[4]) : 0);
					int curveChancePct = ((array2.Length >= 8) ? ((int)array2[5]) : 0);
					int curveHit = ((array2.Length >= 8) ? ((int)array2[6]) : 0);
					int fixedGoldCount = ((array2.Length >= 8) ? ((int)array2[7]) : 0);
					GambleLuckManager.ApplyExtractedTokensLocal(rarities, finalLuck, rolledCount, fullChunks, curveChancePct, curveHit, fixedGoldCount);
				}
				break;
			}
		}
		catch (Exception ex2)
		{
			Log.LogWarning((object)("OnPhotonEvent (179) error: " + ex2.Message));
		}
	}

	private static void ApplyRollResultLocal(ValuableObject v, float oldCurrent, float newOrig, float newCurrent, float mult, int tier, Vector3 cartPos, int newLuck, int newRolled, int newJackpots)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: 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 ((Object)(object)v != (Object)null)
		{
			RolledValuables.Add(((Object)v).GetInstanceID());
		}
		float num = PlayTierSoundLocal(tier, cartPos);
		float num2 = ((num > 0.5f) ? Mathf.Max(0.15f, num - 0.35f) : 0f);
		if ((Object)(object)Instance != (Object)null && num2 > 0.05f)
		{
			((MonoBehaviour)Instance).StartCoroutine(RevealRollAfterSound(v, oldCurrent, newOrig, newCurrent, mult, tier, cartPos, newLuck, newRolled, newJackpots, num2));
		}
		else
		{
			CommitRollOutcomeVisuals(v, oldCurrent, newOrig, newCurrent, mult, tier, cartPos, newLuck, newRolled, newJackpots);
		}
	}

	private static IEnumerator RevealRollAfterSound(ValuableObject v, float oldCurrent, float newOrig, float newCurrent, float mult, int tier, Vector3 cartPos, int newLuck, int newRolled, int newJackpots, float delay)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		yield return (object)new WaitForSeconds(delay);
		CommitRollOutcomeVisuals(v, oldCurrent, newOrig, newCurrent, mult, tier, cartPos, newLuck, newRolled, newJackpots);
	}

	private static void CommitRollOutcomeVisuals(ValuableObject v, float oldCurrent, float newOrig, float newCurrent, float mult, int tier, Vector3 cartPos, int newLuck, int newRolled, int newJackpots)
	{
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)v != (Object)null)
		{
			RolledValuables.Add(((Object)v).GetInstanceID());
			if (ValuableOrigField != null)
			{
				ValuableOrigField.SetValue(v, newOrig);
			}
			if (ValuableCurrField != null)
			{
				ValuableCurrField.SetValue(v, newCurrent);
			}
			if (ValuableSetField != null)
			{
				ValuableSetField.SetValue(v, true);
			}
		}
		GambleLuckManager.SyncHudDisplay(newLuck, newRolled, newJackpots);
		if (EnableRollPopupsAndVfx.Value)
		{
			Vector3 val = (((Object)(object)v != (Object)null) ? ((Component)v).transform.position : cartPos);
			GambleFloatingValuePopup.Spawn(val + Vector3.up * 0.25f, oldCurrent, newCurrent, mult, tier);
			GambleRollVfx.PlayOutcomeEffect(v, val, cartPos, tier);
		}
		if (tier == 5)
		{
			Log.LogInfo((object)("[GambleCart] JACKPOT 100x! $" + oldCurrent.ToString("0") + " -> $" + newCurrent.ToString("0") + " | Luck=" + newLuck));
		}
		else
		{
			Log.LogInfo((object)("[GambleCart] Rolled " + mult.ToString("0.###") + "x: $" + oldCurrent.ToString("0") + " -> $" + newCurrent.ToString("0") + " (Tier " + tier + ") | Luck=" + newLuck));
		}
	}

	internal static float PlayTierSoundLocal(int tier, Vector3 worldPos)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Expected O, but got Unknown
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		if (tier < 0 || tier >= TierClips.Length)
		{
			return 0f;
		}
		AudioClip val = TierClips[tier];
		if ((Object)(object)val == (Object)null)
		{
			return 0f;
		}
		GameObject val2 = new GameObject("GambleCart_Tier" + tier + "_SFX");
		val2.transform.position = worldPos;
		AudioSource val3 = val2.AddComponent<AudioSource>();
		val3.clip = val;
		val3.loop = false;
		if (tier == 5)
		{
			val3.spatialBlend = 0f;
			float num = Mathf.Clamp(JackpotSfxVolumeDb.Value, -30f, 6f);
			val3.volume = Mathf.Pow(10f, num / 20f);
		}
		else
		{
			val3.spatialBlend = 0.85f;
			val3.minDistance = 4f;
			val3.maxDistance = 30f;
			val3.rolloffMode = (AudioRolloffMode)1;
			float num2 = Mathf.Clamp(GambleTierSfxVolumeDb.Value, -30f, 6f);
			val3.volume = Mathf.Pow(10f, num2 / 20f);
		}
		if ((Object)(object)AudioManager.instance != (Object)null && (Object)(object)AudioManager.instance.SoundMasterGroup != (Object)null)
		{
			val3.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
		val3.Play();
		Object.Destroy((Object)(object)val2, val.length + 0.5f);
		return val.length;
	}

	internal static void TrySpawnGambleCartNearPlayer()
	{
		//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_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: 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)
		Item val = FindRegisteredItem("Item Cart Multiplier");
		if ((Object)(object)val == (Object)null)
		{
			Log.LogWarning((object)"Cannot spawn Gamble Cart: Item Cart Multiplier not found.");
			return;
		}
		Vector3 val2 = Vector3.zero;
		Quaternion val3 = Quaternion.identity;
		if ((Object)(object)PlayerAvatar.instance != (Object)null)
		{
			Transform transform = ((Component)PlayerAvatar.instance).transform;
			val2 = transform.position + transform.forward * 2f + Vector3.up * 0.6f;
			val3 = Quaternion.LookRotation(-transform.forward, Vector3.up);
		}
		else if ((Object)(object)TruckScreenText.instance != (Object)null)
		{
			Transform transform2 = ((Component)TruckScreenText.instance).transform;
			val2 = transform2.position + Vector3.down * 1f;
		}
		GameObject val4 = Items.SpawnItem(val, val2, val3);
		Log.LogInfo((object)string.Concat("Spawned test Gamble Cart at ", val2, " -> ", ((Object)(object)val4 != (Object)null) ? ((Object)val4).name : "null"));
	}

	internal static float GetMassScaleTarget(float massOriginal)
	{
		if (massOriginal >= 5f)
		{
			return 0.35f;
		}
		if (massOriginal >= 4.5f)
		{
			return 0.4f;
		}
		if (massOriginal >= 4f)
		{
			return 0.45f;
		}
		if (massOriginal >= 3.5f)
		{
			return 0.5f;
		}
		if (massOriginal >= 3f)
		{
			return 0.55f;
		}
		if (massOriginal >= 2.5f)
		{
			return 0.6f;
		}
		if (massOriginal >= 2f)
		{
			return 0.65f;
		}
		if (massOriginal >= 1.5f)
		{
			return 0.7f;
		}
		if (massOriginal >= 1f)
		{
			return 0.75f;
		}
		return 0.8f;
	}
}
internal static class Patches
{
	[HarmonyPrefix]
	[HarmonyPatch(typeof(ShrinkCartBehaviour), "Update")]
	private static bool SkipPatpackShrinkCart()
	{
		return false;
	}

	[HarmonyPatch(typeof(MultiplierCartBehaviour), "Update")]
	[HarmonyPrefix]
	private static bool SkipPatpackMultiplierCart()
	{
		return false;
	}

	internal static bool Prefix_SkipPatpackOpenButton()
	{
		return false;
	}

	[HarmonyPatch(typeof(PhysGrabCart), "Awake")]
	[HarmonyPostfix]
	private static void OnCartAwake(PhysGrabCart __instance)
	{
		if (!((Object)(object)__instance == (Object)null))
		{
			if ((Object)(object)((Component)__instance).GetComponent<UniversalShrinkCartBehaviour>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<UniversalShrinkCartBehaviour>();
			}
			if (((Object)(object)((Component)__instance).GetComponent<MultiplierCartBehaviour>() != (Object)null || ((Object)((Component)__instance).gameObject).name.IndexOf("Multiplier", StringComparison.OrdinalIgnoreCase) >= 0) && (Object)(object)((Component)__instance).GetComponent<GambleCartBehaviour>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<GambleCartBehaviour>();
				((Component)__instance).gameObject.AddComponent<GambleRimAnimator>();
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(PhysGrabCart), "StateSwitchRPC")]
	private static void OnCartStateSwitch(PhysGrabCart __instance)
	{
		if (!((Object)(object)__instance == (Object)null))
		{
			GambleRimAnimator component = ((Component)__instance).GetComponent<GambleRimAnimator>();
			if ((Object)(object)component != (Object)null)
			{
				component.EnsureCartMeshEmissionNeutral();
			}
		}
	}

	[HarmonyPatch(typeof(PhysGrabObjectImpactDetector), "ImpactLight")]
	[HarmonyPrefix]
	private static bool SuppressInCartLightImpact(PhysGrabObjectImpactDetector __instance)
	{
		return ShouldAllowCartImpact(__instance);
	}

	[HarmonyPatch(typeof(PhysGrabObjectImpactDetector), "ImpactMedium")]
	[HarmonyPrefix]
	private static bool SuppressInCartMediumImpact(PhysGrabObjectImpactDetector __instance)
	{
		return ShouldAllowCartImpact(__instance);
	}

	private static bool ShouldAllowCartImpact(PhysGrabObjectImpactDetector detector)
	{
		if ((Object)(object)detector == (Object)null || !Plugin.SilenceInCartBumpImpacts.Value)
		{
			return true;
		}
		if (!detector.inCart || detector.isCart)
		{
			return true;
		}
		PhysGrabObject val = (PhysGrabObject)((Plugin.ImpactPhysObjField != null) ? /*isinst with value type is only supported in some contexts*/: null);
		if ((Object)(object)val != (Object)null && val.playerGrabbing != null && val.playerGrabbing.Count > 0)
		{
			return true;
		}
		return false;
	}

	[HarmonyPatch(typeof(ValuableObject), "Start")]
	[HarmonyPostfix]
	private static void OnValuableStartClearReset()
	{
		if (Plugin.RolledValuables.Count > 2048)
		{
			Plugin.RolledValuables.Clear();
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(RunManager), "GameDirectorStart")]
	private static void OnGameDirectorStartResetLuck()
	{
		Plugin.RolledValuables.Clear();
		GambleLuckManager.ResetLocal();
		if (SemiFunc.IsMasterClientOrSingleplayer())
		{
			Plugin.BroadcastLevelReset();
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
	private static void OnBeforeChangeLevel(RunManager __instance, bool _completedLevel, bool _levelFailed, ChangeLevelType _changeLevelType)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (!((Object)(object)__instance == (Object)null) && (!(Plugin.RunRestartingField != null) || !(bool)Plugin.RunRestartingField.GetValue(__instance)) && SemiFunc.IsMasterClientOrSingleplayer() && _completedLevel && !_levelFailed && (int)_changeLevelType == 0 && SemiFunc.RunIsLevel())
			{
				GambleLuckManager.HostProcessExtractionRewards();
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("OnBeforeChangeLevel luck/token error: " + ex));
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(ResultScreenUI), "StateCloseDoor")]
	private static bool OnResultStateCloseDoor(ResultScreenUI __instance)
	{
		return GambleSettlementBannerUI.InterceptCloseDoor(__instance);
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(StatsManager), "LoadGame")]
	private static void OnLoadGame(StatsManager __instance, string fileName)
	{
		try
		{
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			bool value = Plugin.AutoGrantTestCartOnce.Value;
			int value2 = Plugin.TestSaveUpgradeLevel.Value;
			if (!value && value2 <= 0)
			{
				return;
			}
			if (value)
			{
				if (__instance.itemsPurchased != null)
				{
					int value3 = 0;
					__instance.itemsPurchased.TryGetValue("Item Cart Multiplier", out value3);
					if (value3 < 1)
					{
						__instance.itemsPurchased["Item Cart Multiplier"] = 1;
					}
				}
				if (__instance.itemsPurchasedTotal != null)
				{
					int value4 = 0;
					__instance.itemsPurchasedTotal.TryGetValue("Item Cart Multiplier", out value4);
					if (value4 < 1)
					{
						__instance.itemsPurchasedTotal["Item Cart Multiplier"] = 1;
					}
				}
				Plugin.PendingTestCartSpawn = true;
				Plugin.AutoGrantTestCartOnce.Value = false;
			}
			if (value2 > 0)
			{
				ApplyUpgradesToKnownPlayers(__instance, value2);
				Plugin.PendingTestUpgradeLevel = value2;
				Plugin.TestSaveUpgradeLevel.Value = 0;
			}
			if (!string.IsNullOrEmpty(fileName))
			{
				__instance.SaveGame(fileName);
			}
			((BaseUnityPlugin)Plugin.Instance).Config.Save();
			Plugin.Log.LogInfo((object)("Applied local test save overrides (cart=" + value + ", upgrades=" + value2 + ") to " + fileName));
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("OnLoadGame test grant failed: " + ex));
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(StatsManager), "PlayersAddAll")]
	private static void OnPlayersAddAll(StatsManager __instance)
	{
		try
		{
			if (SemiFunc.IsMasterClientOrSingleplayer() && Plugin.PendingTestUpgradeLevel > 0)
			{
				ApplyUpgradesToKnownPlayers(__instance, Plugin.PendingTestUpgradeLevel);
				FieldInfo fieldInfo = AccessTools.Field(typeof(StatsManager), "saveFileCurrent");
				string text = ((fieldInfo != null) ? (fieldInfo.GetValue(__instance) as string) : null);
				if (!string.IsNullOrEmpty(text))
				{
					__instance.SaveGame(text);
				}
				Plugin.PendingTestUpgradeLevel = 0;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("OnPlayersAddAll upgrade boost failed: " + ex));
		}
	}

	private static void ApplyUpgradesToKnownPlayers(StatsManager sm, int level)
	{
		if ((Object)(object)sm == (Object)null || sm.playerNames == null)
		{
			return;
		}
		foreach (string key in sm.playerNames.Keys)
		{
			if (!string.IsNullOrEmpty(key))
			{
				SetMinUpgrade(sm.playerUpgradeStamina, key, level);
				SetMinUpgrade(sm.playerUpgradeStrength, key, level);
				SetMinUpgrade(sm.playerUpgradeRange, key, level);
				SetMinUpgrade(sm.playerUpgradeSpeed, key, level);
			}
		}
	}

	private static void SetMinUpgrade(Dictionary<string, int> dict, string key, int minVal)
	{
		if (dict != null)
		{
			int value = 0;
			dict.TryGetValue(key, out value);
			if (value < minVal)
			{
				dict[key] = minVal;
			}
		}
	}

	[HarmonyPatch(typeof(ItemManager), "GetPurchasedItems")]
	[HarmonyPostfix]
	private static void OnItemsGetPurchased()
	{
		if (Plugin.PendingTestCartSpawn && SemiFunc.IsMasterClientOrSingleplayer())
		{
			Plugin.PendingTestCartSpawn = false;
			((MonoBehaviour)Plugin.Instance).StartCoroutine(EnsureTestCartSpawnedInLevel());
		}
	}

	[HarmonyPatch(typeof(ShopManager), "GetAllItemsFromStatsManager")]
	[HarmonyPostfix]
	private static void OnShopGetAllItems()
	{
		if (Plugin.PendingTestCartSpawn && SemiFunc.IsMasterClientOrSingleplayer())
		{
			Plugin.PendingTestCartSpawn = false;
			((MonoBehaviour)Plugin.Instance).StartCoroutine(EnsureTestCartSpawnedInLevel());
		}
	}

	private static IEnumerator EnsureTestCartSpawnedInLevel()
	{
		float waited = 0f;
		while (waited < 15f && ((Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated || (Object)(object)PlayerAvatar.instance == (Object)null))
		{
			waited += 0.25f;
			yield return (object)new WaitForSeconds(0.25f);
		}
		yield return (object)new WaitForSeconds(0.75f);
		GambleCartBehaviour existing = Object.FindFirstObjectByType<GambleCartBehaviour>();
		if ((Object)(object)existing == (Object)null)
		{
			Plugin.TrySpawnGambleCartNearPlayer();
		}
	}
}
public class PermanentShrinkTracker : MonoBehaviour
{
	private Vector3 _baseScale;

	private float _currentRatio = 1f;

	private float _targetRatio = 1f;

	private bool _initialized;

	internal void ApplyTargetRatio(float ratio)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		if (!_initialized)
		{
			_baseScale = ((Component)this).transform.localScale;
			_currentRatio = 1f;
			_targetRatio = 1f;
			_initialized = true;
		}
		if (ratio < _targetRatio)
		{
			_targetRatio = ratio;
		}
	}

	private void Update()
	{
		//IL_005c: 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 (_initialized && Mathf.Abs(_currentRatio - _targetRatio) > 0.001f)
		{
			float num = Mathf.Max(0.05f, Plugin.ShrinkSpeed.Value);
			_currentRatio = Mathf.MoveTowards(_currentRatio, _targetRatio, num * Time.deltaTime);
			((Component)this).transform.localScale = _baseScale * _currentRatio;
		}
	}
}
public class UniversalShrinkCartBehaviour : MonoBehaviour
{
	private PhysGrabCart _cart;

	private static readonly FieldInfo ItemsInCartField = AccessTools.Field(typeof(PhysGrabCart), "itemsInCart");

	private void Awake()
	{
		_cart = ((Component)this).GetComponent<PhysGrabCart>();
	}

	private void Update()
	{
		if (!Plugin.EnableCartShrinking.Value || (Object)(object)_cart == (Object)null || ItemsInCartField == null || !(ItemsInCartField.GetValue(_cart) is List<PhysGrabObject> list))
		{
			return;
		}
		for (int i = 0; i < list.Count; i++)
		{
			PhysGrabObject val = list[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			bool flag = Plugin.PhysIsPlayerField != null && (bool)Plugin.PhysIsPlayerField.GetValue(val);
			bool flag2 = Plugin.PhysIsEnemyField != null && (bool)Plugin.PhysIsEnemyField.GetValue(val);
			if (!flag && !flag2 && !((Object)(object)((Component)val).GetComponent<PhysGrabCart>() != (Object)null) && ((Object)(object)((Component)val).GetComponent<ValuableObject>() != (Object)null || Plugin.ScaleNonValuables.Value))
			{
				PermanentShrinkTracker permanentShrinkTracker = ((Component)val).GetComponent<PermanentShrinkTracker>();
				if ((Object)(object)permanentShrinkTracker == (Object)null)
				{
					permanentShrinkTracker = ((Component)val).gameObject.AddComponent<PermanentShrinkTracker>();
				}
				float massScaleTarget = Plugin.GetMassScaleTarget(val.massOriginal);
				permanentShrinkTracker.ApplyTargetRatio(massScaleTarget);
			}
		}
	}
}
public class GambleCartBehaviour : MonoBehaviour
{
	private PhysGrabCart _cart;

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

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

	private static readonly FieldInfo ItemsInCartField = AccessTools.Field(typeof(PhysGrabCart), "itemsInCart");

	private void Awake()
	{
		_cart = ((Component)this).GetComponent<PhysGrabCart>();
	}

	private void Update()
	{
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)_cart == (Object)null || ItemsInCartField == null || !SemiFunc.IsMasterClientOrSingleplayer() || !(ItemsInCartField.GetValue(_cart) is List<PhysGrabObject> list))
		{
			return;
		}
		Transform inCartTf = (Transform)((Plugin.CartInCartField != null) ? /*isinst with value type is only supported in some contexts*/: null);
		float num = Mathf.Max(0f, Plugin.GambleDwellSeconds.Value);
		float zoneScale = Mathf.Clamp(Plugin.GambleInnerZoneScale.Value, 0.35f, 1f);
		_seenThisFrame.Clear();
		for (int i = 0; i < list.Count; i++)
		{
			PhysGrabObject val = list[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			ValuableObject component = ((Component)val).GetComponent<ValuableObject>();
			if ((Object)(object)component == (Object)null || IsMoneyBag(component) || !(Plugin.ValuableSetField != null) || !(bool)Plugin.ValuableSetField.GetValue(component))
			{
				continue;
			}
			int instanceID = ((Object)component).GetInstanceID();
			if (!Plugin.RolledValuables.Contains(instanceID) && (!Plugin.RequireReleasedInCart.Value || (!val.grabbed && (val.playerGrabbing == null || val.playerGrabbing.Count <= 0))) && IsDeepInsideBasket(inCartTf, val, zoneScale))
			{
				_seenThisFrame.Add(instanceID);
				float value = 0f;
				_insideDwellTimers.TryGetValue(instanceID, out value);
				value += Time.deltaTime;
				_insideDwellTimers[instanceID] = value;
				if (!(value < num))
				{
					_insideDwellTimers.Remove(instanceID);
					float num2 = ((Plugin.ValuableCurrField != null) ? ((float)Plugin.ValuableCurrField.GetValue(component)) : 100f);
					float num3 = ((Plugin.ValuableOrigField != null) ? ((float)Plugin.ValuableOrigField.GetValue(component)) : 100f);
					int tier;
					int luckDelta;
					float num4 = RollMultiplier(out tier, out luckDelta);
					float newCurrent = Mathf.Max(1f, Mathf.Round(num2 * num4));
					float newOrig = Mathf.Max(1f, Mathf.Round(num3 * num4));
					Plugin.ApplyAndBroadcastGambleRoll(component, num4, num2, newOrig, newCurrent, tier, luckDelta, ((Component)this).transform.position);
				}
			}
		}
		if (_insideDwellTimers.Count <= 0)
		{
			return;
		}
		List<int> list2 = null;
		foreach (int key in _insideDwellTimers.Keys)
		{
			if (!_seenThisFrame.Contains(key))
			{
				if (list2 == null)
				{
					list2 = new List<int>();
				}
				list2.Add(key);
			}
		}
		if (list2 != null)
		{
			for (int j = 0; j < list2.Count; j++)
			{
				_insideDwellTimers.Remove(list2[j]);
			}
		}
	}

	private static bool IsDeepInsideBasket(Transform inCartTf, PhysGrabObject obj, float zoneScale)
	{
		//IL_0016: 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_0020: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)inCartTf == (Object)null || (Object)(object)obj == (Object)null)
		{
			return true;
		}
		Vector3 val = inCartTf.InverseTransformPoint(obj.centerPoint);
		float num = 0.5f * zoneScale;
		if (Mathf.Abs(val.x) <= num && Mathf.Abs(val.z) <= num && val.y >= -0.52f)
		{
			return val.y <= 0.55f;
		}
		return false;
	}

	private static bool IsMoneyBag(ValuableObject v)
	{
		if ((Object)(object)v == (Object)null)
		{
			return true;
		}
		if ((Object)(object)((Component)v).GetComponentInParent<SurplusValuable>() != (Object)null)
		{
			return true;
		}
		if (((Object)((Component)v).gameObject).name.IndexOf("Surplus", StringComparison.OrdinalIgnoreCase) >= 0)
		{
			return true;
		}
		return false;
	}

	private static float RollMultiplier(out int tier, out int luckDelta)
	{
		float value = Random.value;
		if (value < 0.02f)
		{
			tier = 0;
			luckDelta = -100;
			return 0.001f;
		}
		if (value < 0.2f)
		{
			tier = 1;
			luckDelta = -15;
			return 0.35f;
		}
		if (value < 0.5f)
		{
			tier = 1;
			luckDelta = -5;
			return 0.7f;
		}
		if (value < 0.75f)
		{
			tier = 2;
			luckDelta = 8;
			return 1.2f;
		}
		if (value < 0.94f)
		{
			tier = 2;
			luckDelta = 15;
			return 1.75f;
		}
		if (value < 0.99f)
		{
			tier = 3;
			luckDelta = 35;
			return 2.6f;
		}
		if (value < 0.999f)
		{
			tier = 4;
			luckDelta = 100;
			return 10f;
		}
		tier = 5;
		luckDelta = 150;
		return 100f;
	}
}
internal static class GambleLuckManager
{
	internal const int DefaultLuck = 100;

	internal const int MinLuck = 0;

	internal const int MaxLuck = 500;

	internal static int HostLuckWeight = 100;

	internal static int HostRolledCount;

	internal static int HostJackpot100xCount;

	internal static int LuckWeight = 100;

	internal static int RolledCount;

	internal static int Jackpot100xCount;

	internal static bool TokensAwardedThisLevel;

	internal static int LastLuckChangeDelta;

	internal static float LastLuckChangeTime = -10f;

	internal static void ResetLocal()
	{
		HostLuckWeight = 100;
		HostRolledCount = 0;
		HostJackpot100xCount = 0;
		LuckWeight = 100;
		RolledCount = 0;
		Jackpot100xCount = 0;
		TokensAwardedThisLevel = false;
		LastLuckChangeDelta = 0;
		LastLuckChangeTime = -10f;
		GambleSettlementBannerUI.Hide();
	}

	internal static void HostRecordRoll(int tier, int luckDelta, out int newLuck, out int newRolled, out int newJackpots)
	{
		HostLuckWeight = Mathf.Clamp(HostLuckWeight + luckDelta, 0, 500);
		HostRolledCount++;
		if (tier == 5)
		{
			HostJackpot100xCount++;
		}
		newLuck = HostLuckWeight;
		newRolled = HostRolledCount;
		newJackpots = HostJackpot100xCount;
	}

	internal static void SyncHudDisplay(int newLuck, int newRolled, int newJackpots)
	{
		int luckWeight = LuckWeight;
		LuckWeight = Mathf.Clamp(newLuck, 0, 500);
		RolledCount = Mathf.Max(0, newRolled);
		Jackpot100xCount = Mathf.Max(0, newJackpots);
		if (LuckWeight != luckWeight)
		{
			LastLuckChangeDelta = LuckWeight - luckWeight;
			LastLuckChangeTime = Time.unscaledTime;
		}
	}

	internal static void GetRarityProbabilities(int weight, out float pGreen, out float pBlue, out float pPurple, out float pGold)
	{
		int num = Mathf.Clamp(weight, 0, 500);
		if (num <= 50)
		{
			pGreen = 0.99f;
			pBlue = 0.01f;
			pPurple = 0f;
			pGold = 0f;
		}
		else if (num <= 80)
		{
			float num2 = ((float)num - 50f) / 30f;
			pGreen = Mathf.Lerp(0.99f, 0.9f, num2);
			pBlue = Mathf.Lerp(0.01f, 0.09f, num2);
			pPurple = Mathf.Lerp(0f, 0.01f, num2);
			pGold = 0f;
		}
		else if (num <= 100)
		{
			float num3 = ((float)num - 80f) / 20f;
			pGreen = Mathf.Lerp(0.9f, 0.68f, num3);
			pBlue = Mathf.Lerp(0.09f, 0.24f, num3);
			pPurple = Mathf.Lerp(0.01f, 0.07f, num3);
			pGold = Mathf.Lerp(0f, 0.01f, num3);
		}
		else if (num <= 200)
		{
			float num4 = ((float)num - 100f) / 100f;
			pGreen = Mathf.Lerp(0.68f, 0.2f, num4);
			pBlue = Mathf.Lerp(0.24f, 0.35f, num4);
			pPurple = Mathf.Lerp(0.07f, 0.35f, num4);
			pGold = Mathf.Lerp(0.01f, 0.1f, num4);
		}
		else
		{
			float num5 = Mathf.Clamp01(((float)num - 200f) / 100f);
			pGreen = Mathf.Lerp(0.2f, 0.05f, num5);
			pBlue = Mathf.Lerp(0.35f, 0.25f, num5);
			pPurple = Mathf.Lerp(0.35f, 0.45f, num5);
			pGold = Mathf.Lerp(0.1f, 0.25f, num5);
		}
	}

	private static byte RollRarityFromWeight(int weight)
	{
		GetRarityProbabilities(weight, out var pGreen, out var pBlue, out var pPurple, out var _);
		float value = Random.value;
		if (value < pGreen)
		{
			return 0;
		}
		if (value < pGreen + pBlue)
		{
			return 1;
		}
		if (value < pGreen + pBlue + pPurple)
		{
			return 2;
		}
		return 3;
	}

	internal static void HostProcessExtractionRewards()
	{
		if (!Plugin.EnableLuckTokenSystem.Value || TokensAwardedThisLevel)
		{
			return;
		}
		if (HostRolledCount <= 0 && HostJackpot100xCount <= 0)
		{
			Plugin.Log.LogInfo((object)"[GambleLuck] Truck extraction: 0 gambled items this level, skipping bonus tokens.");
			return;
		}
		TokensAwardedThisLevel = true;
		List<byte> list = new List<byte>();
		int num = Mathf.Max(5, Plugin.ItemsPerBonusTokenRoll.Value);
		int num2 = HostRolledCount / num;
		int num3 = HostRolledCount % num;
		float num4 = 0f;
		if (num3 > 0)
		{
			float num5 = (float)num3 / (float)Mathf.Max(1, num - 1);
			num4 = 0.5f * Mathf.Pow(num5, 1.35f);
		}
		int num6 = ((num4 > 0f && Random.value < num4) ? 1 : 0);
		int num7 = num2 + num6;
		for (int i = 0; i < num7; i++)
		{
			list.Add(RollRarityFromWeight(HostLuckWeight));
		}
		int num8 = HostJackpot100xCount * 4;
		for (int j = 0; j < num8; j++)
		{
			list.Add(3);
		}
		int num9 = Mathf.RoundToInt(num4 * 100f);
		Plugin.Log.LogInfo((object)("[GambleLuck] Extraction settlement: Luck=" + HostLuckWeight + ", Rolled=" + HostRolledCount + ", GuaranteedByCount=" + num2 + ", CurveChance=" + num9 + "% (Hit=" + num6 + "), Jackpot100x=" + HostJackpot100xCount + " -> Awarding " + list.Count + " tokens."));
		Plugin.BroadcastExtractedTokens(list.ToArray(), HostLuckWeight, HostRolledCount, num2, num9, num6, num8);
	}

	internal static void ApplyExtractedTokensLocal(byte[] rarities, int finalLuck, int rolledCount, int fullChunks, int curveChancePct, int curveHit, int fixedGoldCount)
	{
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		if (rarities == null)
		{
			rarities = new byte[0];
		}
		if (rarities.Length > 0)
		{
			if ((Object)(object)RunManager.instance != (Object)null && Plugin.RunCosmeticCooldownField != null)
			{
				Plugin.RunCosmeticCooldownField.SetValue(RunManager.instance, 0f);
			}
			if ((Object)(object)RoundDirector.instance != (Object)null && Plugin.RoundCosmeticListField != null && Plugin.RoundCosmeticListField.GetValue(RoundDirector.instance) is List<Rarity> list)
			{
				for (int i = 0; i < rarities.Length; i++)
				{
					Rarity item = (Rarity)rarities[i];
					list.Add(item);
				}
				Plugin.Log.LogInfo((object)("[GambleLuck] Injected " + rarities.Length + " cosmetic tokens (Luck=" + finalLuck + ", Rolled=" + rolledCount + "). Total ResultScreen tokens=" + list.Count));
			}
		}
		else
		{
			Plugin.Log.LogInfo((object)("[GambleLuck] Settlement finished with 0 bonus tokens (Luck=" + finalLuck + ", Rolled=" + rolledCount + ")."));
		}
		if (Plugin.ShowExtractionSettlementBanner.Value && rolledCount > 0)
		{
			GambleSettlementBannerUI.PreparePreArmSequence(rarities, finalLuck, rolledCount, fullChunks, curveChancePct, curveHit, fixedGoldCount);
		}
	}
}
internal static class GambleLuckHudUI
{
	private static GameObject _canvasObj;

	private static GameObject _rootObj;

	private static TextMeshProUGUI _tmp;

	private static RectTransform _rect;

	private static int _lastShownLuck = int.MinValue;

	private static int _lastShownRolled = int.MinValue;

	private static float _lastOffsetX = float.NaN;

	private static float _lastOffsetY = float.NaN;

	internal static void TickHud()
	{
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.EnableLuckTokenSystem.Value || !Plugin.ShowLuckHud.Value || !SemiFunc.RunIsLevel() || !((Object)(object)HUD.instance != (Object)null) || HUD.instance.hidden || !((Object)(object)HUD.instance.hideParent != (Object)null) || !HUD.instance.hideParent.activeInHierarchy)
		{
			if ((Object)(object)_canvasObj != (Object)null && _canvasObj.activeSelf)
			{
				_canvasObj.SetActive(false);
			}
			return;
		}
		if ((Object)(object)_canvasObj == (Object)null)
		{
			if (!TryCreateHudElement())
			{
				return;
			}
			_lastShownLuck = int.MinValue;
			_lastShownRolled = int.MinValue;
		}
		if (!_canvasObj.activeSelf)
		{
			_canvasObj.SetActive(true);
		}
		float value = Plugin.LuckHudOffsetX.Value;
		float value2 = Plugin.LuckHudOffsetY.Value;
		if ((!Mathf.Approximately(_lastOffsetX, value) || !Mathf.Approximately(_lastOffsetY, value2)) && (Object)(object)_rect != (Object)null)
		{
			_rect.anchoredPosition = new Vector2(value, value2);
			_lastOffsetX = value;
			_lastOffsetY = value2;
		}
		int luckWeight = GambleLuckManager.LuckWeight;
		int rolledCount = GambleLuckManager.RolledCount;
		float num = Time.unscaledTime - GambleLuckManager.LastLuckChangeTime;
		bool flag = num >= 0f && num < 0.65f && GambleLuckManager.LastLuckChangeDelta != 0;
		if (luckWeight != _lastShownLuck || rolledCount != _lastShownRolled || flag)
		{
			_lastShownLuck = luckWeight;
			_lastShownRolled = rolledCount;
			string luckColorHex = GetLuckColorHex(luckWeight);
			string text = "";
			if (flag)
			{
				int lastLuckChangeDelta = GambleLuckManager.LastLuckChangeDelta;
				string text2 = ((lastLuckChangeDelta > 0) ? "#80FF80" : "#FF6E6E");
				text = " <size=20><color=" + text2 + ">(" + ((lastLuckChangeDelta > 0) ? "+" : "") + lastLuckChangeDelta + ")</color></size>";
			}
			string text3 = "<size=22><color=#B0BEC5>本局战利品:</color><color=#FFFFFF><b>" + rolledCount + "</b></color></size>";
			string text4 = "<size=26><color=#B0BEC5>幸运值:</color><color=" + luckColorHex + "><b>" + luckWeight + "</b></color>" + text + "</size>";
			((TMP_Text)_tmp).text = text3 + "\n" + text4;
			if (flag)
			{
				float num2 = 1f + Mathf.Sin(num / 0.65f * (float)Math.PI) * 0.12f;
				((Transform)_rect).localScale = new Vector3(num2, num2, 1f);
			}
			else
			{
				((Transform)_rect).localScale = Vector3.one;
			}
		}
	}

	private static string GetLuckColorHex(int w)
	{
		if (w <= 50)
		{
			return "#90A4AE";
		}
		if (w < 100)
		{
			return "#FFF176";
		}
		if (w < 150)
		{
			return "#81C784";
		}
		if (w < 200)
		{
			return "#4FC3F7";
		}
		if (w < 260)
		{
			return "#CE93D8";
		}
		return "#FFD54F";
	}

	private static bool TryCreateHudElement()
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		//IL_00c6: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: 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_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)HaulUI.instance == (Object)null)
		{
			return false;
		}
		TextMeshProUGUI component = ((Component)HaulUI.instance).GetComponent<TextMeshProUGUI>();
		if ((Object)(object)component == (Object)null)
		{
			return false;
		}
		_canvasObj = new GameObject("GambleLuckHudCanvas");
		Object.DontDestroyOnLoad((Object)(object)_canvasObj);
		Canvas val = _canvasObj.AddComponent<Canvas>();
		val.renderMode = (RenderMode)0;
		val.sortingOrder = 60;
		CanvasScaler val2 = _canvasObj.AddComponent<CanvasScaler>();
		val2.uiScaleMode = (ScaleMode)1;
		val2.referenceResolution = new Vector2(1920f, 1080f);
		_rootObj = new GameObject("GambleLuckHUD");
		_rootObj.transform.SetParent(_canvasObj.transform, false);
		_rect = _rootObj.AddComponent<RectTransform>();
		_rect.anchorMin = new Vector2(1f, 0f);
		_rect.anchorMax = new Vector2(1f, 0f);
		_rect.pivot = new Vector2(1f, 0f);
		_rect.sizeDelta = new Vector2(460f, 84f);
		float value = Plugin.LuckHudOffsetX.Value;
		float value2 = Plugin.LuckHudOffsetY.Value;
		_rect.anchoredPosition = new Vector2(value, value2);
		((Transform)_rect).localScale = Vector3.one;
		_lastOffsetX = value;
		_lastOffsetY = value2;
		_tmp = _rootObj.AddComponent<TextMeshProUGUI>();
		((TMP_Text)_tmp).font = ((TMP_Text)component).font;
		((TMP_Text)_tmp).fontSharedMaterial = ((TMP_Text)component).fontSharedMaterial;
		((TMP_Text)_tmp).alignment = (TextAlignmentOptions)1028;
		((Graphic)_tmp).raycastTarget = false;
		((TMP_Text)_tmp).textWrappingMode = (TextWrappingModes)0;
		((TMP_Text)_tmp).overflowMode = (TextOverflowModes)0;
		((TMP_Text)_tmp).lineSpacing = 4f;
		((Graphic)_tmp).color = Color.white;
		return true;
	}
}
internal class GambleFloatingValuePopup : MonoBehaviour
{
	private RectTransform _rect;

	private TextMeshProUGUI _tmp;

	private Vector3 _worldPos;

	private float _age;

	private float _duration = 3.2f;

	private float _baseScale = 1f;

	internal static void Spawn(Vector3 worldPos, float oldCurrent, float newCurrent, float mult, int tier)
	{
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_027c: Unknown result type (might be due to invalid IL or missing references)
		//IL_027d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)WorldSpaceUIParent.instance == (Object)null)
		{
			return;
		}
		TextMeshProUGUI val = null;
		if ((Object)(object)WorldSpaceUIParent.instance.valueLostPrefab != (Object)null)
		{
			val = WorldSpaceUIParent.instance.valueLostPrefab.GetComponent<TextMeshProUGUI>();
		}
		if ((Object)(object)val == (Object)null && (Object)(object)HaulUI.instance != (Object)null)
		{
			val = ((Component)HaulUI.instance).GetComponent<TextMeshProUGUI>();
		}
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		GameObject val2 = new GameObject("GambleFloatingValuePopup");
		val2.transform.SetParent(((Component)WorldSpaceUIParent.instance).transform, false);
		RectTransform val3 = val2.AddComponent<RectTransform>();
		val3.sizeDelta = new Vector2(420f, 80f);
		TextMeshProUGUI val4 = val2.AddComponent<TextMeshProUGUI>();
		((TMP_Text)val4).font = ((TMP_Text)val).font;
		((TMP_Text)val4).fontSharedMaterial = ((TMP_Text)val).fontSharedMaterial;
		((TMP_Text)val4).alignment = (TextAlignmentOptions)514;
		((Graphic)val4).raycastTarget = false;
		((TMP_Text)val4).textWrappingMode = (TextWrappingModes)0;
		((TMP_Text)val4).overflowMode = (TextOverflowModes)0;
		int num = Mathf.RoundToInt(oldCurrent);
		int num2 = Mathf.RoundToInt(newCurrent);
		int num3 = num2 - num;
		string text = SemiFunc.DollarGetString(num);
		string text2 = SemiFunc.DollarGetString(Mathf.Abs(num3));
		float num4 = 26f;
		float num5 = 1f;
		string text3;
		switch (tier)
		{
		case 5:
			text3 = "#FFD54F";
			num4 = 36f;
			num5 = 1.45f;
			break;
		case 4:
			text3 = "#E040FB";
			num4 = 32f;
			num5 = 1.25f;
			break;
		case 3:
			text3 = "#40C4FF";
			num4 = 29f;
			num5 = 1.15f;
			break;
		default:
			if (num3 >= 0)
			{
				text3 = "#69F0AE";
				num4 = 26f;
				num5 = 1f;
			}
			else if (tier == 0)
			{
				text3 = "#FF1744";
				num4 = 30f;
				num5 = 1.2f;
			}
			else
			{
				text3 = "#FF6E40";
				num4 = 25f;
				num5 = 0.95f;
			}
			break;
		}
		string text4 = ((num3 >= 0) ? " + " : " - ");
		string text5 = ((tier >= 4 || tier == 0) ? (" <size=75%>(" + mult.ToString("0.###") + "x)</size>") : "");
		((TMP_Text)val4).fontSize = num4;
		((TMP_Text)val4).text = "<color=#FFFFFF>" + text + "</color><color=" + text3 + "><b>" + text4 + text2 + "</b>" + text5 + "</color>";
		GambleFloatingValuePopup gambleFloatingValuePopup = val2.AddComponent<GambleFloatingValuePopup>();
		gambleFloatingValuePopup._rect = val3;
		gambleFloatingValuePopup._tmp = val4;
		gambleFloatingValuePopup._worldPos = worldPos;
		gambleFloatingValuePopup._baseScale = num5;
		gambleFloatingValuePopup.UpdateScreenPosition();
	}

	private void Update()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: 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_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: 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)
		_age += Time.deltaTime;
		if (_age >= _duration)
		{
			Object.Destroy((Object)(object)((Component)this).gameObject);
			return;
		}
		_worldPos += Vector3.up * (0.2f * Time.deltaTime);
		UpdateScreenPosition();
		float num = ((_age < 0.16f) ? Mathf.Lerp(0.2f, 1.18f, _age / 0.16f) : ((_age < 0.3f) ? Mathf.Lerp(1.18f, 1f, (_age - 0.16f) / 0.14f) : ((!(_age > _duration - 0.45f)) ? 1f : Mathf.Clamp01((_duration - _age) / 0.45f))));
		((Transform)_rect).localScale = Vector3.one * (_baseScale * num);
		if (_age > _duration - 0.45f)
		{
			Color color = ((Graphic)_tmp).color;
			color.a = Mathf.Clamp01((_duration - _age) / 0.45f);
			((Graphic)_tmp).color = color;
		}
	}

	private void UpdateScreenPosition()
	{
		//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_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)_rect == (Object)null))
		{
			Vector3 val = SemiFunc.UIWorldToCanvasPosition(_worldPos);
			_rect.anchoredPosition = new Vector2(val.x, val.y);
		}
	}
}
internal static class GambleRollVfx
{
	private static Material _cachedParticleMat;

	internal static void PlayOutcomeEffect(ValuableObject v, Vector3 itemPos, Vector3 cartPos, int tier)
	{
		//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_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_021a: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: 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_019c: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Vector3 val = itemPos + Vector3.up * 0.18f;
			PhysGrabObject val2 = (((Object)(object)v != (Object)null) ? ((Component)v).GetComponent<PhysGrabObject>() : null);
			if ((Object)(object)ValuableDiscover.instance != (Object)null && (Object)(object)val2 != (Object)null)
			{
				ValuableDiscover.instance.New(val2, (State)((tier < 2) ? 2 : 0), (ValuableDiscoverCustom)null);
			}
			if (tier >= 2)
			{
				int count = tier switch
				{
					4 => 65, 
					3 => 28, 
					2 => 10, 
					_ => 130, 
				};
				int count2 = tier switch
				{
					4 => 120, 
					3 => 60, 
					2 => 26, 
					_ => 240, 
				};
				float speed = tier switch
				{
					4 => 5f, 
					3 => 3.8f, 
					2 => 2.6f, 
					_ => 6.4f, 
				};
				EmitVanillaCoins(val, count, speed);
				EmitCelebrationFirework(val, count2, speed, tier);
				if (tier >= 3 && (Object)(object)AssetManager.instance != (Object)null && (Object)(object)AssetManager.instance.prefabTeleportEffect != (Object)null)
				{
					GameObject val3 = Object.Instantiate<GameObject>(AssetManager.instance.prefabTeleportEffect, val, Quaternion.identity);
					Object.Destroy((Object)(object)val3, 3f);
				}
				if (tier == 4 && (Object)(object)GameDirector.instance != (Object)null && (Object)(object)GameDirector.instance.CameraImpact != (Object)null)
				{
					GameDirector.instance.CameraImpact.ShakeDistance(2.5f, 2f, 12f, val, 0.22f);
				}
				else if (tier == 5 && (Object)(object)GameDirector.instance != (Object)null && (Object)(object)GameDirector.instance.CameraImpact != (Object)null)
				{
					GameDirector.instance.CameraImpact.ShakeDistance(5.5f, 4f, 25f, val, 0.35f);
				}
				if (tier == 5 && (Object)(object)Plugin.Instance != (Object)null)
				{
					((MonoBehaviour)Plugin.Instance).StartCoroutine(DelayedSecondJackpotBurst(val));
				}
				return;
			}
			int count3 = ((tier == 0) ? 45 : 18);
			EmitBadSmokeBurst(val, count3, tier == 0);
			if (tier == 0 && (Object)(object)AssetManager.instance != (Object)null)
			{
				if ((Object)(object)AssetManager.instance.physImpactEffect != (Object)null)
				{
					GameObject val4 = Object.Instantiate<GameObject>(AssetManager.instance.physImpactEffect, val, Quaternion.identity);
					Object.Destroy((Object)(object)val4, 3f);
				}
				if ((Object)(object)GameDirector.instance != (Object)null && (Object)(object)GameDirector.instance.CameraImpact != (Object)null)
				{
					GameDirector.instance.CameraImpact.ShakeDistance(3.2f, 2f, 12f, val, 0.28f);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("GambleRollVfx error: " + ex.Message));
		}
	}

	private static IEnumerator DelayedSecondJackpotBurst(Vector3 pos)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		yield return (object)new WaitForSeconds(0.45f);
		EmitVanillaCoins(pos + Vector3.up * 0.2f, 90, 6f);
		EmitCelebrationFirework(pos + Vector3.up * 0.25f, 180, 6.2f, 5);
	}

	private static void EmitVanillaCoins(Vector3 pos, int count, float speed)
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: 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)
		if (!((Object)(object)AssetManager.instance == (Object)null) && !((Object)(object)AssetManager.instance.surplusValuableSmall == (Object)null))
		{
			SurplusValuable component = AssetManager.instance.surplusValuableSmall.GetComponent<SurplusValuable>();
			if (!((Object)(object)component == (Object)null) && !((Object)(object)component.coinParticles == (Object)null))
			{
				ParticleSystem val = Object.Instantiate<ParticleSystem>(component.coinParticles, pos, Quaternion.identity);
				((Object)((Component)val).gameObject).name = "GambleVFX_Coins";
				MainModule main = val.main;
				((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)2;
				((MainModule)(ref main)).startSpeedMultiplier = Mathf.Max(1.5f, speed * 0.85f);
				val.Emit(count);
				Object.Destroy((Object)(object)((Component)val).gameObject, 4f);
			}
		}
	}

	private static Material GetParticleMaterial()
	{
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Expected O, but got Unknown
		if ((Object)(object)_cachedParticleMat != (Object)null)
		{
			return _cachedParticleMat;
		}
		if ((Object)(object)AssetManager.instance != (Object)null && (Object)(object)AssetManager.instance.surplusValuableSmall != (Object)null)
		{
			SurplusValuable component = AssetManager.instance.surplusValuableSmall.GetComponent<SurplusValuable>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.coinParticles != (Object)null)
			{
				ParticleSystemRenderer component2 = ((Component)component.coinParticles).GetComponent<ParticleSystemRenderer>();
				if ((Object)(object)component2 != (Object)null && (Object)(object)((Renderer)component2).sharedMaterial != (Object)null)
				{
					_cachedParticleMat = new Material(((Renderer)component2).sharedMaterial);
					_cachedParticleMat.mainTexture = null;
					return _cachedParticleMat;
				}
			}
		}
		if ((Object)(object)AssetManager.instance != (Object)null && (Object)(object)AssetManager.instance.physImpactEffect != (Object)null)
		{
			ParticleSystemRenderer componentInChildren = AssetManager.instance.physImpactEffect.GetComponentInChildren<ParticleSystemRenderer>();
			if ((Object)(object)componentInChildren != (Object)null && (Object)(object)((Renderer)componentInChildren).sharedMaterial != (Object)null)
			{
				_cachedParticleMat = ((Renderer)componentInChildren).sharedMaterial;
				return _cachedParticleMat;
			}
		}
		return null;
	}

	private static void EmitCelebrationFirework(Vector3 pos, int count, float speed, int tier)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: 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_00f9: Expected O, but got Unknown
		//IL_0120: 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_012f: 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_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: 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_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_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_031e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0328: Unknown result type (might be due to invalid IL or missing references)
		//IL_032d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0349: Unknown result type (might be due to invalid IL or missing references)
		//IL_0353: Unknown result type (might be due to invalid IL or missing references)
		//IL_0358: Unknown result type (might be due to invalid IL or missing references)
		//IL_0379: Unknown result type (might be due to invalid IL or missing references)
		//IL_037e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0395: Unknown result type (might be due to invalid IL or missing references)
		//IL_039a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0225: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_0250: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_027b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0292: Unknown result type (might be due to invalid IL or missing references)
		//IL_0297: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_040b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0410: Unknown result type (might be due to invalid IL or missing references)
		//IL_041a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0421: Expected O, but got Unknown
		//IL_0433: Unknown result type (might be due to invalid IL or missing references)
		//IL_043d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0442: Unknown result type (might be due to invalid IL or missing references)
		//IL_044f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0459: Unknown result type (might be due to invalid IL or missing references)
		//IL_045e: Unknown result type (might be due to invalid IL or missing references)
		//IL_047f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0484: Unknown result type (might be due to invalid IL or missing references)
		//IL_049b: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("GambleVFX_Firework_" + tier);
		val.transform.position = pos;
		val.transform.rotation = Quaternion.Euler(-90f, 0f, 0f);
		ParticleSystem val2 = val.AddComponent<ParticleSystem>();
		val2.Stop(true, (ParticleSystemStopBehavior)0);
		MainModule main = val2.main;
		((MainModule)(ref main)).loop = false;
		((MainModule)(ref main)).playOnAwake = false;
		((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
		((MainModule)(ref main)).duration = 2f;
		((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.75f, 1.55f + (float)(tier - 2) * 0.25f);
		((MainModule)(ref main)).startSpeed = new MinMaxCurve(speed * 0.55f, speed * 1.25f);
		((MainModule)(ref main)).startSize = new MinMaxCurve(0.05f, 0.11f + (float)(tier - 2) * 0.025f);
		((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(0.65f);
		((MainModule)(ref main)).maxParticles = count + 10;
		Gradient val3 = new Gradient();
		switch (tier)
		{
		case 2:
			val3.SetKeys((GradientColorKey[])(object)new GradientColorKey[3]
			{
				new GradientColorKey(new Color(0.45f, 1f, 0.55f), 0f),
				new GradientColorKey(new Color(1f, 0.9f, 0.35f), 0.5f),
				new GradientColorKey(Color.white, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(1f, 0f),
				new GradientAlphaKey(1f, 1f)
			});
			break;
		case 3:
			val3.SetKeys((GradientColorKey[])(object)new GradientColorKey[3]
			{
				new GradientColorKey(new Color(0.25f, 0.85f, 1f), 0f),
				new GradientColorKey(new Color(0.75f, 0.45f, 1f), 0.5f),
				new GradientColorKey(new Color(1f, 0.88f, 0.3f), 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(1f, 0f),
				new GradientAlphaKey(1f, 1f)
			});
			break;
		default:
			val3.SetKeys((GradientColorKey[])(object)new GradientColorKey[4]
			{
				new GradientColorKey(new Color(1f, 0.84f, 0.2f), 0f),
				new GradientColorKey(new Color(1f, 0.35f, 0.85f), 0.33f),
				new GradientColorKey(new Color(0.25f, 0.92f, 1f), 0.66f),
				new GradientColorKey(new Color(0.55f, 1f, 0.5f), 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(1f, 0f),
				new GradientAlphaKey(1f, 1f)
			});
			break;
		}
		MinMaxGradient startColor = default(MinMaxGradient);
		((MinMaxGradient)(ref startColor))..ctor(val3);
		((MinMaxGradient)(ref startColor)).mode = (ParticleSystemGradientMode)4;
		((MainModule)(ref main)).startColor = startColor;
		EmissionModule emission = val2.emission;
		((EmissionModule)(ref emission)).enabled = false;
		ShapeModule shape = val2.shape;
		((ShapeModule)(ref shape)).enabled = true;
		((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)4;
		((ShapeModule)(ref shape)).angle = ((tier >= 4) ? 46f : 32f);
		((ShapeModule)(ref shape)).radius = 0.08f;
		ColorOverLifetimeModule colorOverLifetime = val2.colorOverLifetime;
		((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
		Gradient val4 = new Gradient();
		val4.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
		{
			new GradientColorKey(Color.white, 0f),
			new GradientColorKey(Color.white, 1f)
		}, (GradientAlphaKey[])(object)new GradientAlphaKey[3]
		{
			new GradientAlphaKey(1f, 0f),
			new GradientAlphaKey(1f, 0.6f),
			new GradientAlphaKey(0f, 1f)
		});
		((ColorOverLifetimeModule)(ref colorOverLifetime)).color = MinMaxGradient.op_Implicit(val4);
		Material particleMaterial = GetParticleMaterial();
		ParticleSystemRenderer component = ((Component)val2).GetComponent<ParticleSystemRenderer>();
		if ((Object)(object)component != (Object)null && (Object)(object)particleMaterial != (Object)null)
		{
			((Renderer)component).sharedMaterial = particleMaterial;
		}
		val2.Emit(count);
		Object.Destroy((Object)(object)val, 3.5f);
	}

	private static void EmitBadSmokeBurst(Vector3 pos, int count, bool severe)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Expected O, but got Unknown
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_021a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_024a: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0266: Unknown result type (might be due to invalid IL or missing references)
		//IL_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: 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_01a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_0289: Unknown result type (might be due to invalid IL or missing references)
		//IL_0291: Unknown result type (might be due to invalid IL or missing references)
		//IL_0296: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02db: Expected O, but got Unknown
		//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0309: Unknown result type (might be due to invalid IL or missing references)
		//IL_0313: Unknown result type (might be due to invalid IL or missing references)
		//IL_0318: Unknown result type (might be due to invalid IL or missing references)
		//IL_0339: Unknown result type (might be due to invalid IL or missing references)
		//IL_033e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0355: Unknown result type (might be due to invalid IL or missing references)
		//IL_035a: Unknown result type (might be due to invalid IL or missing references)
		//IL_036a: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("GambleVFX_Bad");
		val.transform.position = pos;
		val.transform.rotation = Quaternion.Euler(-90f, 0f, 0f);
		ParticleSystem val2 = val.AddComponent<ParticleSystem>();
		val2.Stop(true, (ParticleSystemStopBehavior)0);
		MainModule main = val2.main;
		((MainModule)(ref main)).loop = false;
		((MainModule)(ref main)).playOnAwake = false;
		((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
		((MainModule)(ref main)).duration = 1.6f;
		((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.