Decompiled source of InfiniteEnergyButGood v0.1.0

InfiniteEnergyButGood.dll

Decompiled an hour ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[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("InfiniteEnergyButGood")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("InfiniteEnergyButGood")]
[assembly: AssemblyTitle("InfiniteEnergyButGood")]
[assembly: AssemblyVersion("1.0.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 InfiniteEnergyButGood
{
	[HarmonyPatch(typeof(ChargingStation), "ChargeAreaCheck")]
	internal static class ChargingStationPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ChargingStation __instance)
		{
			if ((Object)(object)Plugin.Instance != (Object)null)
			{
				Plugin.Instance.OnChargeAreaCheck(__instance);
			}
		}
	}
	[BepInPlugin("local.infiniteenergybutgood", "InfiniteEnergyButGood", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGuid = "local.infiniteenergybutgood";

		public const string ModName = "InfiniteEnergyButGood";

		public const string ModVersion = "1.0.0";

		private const float MaxChargeFloat = 1f;

		private const int MaxChargeTotal = 100;

		private const int MaxChargeInt = 6;

		private const float StationSearchTimeout = 120f;

		private ConfigEntry<bool> _enableLogs;

		private ConfigEntry<float> _resetInterval;

		private ConfigEntry<float> _removedDelay;

		private FieldRef<ChargingStation, float> _floatRef;

		private FieldRef<ChargingStation, int> _totalRef;

		private FieldRef<ChargingStation, int> _intRef;

		private bool _fieldsOk;

		private Harmony _harmony;

		private ChargingStation _station;

		private bool _levelPending;

		private float _levelPendingSince;

		private float _nextSearch;

		private bool _itemActive;

		private float _lastDrainTime;

		private float _lastResetTime;

		private float _lastFloat;

		private int _lastTotal;

		private bool _handlerErrorLogged;

		internal static Plugin Instance { get; private set; }

		private void Awake()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			Instance = this;
			((Component)this).transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			_enableLogs = ((BaseUnityPlugin)this).Config.Bind<bool>("Logging", "EnableLogMessages", true, "Show this mod's log messages (level loaded, item detected, item removed, errors).");
			_resetInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Timing", "ResetIntervalSeconds", 5f, new ConfigDescription("Minimum seconds between refills while an item is being charged.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>()));
			_removedDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Timing", "ItemRemovedDelaySeconds", 1f, new ConfigDescription("Seconds without energy drain before an item counts as removed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 10f), Array.Empty<object>()));
			ResolveFields();
			SceneManager.sceneLoaded += OnSceneLoaded;
			BeginLevelSearch();
			try
			{
				_harmony = new Harmony("local.infiniteenergybutgood");
				_harmony.PatchAll(typeof(ChargingStationPatch));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Patching ChargingStation failed: " + ex.Message));
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void ResolveFields()
		{
			try
			{
				_floatRef = AccessTools.FieldRefAccess<ChargingStation, float>("chargeFloat");
				_totalRef = AccessTools.FieldRefAccess<ChargingStation, int>("chargeTotal");
				_intRef = AccessTools.FieldRefAccess<ChargingStation, int>("chargeInt");
				_fieldsOk = true;
			}
			catch (Exception ex)
			{
				_fieldsOk = false;
				((BaseUnityPlugin)this).Logger.LogError((object)("ChargingStation fields not found: " + ex.Message));
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			BeginLevelSearch();
		}

		private void BeginLevelSearch()
		{
			_levelPending = true;
			_levelPendingSince = Time.realtimeSinceStartup;
			_nextSearch = 0f;
			_station = null;
			_itemActive = false;
		}

		private void Update()
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (_levelPending)
			{
				TrySearchStation(realtimeSinceStartup);
			}
			else if (_itemActive)
			{
				CheckItemRemoved(realtimeSinceStartup);
			}
		}

		private void TrySearchStation(float now)
		{
			if (now - _levelPendingSince > 120f)
			{
				_levelPending = false;
			}
			else
			{
				if (now < _nextSearch)
				{
					return;
				}
				_nextSearch = now + 1f;
				if (IsHost())
				{
					ChargingStation val = Object.FindObjectOfType<ChargingStation>();
					if ((Object)(object)val != (Object)null)
					{
						InitLevel(val, now);
					}
				}
			}
		}

		private void InitLevel(ChargingStation station, float now)
		{
			_levelPending = false;
			_station = station;
			_itemActive = false;
			if (TrySetMax(station, now))
			{
				Say("Level geladen - Energiespeicher max", isError: false);
			}
			else
			{
				Say("Level geladen - Fehler bei Energiespeicher", isError: true);
			}
		}

		internal void OnChargeAreaCheck(ChargingStation station)
		{
			if (!_fieldsOk || (Object)(object)station == (Object)null)
			{
				return;
			}
			try
			{
				if (!IsHost())
				{
					return;
				}
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				if (_levelPending)
				{
					InitLevel(station, realtimeSinceStartup);
					return;
				}
				if ((Object)(object)station != (Object)(object)_station)
				{
					_station = station;
					_itemActive = false;
					_lastFloat = _floatRef.Invoke(station);
					_lastTotal = _totalRef.Invoke(station);
					return;
				}
				float num = _floatRef.Invoke(station);
				int num2 = _totalRef.Invoke(station);
				bool num3 = num < _lastFloat - 1E-05f || num2 < _lastTotal;
				_lastFloat = num;
				_lastTotal = num2;
				if (!num3)
				{
					return;
				}
				_lastDrainTime = realtimeSinceStartup;
				if (!_itemActive)
				{
					_itemActive = true;
					if (TrySetMax(station, realtimeSinceStartup))
					{
						Say("Item erkannt - Energiespeicher max", isError: false);
					}
				}
				else if (realtimeSinceStartup - _lastResetTime >= _resetInterval.Value)
				{
					TrySetMax(station, realtimeSinceStartup);
				}
			}
			catch (Exception ex)
			{
				if (!_handlerErrorLogged)
				{
					_handlerErrorLogged = true;
					((BaseUnityPlugin)this).Logger.LogError((object)("Charge check failed: " + ex.Message));
				}
			}
		}

		private void CheckItemRemoved(float now)
		{
			if ((Object)(object)_station == (Object)null)
			{
				_itemActive = false;
			}
			else if (!(now - _lastDrainTime < _removedDelay.Value))
			{
				_itemActive = false;
				if (TrySetMax(_station, now))
				{
					Say("Item entfernt - Energiespeicher max", isError: false);
				}
				else
				{
					Say("Item entfernt - Fehler bei Energiespeicher", isError: true);
				}
			}
		}

		private bool TrySetMax(ChargingStation station, float now)
		{
			if (!_fieldsOk || (Object)(object)station == (Object)null)
			{
				return false;
			}
			try
			{
				_floatRef.Invoke(station) = 1f;
				_totalRef.Invoke(station) = 100;
				_intRef.Invoke(station) = 6;
				_lastFloat = 1f;
				_lastTotal = 100;
				_lastResetTime = now;
				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static bool IsHost()
		{
			try
			{
				return SemiFunc.IsMasterClientOrSingleplayer();
			}
			catch (Exception)
			{
				return false;
			}
		}

		private void Say(string message, bool isError)
		{
			if (_enableLogs.Value)
			{
				if (isError)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)message);
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)message);
				}
			}
		}
	}
}