Decompiled source of SakeysPlantGrowthFix v0.0.2

BepInEx/plugins/Sakey's Plant Growth Fix/SakeysPlantGrowthFix.dll

Decompiled 4 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("SakeysPlantGrowthFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("SakeysPlantGrowthFix")]
[assembly: AssemblyTitle("SakeysPlantGrowthFix")]
[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 Sakey.PlantGrowthFix
{
	[BepInPlugin("com.sakey.plantgrowthfix", "Sakey's Plant Growth Fix", "0.0.1")]
	public sealed class PlantGrowthFixPlugin : BaseUnityPlugin
	{
		private sealed class Entry
		{
			public Plant Plant;

			public ZNetView View;

			public int Id;

			public float LoadedAt;

			public float NextCheck;

			public bool Quarantined;
		}

		public const string PluginGuid = "com.sakey.plantgrowthfix";

		public const string PluginName = "Sakey's Plant Growth Fix";

		public const string PluginVersion = "0.0.1";

		private static PlantGrowthFixPlugin instance;

		private Harmony harmony;

		private ConfigEntry<bool> enabledFix;

		private ConfigEntry<bool> logRepairs;

		private ConfigEntry<int> graceSeconds;

		private ConfigEntry<int> checkSeconds;

		private ConfigEntry<int> batchSize;

		private MethodInfo elapsedMethod;

		private MethodInfo growTimeMethod;

		private MethodInfo healthMethod;

		private MethodInfo growMethod;

		private FieldInfo statusField;

		private object healthyStatus;

		private float nextTick;

		private float nextDiagnostic;

		private int inspected;

		private int overdue;

		private int unhealthy;

		private int attempts;

		private int deferred;

		private int settling;

		private int inactive;

		private int errors;

		private bool firstInspectionLogged;

		private bool worldWasReady;

		private ConfigEntry<bool> logDiagnostics;

		private ConfigEntry<bool> logDetails;

		private bool failed;

		private float nextWarning;

		private int recovered;

		private float nextSummary;

		private const float Tick = 0.25f;

		private const float LoadSettleSeconds = 5f;

		private const double BudgetMs = 2.0;

		private readonly Stopwatch budget = new Stopwatch();

		private readonly LinkedList<Entry> queue = new LinkedList<Entry>();

		private readonly Dictionary<int, LinkedListNode<Entry>> entries = new Dictionary<int, LinkedListNode<Entry>>();

		private static float Clock => Time.realtimeSinceStartup;

		private void Awake()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Expected O, but got Unknown
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Expected O, but got Unknown
			enabledFix = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable the stalled plant watchdog. No change to normal growth times or planting rules.");
			logRepairs = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogRepairs", true, "Log a summary of successful repairs (not every plant check).");
			graceSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("Advanced", "GraceSeconds", 60, new ConfigDescription("Minimum overdue WORLD seconds before a repair is attempted. Does not delay initial plant inspection or reset on native Grow calls.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(30, 600), Array.Empty<object>()));
			checkSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("Advanced", "CheckIntervalSeconds", 30, new ConfigDescription("Minimum interval between checks of the same plant.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 300), Array.Empty<object>()));
			batchSize = ((BaseUnityPlugin)this).Config.Bind<int>("Advanced", "PlantsPerTick", 8, new ConfigDescription("Maximum number of queued plants checked per 0.25 real-time seconds. A soft 2 ms budget also applies.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 32), Array.Empty<object>()));
			logDiagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogWatchdog", true, "Log watchdog activity every 30 real seconds while playing. No UI interaction required.");
			logDetails = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogRepairDetails", true, "Log plant name, elapsed growth percentage and overdue seconds for confirmed repairs.");
			instance = this;
			try
			{
				Type typeFromHandle = typeof(Plant);
				MethodInfo methodInfo = NeedMethod(typeFromHandle, "Awake", Type.EmptyTypes);
				elapsedMethod = NeedMethod(typeFromHandle, "TimeSincePlanted", Type.EmptyTypes);
				growTimeMethod = NeedMethod(typeFromHandle, "GetGrowTime", Type.EmptyTypes);
				healthMethod = NeedMethod(typeFromHandle, "UpdateHealth", new Type[1] { typeof(double) });
				growMethod = NeedMethod(typeFromHandle, "Grow", Type.EmptyTypes);
				statusField = AccessTools.Field(typeFromHandle, "m_status");
				if (statusField == null || !statusField.FieldType.IsEnum || !Enum.IsDefined(statusField.FieldType, "Healthy"))
				{
					throw new MissingFieldException(typeFromHandle.FullName, "m_status (Healthy)");
				}
				healthyStatus = Enum.Parse(statusField.FieldType, "Healthy");
				if ((elapsedMethod.ReturnType != typeof(double) && elapsedMethod.ReturnType != typeof(float)) || (growTimeMethod.ReturnType != typeof(double) && growTimeMethod.ReturnType != typeof(float)))
				{
					throw new InvalidOperationException("Unexpected plant timer signatures.");
				}
				harmony = new Harmony("com.sakey.plantgrowthfix");
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PlantGrowthFixPlugin), "AfterPlantAwake", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)NeedMethod(typeFromHandle, "Start", Type.EmptyTypes), (HarmonyMethod)null, new HarmonyMethod(typeof(PlantGrowthFixPlugin), "AfterPlantAwake", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				nextTick = Clock;
				nextDiagnostic = Clock + 30f;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Plant Growth Fix 0.1.2 ready. Plant timers and health rules remain unchanged.");
			}
			catch (Exception ex)
			{
				failed = true;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				((BaseUnityPlugin)this).Logger.LogError((object)("Plant Growth Fix disabled: incompatible API or patch failure. " + ex));
			}
		}

		private static MethodInfo NeedMethod(Type type, string name, Type[] args)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, args, (Type[])null);
			if (methodInfo == null || methodInfo.IsStatic)
			{
				throw new MissingMethodException(type.FullName, name);
			}
			return methodInfo;
		}

		private static void AfterPlantAwake(Plant __instance)
		{
			PlantGrowthFixPlugin plantGrowthFixPlugin = instance;
			if ((Object)(object)plantGrowthFixPlugin == (Object)null || plantGrowthFixPlugin.failed || !Object.op_Implicit((Object)(object)__instance))
			{
				return;
			}
			try
			{
				plantGrowthFixPlugin.Register(__instance);
			}
			catch (Exception ex)
			{
				plantGrowthFixPlugin.Warn(ex);
			}
		}

		private void Register(Plant plant)
		{
			ZNetView component = ((Component)plant).GetComponent<ZNetView>();
			if (!Object.op_Implicit((Object)(object)component) || !component.IsValid())
			{
				return;
			}
			int instanceID = ((Object)plant).GetInstanceID();
			if (entries.TryGetValue(instanceID, out var value))
			{
				if (value.Value.Plant == plant)
				{
					return;
				}
				Remove(value);
			}
			float clock = Clock;
			Entry value2 = new Entry
			{
				Plant = plant,
				View = component,
				Id = instanceID,
				LoadedAt = clock,
				NextCheck = clock + 5f
			};
			entries.Add(instanceID, queue.AddLast(value2));
		}

		private void Remove(LinkedListNode<Entry> node)
		{
			if (node.List != null)
			{
				queue.Remove(node);
				if (entries.TryGetValue(node.Value.Id, out var value) && value == node)
				{
					entries.Remove(node.Value.Id);
				}
			}
		}

		private void Update()
		{
			if (failed || enabledFix == null)
			{
				return;
			}
			float clock = Clock;
			if (clock < nextTick)
			{
				return;
			}
			nextTick = clock + 0.25f;
			try
			{
				bool flag = (Object)(object)ZNet.instance != (Object)null && (Object)(object)ZNetScene.instance != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null;
				if (flag && !worldWasReady)
				{
					firstInspectionLogged = false;
				}
				worldWasReady = flag;
				bool flag2 = enabledFix.Value && flag && Time.timeScale > 0f;
				if (flag2)
				{
					Step();
				}
				FlushSummary(force: false);
				if (!flag)
				{
					nextDiagnostic = clock + 30f;
				}
				else if (clock >= nextDiagnostic)
				{
					nextDiagnostic = clock + 30f;
					if (logDiagnostics.Value)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)("[PlantGrowthFix] Watchdog: enabled=" + enabledFix.Value + " running=" + flag2 + " timeScale=" + Time.timeScale + " tracked=" + queue.Count + " checked=" + inspected + " overdue=" + overdue + " unhealthy=" + unhealthy + " intervalDeferred=" + deferred + " loadSettling=" + settling + " inactiveOrNonOwner=" + inactive + " attempts=" + attempts + " errors=" + errors + " at=" + DateTime.Now.ToString("HH:mm:ss")));
					}
					inspected = (overdue = (unhealthy = (deferred = (settling = (inactive = (attempts = (errors = 0)))))));
				}
			}
			catch (Exception ex)
			{
				Warn(ex);
			}
		}

		private void Step()
		{
			float clock = Clock;
			int num = Math.Min(batchSize.Value, queue.Count);
			budget.Restart();
			for (int i = 0; i < num && (i == 0 || budget.Elapsed.TotalMilliseconds < 2.0); i++)
			{
				LinkedListNode<Entry> first = queue.First;
				if (first == null)
				{
					break;
				}
				Entry value = first.Value;
				queue.RemoveFirst();
				queue.AddLast(first);
				if (!Object.op_Implicit((Object)(object)value.Plant) || !Object.op_Implicit((Object)(object)value.View) || !value.View.IsValid())
				{
					Remove(first);
				}
				else
				{
					if (value.Quarantined)
					{
						continue;
					}
					if (clock - value.LoadedAt < 5f)
					{
						settling++;
						continue;
					}
					if (clock < value.NextCheck)
					{
						deferred++;
						continue;
					}
					if (!((Behaviour)value.Plant).isActiveAndEnabled || !value.View.IsOwner())
					{
						inactive++;
						value.NextCheck = clock + 5f;
						continue;
					}
					value.NextCheck = clock + (float)checkSeconds.Value;
					try
					{
						Inspect(value);
					}
					catch (Exception ex)
					{
						value.Quarantined = true;
						Warn(ex);
					}
				}
			}
			budget.Stop();
		}

		private void Inspect(Entry e)
		{
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			inspected++;
			Plant plant = e.Plant;
			if (!firstInspectionLogged)
			{
				firstInspectionLogged = true;
				if (logDiagnostics.Value)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("[PlantGrowthFix] First automatic check: at=" + DateTime.Now.ToString("HH:mm:ss") + " tracked=" + queue.Count + " loadedFor=" + (Clock - e.LoadedAt).ToString("F1", CultureInfo.InvariantCulture) + "s timeScale=" + Time.timeScale + " plant=" + ((Object)((Component)plant).gameObject).name));
				}
			}
			double num = Convert.ToDouble(elapsedMethod.Invoke(plant, null));
			double num2 = Convert.ToDouble(growTimeMethod.Invoke(plant, null));
			if (double.IsNaN(num) || double.IsInfinity(num) || double.IsNaN(num2) || double.IsInfinity(num2) || num2 <= 0.0 || num <= num2 + (double)graceSeconds.Value)
			{
				return;
			}
			overdue++;
			healthMethod.Invoke(plant, new object[1] { num });
			if (!Object.op_Implicit((Object)(object)plant) || !Object.op_Implicit((Object)(object)e.View) || !e.View.IsValid() || !e.View.IsOwner() || !((Behaviour)plant).isActiveAndEnabled || !object.Equals(statusField.GetValue(plant), healthyStatus))
			{
				unhealthy++;
				return;
			}
			num = Convert.ToDouble(elapsedMethod.Invoke(plant, null));
			num2 = Convert.ToDouble(growTimeMethod.Invoke(plant, null));
			if (double.IsNaN(num) || double.IsInfinity(num) || double.IsNaN(num2) || double.IsInfinity(num2) || num2 <= 0.0 || num <= num2 + (double)graceSeconds.Value)
			{
				return;
			}
			string name = ((Object)((Component)plant).gameObject).name;
			attempts++;
			object obj = growMethod.Invoke(plant, null);
			if (obj is GameObject && Object.op_Implicit((Object)(GameObject)obj))
			{
				recovered++;
				if (logDetails.Value)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("[PlantGrowthFix] Recovered: " + name + " growth=" + (num / num2 * 100.0).ToString("F1", CultureInfo.InvariantCulture) + "% overdue=" + (num - num2).ToString("F0", CultureInfo.InvariantCulture) + "s loadedFor=" + (Clock - e.LoadedAt).ToString("F1", CultureInfo.InvariantCulture) + "s at=" + DateTime.Now.ToString("HH:mm:ss")));
				}
				RemoveIfCurrent(e);
				if (recovered == 1)
				{
					nextSummary = Clock + 5f;
				}
			}
		}

		private void RemoveIfCurrent(Entry e)
		{
			if (entries.TryGetValue(e.Id, out var value) && value.Value == e)
			{
				Remove(value);
			}
		}

		private void FlushSummary(bool force)
		{
			if (recovered != 0 && (force || !(Clock < nextSummary)))
			{
				if (logRepairs.Value)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("[PlantGrowthFix] Recovered plants: " + recovered));
				}
				recovered = 0;
			}
		}

		private void Warn(Exception ex)
		{
			errors++;
			if (!(Clock < nextWarning))
			{
				nextWarning = Clock + 30f;
				((BaseUnityPlugin)this).Logger.LogWarning((object)("[PlantGrowthFix] Watchdog error (affected instance skipped if applicable): " + ex));
			}
		}

		private void OnDestroy()
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			if (logRepairs != null)
			{
				FlushSummary(force: true);
			}
			queue.Clear();
			entries.Clear();
			if (instance == this)
			{
				instance = null;
			}
		}
	}
}