Decompiled source of KALI Torch Refill v0.1.0

BepInEx/plugins/KALI_Torch_Refill/FinallyTorchRefill.dll

Decompiled 10 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using ServersideQoL.Processors;
using ServersideQoL.Utilities;
using UnityEngine;

[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("FinallyTorchRefill")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("FinallyTorchRefill")]
[assembly: AssemblyTitle("FinallyTorchRefill")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 ServersideQoL.FinallyTorchRefill
{
	[BepInPlugin("local.finally.torchrefill", "Finally Torch Refill", "0.1.0")]
	[BepInDependency("ArgusMagnus.ServersideQoL", "2.5.1")]
	public sealed class TorchRefillPlugin : ServersideQoLPluginBase<TorchRefillPlugin, TorchConfig>
	{
		protected override TorchConfig CreateConfigSingleton(ConfigFile cfg, Logger logger)
		{
			return new TorchConfig(cfg, logger);
		}

		protected override void RegisterProcessors(IProcessorCollection processors)
		{
			processors.Add<TorchProcessor>();
		}
	}
	public sealed class TorchConfig : ConfigBase<TorchConfig>
	{
		public override ConfigEntry<bool> Enabled { get; }

		public ConfigEntry<float> Range { get; }

		public ConfigEntry<int> LeaveAtLeast { get; }

		public ConfigEntry<float> CheckInterval { get; }

		public ConfigEntry<string> Fireplaces { get; }

		public ConfigEntry<bool> LogRefills { get; }

		public TorchConfig(ConfigFile cfg, Logger logger)
			: base(cfg, logger)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			Enabled = cfg.Bind<bool>("TorchRefill", "Enabled", true, "Refill selected player-built torches and braziers from nearby chests.");
			Range = cfg.Bind<float>("TorchRefill", "Range", 10f, new ConfigDescription("Chest-to-light distance in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			LeaveAtLeast = cfg.Bind<int>("TorchRefill", "LeaveAtLeast", 1, new ConfigDescription("Keep this many of the required fuel item in EACH source chest.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000), Array.Empty<object>()));
			CheckInterval = cfg.Bind<float>("TorchRefill", "CheckInterval", 5f, new ConfigDescription("Seconds between retries. Replicated changes may trigger an earlier check.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>()));
			Fireplaces = cfg.Bind<string>("TorchRefill", "Fireplaces", "piece_groundtorch_wood,piece_groundtorch,piece_groundtorch_green,piece_groundtorch_blue,piece_walltorch,piece_brazierfloor01,piece_brazierfloor02,piece_brazierceiling01", "Comma-separated prefab names. Campfires, hearths, smelters and cooking stations are excluded by default.");
			LogRefills = cfg.Bind<bool>("TorchRefill", "LogRefills", false, "Record successful transfers in the server log.");
		}
	}
	[Processor("b9519a30-ad12-49be-bbf7-1452a5b60698")]
	[DependsOn<ContainerRegistryProcessor>]
	[RunAfter<ContainerRegistryProcessor>]
	public sealed class TorchProcessor : Processor<ProcessorPrefabInfo<Fireplace>>
	{
		private HashSet<int> allowed = new HashSet<int>();

		private SectorDictionary<HashSet<ServersideQoLZDO>> containers;

		private static readonly HashSet<string> ChestPrefabs = new HashSet<string>(StringComparer.Ordinal) { "piece_chest_wood", "piece_chest", "piece_chest_blackmetal", "piece_chest_grausten", "piece_chest_barrel" };

		protected override void Initialize()
		{
			allowed = new HashSet<int>(from s in ConfigBase<TorchConfig>.Instance.Fireplaces.Value.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select StringExtensionMethods.GetStableHashCode(s));
			containers = Processor.Instance<ContainerRegistryProcessor>().GetContainers(ConfigBase<TorchConfig>.Instance.Range.Value);
			((Processor)this).Logger.LogInfo((object)$"Torch refill ready: {ConfigBase<TorchConfig>.Instance.Range.Value}m, leave {ConfigBase<TorchConfig>.Instance.LeaveAtLeast.Value} fuel per chest; selected torches/braziers only.");
		}

		protected override ProcessResult Process(ServersideQoLZDO fire, IReadOnlyList<Peer> peers, ProcessorPrefabInfo<Fireplace> info)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0512: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_0355: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Expected O, but got Unknown
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Expected O, but got Unknown
			//IL_041d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Expected O, but got Unknown
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Unknown result type (might be due to invalid IL or missing references)
			//IL_04db: Unknown result type (might be due to invalid IL or missing references)
			TorchConfig instance = ConfigBase<TorchConfig>.Instance;
			Fireplace component = info.Component;
			if (allowed.Contains(fire.ZDO.GetPrefab()))
			{
				ZDOVars vars = fire.Vars;
				PlayerID val = default(PlayerID);
				val = ((ZDOVars)(ref vars)).GetCreator(val);
				if (((PlayerID)(ref val)).Value != 0L && !((Object)(object)component.m_fuelItem == (Object)null) && component.m_canRefill && !component.m_infiniteFuel)
				{
					long num = fire.ZDO.GetLong(ZDOVars.s_lastTime, 0L);
					long ticks = ZNet.instance.GetTime().Ticks;
					if (num <= 0 || num > ticks || ticks - num > 100000000)
					{
						return ((Processor)this).ScheduleReprocessing(instance.CheckInterval.Value);
					}
					float num2 = fire.ZDO.GetFloat(ZDOVars.s_fuel, -1f);
					float num3 = fire.Fields<Fireplace>().GetFloat((Func<Expression<Func<Fireplace, float>>>)(() => (Fireplace x) => x.m_maxFuel), "C:\\Users\\Graham\\Documents\\Codex\\2026-09-24\\my-x20\\work\\torch-refill\\src\\FinallyTorchRefill.cs", 72);
					if (float.IsNaN(num2) || float.IsInfinity(num2) || num2 < 0f || num3 <= 0f || num2 > num3 / 2f)
					{
						return ((Processor)this).ScheduleReprocessing(instance.CheckInterval.Value);
					}
					int num4 = Mathf.FloorToInt(num3 - num2);
					if (num4 <= 0)
					{
						return ((Processor)this).ScheduleReprocessing(instance.CheckInterval.Value);
					}
					ContainerRegistryProcessor val2 = Processor.Instance<ContainerRegistryProcessor>();
					float num5 = instance.Range.Value * instance.Range.Value;
					List<ServersideQoLZDO> list = new List<ServersideQoLZDO>();
					AdjacentEnumerator<HashSet<ServersideQoLZDO>> enumerator = containers.EnumerateAdjacent(fire.ZDO.GetPosition()).GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							foreach (ServersideQoLZDO item in enumerator.Current)
							{
								Vector3 val3 = item.ZDO.GetPosition() - fire.ZDO.GetPosition();
								if (((Vector3)(ref val3)).sqrMagnitude <= num5)
								{
									list.Add(item);
								}
							}
						}
					}
					finally
					{
						((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
					}
					ServersideQoLZDO[] array = list.OrderBy(delegate(ServersideQoLZDO c)
					{
						//IL_0006: 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_001b: Unknown result type (might be due to invalid IL or missing references)
						//IL_0020: Unknown result type (might be due to invalid IL or missing references)
						Vector3 val7 = c.ZDO.GetPosition() - fire.ZDO.GetPosition();
						return ((Vector3)(ref val7)).sqrMagnitude;
					}).ToArray();
					foreach (ServersideQoLZDO val4 in array)
					{
						ContainerState state = val2.GetState(val4);
						if (state == null || !ChestPrefabs.Contains(((Object)((Component)state.Container).gameObject).name))
						{
							continue;
						}
						vars = val4.Vars;
						val = default(PlayerID);
						val = ((ZDOVars)(ref vars)).GetCreator(val);
						if (((PlayerID)(ref val)).Value == 0L)
						{
							continue;
						}
						vars = val4.Vars;
						if (((ZDOVars)(ref vars)).GetInUse(false) || (int)state.Container.m_privacy == 0)
						{
							continue;
						}
						byte[] byteArray = val4.ZDO.GetByteArray(ZDOVars.s_items, (byte[])null);
						if (byteArray == null || byteArray.Length == 0)
						{
							continue;
						}
						Inventory inventory = state.GetInventory().Inventory;
						Inventory val5 = new Inventory("Torch refill", (Sprite)null, inventory.GetWidth(), inventory.GetHeight());
						val5.Load(new ZPackage(byteArray));
						string fuel = component.m_fuelItem.m_itemData.m_shared.m_name;
						int num7 = (from i in val5.GetAllItems()
							where i.m_shared.m_name == fuel
							select i).Sum((ItemData i) => i.m_stack);
						int num8 = Math.Min(num4, Math.Max(0, num7 - instance.LeaveAtLeast.Value));
						if (num8 == 0)
						{
							continue;
						}
						if (!val4.IsOwnerOrUnassigned())
						{
							val = default(PlayerID);
							val2.RequestOwnership(val4, val);
							continue;
						}
						val5.RemoveItem(fuel, num8, -1, true);
						ZPackage val6 = new ZPackage();
						val5.Save(val6);
						fire.ReleaseOwnership();
						val4.ZDO.Set(ZDOVars.s_items, val6.GetArray());
						num2 += (float)num8;
						fire.ZDO.Set(ZDOVars.s_fuel, num2);
						num4 -= num8;
						if (instance.LogRefills.Value)
						{
							((Processor)this).Logger.LogInfo((object)$"Refilled {((Object)((Component)component).gameObject).name} {fire.ZDO.m_uid}: {num8} {((Object)component.m_fuelItem).name} from {val4.ZDO.m_uid}.");
						}
						if (num4 <= 0)
						{
							break;
						}
					}
					return ((Processor)this).ScheduleReprocessing(instance.CheckInterval.Value);
				}
			}
			return (ProcessResult)2;
		}
	}
}