Decompiled source of ResourceCampUpgrades v0.1.1

plugins/ResourceCampUpgrades.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Clickable;
using SuperFantasyKingdom.UI;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ResourceCampUpgrades")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1+1090a5a7af92a3a7e32d237a25eaa7db00f8ff03")]
[assembly: AssemblyProduct("ResourceCampUpgrades")]
[assembly: AssemblyTitle("ResourceCampUpgrades")]
[assembly: AssemblyVersion("0.1.1.0")]
namespace ResourceCampUpgrades;

[HarmonyPatch(typeof(BuildingCity), "GetQueue", new Type[] { })]
internal static class WriteCampTier
{
	private static void Postfix(BuildingCity __instance, ref List<int> __result)
	{
		if (__result == null)
		{
			BuildingResourceWorld val = (BuildingResourceWorld)(object)((__instance is BuildingResourceWorld) ? __instance : null);
			if (val != null && Camps.IsCamp(val))
			{
				__result = Camps.State(val).Save();
			}
		}
	}
}
[HarmonyPatch(typeof(BuildingResource), "SetQueue", new Type[] { typeof(List<int>) })]
internal static class ReadCampTier
{
	private static void Postfix(BuildingResource __instance, List<int> queue)
	{
		BuildingResourceWorld val = (BuildingResourceWorld)(object)((__instance is BuildingResourceWorld) ? __instance : null);
		if (val != null && Camps.IsCamp(val))
		{
			Camps.State(val).Restore(queue);
		}
	}
}
[HarmonyPatch(typeof(UIOverlayVariable), "Generate", new Type[]
{
	typeof(Building),
	typeof(List<UIBuildingOverlayElement>),
	typeof(string)
})]
internal static class AppendCampPanel
{
	private static void Prefix(Building building, ref List<UIBuildingOverlayElement> elements)
	{
		BuildingResourceWorld val = (BuildingResourceWorld)(object)((building is BuildingResourceWorld) ? building : null);
		if (val != null && Camps.CanUse(val))
		{
			elements = ((elements == null) ? new List<UIBuildingOverlayElement>() : new List<UIBuildingOverlayElement>(elements));
			if (elements.Count > 0 && ((object)elements[0])?.GetType() == typeof(UIBuildingOverlayElementLocalized))
			{
				elements.RemoveAt(0);
			}
			elements.Insert(0, (UIBuildingOverlayElement)(object)new CampPanel());
		}
	}
}
internal sealed class CampPanel : UIBuildingOverlayElement
{
	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static UnityAction <>9__1_0;

		internal void <Render>b__1_0()
		{
			OverlayManager.Instance.Cancel(true);
		}
	}

	public override GameObject Draw(Building building)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		BuildingResourceWorld site = (BuildingResourceWorld)building;
		UIOverlayMessage component = Object.Instantiate<GameObject>(Resources.Load<GameObject>("UI/OverlayMessage"), ((UIBuildingOverlayElement)this).GetOverlaySelection()).GetComponent<UIOverlayMessage>();
		((Behaviour)((Component)component).GetComponent<Image>()).enabled = false;
		((Behaviour)((Component)component).GetComponent<ContentSizeFitter>()).enabled = false;
		((LayoutGroup)((Component)component).GetComponent<VerticalLayoutGroup>()).padding = new RectOffset();
		Render(component, site);
		return null;
	}

	private static void Render(UIOverlayMessage panel, BuildingResourceWorld site)
	{
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: 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_00dd: Expected O, but got Unknown
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Expected O, but got Unknown
		UpgradeState upgradeState = Camps.State(site);
		int level = upgradeState.Level;
		ResourceData resourceData = RaceManager.Instance.GetResourceData(((Building)site).GetResource());
		string arg = "<sprite name=" + ((Object)resourceData.icon).name + ">";
		string text = $"Morning shipment  {UpgradeState.Payout(level)} {arg}";
		string text2 = $"Camp level {upgradeState.CampLevel}/{4}";
		Button component = ((Component)((Component)panel).transform.Find("Buttons/Cancel")).GetComponent<Button>();
		UIOverlayMessage obj = panel;
		object obj2 = <>c.<>9__1_0;
		if (obj2 == null)
		{
			UnityAction val = delegate
			{
				OverlayManager.Instance.Cancel(true);
			};
			<>c.<>9__1_0 = val;
			obj2 = (object)val;
		}
		obj.SetCancel("", (UnityAction)obj2);
		if (level == 3)
		{
			panel.SetMessage("<color=#FFF0D4>" + text2 + " (Max level)\n" + text + "</color>");
			panel.RemoveAccept();
			GamepadManager.Instance.SetGameObjectToSelect(((Component)component).gameObject, true);
			return;
		}
		ResourceAmount val2 = default(ResourceAmount);
		((ResourceAmount)(ref val2))..ctor((ResourceType)12, UpgradeState.Price(level));
		bool flag = ResourceManager.Instance.GetCoins() >= val2.amount;
		string text3 = $"{UpgradeState.Payout(level + 1)} {arg}";
		string text4 = (flag ? "" : "\nNot enough coins");
		panel.SetMessage("<color=#FFF0D4>" + text2 + "\n" + text + "\nAfter upgrade  " + text3 + text4 + "</color>");
		Button val3 = panel.SetAccept(val2, (UnityAction)delegate
		{
			if (!((Object)(object)panel == (Object)null) && ((Component)panel).gameObject.activeInHierarchy)
			{
				if (Camps.TryPurchase(site, level))
				{
					OverlayManager.Instance.Confirm();
				}
				else if (Camps.CanUse(site))
				{
					Render(panel, site);
				}
			}
		}, true);
		((Selectable)val3).interactable = flag;
		GamepadManager.Instance.SetGameObjectToSelect(((Component)(flag ? val3 : component)).gameObject, true);
	}
}
[HarmonyPatch(typeof(BuildingResourceWorld), "Start", new Type[] { })]
internal static class AddMissingCampClick
{
	private static void Postfix(BuildingResourceWorld __instance)
	{
		if (Camps.IsCamp(__instance) && (Object)(object)((Component)__instance).GetComponent<UIBuildingOverlay>() == (Object)null && (Object)(object)((Component)__instance).GetComponent<CampClick>() == (Object)null)
		{
			((Component)__instance).gameObject.AddComponent<CampClick>();
		}
	}
}
public sealed class CampClick : ClickableSprite
{
	private BuildingResourceWorld site;

	protected override void Awake()
	{
		site = ((Component)this).GetComponent<BuildingResourceWorld>();
		Transform obj = ((Component)this).transform.Find("Click");
		base.boxCollider2D = ((obj != null) ? ((Component)obj).GetComponent<BoxCollider2D>() : null);
		base.doNotHighlight = true;
		((ClickableSprite)this).Awake();
	}

	public override bool IsInteractable()
	{
		if (Camps.CanUse(site) && (Object)(object)base.boxCollider2D != (Object)null)
		{
			return ((ClickableSprite)this).IsInteractable();
		}
		return false;
	}

	public override void OnClick()
	{
		if (((ClickableSprite)this).IsInteractable() && !SpellManager.Instance.IsAtCasting() && !FaithManager.Instance.IsInWorshipperMode() && !FaithManager.Instance.IsInExtraSpecialistMode())
		{
			OverlayManager.Instance.OverlayVariable((Building)(object)site, new List<UIBuildingOverlayElement>(), ((Building)site).GetTitle());
		}
	}
}
[HarmonyPatch(typeof(BuildingResourceWorld), "ClickOnMarker", new Type[] { })]
internal static class CampShipment
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		List<CodeInstruction> list = instructions.ToList();
		ConstructorInfo constructor = AccessTools.Constructor(typeof(ResourceAmount), new Type[2]
		{
			typeof(ResourceType),
			typeof(int)
		}, false);
		List<CodeInstruction> list2 = list.Where((CodeInstruction instruction) => instruction.opcode == OpCodes.Newobj && object.Equals(instruction.operand, constructor)).ToList();
		if (list2.Count != 1)
		{
			throw new InvalidOperationException("The native camp shipment must construct exactly one cargo amount.");
		}
		CodeInstruction val = list2[0];
		int num = list.IndexOf(val);
		val.opcode = OpCodes.Ldarg_0;
		val.operand = null;
		list.Insert(num + 1, CodeInstruction.Call(typeof(CampShipment), "CreateCargo", (Type[])null, (Type[])null));
		return list;
	}

	private static ResourceAmount CreateCargo(ResourceType resource, int amount, BuildingResourceWorld site)
	{
		//IL_002b: 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_0008: 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_001e: Unknown result type (might be due to invalid IL or missing references)
		if (Camps.IsCamp(site) && resource == ((Building)site).GetResource())
		{
			amount = Camps.State(site).Shipment(amount, ((Building)site).GetStorage().GetStorageSpace(resource));
		}
		return new ResourceAmount(resource, amount);
	}
}
[BepInPlugin("gkj.sfk.resourcecampupgrades", "Resource Camp Upgrades", "0.1.1")]
public sealed class Plugin : BaseUnityPlugin
{
	private const string Id = "gkj.sfk.resourcecampupgrades";

	private static readonly Guid SupportedGame = new Guid("da6b1cd7-6dac-4d65-8647-db23f22f811b");

	private Harmony harmony;

	internal static Plugin Instance { get; private set; }

	private void Awake()
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Expected O, but got Unknown
		if (typeof(BuildingResourceWorld).Module.ModuleVersionId != SupportedGame)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Resource Camp Upgrades requires the verified Super Fantasy Kingdom 0.8.070 build.");
			return;
		}
		try
		{
			harmony = new Harmony("gkj.sfk.resourcecampupgrades");
			harmony.PatchAll(typeof(Plugin).Assembly);
			Instance = this;
		}
		catch (Exception ex)
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			((BaseUnityPlugin)this).Logger.LogError((object)ex);
		}
	}

	internal void LogNotificationError(Exception error)
	{
		((BaseUnityPlugin)this).Logger.LogWarning((object)error);
	}

	private void OnDestroy()
	{
		Instance = null;
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
	}
}
internal static class Camps
{
	private static readonly ConditionalWeakTable<BuildingResourceWorld, UpgradeState> Levels = new ConditionalWeakTable<BuildingResourceWorld, UpgradeState>();

	internal static UpgradeState State(BuildingResourceWorld site)
	{
		return Levels.GetValue(site, (BuildingResourceWorld _) => new UpgradeState());
	}

	internal static bool IsCamp(BuildingResourceWorld site)
	{
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Invalid comparison between Unknown and I4
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Invalid comparison between Unknown and I4
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Invalid comparison between Unknown and I4
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Invalid comparison between Unknown and I4
		if ((Object)(object)site == (Object)null)
		{
			return false;
		}
		string text = ((Object)site).name;
		if (text.EndsWith("(Clone)", StringComparison.Ordinal))
		{
			text = text.Substring(0, text.Length - "(Clone)".Length).TrimEnd();
		}
		switch (text)
		{
		case "UndeadSewageOutside":
		case "HumanFarmOutside":
			return (int)((Building)site).GetResource() == 7;
		case "HumanLumberyardOutside":
		case "UndeadBoneyardOutside":
			return (int)((Building)site).GetResource() == 2;
		case "UndeadQuarryOutside":
		case "HumanQuarryOutside":
			return (int)((Building)site).GetResource() == 4;
		case "UndeadBloodOutside":
		case "HumanGoldMineOutside":
			return (int)((Building)site).GetResource() == 15;
		default:
			return false;
		}
	}

	internal static bool CanUse(BuildingResourceWorld site)
	{
		if ((Object)(object)Plugin.Instance != (Object)null && (Object)(object)GameManager.Instance != (Object)null && GameManager.Instance.IsGameLoaded() && IsCamp(site) && ((Behaviour)site).isActiveAndEnabled)
		{
			return !((BuildingCity)site).ShouldRemove();
		}
		return false;
	}

	internal static bool TryPurchase(BuildingResourceWorld site, int quotedLevel)
	{
		if (!CanUse(site) || (Object)(object)ResourceManager.Instance == (Object)null)
		{
			return false;
		}
		ResourceManager instance = ResourceManager.Instance;
		if (!State(site).TryBuy(quotedLevel, instance.GetCoins(), unlocked: true, out var remainingCoins))
		{
			return false;
		}
		instance.SetCoins(remainingCoins);
		try
		{
			instance.ResourceAmountChanged((ResourceType)12);
		}
		catch (Exception error)
		{
			Plugin.Instance?.LogNotificationError(error);
		}
		return true;
	}
}
internal sealed class UpgradeState
{
	internal const int Maximum = 3;

	internal const int MaxCampLevel = 4;

	private const int QueueMarker = 1380144385;

	private static readonly int[] Prices = new int[3] { 8, 16, 32 };

	private bool shipped;

	internal int Level { get; private set; }

	internal int CampLevel => Level + 1;

	internal static int Price(int level)
	{
		if (level < 0 || level >= 3)
		{
			return 0;
		}
		return Prices[level];
	}

	internal static int Payout(int level)
	{
		return 1 + Math.Max(0, Math.Min(level, 3));
	}

	internal bool TryBuy(int quotedLevel, int coins, bool unlocked, out int remainingCoins)
	{
		remainingCoins = coins;
		int num = Price(quotedLevel);
		if (!unlocked || quotedLevel != Level || num == 0 || coins < num)
		{
			return false;
		}
		remainingCoins = coins - num;
		Level++;
		return true;
	}

	internal List<int> Save()
	{
		if (Level != 0)
		{
			return new List<int> { 1380144385, Level };
		}
		return null;
	}

	internal void Restore(List<int> queue)
	{
		Level = ((queue != null && queue.Count == 2 && queue[0] == 1380144385 && queue[1] > 0 && queue[1] <= 3) ? queue[1] : 0);
	}

	internal int Shipment(int nativeAmount, int capacity)
	{
		if (shipped || nativeAmount <= 0)
		{
			return nativeAmount;
		}
		shipped = true;
		int num = ((nativeAmount < capacity) ? Math.Min(Level, capacity - nativeAmount) : 0);
		return nativeAmount + num;
	}
}