Decompiled source of AutoTorch v1.0.0

AutoTorch.dll

Decompiled 3 hours ago
using System;
using System.Collections.Generic;
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;

[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("AutoTorch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+15e4995dbf71adc8fdf3a6851464c2e8bf6e0a92")]
[assembly: AssemblyProduct("AutoTorch")]
[assembly: AssemblyTitle("AutoTorch")]
[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 DarthJML.AutoTorch
{
	[BepInPlugin("com.darthjml.autotorch", "AutoTorch", "1.0.0")]
	public class AutoTorchPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.darthjml.autotorch";

		public const string PluginName = "AutoTorch";

		public const string PluginVersion = "1.0.0";

		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<bool> DebugLog;

		public static ConfigEntry<bool> WoodFires;

		public static ConfigEntry<bool> OnlyAtNight;

		public static ConfigEntry<bool> AlwaysLit;

		public static ConfigEntry<float> Radius;

		public static ConfigEntry<float> CheckSeconds;

		public static ConfigEntry<int> KeepInChest;

		public static ConfigEntry<string> NeverUse;

		internal static readonly List<Fireplace> Fires = new List<Fireplace>();

		internal static readonly List<Container> Containers = new List<Container>();

		private static readonly FieldRef<Fireplace, ZNetView> FireNView = AccessTools.FieldRefAccess<Fireplace, ZNetView>("m_nview");

		private static readonly FieldRef<Container, ZNetView> ContainerNView = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");

		private static readonly FieldRef<Container, uint> ContainerLastRevision = AccessTools.FieldRefAccess<Container, uint>("m_lastRevision");

		private static readonly Func<Container, long, bool> ContainerCheckAccess = AccessTools.MethodDelegate<Func<Container, long, bool>>(AccessTools.Method(typeof(Container), "CheckAccess", (Type[])null, (Type[])null), (object)null, true);

		private float _timer = 110f;

		private bool _errorLogged;

		private string _neverRaw;

		private HashSet<string> _never = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private readonly List<Container> _near = new List<Container>();

		private void Awake()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Keep fires fuelled from nearby chests.");
			Radius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Radius", 32f, new ConfigDescription("How far (meters) from each torch or fire to look for a chest with fuel. One floor tile = 2 m, so 32 m = 16 tiles.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 64f), Array.Empty<object>()));
			CheckSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "CheckSeconds", 120f, new ConfigDescription("Seconds between checks. Fires burn slowly, so a check every couple of minutes is plenty.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 600f), Array.Empty<object>()));
			OnlyAtNight = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RefuelOnlyAtNight", false, "Only top fires up while it is night. During the day they burn what they have and are not refilled.");
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Debug", false, "Write a log line for every refuel.");
			WoodFires = ((BaseUnityPlugin)this).Config.Bind<bool>("Fuel", "IncludeWoodFires", true, "Also feed fires that burn wood (campfire, hearth, bonfire, hot tub). Turn off to feed only torches, sconces and braziers.");
			KeepInChest = ((BaseUnityPlugin)this).Config.Bind<int>("Fuel", "KeepInChest", 1, new ConfigDescription("Always leave at least this many of the fuel item in each chest, so the chest still counts as the home for that item when sorting.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), Array.Empty<object>()));
			NeverUse = ((BaseUnityPlugin)this).Config.Bind<string>("Fuel", "NeverUseTheseItems", "", "Comma-separated fuel items that are never taken from chests, by in-game name or prefab name (for example: Coal, Guck).");
			AlwaysLit = ((BaseUnityPlugin)this).Config.Bind<bool>("Cheat", "AlwaysLitNoFuel", false, "Keep every fire full without using any fuel at all.");
			new Harmony("com.darthjml.autotorch").PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"AutoTorch v1.0.0 loaded.");
		}

		private void Update()
		{
			if (!Enabled.Value)
			{
				return;
			}
			_timer += Time.deltaTime;
			if (_timer < CheckSeconds.Value)
			{
				return;
			}
			_timer = 0f;
			try
			{
				Tick();
			}
			catch (Exception ex)
			{
				if (DebugLog.Value || !_errorLogged)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)ex);
				}
				_errorLogged = true;
			}
		}

		private static bool CanWrite(Container c)
		{
			if (!c.IsOwner() || c.IsInUse() || c.GetInventory() == null)
			{
				return false;
			}
			ZNetView val = ContainerNView.Invoke(c);
			if ((Object)(object)val != (Object)null && val.IsValid())
			{
				return ContainerLastRevision.Invoke(c) == val.GetZDO().DataRevision;
			}
			return false;
		}

		private bool Blocked(ItemDrop fuel)
		{
			if (NeverUse.Value != _neverRaw)
			{
				_neverRaw = NeverUse.Value;
				_never = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
				string[] array = (_neverRaw ?? "").Split(new char[1] { ',' });
				foreach (string text in array)
				{
					if (text.Trim().Length > 0)
					{
						_never.Add(text.Trim());
					}
				}
			}
			if (_never.Count == 0)
			{
				return false;
			}
			string name = fuel.m_itemData.m_shared.m_name;
			string item = ((Localization.instance != null) ? Localization.instance.Localize(name) : name);
			if (!_never.Contains(((Object)((Component)fuel).gameObject).name) && !_never.Contains(item))
			{
				return _never.Contains(name);
			}
			return true;
		}

		private void Tick()
		{
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (OnlyAtNight.Value && !AlwaysLit.Value && !EnvMan.IsNight()))
			{
				return;
			}
			Fires.RemoveAll((Fireplace f) => (Object)(object)f == (Object)null);
			Containers.RemoveAll((Container c) => (Object)(object)c == (Object)null);
			long playerID = localPlayer.GetPlayerID();
			float num = Radius.Value * Radius.Value;
			foreach (Fireplace fire in Fires)
			{
				ZNetView val = FireNView.Invoke(fire);
				if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner() || fire.m_infiniteFuel || !fire.m_canRefill || (Object)(object)fire.m_fuelItem == (Object)null)
				{
					continue;
				}
				float num2 = val.GetZDO().GetFloat(ZDOVars.s_fuel, 0f);
				int num3 = (int)fire.m_maxFuel - Mathf.CeilToInt(num2);
				if (num3 <= 0)
				{
					continue;
				}
				if (AlwaysLit.Value)
				{
					fire.SetFuel(fire.m_maxFuel);
					if (DebugLog.Value)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)("AutoTorch: " + ((Object)fire).name + " kept full (AlwaysLitNoFuel)"));
					}
					continue;
				}
				string name = fire.m_fuelItem.m_itemData.m_shared.m_name;
				if ((!WoodFires.Value && name == "$item_wood") || Blocked(fire.m_fuelItem))
				{
					continue;
				}
				Vector3 pos = ((Component)fire).transform.position;
				_near.Clear();
				foreach (Container container in Containers)
				{
					Vector3 val2 = ((Component)container).transform.position - pos;
					if (!(((Vector3)(ref val2)).sqrMagnitude > num) && CanWrite(container) && ContainerCheckAccess(container, playerID) && !((Object)(object)((Component)container).GetComponentInParent<TombStone>() != (Object)null) && container.GetInventory().CountItems(name, -1, true) > KeepInChest.Value)
					{
						_near.Add(container);
					}
				}
				if (_near.Count == 0)
				{
					continue;
				}
				_near.Sort(delegate(Container a, Container b)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: 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_0016: Unknown result type (might be due to invalid IL or missing references)
					//IL_0027: Unknown result type (might be due to invalid IL or missing references)
					//IL_002d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0032: Unknown result type (might be due to invalid IL or missing references)
					//IL_0037: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val3 = ((Component)a).transform.position - pos;
					float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
					val3 = ((Component)b).transform.position - pos;
					return sqrMagnitude.CompareTo(((Vector3)(ref val3)).sqrMagnitude);
				});
				foreach (Container item in _near)
				{
					if (num3 <= 0)
					{
						break;
					}
					Inventory inventory = item.GetInventory();
					int num4 = inventory.CountItems(name, -1, true);
					int num5 = Math.Min(num3, num4 - KeepInChest.Value);
					if (num5 > 0)
					{
						inventory.RemoveItem(name, num5, -1, true);
						int num6 = num4 - inventory.CountItems(name, -1, true);
						for (int num7 = 0; num7 < num6; num7++)
						{
							val.InvokeRPC("RPC_AddFuel", Array.Empty<object>());
						}
						num3 -= num6;
						if (DebugLog.Value && num6 > 0)
						{
							((BaseUnityPlugin)this).Logger.LogInfo((object)$"AutoTorch: {num6}x {name} from {((Object)item).name} -> {((Object)fire).name}");
						}
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(Fireplace), "Awake")]
	internal static class Fireplace_Awake_Patch
	{
		private static void Postfix(Fireplace __instance)
		{
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.GetZDO() != null)
			{
				AutoTorchPlugin.Fires.Add(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class Container_Awake_Patch
	{
		private static void Postfix(Container __instance)
		{
			if (__instance.GetInventory() != null)
			{
				AutoTorchPlugin.Containers.Add(__instance);
			}
		}
	}
}