Decompiled source of Worthwhile Treasures v1.0.0

BepInEx/plugins/OctoberJemini-WorthwhileTreasures/WorthwhileTreasures.dll

Decompiled 7 hours ago
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Utils;
using UnityEngine;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("1.0.0.0")]
namespace OctoberJemini.WorthwhileTreasures;

[BepInPlugin("OctoberJemini.WorthwhileTreasures", "Worthwhile Treasures", "1.0.0")]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
[BepInDependency("com.jotunn.jotunn", "2.30.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Container), "AddDefaultItems")]
	private static class GeneratePatch
	{
		[HarmonyPrefix]
		private static void Prefix(Container __instance, ZNetView ___m_nview)
		{
			Audit(__instance, ___m_nview, "defaults-before", "entry");
		}

		[HarmonyAfter(new string[] { "randyknapp.mods.epicloot" })]
		[HarmonyPriority(0)]
		[HarmonyPostfix]
		private static void Postfix(Container __instance, ZNetView ___m_nview)
		{
			try
			{
				Reward(__instance, ___m_nview);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)instance).Logger.LogError((object)("Treasure generation failed: " + ex));
			}
		}
	}

	[HarmonyPatch(typeof(Container), "RPC_OpenResponse")]
	private static class OpenPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Container __instance, ZNetView ___m_nview, bool __1)
		{
			Audit(__instance, ___m_nview, "open-response", __1 ? "granted" : "denied");
			try
			{
				Celebrate(__instance, ___m_nview, __1);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)("Treasure chime failed: " + ex.Message));
			}
		}
	}

	[HarmonyPatch(typeof(Container), "Awake")]
	private static class AwakeAudit
	{
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix(Container __instance, ZNetView ___m_nview)
		{
			Audit(__instance, ___m_nview, "awake-complete", "observed");
		}
	}

	[HarmonyPatch(typeof(Container), "RPC_RequestOpen")]
	private static class RequestAudit
	{
		[HarmonyPrefix]
		private static void Prefix(Container __instance, ZNetView ___m_nview)
		{
			Audit(__instance, ___m_nview, "open-request", "observed");
		}
	}

	public const string Guid = "OctoberJemini.WorthwhileTreasures";

	private const string Applied = "oct_treasure_reward_v1";

	private const string Jackpot = "oct_treasure_jackpot_v1";

	private const string Heard = "oct_treasure_heard_v1";

	private ConfigEntry<bool> diagnosticLogging;

	private static Plugin instance;

	private Harmony harmony;

	private static AudioClip chime;

	private static readonly MethodInfo Save = AccessTools.Method(typeof(Container), "Save", (Type[])null, (Type[])null);

	private static readonly FieldInfo InventoryField = AccessTools.Field(typeof(Container), "m_inventory");

	private void Awake()
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		instance = this;
		diagnosticLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "VerboseLogging", false, "Log chest identities and contents for troubleshooting. Disabled by default.");
		harmony = new Harmony("OctoberJemini.WorthwhileTreasures");
		harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Worthwhile Treasures 1.0.0 loaded.");
	}

	private void OnDestroy()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		if (Object.op_Implicit((Object)(object)chime))
		{
			Object.Destroy((Object)(object)chime);
		}
	}

	private static void Audit(Container chest, ZNetView view, string stage, string reason)
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Expected O, but got Unknown
		//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)instance == (Object)null || !instance.diagnosticLogging.Value)
		{
			return;
		}
		try
		{
			string name = ((Object)((Component)chest).gameObject).name;
			string text = (Object.op_Implicit((Object)(object)view) ? Utils.GetPrefabName(((Component)view).gameObject) : "");
			if (name.IndexOf("TreasureChest", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("TreasureChest", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return;
			}
			ZDO val = (Object.op_Implicit((Object)(object)view) ? view.GetZDO() : null);
			Inventory val2 = (Inventory)InventoryField.GetValue(chest);
			int num = 0;
			int num2 = 0;
			string text2 = "";
			if (val2 != null)
			{
				foreach (ItemData allItem in val2.GetAllItems())
				{
					num2++;
					string text3 = (Object.op_Implicit((Object)(object)allItem.m_dropPrefab) ? ((Object)allItem.m_dropPrefab).name : allItem.m_shared.m_name);
					if (text3 == "Coins" || allItem.m_shared.m_name == "$item_coins")
					{
						num += allItem.m_stack;
					}
					object obj = text2;
					text2 = string.Concat(obj, text3, "x", allItem.m_stack, ";");
				}
			}
			Piece component = ((Component)chest).GetComponent<Piece>();
			((BaseUnityPlugin)instance).Logger.LogInfo((object)string.Concat("CHEST AUDIT stage=", stage, " reason=", reason, " raw=", name, " canonical=", text, " position=", ((Component)chest).transform.position, " id=", (val == null) ? "none" : ((object)Unsafe.As<ZDOID, ZDOID>(ref val.m_uid)/*cast due to .constrained prefix*/).ToString(), " prefab=", (val != null) ? val.GetPrefab() : 0, " owner=", Object.op_Implicit((Object)(object)view) && view.IsOwner(), " creator=", Object.op_Implicit((Object)(object)component) ? component.GetCreator() : 0, " applied=", val != null && val.GetBool("oct_treasure_reward_v1", false), " defaults=", val != null && val.GetBool(ZDOVars.s_addedDefaultItems, false), " db=", (Object)(object)ObjectDB.instance != (Object)null, " slots=", (val2 == null) ? "none" : (val2.GetWidth() + "x" + val2.GetHeight()), " coins=", num, " items=", num2, " contents=", text2));
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)instance).Logger.LogWarning((object)("Chest audit failed: " + ex.Message));
		}
	}

	private static void Reward(Container chest, ZNetView view)
	{
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Expected O, but got Unknown
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Expected O, but got Unknown
		if (!Object.op_Implicit((Object)(object)view) || !view.IsOwner() || view.GetZDO() == null)
		{
			Audit(chest, view, "reward-skip", "network-or-owner");
			return;
		}
		ZDO zDO = view.GetZDO();
		if (zDO.GetBool("oct_treasure_reward_v1", false))
		{
			Audit(chest, view, "reward-skip", "already-applied");
			return;
		}
		Piece component = ((Component)chest).GetComponent<Piece>();
		if (Object.op_Implicit((Object)(object)component) && component.IsPlacedByPlayer())
		{
			Audit(chest, view, "reward-skip", "player-created");
			return;
		}
		int num = RewardPolicy.Tier(((Object)((Component)chest).gameObject).name.Replace("(Clone)", "").Trim());
		if (num < 0)
		{
			Audit(chest, view, "reward-skip", "name-not-allowed");
			return;
		}
		Inventory val = (Inventory)InventoryField.GetValue(chest);
		if (val == null || !Object.op_Implicit((Object)(object)ObjectDB.instance))
		{
			Audit(chest, view, "reward-skip", "inventory-or-db");
			return;
		}
		Inventory val2 = new Inventory("Treasure staging", (Sprite)null, val.GetWidth(), val.GetHeight());
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Coins");
		if (!Object.op_Implicit((Object)(object)itemPrefab))
		{
			Audit(chest, view, "reward-skip", "missing-coins-prefab");
			return;
		}
		string name = itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
		foreach (ItemData allItem in val.GetAllItems())
		{
			if ((!(allItem.m_shared.m_name == name) || allItem.m_customData.Count != 0) && !val2.AddItem(allItem.Clone()))
			{
				Audit(chest, view, "reward-skip", "staging-original-item-failed");
				return;
			}
		}
		bool flag = Random.Range(0, 100) < 2;
		int num2 = RewardPolicy.Coins(num, flag, Random.Range(0, 201));
		string[] array = new string[3] { "Amber", "AmberPearl", "SilverNecklace" };
		int num3 = Random.Range(0, array.Length);
		GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(array[num3]);
		int count = ((num3 == 2) ? 1 : Random.Range(1, 4));
		if (!Object.op_Implicit((Object)(object)itemPrefab2) || !AddFullAmount(val2, itemPrefab, num2) || !AddFullAmount(val2, itemPrefab2, count))
		{
			zDO.Set("oct_treasure_reward_v1", true);
			((BaseUnityPlugin)instance).Logger.LogWarning((object)"Treasure bonus skipped: insufficient space or missing item. Original loot preserved.");
			Audit(chest, view, "reward-skip", "reward-capacity-or-prefab");
			return;
		}
		val.GetAllItems().Clear();
		val.GetAllItems().AddRange(val2.GetAllItems());
		AccessTools.Method(typeof(Inventory), "UpdateTotalWeight", (Type[])null, (Type[])null).Invoke(val, null);
		Save.Invoke(chest, null);
		zDO.Set("oct_treasure_jackpot_v1", flag);
		zDO.Set("oct_treasure_reward_v1", true);
		((BaseUnityPlugin)instance).Logger.LogInfo((object)("Treasure generated: " + ((Object)((Component)chest).gameObject).name + ", coins=" + num2 + ", jackpot=" + flag));
		Audit(chest, view, "reward-saved", "success");
	}

	private static bool AddFullAmount(Inventory inv, GameObject prefab, int count)
	{
		int maxStackSize = prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxStackSize;
		if (maxStackSize < 1)
		{
			return false;
		}
		while (count > 0)
		{
			int num = Math.Min(maxStackSize, count);
			if (!inv.AddItem(prefab, num))
			{
				return false;
			}
			count -= num;
		}
		return true;
	}

	private static void Celebrate(Container chest, ZNetView view, bool granted)
	{
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Expected O, but got Unknown
		if (!granted || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)view) || !view.IsOwner())
		{
			return;
		}
		ZDO zDO = view.GetZDO();
		if (zDO == null || !zDO.GetBool("oct_treasure_jackpot_v1", false) || zDO.GetBool("oct_treasure_heard_v1", false))
		{
			return;
		}
		zDO.Set("oct_treasure_heard_v1", true);
		((Character)Player.m_localPlayer).Message((MessageType)2, "Treasure jackpot!", 0, (Sprite)null, false);
		if (!Object.op_Implicit((Object)(object)chime))
		{
			float[] array = new float[22050];
			for (int i = 0; i < array.Length; i++)
			{
				double num = (double)i / 22050.0;
				double num2 = Math.Min(1.0, num * 100.0) * Math.Exp(-5.0 * num);
				array[i] = (float)(0.22 * num2 * (Math.Sin(Math.PI * 1760.0 * num) + 0.5 * Math.Sin(Math.PI * 2640.0 * num)));
			}
			chime = AudioClip.Create("Worthwhile Treasures chime", array.Length, 1, 22050, false);
			chime.SetData(array, 0);
		}
		GameObject val = new GameObject("Treasure chime");
		AudioSource val2 = val.AddComponent<AudioSource>();
		val2.spatialBlend = 0f;
		val2.volume = 1f;
		val2.clip = chime;
		val2.Play();
		Object.Destroy((Object)(object)val, 1.2f);
	}
}
public static class RewardPolicy
{
	public static int Tier(string name)
	{
		switch (name)
		{
		case "TreasureChest_dvergrtown":
		case "TreasureChest_dvergrtower":
		case "TreasureChest_dvergr_loose_stone":
			return 0;
		case "TreasureChest_charredfortress":
			return 1;
		case "TreasureChest_deepnorth_village":
			return 2;
		default:
			return -1;
		}
	}

	public static int Coins(int tier, bool jackpot, int roll)
	{
		if (tier < 0 || tier > 2 || roll < 0 || roll > 200)
		{
			throw new ArgumentOutOfRangeException();
		}
		if (!jackpot)
		{
			return 100 + 50 * tier + roll;
		}
		return 1000 + 250 * tier;
	}
}