Decompiled source of ItemBuffTrinkets v1.0.1

plugins/ItemBuffTrinkets.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ItemBuffTrinkets;

[BepInPlugin("local.whiteknuckle.itembufftrinkets", "Item Buff Trinkets", "1.1.2")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "local.whiteknuckle.itembufftrinkets";

	internal static ManualLogSource Log;

	internal static ConfigEntry<float> BuffStrength;

	internal static ConfigEntry<float> ScoreMultiplierBonus;

	internal static ConfigEntry<int> BackgroundTolerance;

	internal static ConfigEntry<bool> RemoveFovBuffs;

	internal static ConfigEntry<string> ScreenEffectBuffs;

	internal static ConfigEntry<bool> DebugItems;

	internal static ConfigEntry<bool> ShowNumbers;

	internal static ConfigEntry<string> PillEffectBuffs;

	internal static HashSet<string> ScreenEffectSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	internal static ConfigEntry<int> GrayTolerance;

	internal static string CacheDir;

	private void Awake()
	{
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		BuffStrength = ((BaseUnityPlugin)this).Config.Bind<float>("General", "BuffStrength", 1f, "Multiplier applied to every buff amount copied from the item. 1.0 = the item's full buff, but permanent. Lower values make the trinkets weaker.");
		ScoreMultiplierBonus = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ScoreMultiplierBonus", 0f, "Score multiplier bonus attached to each generated trinket (0 = no change to score).");
		RemoveFovBuffs = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RemoveFovBuffs", true, "Leave out the camera field-of-view part of the item buffs (addFOV / addZoomFOV), which otherwise grows with every stacked trinket.");
		ScreenEffectBuffs = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ScreenEffectBuffs", "roided,bloodied,gooped_screen,gooped", "Comma separated buff ids that are left out of the trinkets because they only cause screen effects (red vignette, grub goop on the screen). Other ids you can add: pilled, boosted, unbound, poisoned, freezing, warming. Clear the value to keep every screen effect. The log shows the ids of each trinket's buff.");
		ShowNumbers = ((BaseUnityPlugin)this).Config.Bind<bool>("Descriptions", "ShowNumbers", false, "Add the buff amounts to the description (e.g. \"walking speed by 0.25\"). Off = wiki-style text only.");
		DebugItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogItemsAndVending", false, "Write every item prefab and vending machine entry to the log (helps to find an item's real name). Turn off when done.");
		PillEffectBuffs = ((BaseUnityPlugin)this).Config.Bind<string>("General", "PillEffectBuffs", "pilled,sway,swaySpeed,intoxication", "More buff ids left out for their visual effect: the pill vignette and the camera sway / drunk look. Clear the value to keep the pill visuals.");
		string[] array = (ScreenEffectBuffs.Value + "," + PillEffectBuffs.Value).Split(',');
		foreach (string text in array)
		{
			if (text.Trim().Length > 0)
			{
				ScreenEffectSet.Add(text.Trim());
			}
		}
		BackgroundTolerance = ((BaseUnityPlugin)this).Config.Bind<int>("Images", "BackgroundTolerance", 40, "How different (0-255 per colour channel) a pixel may be from the image's background colour and still be removed. Raise it if a background is left over, lower it if the item gets eaten. After changing it, delete the 'icons' cache folder next to the config file.");
		GrayTolerance = ((BaseUnityPlugin)this).Config.Bind<int>("Images", "GrayTolerance", 24, "How colourful a pixel may be (max channel minus min channel) and still count as a grey background pixel. 0 = only pure greys. Grey shades that appear on the image border are removed everywhere in the picture. Delete the 'icons' cache folder after changing it.");
		CacheDir = Path.Combine(Path.Combine(Paths.ConfigPath, "ItemBuffTrinkets"), "icons");
		try
		{
			Directory.CreateDirectory(CacheDir);
		}
		catch
		{
		}
		TrinketFactory.LoadCache();
		new Harmony("local.whiteknuckle.itembufftrinkets").PatchAll(typeof(Plugin).Assembly);
		Log.LogInfo((object)"Item Buff Trinkets loaded.");
	}
}
internal static class TrinketFactory
{
	private class Candidate
	{
		public string Key;

		public string Title;

		public string Id;

		public string[] Keys;

		public BuffContainer Buff;

		public List<BuffContainer> Secondary;

		public bool Created;

		public bool Warned;
	}

	public const string Prefix = "wkibt_";

	public const string Suffix = "__end";

	private static readonly List<Candidate> Candidates = new List<Candidate>();

	private static readonly List<Trinket> Trinkets = new List<Trinket>();

	private static readonly Dictionary<string, Sprite> VendingSprites = new Dictionary<string, Sprite>();

	private static WKAssetDatabase baseDb;

	private static bool built;

	private static int scanCount;

	private static float lastScan = -10f;

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

	private static readonly Dictionary<string, string> Names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
	{
		{ "addSpeed", "Move speed" },
		{ "addGroundedSpeed", "Ground speed" },
		{ "addHangSpeed", "Hanging speed" },
		{ "addClimb", "Climb speed" },
		{ "addSlow", "Slowdown" },
		{ "addJump", "Jump height" },
		{ "addGroundedJump", "Ground jump height" },
		{ "addClimbingJump", "Jump from climbing" },
		{ "addJumpBoost", "Jump boost" },
		{ "addExtraJumps", "Extra jumps" },
		{ "addAirControl", "Air control" },
		{ "addGravity", "Gravity" },
		{ "addDrag", "Air drag" },
		{ "addRestingFriction", "Resting friction" },
		{ "addStamina", "Grip stamina" },
		{ "addStaminaRegen", "Stamina regen" },
		{ "addGroundedStaminaRegen", "Stamina regen on ground" },
		{ "addGripStrength", "Grip strength" },
		{ "addStillGripStrength", "Grip strength when still" },
		{ "regenerateGripStrength", "Grip regen" },
		{ "gripResist", "Grip resistance" },
		{ "addHealthRegen", "Health regen" },
		{ "damageResist", "Damage resistance" },
		{ "damageMult", "Damage taken" },
		{ "knockbackResist", "Knockback resistance" },
		{ "reduceFallDamageDistance", "Safe fall distance" },
		{ "addFreezeResist", "Cold resistance" },
		{ "addReach", "Reach" },
		{ "addCapacity", "Carry capacity" },
		{ "addPocketCapacity", "Pocket capacity" },
		{ "addPocketBigItemCapacity", "Big item pocket capacity" },
		{ "addHammer", "Hammer power" },
		{ "addStrike", "Strike power" },
		{ "addPitonSecure", "Piton grip" },
		{ "addRecoil", "Recoil" },
		{ "addPlayerScale", "Player size" },
		{ "addPlayerWidth", "Player width" },
		{ "addRoachDepositMult", "Roach deposit bonus" },
		{ "addSensitivity", "Mouse sensitivity" },
		{ "addLookSmooth", "Look smoothing" },
		{ "addLimp", "Limp" },
		{ "slowTime", "Slow time" },
		{ "extraLife", "Extra life" },
		{ "flight", "Flight" },
		{ "grabAnything", "Grab anything" },
		{ "divideSpeed", "Less speed" },
		{ "divideJump", "Less jump" },
		{ "divideStamina", "Less grip stamina" },
		{ "divideStaminaRegen", "Less stamina regen" },
		{ "divideCapacity", "Less carry capacity" },
		{ "divideSensitivity", "Less mouse sensitivity" }
	};

	private static readonly HashSet<string> NoStack = new HashSet<string> { "sluggrub" };

	private static readonly HashSet<string> Silent = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
	{
		"food", "boosted", "unbound", "gooped", "gooped_screen", "roided", "pilled", "intoxication", "bloodied", "freezing",
		"warming", "poisoned", "sway", "swaySpeed"
	};

	private static readonly HashSet<string> HigherIsWorse = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "addGravity", "addSlow", "damageMult", "addRecoil", "addDrag", "addLimp", "addLookSmooth" };

	private static readonly Dictionary<string, string> Wiki = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
	{
		{ "addSpeed", "walking speed" },
		{ "addGroundedSpeed", "ground speed" },
		{ "addJump", "jump height" },
		{ "addClimb", "climb speed" },
		{ "addHangSpeed", "hanging speed" },
		{ "addStamina", "stamina" },
		{ "addStaminaRegen", "stamina regeneration" },
		{ "addGroundedStaminaRegen", "stamina regeneration on the ground" },
		{ "addGripStrength", "grip strength" },
		{ "addHealthRegen", "health regeneration" },
		{ "damageResist", "damage resistance" },
		{ "damageMult", "damage taken" },
		{ "addReach", "reach" },
		{ "addCapacity", "carry capacity" },
		{ "addGravity", "gravity" },
		{ "addExtraJumps", "midair jumps" },
		{ "addAirControl", "air control" },
		{ "addPlayerScale", "player size" },
		{ "addHammer", "hammer power" },
		{ "knockbackResist", "knockback resistance" },
		{ "addFreezeResist", "cold resistance" }
	};

	public static IReadOnlyList<Trinket> Build(bool scan = false)
	{
		if (!built)
		{
			CollectCandidates();
		}
		if (scan && scanCount < 3 && !AllCreated())
		{
			scanCount++;
			HarvestLoaded();
		}
		CreateReady();
		return Trinkets;
	}

	private static bool AllCreated()
	{
		if (!built)
		{
			return false;
		}
		foreach (Candidate candidate in Candidates)
		{
			if (!candidate.Created)
			{
				return false;
			}
		}
		return true;
	}

	public static void OnVendingStart(ENV_VendingMachine vm)
	{
		if (!((Object)(object)vm == (Object)null) && !AllCreated() && harvested.Add(((Object)vm).GetInstanceID()))
		{
			Harvest(vm);
			if (!built)
			{
				CollectCandidates();
			}
			CreateReady();
		}
	}

	private static void CollectCandidates()
	{
		try
		{
			baseDb = CL_AssetManager.GetBaseAssetDatabase();
		}
		catch
		{
			return;
		}
		if ((Object)(object)baseDb == (Object)null)
		{
			return;
		}
		WKAssetDatabase fullCombinedAssetDatabase;
		try
		{
			fullCombinedAssetDatabase = CL_AssetManager.GetFullCombinedAssetDatabase();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Asset database not ready: " + ex.Message));
			return;
		}
		if ((Object)(object)fullCombinedAssetDatabase == (Object)null || fullCombinedAssetDatabase.itemPrefabs == null || fullCombinedAssetDatabase.itemPrefabs.Count == 0)
		{
			return;
		}
		HashSet<string> hashSet = new HashSet<string>();
		foreach (GameObject itemPrefab in fullCombinedAssetDatabase.itemPrefabs)
		{
			if ((Object)(object)itemPrefab == (Object)null)
			{
				continue;
			}
			try
			{
				Item_Object component = itemPrefab.GetComponent<Item_Object>();
				Item val = (((Object)(object)component != (Object)null) ? component.itemData : null);
				if (val == null)
				{
					continue;
				}
				if (Plugin.DebugItems.Value)
				{
					Plugin.Log.LogInfo((object)("[items] prefab=" + ((Object)itemPrefab).name + " itemName=" + val.itemName + " hand=" + (((Object)(object)val.handItemAsset != (Object)null) ? ((object)val.handItemAsset).GetType().Name : "none")));
				}
				bool flag = ((Object)itemPrefab).name.IndexOf("beans_periphery", StringComparison.OrdinalIgnoreCase) >= 0;
				BuffContainer val2 = null;
				List<BuffContainer> secondary = null;
				HandItem handItemAsset = val.handItemAsset;
				HandItem_Buff val3 = (HandItem_Buff)(object)((handItemAsset is HandItem_Buff) ? handItemAsset : null);
				HandItem handItemAsset2 = val.handItemAsset;
				HandItem_Food val4 = (HandItem_Food)(object)((handItemAsset2 is HandItem_Food) ? handItemAsset2 : null);
				if ((Object)(object)val3 != (Object)null)
				{
					val2 = val3.buff;
					if (val3.useSecondaryBuffs)
					{
						secondary = val3.secondaryBuffs;
					}
				}
				else if ((Object)(object)val4 != (Object)null && (val4.useBuff || flag))
				{
					val2 = val4.buff;
				}
				if (val2 == null || val2.buffs == null || val2.buffs.Count == 0)
				{
					if (flag)
					{
						Plugin.Log.LogInfo((object)("P-Beans (" + ((Object)itemPrefab).name + ") has no buff in its hand item (" + (((Object)(object)val.handItemAsset != (Object)null) ? ((object)val.handItemAsset).GetType().Name : "none") + ") - nothing to turn into a trinket."));
					}
					continue;
				}
				string text = ((!string.IsNullOrEmpty(val.itemName)) ? val.itemName : ((Object)itemPrefab).name);
				string text2 = Sanitize(text);
				if (text2.Length == 0 || !hashSet.Add(text2))
				{
					continue;
				}
				List<string> list = new List<string>();
				list.Add(text2);
				list.Add(Sanitize(((Object)itemPrefab).name));
				if (flag)
				{
					list.Add("pbeans");
					list.Add("itembeans");
					list.Add("canofbeans");
					list.Add("beans");
				}
				if (flag)
				{
					StringBuilder stringBuilder = new StringBuilder();
					foreach (Buff buff in val2.buffs)
					{
						if (buff != null)
						{
							stringBuilder.Append(buff.id).Append(' ');
						}
					}
					Plugin.Log.LogInfo((object)("P-Beans found: item '" + text + "', buff ids: " + stringBuilder.ToString().Trim()));
				}
				Candidates.Add(new Candidate
				{
					Key = text2,
					Title = (flag ? "P-Beans" : WikiTitle(text2, Prettify(text))),
					Id = "wkibt_" + text2 + "__end",
					Keys = list.ToArray(),
					Buff = val2,
					Secondary = secondary
				});
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("Skipped " + ((Object)itemPrefab).name + ": " + ex2.Message));
			}
		}
		built = true;
		Plugin.Log.LogInfo((object)("Found " + Candidates.Count + " usable buff items."));
	}

	private static void CreateReady()
	{
		int num = 0;
		foreach (Candidate candidate in Candidates)
		{
			if (candidate.Created)
			{
				continue;
			}
			Sprite value = null;
			string[] keys = candidate.Keys;
			foreach (string text in keys)
			{
				if (text.Length > 0 && VendingSprites.TryGetValue(text, out value) && (Object)(object)value != (Object)null)
				{
					break;
				}
			}
			if ((Object)(object)value == (Object)null)
			{
				if (candidate.Key.Contains("bean") && !candidate.Warned)
				{
					candidate.Warned = true;
					Plugin.Log.LogInfo((object)(candidate.Title + ": no vending picture yet. Known vending pictures: " + string.Join(", ", new List<string>(VendingSprites.Keys).ToArray())));
				}
				continue;
			}
			try
			{
				Create(candidate, value);
				candidate.Created = true;
				num++;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not create trinket " + candidate.Title + ": " + ex.Message));
				candidate.Created = true;
			}
		}
		if (num > 0)
		{
			Plugin.Log.LogInfo((object)("Created " + num + " trinkets (" + Trinkets.Count + " total)."));
		}
	}

	private static void Create(Candidate c, Sprite sprite)
	{
		//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_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: 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_0062: 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_0079: Expected O, but got Unknown
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		float value = Plugin.BuffStrength.Value;
		BuffContainer val = new BuffContainer
		{
			id = c.Id,
			desc = c.Buff.desc,
			buffs = new List<Buff>(),
			loseOverTime = false,
			loseRate = 0f,
			loseRateEffectedByPerks = false,
			unscaledTime = c.Buff.unscaledTime,
			buffTime = 1f,
			multiplier = 1f
		};
		Dictionary<string, float> totals = new Dictionary<string, float>();
		StringBuilder stringBuilder = new StringBuilder();
		foreach (Buff buff in c.Buff.buffs)
		{
			if (buff != null)
			{
				stringBuilder.Append(buff.id).Append(' ');
			}
		}
		Plugin.Log.LogInfo((object)(c.Title + " buff ids: " + stringBuilder.ToString().Trim()));
		AppendBuffs(val, c.Buff, value, totals);
		if (c.Secondary != null)
		{
			foreach (BuffContainer item in c.Secondary)
			{
				if (item != null && item.buffs != null)
				{
					AppendBuffs(val, item, value, totals);
				}
			}
		}
		Perk val2 = ScriptableObject.CreateInstance<Perk>();
		((Object)val2).hideFlags = (HideFlags)61;
		((Object)val2).name = c.Id;
		val2.id = c.Id;
		val2.title = c.Title;
		WikiText(totals, out var perkText, out var sentence);
		val2.description = perkText + "\nPermanent.";
		val2.flavorText = "";
		val2.perkType = (PerkType)8;
		val2.icon = Normalize(sprite, FindPerkReference());
		val2.useBuff = true;
		val2.buff = val;
		val2.useBaseBuff = false;
		val2.buffMultiplier = 1f;
		val2.stackMax = ((!(val2.canStack = !NoStack.Contains(c.Key))) ? 1 : 99);
		val2.spawnPool = (PerkPool)2;
		val2.removeOnCleanse = false;
		val2.cost = 0;
		val2.multiplierCurve = AnimationCurve.Constant(0f, 1f, 1f);
		val2.tags = new List<string>();
		val2.flags = new List<string>();
		val2.playerTag = new List<string>();
		val2.modules = new List<PerkModule>();
		val2.perkBlacklist = new List<string>();
		val2.perkWhitelist = new List<string>();
		Trinket val3 = ScriptableObject.CreateInstance<Trinket>();
		((Object)val3).hideFlags = (HideFlags)61;
		((Object)val3).name = c.Id;
		val3.title = c.Title;
		val3.description = "Permanently " + sentence + ", as if you had just used " + Article(c.Title) + ".";
		val3.flavorText = "";
		val3.isBinding = false;
		val3.lockIcon = (val3.icon = Normalize(sprite, FindTrinketReference()));
		val3.cost = 0;
		val3.itemsToGrant = new List<Item_Object>();
		val3.perksToGrant = new List<Perk> { val2 };
		val3.pouchesToGrant = 0;
		val3.progressionUnlock = null;
		val3.scoreMultiplierBonus = Plugin.ScoreMultiplierBonus.Value;
		val3.scoreBonus = 0f;
		val3.comingSoon = false;
		val3.settingBlacklist = new List<string>();
		val3.activateOrder = 0;
		Trinkets.Add(val3);
		if ((Object)(object)baseDb != (Object)null)
		{
			if (baseDb.perkAssets != null)
			{
				baseDb.perkAssets.Add(val2);
			}
			if (baseDb.trinketAssets != null)
			{
				baseDb.trinketAssets.Add(val3);
			}
		}
	}

	private static Sprite Normalize(Sprite s, Sprite reference)
	{
		//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_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)s == (Object)null || (Object)(object)reference == (Object)null)
		{
			return s;
		}
		Rect rect = reference.rect;
		float width = ((Rect)(ref rect)).width;
		rect = reference.rect;
		float num = Mathf.Max(width, ((Rect)(ref rect)).height) / Mathf.Max(0.0001f, reference.pixelsPerUnit);
		rect = s.rect;
		float width2 = ((Rect)(ref rect)).width;
		rect = s.rect;
		float num2 = Mathf.Max(width2, ((Rect)(ref rect)).height);
		if (num <= 0f || num2 <= 0f)
		{
			return s;
		}
		Sprite obj = Sprite.Create(s.texture, s.rect, new Vector2(0.5f, 0.5f), num2 / num);
		((Object)obj).name = ((Object)s).name;
		return obj;
	}

	private static Sprite FindPerkReference()
	{
		if ((Object)(object)baseDb == (Object)null || baseDb.perkAssets == null)
		{
			return null;
		}
		foreach (Perk perkAsset in baseDb.perkAssets)
		{
			if ((Object)(object)perkAsset != (Object)null && (Object)(object)perkAsset.icon != (Object)null && !((Object)perkAsset).name.StartsWith("wkibt_"))
			{
				return perkAsset.icon;
			}
		}
		return null;
	}

	private static Sprite FindTrinketReference()
	{
		if ((Object)(object)baseDb == (Object)null || baseDb.trinketAssets == null)
		{
			return null;
		}
		foreach (Trinket trinketAsset in baseDb.trinketAssets)
		{
			if ((Object)(object)trinketAsset != (Object)null && (Object)(object)trinketAsset.icon != (Object)null && !((Object)trinketAsset).name.StartsWith("wkibt_"))
			{
				return trinketAsset.icon;
			}
		}
		return null;
	}

	private static void AppendBuffs(BuffContainer dest, BuffContainer src, float k, Dictionary<string, float> totals)
	{
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Expected O, but got Unknown
		foreach (Buff buff in src.buffs)
		{
			if (buff != null && (!Plugin.RemoveFovBuffs.Value || buff.id == null || buff.id.IndexOf("fov", StringComparison.OrdinalIgnoreCase) < 0))
			{
				if (buff.id != null && Plugin.ScreenEffectSet.Contains(buff.id))
				{
					Plugin.Log.LogInfo((object)("  left out screen-effect buff '" + buff.id + "'"));
					continue;
				}
				float num = buff.maxAmount * k;
				dest.buffs.Add(new Buff
				{
					id = buff.id,
					maxAmount = num,
					amount = num
				});
				totals.TryGetValue(buff.id ?? "", out var value);
				totals[buff.id ?? ""] = value + num;
			}
		}
	}

	private static string WikiTitle(string key, string fallback)
	{
		return key switch
		{
			"canofbeans" => "Beans", 
			"beanbar" => "Food Bar", 
			"pillbottle" => "Pills", 
			"sluggrub" => "Grub", 
			_ => fallback, 
		};
	}

	private static string Article(string title)
	{
		if (title.EndsWith("s", StringComparison.Ordinal))
		{
			return title;
		}
		if ("AEIOU".IndexOf(char.ToUpperInvariant(title[0])) < 0)
		{
			return "a " + title;
		}
		return "an " + title;
	}

	private static string StatName(string id)
	{
		if (Wiki.TryGetValue(id, out var value))
		{
			return value;
		}
		string text = ((id.StartsWith("add") || id.StartsWith("divide")) ? id.Substring(id.StartsWith("add") ? 3 : 6) : id);
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < text.Length; i++)
		{
			if (i > 0 && char.IsUpper(text[i]))
			{
				stringBuilder.Append(' ');
			}
			stringBuilder.Append(char.ToLowerInvariant(text[i]));
		}
		string text2 = stringBuilder.ToString().Trim();
		if (text2 == "jump strain")
		{
			return "jump stamina cost";
		}
		if (text2.Length != 0)
		{
			return text2;
		}
		return id;
	}

	private static void WikiText(Dictionary<string, float> totals, out string perkText, out string sentence)
	{
		Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>
		{
			{
				"Increases",
				new List<string>()
			},
			{
				"Reduces",
				new List<string>()
			}
		};
		Dictionary<string, List<string>> dictionary2 = new Dictionary<string, List<string>>
		{
			{
				"Increases",
				new List<string>()
			},
			{
				"Reduces",
				new List<string>()
			}
		};
		List<string> list = new List<string>();
		bool value = Plugin.ShowNumbers.Value;
		foreach (KeyValuePair<string, float> total in totals)
		{
			string text = total.Key ?? "";
			if (text.Length != 0 && !Silent.Contains(text))
			{
				if (text.Equals("grabAnything", StringComparison.OrdinalIgnoreCase))
				{
					list.Add("lets you grab onto any surface");
					continue;
				}
				string text2 = StatName(text);
				float value2 = total.Value;
				bool num = text.StartsWith("divide", StringComparison.OrdinalIgnoreCase);
				string key = (num ? "Reduces" : ((value2 >= 0f) ? "Increases" : "Reduces"));
				bool flag = ((!num) ? (HigherIsWorse.Contains(text) ? (value2 < 0f) : (value2 >= 0f)) : (text2.Contains("cost") || text2.Contains("strain") || text2.Contains("drain")));
				string item = (value ? (text2 + " by " + Math.Abs(value2).ToString("0.##", CultureInfo.InvariantCulture)) : text2);
				(flag ? dictionary : dictionary2)[key].Add(item);
			}
		}
		List<string> list2 = new List<string>();
		List<string> list3 = new List<string>();
		string[] array = new string[2] { "Increases", "Reduces" };
		foreach (string text3 in array)
		{
			if (dictionary[text3].Count > 0)
			{
				list2.Add("+ " + text3 + " " + Join(dictionary[text3]) + ".");
				list3.Add(text3.ToLowerInvariant() + " " + Join(dictionary[text3]));
			}
		}
		foreach (string item2 in list)
		{
			list2.Add("+ " + char.ToUpperInvariant(item2[0]) + item2.Substring(1) + ".");
			list3.Add(item2);
		}
		array = new string[2] { "Increases", "Reduces" };
		foreach (string text4 in array)
		{
			if (dictionary2[text4].Count > 0)
			{
				list2.Add("- " + text4 + " " + Join(dictionary2[text4]) + ".");
				list3.Add(text4.ToLowerInvariant() + " " + Join(dictionary2[text4]));
			}
		}
		perkText = ((list2.Count > 0) ? string.Join("\n", list2.ToArray()) : "+ Grants the hidden effects of the item.");
		sentence = ((list3.Count > 0) ? Join(list3) : "grants the hidden effects of the item");
	}

	private static string Join(List<string> items)
	{
		if (items.Count == 1)
		{
			return items[0];
		}
		return string.Join(", ", items.GetRange(0, items.Count - 1).ToArray()) + " and " + items[items.Count - 1];
	}

	private static string Friendly(string id)
	{
		if (id != null && Names.TryGetValue(id, out var value))
		{
			return value;
		}
		if (string.IsNullOrEmpty(id))
		{
			return "Unknown";
		}
		string text = id;
		if (text.StartsWith("add"))
		{
			text = text.Substring(3);
		}
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < text.Length; i++)
		{
			char c = text[i];
			if (i > 0 && char.IsUpper(c))
			{
				stringBuilder.Append(' ');
			}
			stringBuilder.Append((i == 0) ? char.ToUpperInvariant(c) : char.ToLowerInvariant(c));
		}
		return stringBuilder.ToString();
	}

	private static string FormatEffects(Dictionary<string, float> totals)
	{
		if (totals.Count == 0)
		{
			return "no stat changes";
		}
		StringBuilder stringBuilder = new StringBuilder();
		foreach (KeyValuePair<string, float> total in totals)
		{
			if (stringBuilder.Length > 0)
			{
				stringBuilder.Append(", ");
			}
			stringBuilder.Append(Friendly(total.Key)).Append(' ').Append((total.Value >= 0f) ? "+" : "")
				.Append(total.Value.ToString("0.##", CultureInfo.InvariantCulture));
		}
		return stringBuilder.ToString();
	}

	public static void Harvest(ENV_VendingMachine vm)
	{
		if ((Object)(object)vm == (Object)null || vm.purchaseList == null)
		{
			return;
		}
		foreach (Purchase purchase in vm.purchaseList)
		{
			if (purchase == null || (Object)(object)purchase.purchaseSprite == (Object)null)
			{
				continue;
			}
			Item_Object itemObject = purchase.itemObject;
			if (Plugin.DebugItems.Value)
			{
				Plugin.Log.LogInfo((object)("[vending] purchase=" + purchase.name + " item=" + (((Object)(object)itemObject != (Object)null && itemObject.itemData != null) ? itemObject.itemData.itemName : "?") + " prefab=" + (((Object)(object)itemObject != (Object)null) ? ((Object)itemObject).name : "?")));
			}
			string[] array = new string[3]
			{
				((Object)(object)itemObject != (Object)null && itemObject.itemData != null) ? Sanitize(itemObject.itemData.itemName ?? "") : "",
				((Object)(object)itemObject != (Object)null) ? Sanitize(((Object)itemObject).name ?? "") : "",
				Sanitize(purchase.name ?? "")
			};
			bool flag = false;
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text.Length > 0 && !VendingSprites.ContainsKey(text))
				{
					flag = true;
				}
			}
			if (!flag)
			{
				continue;
			}
			Sprite val = null;
			try
			{
				val = RemoveBackground(purchase.purchaseSprite, array);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Background removal failed: " + ex.Message));
			}
			if ((Object)(object)val == (Object)null)
			{
				val = purchase.purchaseSprite;
			}
			array2 = array;
			foreach (string text2 in array2)
			{
				if (text2.Length > 0 && !VendingSprites.ContainsKey(text2))
				{
					VendingSprites[text2] = val;
				}
			}
		}
	}

	public static void HarvestLoaded()
	{
		try
		{
			ENV_VendingMachine[] array = Resources.FindObjectsOfTypeAll<ENV_VendingMachine>();
			foreach (ENV_VendingMachine val in array)
			{
				if ((Object)(object)val != (Object)null && harvested.Add(((Object)val).GetInstanceID()))
				{
					Harvest(val);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Vending scan failed: " + ex.Message));
		}
	}

	private static Sprite RemoveBackground(Sprite src, string[] keys)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Expected O, but got Unknown
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: 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_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_020c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0227: Unknown result type (might be due to invalid IL or missing references)
		//IL_024d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_0479: Unknown result type (might be due to invalid IL or missing references)
		//IL_047e: 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_042e: Unknown result type (might be due to invalid IL or missing references)
		//IL_059f: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_079c: Unknown result type (might be due to invalid IL or missing references)
		//IL_07a3: Expected O, but got Unknown
		//IL_07d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_07e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_076d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0772: Unknown result type (might be due to invalid IL or missing references)
		//IL_06e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_06ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_064a: Unknown result type (might be due to invalid IL or missing references)
		//IL_064f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0651: Unknown result type (might be due to invalid IL or missing references)
		//IL_0674: Unknown result type (might be due to invalid IL or missing references)
		//IL_065a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0661: Unknown result type (might be due to invalid IL or missing references)
		//IL_0669: Unknown result type (might be due to invalid IL or missing references)
		//IL_067f: Unknown result type (might be due to invalid IL or missing references)
		//IL_068b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0697: Unknown result type (might be due to invalid IL or missing references)
		Texture2D texture = src.texture;
		Rect textureRect = src.textureRect;
		int num = (int)((Rect)(ref textureRect)).width;
		int num2 = (int)((Rect)(ref textureRect)).height;
		if (num < 2 || num2 < 2)
		{
			return null;
		}
		RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0);
		Graphics.Blit((Texture)(object)texture, temporary);
		RenderTexture active = RenderTexture.active;
		RenderTexture.active = temporary;
		Texture2D val = new Texture2D(num, num2, (TextureFormat)4, false);
		val.ReadPixels(new Rect(((Rect)(ref textureRect)).x, ((Rect)(ref textureRect)).y, (float)num, (float)num2), 0, 0);
		val.Apply();
		RenderTexture.active = active;
		RenderTexture.ReleaseTemporary(temporary);
		((Texture)val).filterMode = ((Texture)texture).filterMode;
		Color32[] px = val.GetPixels32();
		Color32[] obj = new Color32[4]
		{
			px[0],
			px[num - 1],
			px[(num2 - 1) * num],
			px[num2 * num - 1]
		};
		int num3 = 0;
		int num4 = 0;
		int num5 = 0;
		int num6 = 0;
		Color32[] array = (Color32[])(object)obj;
		foreach (Color32 val2 in array)
		{
			if (val2.a > 200)
			{
				num4 += val2.r;
				num5 += val2.g;
				num6 += val2.b;
				num3++;
			}
		}
		bool hasBg = num3 > 0;
		int br = (hasBg ? (num4 / num3) : 0);
		int bg = (hasBg ? (num5 / num3) : 0);
		int bb = (hasBg ? (num6 / num3) : 0);
		int tol = Plugin.BackgroundTolerance.Value;
		int graySat = Plugin.GrayTolerance.Value;
		Dictionary<int, int> counts = new Dictionary<int, int>();
		Action<Color32> action = delegate(Color32 c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (c.a >= 200 && Sat(c) <= graySat)
			{
				int key = (c.r << 16) | (c.g << 8) | c.b;
				counts.TryGetValue(key, out var value);
				counts[key] = value + 1;
			}
		};
		for (int num7 = 0; num7 < num; num7++)
		{
			action(px[num7]);
			action(px[(num2 - 1) * num + num7]);
		}
		for (int num8 = 0; num8 < num2; num8++)
		{
			action(px[num8 * num]);
			action(px[num8 * num + num - 1]);
		}
		List<KeyValuePair<int, int>> palette = new List<KeyValuePair<int, int>>(counts);
		palette.Sort((KeyValuePair<int, int> a, KeyValuePair<int, int> b) => b.Value.CompareTo(a.Value));
		if (palette.Count > 8)
		{
			palette.RemoveRange(8, palette.Count - 8);
		}
		Func<Color32, bool> inPalette = delegate(Color32 c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			if (c.a < 200)
			{
				return false;
			}
			foreach (KeyValuePair<int, int> item in palette)
			{
				int num44 = (item.Key >> 16) & 0xFF;
				int num45 = (item.Key >> 8) & 0xFF;
				int num46 = item.Key & 0xFF;
				if (Math.Abs(c.r - num44) <= 8 && Math.Abs(c.g - num45) <= 8 && Math.Abs(c.b - num46) <= 8)
				{
					return true;
				}
			}
			return false;
		};
		Func<Color32, bool> isBg = (Color32 c) => c.a < 20 || (c.a < 250 && Sat(c) <= graySat) || inPalette(c) || (hasBg && Math.Abs(c.r - br) <= tol && Math.Abs(c.g - bg) <= tol && Math.Abs(c.b - bb) <= tol);
		bool[] visited = new bool[num * num2];
		Stack<int> stack = new Stack<int>();
		Action<int> action2 = delegate(int num44)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (!visited[num44] && isBg(px[num44]))
			{
				visited[num44] = true;
				stack.Push(num44);
			}
		};
		for (int num9 = 0; num9 < num; num9++)
		{
			action2(num9);
			action2((num2 - 1) * num + num9);
		}
		for (int num10 = 0; num10 < num2; num10++)
		{
			action2(num10 * num);
			action2(num10 * num + num - 1);
		}
		while (stack.Count > 0)
		{
			int num11 = stack.Pop();
			int num12 = num11 % num;
			int num13 = num11 / num;
			if (num12 > 0)
			{
				action2(num11 - 1);
			}
			if (num12 < num - 1)
			{
				action2(num11 + 1);
			}
			if (num13 > 0)
			{
				action2(num11 - num);
			}
			if (num13 < num2 - 1)
			{
				action2(num11 + num);
			}
		}
		int num14 = 0;
		for (int num15 = 0; num15 < px.Length; num15++)
		{
			if (visited[num15] || (palette.Count > 0 && inPalette(px[num15]) && !c_isDark(px[num15])))
			{
				px[num15] = new Color32(px[num15].r, px[num15].g, px[num15].b, (byte)0);
				num14++;
			}
		}
		if ((float)num14 > (float)(num * num2) * 0.95f)
		{
			Object.Destroy((Object)(object)val);
			return null;
		}
		int num16 = num;
		int num17 = num2;
		int num18 = -1;
		int num19 = -1;
		for (int num20 = 0; num20 < num2; num20++)
		{
			for (int num21 = 0; num21 < num; num21++)
			{
				if (px[num20 * num + num21].a > 0)
				{
					if (num21 < num16)
					{
						num16 = num21;
					}
					if (num21 > num18)
					{
						num18 = num21;
					}
					if (num20 < num17)
					{
						num17 = num20;
					}
					if (num20 > num19)
					{
						num19 = num20;
					}
				}
			}
		}
		if (num18 < 0)
		{
			Object.Destroy((Object)(object)val);
			return null;
		}
		int num22 = num18 - num16 + 1;
		int num23 = num19 - num17 + 1;
		int num24 = Math.Max(num22, num23) + 2;
		Color32[] array2 = (Color32[])(object)new Color32[num24 * num24];
		int num25 = (num24 - num22) / 2;
		int num26 = (num24 - num23) / 2;
		for (int num27 = 0; num27 < num23; num27++)
		{
			for (int num28 = 0; num28 < num22; num28++)
			{
				array2[(num27 + num26) * num24 + (num28 + num25)] = px[(num27 + num17) * num + (num28 + num16)];
			}
		}
		for (int num29 = 0; num29 < 2; num29++)
		{
			Color32[] array3 = (Color32[])array2.Clone();
			for (int num30 = 0; num30 < num24; num30++)
			{
				for (int num31 = 0; num31 < num24; num31++)
				{
					if (array2[num30 * num24 + num31].a != 0)
					{
						continue;
					}
					int num32 = 0;
					int num33 = 0;
					int num34 = 0;
					int num35 = 0;
					for (int num36 = -1; num36 <= 1; num36++)
					{
						for (int num37 = -1; num37 <= 1; num37++)
						{
							int num38 = num31 + num37;
							int num39 = num30 + num36;
							if (num38 >= 0 && num39 >= 0 && num38 < num24 && num39 < num24)
							{
								Color32 val3 = array2[num39 * num24 + num38];
								if ((val3.a != 0 || val3.r + val3.g + val3.b > 0) && val3.a != 0)
								{
									num32 += val3.r;
									num33 += val3.g;
									num34 += val3.b;
									num35++;
								}
							}
						}
					}
					if (num35 > 0)
					{
						array3[num30 * num24 + num31] = new Color32((byte)(num32 / num35), (byte)(num33 / num35), (byte)(num34 / num35), (byte)0);
					}
				}
			}
			array2 = array3;
		}
		int num40 = Mathf.Clamp(Mathf.CeilToInt(128f / (float)num24), 1, 8);
		int num41 = num24 * num40;
		Color32[] array4 = (Color32[])(object)new Color32[num41 * num41];
		for (int num42 = 0; num42 < num41; num42++)
		{
			for (int num43 = 0; num43 < num41; num43++)
			{
				array4[num42 * num41 + num43] = array2[num42 / num40 * num24 + num43 / num40];
			}
		}
		Object.Destroy((Object)(object)val);
		Texture2D val4 = new Texture2D(num41, num41, (TextureFormat)4, false);
		((Texture)val4).filterMode = (FilterMode)0;
		((Texture)val4).wrapMode = (TextureWrapMode)1;
		val4.SetPixels32(array4);
		val4.Apply();
		Sprite result = Sprite.Create(val4, new Rect(0f, 0f, (float)num41, (float)num41), new Vector2(0.5f, 0.5f), src.pixelsPerUnit * (float)num40);
		try
		{
			foreach (string text in keys)
			{
				if (text.Length > 0)
				{
					File.WriteAllBytes(Path.Combine(Plugin.CacheDir, text + ".png"), ImageConversion.EncodeToPNG(val4));
					break;
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Could not cache icon: " + ex.Message));
		}
		return result;
	}

	private static int Sat(Color32 c)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		byte num = Math.Max(c.r, Math.Max(c.g, c.b));
		int num2 = Math.Min(c.r, Math.Min(c.g, c.b));
		return num - num2;
	}

	private static bool c_isDark(Color32 c)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: 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 (c.r < 50 && c.g < 50)
		{
			return c.b < 50;
		}
		return false;
	}

	public static void LoadCache()
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Expected O, but got Unknown
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (!Directory.Exists(Plugin.CacheDir))
			{
				return;
			}
			string[] files = Directory.GetFiles(Plugin.CacheDir, "*.png");
			foreach (string path in files)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
				if (!VendingSprites.ContainsKey(fileNameWithoutExtension))
				{
					Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
					if (ImageConversion.LoadImage(val, File.ReadAllBytes(path)))
					{
						((Texture)val).filterMode = (FilterMode)0;
						((Texture)val).wrapMode = (TextureWrapMode)1;
						VendingSprites[fileNameWithoutExtension] = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
					}
				}
			}
			Plugin.Log.LogInfo((object)("Loaded " + VendingSprites.Count + " cached vending icons."));
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Icon cache load failed: " + ex.Message));
		}
	}

	internal static string Sanitize(string s)
	{
		StringBuilder stringBuilder = new StringBuilder();
		string text = s.ToLowerInvariant();
		foreach (char c in text)
		{
			if (char.IsLetterOrDigit(c))
			{
				stringBuilder.Append(c);
			}
		}
		return stringBuilder.ToString();
	}

	private static string Prettify(string s)
	{
		s = s.Replace("Item_", "").Replace("item_", "").Replace('_', ' ')
			.Trim();
		if (s.Length != 0)
		{
			return char.ToUpperInvariant(s[0]) + s.Substring(1);
		}
		return s;
	}
}
[HarmonyPatch(typeof(UI_TrinketPicker), "ReloadTrinkets")]
internal static class TrinketPickerPatch
{
	private static void Prefix(M_Gamemode ___currentGamemode)
	{
		try
		{
			List<Trinket> list = (((Object)(object)___currentGamemode != (Object)null && (Object)(object)___currentGamemode.availableTrinkets != (Object)null) ? ___currentGamemode.availableTrinkets.trinkets : null);
			if (list == null)
			{
				return;
			}
			foreach (Trinket item in TrinketFactory.Build())
			{
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Failed to add trinkets: " + ex));
		}
	}
}
[HarmonyPatch(typeof(CL_AssetManager), "InitializeDatabases")]
internal static class DatabasesPatch
{
	private static void Postfix()
	{
		try
		{
			TrinketFactory.Build(scan: true);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Early build failed (will retry later): " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(ENV_VendingMachine), "Start")]
internal static class VendingStartPatch
{
	private static void Postfix(ENV_VendingMachine __instance)
	{
		try
		{
			TrinketFactory.OnVendingStart(__instance);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Vending harvest failed: " + ex.Message));
		}
	}
}