Decompiled source of CampsUpgrade v1.0.0

CampsUpgrade.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Eremite;
using Eremite.Buildings;
using Eremite.Buildings.UI;
using Eremite.Controller;
using Eremite.Model;
using Eremite.Services;
using Eremite.View;
using Eremite.View.UI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("CampsUpgrade")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Allow the Woodcutters Camp to be upgraded")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+1eef87e9b9c9758b5b96d4750f9d08816f07243b")]
[assembly: AssemblyProduct("CampsUpgrade")]
[assembly: AssemblyTitle("CampsUpgrade")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CampsUpgrade
{
	[HarmonyPatch]
	[BepInPlugin("CampsUpgrade", "CampsUpgrade", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource Log;

		private static ConfigEntry<bool> DebugLog;

		private const string SourceBuildingName = "Woodcutters Camp";

		private static readonly string[] TargetBuildingNames = new string[10] { "Forager's Camp", "Primitive Forager's Camp", "Herbalist's Camp", "Primitive Herbalist's Camp", "Trapper's Camp", "Primitive Trapper's Camp", "Harvester Camp", "Stonecutter's Camp", "Fishing Hut", "Primitive Fishing Hut" };

		private static readonly Dictionary<string, ConfigEntry<bool>> UpgradeEnabled = new Dictionary<string, ConfigEntry<bool>>();

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

		private static bool upgradesCopied;

		private static readonly Dictionary<ProductionBuildingPanel, AnimatedTab> UpgradeTabs = new Dictionary<ProductionBuildingPanel, AnimatedTab>();

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("DebugLog", "DebugLog", false, "If true, add the gi logs to bepinex log window");
			BindConfigs();
			Harmony.CreateAndPatchAll(typeof(Plugin), (string)null);
			Log.LogInfo((object)"CampsUpgrade v1.0.0 loaded");
		}

		private static void DebugInfo(string message)
		{
			if (DebugLog.Value)
			{
				Log.LogInfo((object)message);
			}
		}

		private void BindConfigs()
		{
			foreach (string item in new string[1] { "Woodcutters Camp" }.Concat(TargetBuildingNames))
			{
				UpgradeEnabled[item] = ((BaseUnityPlugin)this).Config.Bind<bool>("Buildings", ConfigKey(item), true, "If true, this building can be upgraded. Takes effect the next time the game starts. This is for the small version of the building as well");
			}
		}

		private static string ConfigKey(string name)
		{
			return name.Replace("'", "");
		}

		private static bool IsUpgradeEnabled(string name)
		{
			ConfigEntry<bool> value;
			return !UpgradeEnabled.TryGetValue(name, out value) || value.Value;
		}

		[HarmonyPatch(typeof(CampModel), "AreUpgradesUnlockd")]
		[HarmonyPostfix]
		private static void AllowWoodcutterUpgrades(CampModel __instance, ref bool __result)
		{
			if (!__result && ((SO)__instance).Name.Contains("Woodcutter") && IsUpgradeEnabled("Woodcutters Camp"))
			{
				__result = true;
			}
		}

		[HarmonyPatch(typeof(MainController), "OnServicesReady")]
		[HarmonyPostfix]
		private static void OnServicesReady()
		{
			try
			{
				CopyUpgradesToTargets();
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("{0} copying upgrades failed: {1}", "CampsUpgrade", arg));
			}
		}

		[HarmonyPatch(typeof(TextsService), "GetLocaText")]
		[HarmonyPostfix]
		private static void CustomLocaText(string key, ref string __result)
		{
			if (key != null && CustomTexts.TryGetValue(key, out var value))
			{
				__result = value;
			}
		}

		private static void CopyUpgradesToTargets()
		{
			if (upgradesCopied)
			{
				return;
			}
			upgradesCopied = true;
			Dictionary<string, UpgradableBuildingModel> dictionary = new Dictionary<string, UpgradableBuildingModel>();
			foreach (UpgradableBuildingModel item in Serviceable.Settings.Buildings.OfType<UpgradableBuildingModel>())
			{
				if (!dictionary.ContainsKey(((SO)item).Name))
				{
					dictionary.Add(((SO)item).Name, item);
				}
			}
			if (dictionary.TryGetValue("Woodcutters Camp", out var value))
			{
				CampModel val = (CampModel)(object)((value is CampModel) ? value : null);
				if (val != null && ((UpgradableBuildingModel)val).levels != null)
				{
					BuildingLevelModel[] array = CreateLevelsFrom((UpgradableBuildingModel)(object)val);
					string[] targetBuildingNames = TargetBuildingNames;
					foreach (string text in targetBuildingNames)
					{
						if (!IsUpgradeEnabled(text))
						{
							DebugInfo("Upgrades for '" + text + "' are disabled in the config, skipped.");
							continue;
						}
						if (!dictionary.TryGetValue(text, out var value2))
						{
							Log.LogWarning((object)("CampsUpgrade building '" + text + "' not found, skipped"));
							continue;
						}
						value2.levels = array;
						DebugInfo($"{((SO)value2).Name} now has {array.Length} upgrade levels copied from {((SO)val).Name}.");
					}
					return;
				}
			}
			Log.LogWarning((object)"CampsUpgrade upgrades not copied: 'Woodcutters Camp' not found");
		}

		private static BuildingLevelModel[] CreateLevelsFrom(UpgradableBuildingModel source)
		{
			//IL_0031: 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)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			BuildingLevelModel[] array = (BuildingLevelModel[])(object)new BuildingLevelModel[source.levels.Length];
			for (int i = 0; i < array.Length; i++)
			{
				BuildingLevelModel val = source.levels[i];
				int level = i;
				array[level] = new BuildingLevelModel
				{
					requiredGoods = val.requiredGoods,
					options = val.options.Select((BuildingPerkModel perk, int perkIndex) => ClonePerk(perk, level, perkIndex)).ToArray()
				};
			}
			return array;
		}

		private static BuildingPerkModel ClonePerk(BuildingPerkModel original, int level, int perkIndex)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			BuildingPerkModel val = Object.Instantiate<BuildingPerkModel>(original);
			((Object)val).name = ((SO)original).Name + " (copy)";
			GetPerkText(original, out var displayName, out var description);
			string key = $"CampsUpgrade_L{level}_{perkIndex}_Name";
			string key2 = $"CampsUpgrade_L{level}_{perkIndex}_Desc";
			CustomTexts[key] = displayName;
			CustomTexts[key2] = description;
			val.displayName = new LocaText
			{
				key = key
			};
			val.description = new LocaText
			{
				key = key2
			};
			val.formatDescription = false;
			return val;
		}

		private static void GetPerkText(BuildingPerkModel perk, out string displayName, out string description)
		{
			if (!(perk is VillagerPerkBuildingPerkModel))
			{
				WorkersExtraCapacityBuildingPerkModel val = (WorkersExtraCapacityBuildingPerkModel)(object)((perk is WorkersExtraCapacityBuildingPerkModel) ? perk : null);
				if (val == null)
				{
					ExtraProductionChanceBuildingPerkModel val2 = (ExtraProductionChanceBuildingPerkModel)(object)((perk is ExtraProductionChanceBuildingPerkModel) ? perk : null);
					if (val2 == null)
					{
						AutomatonBuildingPerkModel val3 = (AutomatonBuildingPerkModel)(object)((perk is AutomatonBuildingPerkModel) ? perk : null);
						if (val3 != null)
						{
							displayName = "Storage Automaton";
							description = $"Adds {val3.amount} hauling cart to this building. That will take the good back to the warehouse.";
						}
						else
						{
							displayName = ((SO)perk).Name;
							description = ((SO)perk).Name;
						}
					}
					else
					{
						displayName = "Extra Production Chance";
						description = $"{(int)Math.Round(val2.amount * 100f)}% chance to produce extra goods.";
					}
				}
				else
				{
					displayName = "Worker Capacity";
					description = $"Workers carry {val.amount} more goods per trip.";
				}
			}
			else
			{
				displayName = "Worker Speed";
				description = "Workers work 25% faster.";
			}
		}

		[HarmonyPatch(typeof(GameController), "StartGame")]
		[HarmonyPostfix]
		private static void OnGameStart()
		{
			try
			{
				AddUpgradesUi((ProductionBuildingPanel)(object)GathererHutPanel.Instance);
				AddUpgradesUi((ProductionBuildingPanel)(object)FishingHutPanel.Instance);
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("{0} adding upgrades UI failed: {1}", "CampsUpgrade", arg));
			}
		}

		[HarmonyPatch(typeof(GathererHutPanel), "Show", new Type[] { typeof(GathererHut) })]
		[HarmonyPostfix]
		private static void GathererHutPanel_Show_Postfix(GathererHutPanel __instance, GathererHut gathererHut)
		{
			UpdateUpgradesTab((ProductionBuildingPanel)(object)__instance, (Building)(object)gathererHut);
		}

		[HarmonyPatch(typeof(FishingHutPanel), "Show", new Type[] { typeof(FishingHut) })]
		[HarmonyPostfix]
		private static void FishingHutPanel_Show_Postfix(FishingHutPanel __instance, FishingHut hut)
		{
			UpdateUpgradesTab((ProductionBuildingPanel)(object)__instance, (Building)(object)hut);
		}

		private static void UpdateUpgradesTab(ProductionBuildingPanel panel, Building building)
		{
			if (UpgradeTabs.TryGetValue(panel, out var value))
			{
				panel.tabsPanel.SwitchTab(value, building.HasUpgrades);
			}
		}

		private static void AddUpgradesUi(ProductionBuildingPanel panel)
		{
			if (!((Object)(object)panel == (Object)null) && !UpgradeTabs.ContainsKey(panel))
			{
				CampPanel instance = CampPanel.Instance;
				Transform val = (((Object)(object)instance != (Object)null) ? ((Component)instance).transform.Find("Content/TabsPanel/Upgrades") : null);
				Transform val2 = (((Object)(object)instance != (Object)null) ? ((Component)instance).transform.Find("Content/UpgradesPanel") : null);
				Transform val3 = ((Component)panel).transform.Find("Content");
				Transform val4 = (((Object)(object)val3 != (Object)null) ? val3.Find("TabsPanel") : null);
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val4 == (Object)null)
				{
					Log.LogWarning((object)("CampsUpgrade upgrades UI not added to " + ((object)panel).GetType().Name + ": " + $"campPanel={(Object)(object)instance != (Object)null} campTab={(Object)(object)val != (Object)null} " + $"campUpgradesPanel={(Object)(object)val2 != (Object)null} tabsParent={(Object)(object)val4 != (Object)null}"));
					return;
				}
				Transform val5 = Object.Instantiate<Transform>(val2, val3);
				((Object)val5).name = ((Object)val2).name;
				Transform val6 = val3.Find("ConstructionPanel");
				val5.SetSiblingIndex(((Object)(object)val6 != (Object)null) ? (val6.GetSiblingIndex() + 1) : (val3.childCount - 1));
				Transform val7 = Object.Instantiate<Transform>(val, val4);
				((Object)val7).name = ((Object)val).name;
				val7.SetSiblingIndex(1);
				AnimatedTab component = ((Component)val7).GetComponent<AnimatedTab>();
				component.toEnable = (ActivationLock[])(object)new ActivationLock[1] { ((Component)val5).GetComponent<ActivationLock>() };
				List<AnimatedTab> list = panel.tabsPanel.tabs.ToList();
				list.Insert(1, component);
				panel.tabsPanel.tabs = list.ToArray();
				component.SetUp((Action<AnimatedTab>)panel.tabsPanel.OnTabClicked);
				((BuildingPanel)panel).upgradesPanel = ((Component)val5).GetComponent<BuildingUpgradesPanel>();
				UpgradeTabs[panel] = component;
				DebugInfo("Added upgrades tab and panel to " + ((object)panel).GetType().Name + ".");
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "CampsUpgrade";

		public const string PLUGIN_NAME = "CampsUpgrade";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}