Decompiled source of SapExtractorProgressionFix v0.1.0

BepInEx/plugins/SapExtractorProgressionFix.dll

Decompiled 2 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("SapExtractorProgressionFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+81ccfef6e1ec16d9e4bbdad40f6afea966006348")]
[assembly: AssemblyProduct("SapExtractorProgressionFix")]
[assembly: AssemblyTitle("SapExtractorProgressionFix")]
[assembly: AssemblyVersion("0.1.0.0")]
[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 SapExtractorProgressionFix
{
	[HarmonyPatch(typeof(SapCollector), "UpdateTick")]
	internal static class SapCollectorPatch
	{
		private sealed class State
		{
			public float FirstTick = -1f;

			public bool HeldForRoot;

			public bool HoldLogged;
		}

		private const float RootGraceSeconds = 30f;

		private const double AbsenceSeconds = 60.0;

		private static readonly ConditionalWeakTable<SapCollector, State> States = new ConditionalWeakTable<SapCollector, State>();

		private static readonly Action<ResourceRoot> RootTick = BindRootTick();

		private static Action<ResourceRoot> BindRootTick()
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(ResourceRoot), "UpdateTick", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				ManualLogSource log = SapExtractorProgressionFixMod.Log;
				if (log != null)
				{
					log.LogWarning((object)"ResourceRoot.UpdateTick not found; roots will not be regenerated ahead of their extractors.");
				}
				return null;
			}
			return AccessTools.MethodDelegate<Action<ResourceRoot>>(methodInfo, (object)null, true);
		}

		private static bool Prefix(SapCollector __instance, ZNetView ___m_nview, ref ResourceRoot ___m_root)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			if (!SapExtractorProgressionFixMod.ModEnabled.Value)
			{
				return true;
			}
			if ((Object)(object)___m_nview == (Object)null || !___m_nview.IsValid() || (Object)(object)ZNet.instance == (Object)null)
			{
				return true;
			}
			ZDO zDO = ___m_nview.GetZDO();
			State orCreateValue = States.GetOrCreateValue(__instance);
			if (orCreateValue.FirstTick < 0f)
			{
				orCreateValue.FirstTick = Time.time;
			}
			if (Object.op_Implicit((Object)(object)__instance.m_mustConnectTo) && !Object.op_Implicit((Object)(object)___m_root))
			{
				___m_root = FindRoot(((Component)__instance).transform.position);
			}
			ResourceRoot val = ___m_root;
			if (___m_nview.IsOwner())
			{
				OwnerTick(__instance, zDO, val, orCreateValue);
			}
			int num = zDO.GetInt(ZDOVars.s_level, 0);
			bool active = num < __instance.m_maxLevel && Object.op_Implicit((Object)(object)val) && val.CanDrain(1f);
			if (Object.op_Implicit((Object)(object)__instance.m_notEmptyEffect))
			{
				__instance.m_notEmptyEffect.SetActive(num > 0);
			}
			if (Object.op_Implicit((Object)(object)__instance.m_workingEffect))
			{
				__instance.m_workingEffect.SetActive(active);
			}
			return false;
		}

		private static ResourceRoot FindRoot(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(position, 0.2f);
			for (int i = 0; i < array.Length; i++)
			{
				ResourceRoot componentInParent = ((Component)array[i]).GetComponentInParent<ResourceRoot>();
				if (componentInParent != null)
				{
					return componentInParent;
				}
			}
			return null;
		}

		private static void OwnerTick(SapCollector collector, ZDO zdo, ResourceRoot root, State state)
		{
			DateTime time = ZNet.instance.GetTime();
			long ticks = zdo.GetLong(ZDOVars.s_lastTime, time.Ticks);
			double num = Math.Max(0.0, (time - new DateTime(ticks)).TotalSeconds);
			bool flag = num >= 60.0;
			float num2 = Time.time - state.FirstTick;
			if (!Object.op_Implicit((Object)(object)root) && Object.op_Implicit((Object)(object)collector.m_mustConnectTo) && num2 < 30f)
			{
				state.HeldForRoot = true;
				if (flag && !state.HoldLogged)
				{
					state.HoldLogged = true;
					Report($"{Where(collector)}: away {num:F0} s, root not loaded yet. " + "Vanilla discards the time here (trigger 1). Holding it until the root appears.");
				}
				return;
			}
			float num3 = (Object.op_Implicit((Object)(object)root) ? root.GetLevel() : 0f);
			bool flag2 = false;
			if (Object.op_Implicit((Object)(object)root))
			{
				ZNetView component = ((Component)root).GetComponent<ZNetView>();
				flag2 = Object.op_Implicit((Object)(object)component) && component.IsValid() && component.IsOwner();
				if (flag2 && RootTick != null)
				{
					RootTick(root);
				}
			}
			float num4 = (Object.op_Implicit((Object)(object)root) ? root.GetLevel() : 0f);
			zdo.Set(ZDOVars.s_lastTime, time.Ticks);
			int maxLevel = collector.m_maxLevel;
			float secPerUnit = collector.m_secPerUnit;
			int num5 = zdo.GetInt(ZDOVars.s_level, 0);
			float num6 = zdo.GetFloat(ZDOVars.s_product, 0f);
			int num7 = ((secPerUnit > 0f && num6 + (float)num > secPerUnit) ? ((int)((num6 + (float)num) / secPerUnit)) : 0);
			int num8 = 0;
			if (num5 < maxLevel && Object.op_Implicit((Object)(object)root) && root.CanDrain(1f))
			{
				float num9 = num6 + (float)num;
				if (num7 > 0)
				{
					num8 = Mathf.Min(new int[3]
					{
						num7,
						maxLevel - num5,
						Mathf.CeilToInt(num4) - 1
					});
					if (num8 > 0)
					{
						zdo.Set(ZDOVars.s_level, num5 + num8, false);
						root.Drain((float)num8);
					}
					num9 = 0f;
				}
				zdo.Set(ZDOVars.s_product, num9);
			}
			if (!flag)
			{
				return;
			}
			string text;
			if (state.HeldForRoot)
			{
				text = "discards it all, root not loaded on the extractor's first tick (trigger 1)";
			}
			else if (!Object.op_Implicit((Object)(object)root))
			{
				text = "discards it all, no root connected";
			}
			else if (num5 >= maxLevel)
			{
				text = "credits nothing, already full";
			}
			else if (!(num3 > 1f))
			{
				text = $"discards it all, root not regenerated yet at {num3:F1} (trigger 2)";
			}
			else
			{
				int num10 = Mathf.Min((int)num3, num7);
				int num11 = Mathf.Min(num10, maxLevel - num5);
				text = (((int)num3 < Mathf.Min(num7, maxLevel - num5)) ? $"credits {num11}, capped by a root not regenerated yet at {num3:F1} (trigger 2)" : $"credits {num11}");
				if (num10 > num11)
				{
					text += $" but drains the root by {num10} (trigger 3)";
				}
			}
			string text2 = ((!Object.op_Implicit((Object)(object)root)) ? "no root" : string.Format("root {0:F1} -> {1:F1} after regen{2}", num3, num4, flag2 ? "" : " (root owned by someone else, not regenerated here)"));
			string text3 = (state.HeldForRoot ? $", root appeared after {num2:F0} s" : "");
			Report($"{Where(collector)}: away {num:F0} s, worth {num7} at {secPerUnit:F0} s each{text3}. " + $"Vanilla {text}. Fix: {num5} -> {num5 + num8} of {maxLevel}, {text2}, drained {num8}.");
		}

		private static string Where(SapCollector collector)
		{
			//IL_0006: 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_0011: 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)
			Vector3 position = ((Component)collector).transform.position;
			return $"Sap extractor at ({position.x:F0}, {position.z:F0})";
		}

		private static void Report(string line)
		{
			if (SapExtractorProgressionFixMod.LogCatchUp.Value)
			{
				SapExtractorProgressionFixMod.Log.LogInfo((object)line);
			}
		}
	}
	[BepInPlugin("DeathMonger.SapExtractorProgressionFix", "Sap Extractor Progression Fix", "0.1.0")]
	[BepInProcess("valheim.exe")]
	public class SapExtractorProgressionFixMod : BaseUnityPlugin
	{
		public const string ModGuid = "DeathMonger.SapExtractorProgressionFix";

		public const string ModName = "Sap Extractor Progression Fix";

		public const string ModVersion = "0.1.0";

		internal static ConfigEntry<bool> ModEnabled;

		internal static ConfigEntry<bool> LogCatchUp;

		private Harmony _harmony;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Mod Enabled", true, "Master switch. Off leaves sap extractors exactly as the game runs them. Takes effect immediately.");
			LogCatchUp = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Log Catch Up", true, "Write a line to the BepInEx log each time you return to a sap extractor: how long you were away, what the unmodified game would have done with that time, and what was credited instead.");
			_harmony = new Harmony("DeathMonger.SapExtractorProgressionFix");
			_harmony.PatchAll();
			Log.LogInfo((object)"Sap Extractor Progression Fix 0.1.0 loaded.");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
}