Decompiled source of WeedKillerAdjuster v1.0.1

WeedKillerAdjuster.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using OniroDev.patch;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using WeedKillerAdjuster.NetcodePatcher;

[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.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("WeedKillerAdjuster")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0-alpha.0")]
[assembly: AssemblyProduct("WeedKillerAdjuster")]
[assembly: AssemblyTitle("WeedKillerAdjuster")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 OniroDev
{
	[BepInPlugin("WeedKillerAdjuster", "WeedKillerAdjuster", "1.0.0")]
	public class WeedKillerAdjusterBase : BaseUnityPlugin
	{
		internal static bool IsSynced;

		private readonly Harmony _harmony = new Harmony("WeedKillerAdjuster");

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static WeedKillerAdjusterBase Instance { get; set; }

		internal static WeedKillerConfig BoundConfig { get; private set; }

		public WeedKillerAdjusterBase()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			Instance = this;
		}

		private void Awake()
		{
			WeedKillerAdjusterLogger.Initialize("WeedKillerAdjuster");
			WeedKillerAdjusterLogger.Log("WEEDKILLERADJUSTER MOD STARTING UP WeedKillerAdjuster");
			BoundConfig = new WeedKillerConfig(((BaseUnityPlugin)this).Config);
			WeedKillerAdjusterLogger.Log("Applying patches...");
			ApplyPluginPatch();
			WeedKillerAdjusterLogger.Log("Patches applied");
		}

		private void ApplyPluginPatch()
		{
			_harmony.PatchAll(typeof(WeedKillerAdjusterBase));
			_harmony.PatchAll(typeof(WeedKillerPatch));
			_harmony.PatchAll(typeof(WeedKillerConfig));
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; private set; }

		public static T Instance { get; private set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
			IntSize = 4;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				WeedKillerAdjusterLogger.LogError($"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				WeedKillerAdjusterLogger.LogError($"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	public static class WeedKillerAdjusterLogger
	{
		internal static ManualLogSource logSource;

		public static void Initialize(string pluginGUID)
		{
			logSource = Logger.CreateLogSource(pluginGUID);
		}

		public static void Log(object message)
		{
			logSource.LogInfo(message);
		}

		public static void LogError(object message)
		{
			logSource.LogError(message);
		}

		public static void LogWarning(object message)
		{
			logSource.LogWarning(message);
		}
	}
	[Serializable]
	internal class WeedKillerConfig : SyncedInstance<WeedKillerConfig>
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequestSync;

			public static HandleNamedMessageDelegate <1>__OnReceiveSync;
		}

		public const float DEFAULT_KILL_RATE = 1f;

		public const bool DEFAULT_CHARGING = false;

		public static ConfigEntry<float> weedKillRate;

		public static ConfigEntry<float> weedKillTank;

		public static ConfigEntry<bool> usesBattery;

		public WeedKillerConfig(ConfigFile configFile)
		{
			InitInstance(this);
			configFile.SaveOnConfigSet = false;
			weedKillRate = configFile.Bind<float>("Weed Killer Settings", "Vain Shroud Kill Rate", 1f, "Adjust the kill rate at which Vain Shrouds will die.\nIf you change the rate to 7, they will die 7 times faster than normal.");
			WeedKillerAdjusterLogger.Log($"weedKillRate; VALUE LOAD FROM CONFIG: {weedKillRate.Value}");
			weedKillTank = configFile.Bind<float>("Weed Killer Settings", "Weed Killer Base Fuel Tank", 1f, "Adjust the fuel capacity of the Weed Killer spray bottle\nIf you change the rate to 7, they will contain 7 times more spray fuel than normal.");
			WeedKillerAdjusterLogger.Log($"weedKillTank; VALUE LOAD FROM CONFIG: {weedKillTank.Value}");
			usesBattery = configFile.Bind<bool>("Weed Killer Settings", "Use battery charges", false, "Enables the Weed Killer spray bottle to use batteries and be rechargeable in the company ship\nIf set to TRUE, the value for the Weed Killer Base Fuel Tank is ignored");
			WeedKillerAdjusterLogger.Log($"usesBattery; VALUE LOAD FROM CONFIG: {usesBattery.Value}");
			ClearOrphanedEntries(configFile);
			configFile.Save();
			configFile.SaveOnConfigSet = true;
		}

		private static void ClearOrphanedEntries(ConfigFile configFile)
		{
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ConfigFile), "OrphanedEntries");
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)propertyInfo.GetValue(configFile);
			dictionary.Clear();
		}

		public static void RequestSync()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<WeedKillerConfig>.IsClient)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(SyncedInstance<WeedKillerConfig>.IntSize, (Allocator)2, -1);
			try
			{
				SyncedInstance<WeedKillerConfig>.MessageManager.SendNamedMessage("WeedKillerAdjuster_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<WeedKillerConfig>.IsHost)
			{
				return;
			}
			WeedKillerAdjusterLogger.Log($"Config sync request received from client: {clientId}");
			byte[] array = SyncedInstance<WeedKillerConfig>.SerializeToBytes(SyncedInstance<WeedKillerConfig>.Instance);
			int num = array.Length;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<WeedKillerConfig>.IntSize, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				SyncedInstance<WeedKillerConfig>.MessageManager.SendNamedMessage("WeedKillerAdjuster_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				WeedKillerAdjusterLogger.Log($"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<WeedKillerConfig>.IntSize))
			{
				WeedKillerAdjusterLogger.LogError("Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				WeedKillerAdjusterLogger.LogError("Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<WeedKillerConfig>.SyncInstance(data);
			WeedKillerAdjusterLogger.Log("Successfully synced config with host.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		public static void InitializeLocalPlayer()
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if (SyncedInstance<WeedKillerConfig>.IsHost)
			{
				CustomMessagingManager messageManager = SyncedInstance<WeedKillerConfig>.MessageManager;
				object obj = <>O.<0>__OnRequestSync;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnRequestSync;
					<>O.<0>__OnRequestSync = val;
					obj = (object)val;
				}
				messageManager.RegisterNamedMessageHandler("WeedKillerAdjuster_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
				SyncedInstance<WeedKillerConfig>.Synced = true;
				return;
			}
			SyncedInstance<WeedKillerConfig>.Synced = false;
			CustomMessagingManager messageManager2 = SyncedInstance<WeedKillerConfig>.MessageManager;
			object obj2 = <>O.<1>__OnReceiveSync;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = OnReceiveSync;
				<>O.<1>__OnReceiveSync = val2;
				obj2 = (object)val2;
			}
			messageManager2.RegisterNamedMessageHandler("WeedKillerAdjuster_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
			RequestSync();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<WeedKillerConfig>.RevertSync();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "WeedKillerAdjuster";

		public const string PLUGIN_NAME = "WeedKillerAdjuster";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace OniroDev.patch
{
	[HarmonyPatch(typeof(SprayPaintItem))]
	public class WeedKillerPatch
	{
		private static FieldRef<SprayPaintItem, float> sprayPaintTank = AccessTools.FieldRefAccess<SprayPaintItem, float>("sprayCanTank");

		private static float tempCanTank;

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void WeedKillerKillRatePatch(ref float ___killWeedSpeed)
		{
			WeedKillerAdjusterLogger.Log($"weedkillerKillRatePatch: {WeedKillerConfig.weedKillRate.Value}");
			___killWeedSpeed *= WeedKillerConfig.weedKillRate.Value;
		}

		[HarmonyPatch(typeof(GrabbableObject), "ChargeBatteries")]
		[HarmonyPrefix]
		private static void WeedKillerChargeBatteries(GrabbableObject __instance)
		{
			WeedKillerAdjusterLogger.Log($"__instance: {__instance}");
			SprayPaintItem val = (SprayPaintItem)(object)((__instance is SprayPaintItem) ? __instance : null);
			if (val != null && val.isWeedKillerSprayBottle && WeedKillerConfig.usesBattery.Value)
			{
				sprayPaintTank.Invoke(val) = ((GrabbableObject)val).insertedBattery.charge;
			}
		}

		[HarmonyPatch(typeof(SprayPaintItem), "Start")]
		[HarmonyPostfix]
		private static void Start(SprayPaintItem __instance)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			if (__instance.isWeedKillerSprayBottle && WeedKillerConfig.usesBattery.Value)
			{
				((GrabbableObject)__instance).insertedBattery = new Battery(false, sprayPaintTank.Invoke(__instance));
				((GrabbableObject)__instance).itemProperties.requiresBattery = true;
			}
		}

		[HarmonyPatch(typeof(SprayPaintItem), "LateUpdate")]
		[HarmonyPrefix]
		private static void PreWeedKillerLateUpdate(SprayPaintItem __instance)
		{
			if (__instance.isWeedKillerSprayBottle)
			{
				tempCanTank = sprayPaintTank.Invoke(__instance);
			}
		}

		[HarmonyPatch(typeof(SprayPaintItem), "LateUpdate")]
		[HarmonyPostfix]
		private static void PostWeedKillerLateUpdate(SprayPaintItem __instance, ref bool ___isSpraying)
		{
			if (__instance.isWeedKillerSprayBottle)
			{
				if (((GrabbableObject)__instance).isHeld & ___isSpraying)
				{
					sprayPaintTank.Invoke(__instance) = Mathf.Max(tempCanTank - Time.deltaTime / (15f * WeedKillerConfig.weedKillTank.Value), 0f);
				}
				if (WeedKillerConfig.usesBattery.Value)
				{
					((GrabbableObject)__instance).insertedBattery.charge = sprayPaintTank.Invoke(__instance);
				}
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace WeedKillerAdjuster.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}