Decompiled source of CoglingReimagined v0.1.2

plugins/CoglingReimagined.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
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("CoglingReimagined")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Independent automatic machine-loading extension for Cogling.")]
[assembly: AssemblyFileVersion("0.1.2.0")]
[assembly: AssemblyInformationalVersion("0.1.2+a43828f8be0e4ae002fdc3f83a01dabb0447ceb1")]
[assembly: AssemblyProduct("CoglingReimagined")]
[assembly: AssemblyTitle("CoglingReimagined")]
[assembly: AssemblyVersion("0.1.2.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 CoglingReimagined
{
	internal static class AntennaCall
	{
		public static IEnumerable<CodeInstruction> FixLandingHeight(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo original = AccessTools.Method(typeof(ZoneSystem), "GetSolidHeight", new Type[3]
			{
				typeof(Vector3),
				typeof(float).MakeByRefType(),
				typeof(int)
			}, (Type[])null);
			MethodInfo replacement = AccessTools.Method(typeof(AntennaCall), "TryGetLandingHeight", (Type[])null, (Type[])null);
			int replacements = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, original))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = replacement;
					replacements++;
				}
				yield return instruction;
			}
			if (replacements != 1)
			{
				throw new NotSupportedException("Cogling's antenna height lookup changed.");
			}
		}

		private static bool TryGetLandingHeight(ZoneSystem zone, Vector3 spot, out float height, int originalOffset)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			Rules? activeRules = Plugin.ActiveRules;
			if (activeRules == null || !activeRules.Enabled)
			{
				return zone.GetSolidHeight(spot, ref height, originalOffset);
			}
			Vector3 val = spot + Vector3.up * 0.5f;
			if (zone.GetSolidHeight(val, ref height, 0))
			{
				return spot.y - height <= 1.5f;
			}
			return false;
		}

		public static void BeforeGathered(BaseAI __instance)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CoglingBridge bridge = Plugin.Bridge;
				if (bridge.HasGathered(__instance))
				{
					return;
				}
				Rules? activeRules = Plugin.ActiveRules;
				if (activeRules == null || !activeRules.Enabled)
				{
					return;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
				{
					return;
				}
				Vector3 position = bridge.CallSpot(__instance);
				Rigidbody component2 = ((Component)__instance).GetComponent<Rigidbody>();
				__instance.StopMoving();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.position = position;
					if (!component2.isKinematic)
					{
						component2.linearVelocity = Vector3.zero;
						component2.angularVelocity = Vector3.zero;
					}
				}
				((Component)__instance).transform.position = position;
				ZSyncTransform component3 = ((Component)__instance).GetComponent<ZSyncTransform>();
				if ((Object)(object)component3 != (Object)null)
				{
					component3.SyncNow();
				}
				else
				{
					component.GetZDO().SetPosition(position);
				}
			}
			catch (Exception error)
			{
				Plugin.Report(error);
			}
		}
	}
	internal sealed class DeliveryAttempt
	{
		internal const float TimeoutSeconds = 30f;

		private readonly float _startedAt;

		private bool _retried;

		internal DeliveryAttempt(float now)
		{
			_startedAt = now;
		}

		internal bool Expired(float now)
		{
			return now - _startedAt >= 30f;
		}

		internal bool TryReroute(float now)
		{
			if (_retried || Expired(now))
			{
				return false;
			}
			_retried = true;
			return true;
		}
	}
	internal static class ChestDelivery
	{
		private static readonly ConditionalWeakTable<object, DeliveryAttempt> Attempts = new ConditionalWeakTable<object, DeliveryAttempt>();

		public static bool BeforeStep(object __instance, ref object? __result)
		{
			if (!Track(__instance))
			{
				return true;
			}
			float now = Time.time;
			if (!Attempts.GetValue(__instance, (object _) => new DeliveryAttempt(now)).Expired(now))
			{
				return true;
			}
			return Stop(__instance, "extension: chest delivery timed out", ref __result);
		}

		public static bool BeforeReroute(object __instance, string __0, ref object? __result)
		{
			if (!Track(__instance))
			{
				return true;
			}
			float now = Time.time;
			if (Attempts.GetValue(__instance, (object _) => new DeliveryAttempt(now)).TryReroute(now))
			{
				return true;
			}
			return Stop(__instance, "extension: chest delivery ended after reroute failure: " + __0, ref __result);
		}

		public static void Reset(object __instance)
		{
			Attempts.Remove(__instance);
		}

		private static bool Track(object job)
		{
			if (Plugin.Bridge.IsDeliveringToChest(job))
			{
				Rules? activeRules = Plugin.ActiveRules;
				if (activeRules != null && activeRules.Enabled)
				{
					return true;
				}
			}
			Reset(job);
			return false;
		}

		private static bool Stop(object job, string reason, ref object? result)
		{
			try
			{
				result = Plugin.Bridge.EndDelivery(job, reason);
				return false;
			}
			catch (Exception error)
			{
				Plugin.Report(error);
				return true;
			}
		}
	}
	internal sealed class CoglingBridge
	{
		private readonly Type _feed;

		private readonly MethodInfo _area;

		private readonly MethodInfo _stored;

		private readonly MethodInfo _mayUse;

		private readonly MethodInfo _finish;

		private readonly FieldInfo _enabled;

		private readonly FieldInfo _claims;

		private readonly FieldInfo _jobFeed;

		private readonly FieldInfo _jobNetwork;

		private readonly FieldInfo _source;

		private readonly FieldInfo _count;

		private readonly FieldInfo _phase;

		private readonly FieldInfo _until;

		private readonly MethodInfo _jobZdo;

		private readonly MethodInfo _readCarried;

		private readonly MethodInfo _putDown;

		private readonly object _toChest;

		private readonly object _opening;

		private readonly FieldInfo _callSpot;

		private readonly FieldInfo _gathered;

		private readonly Dictionary<string, FieldInfo> _fields = new Dictionary<string, FieldInfo>();

		internal readonly MethodInfo Next;

		internal readonly MethodInfo StillWanted;

		internal readonly MethodInfo Step;

		internal readonly MethodInfo Reroute;

		internal readonly MethodInfo Abandon;

		internal readonly MethodInfo Called;

		internal readonly MethodInfo Gathered;

		internal bool TendingEnabled => ((ConfigEntry<bool>)_enabled.GetValue(null)).Value;

		internal CoglingBridge()
		{
			PluginInfo val = Chainloader.PluginInfos["nick.Cogling"];
			if (val.Metadata.Version != new Version(1, 0, 0))
			{
				throw new NotSupportedException("This build supports Cogling 1.0.0 only. A newer version needs compatibility verification.");
			}
			Assembly assembly = ((object)val.Instance).GetType().Assembly;
			Type type = Type("Tending");
			Type type2 = Type("CoglingJob");
			_feed = type.GetNestedType("Feed", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new TypeLoadException("Cogling.Tending.Feed missing");
			Next = Method(type, "Next");
			StillWanted = Method(type, "StillWanted");
			Step = Method(type2, "Step");
			_area = Method(Type("Antenna"), "InArea");
			_stored = Method(Type("Chests"), "Stored");
			_mayUse = Method(Type("ContainerAccess"), "MayUse");
			_enabled = Field(Type("Plugin"), "TendSmelters");
			_claims = Field(type, "Claimed");
			_jobFeed = Field(type2, "_feed");
			_jobNetwork = Field(type2, "_network");
			_source = Field(type2, "_source");
			_count = Field(type2, "_takeCount");
			_phase = Field(type2, "_phase");
			_until = Field(type2, "_until");
			_finish = Method(type2, "Finish");
			Reroute = Method(type2, "Reroute");
			Abandon = Method(type2, "Abandon");
			_jobZdo = Method(type2, "get_Zdo");
			_readCarried = Method(Type("Carried"), "Read");
			_putDown = Method(type2, "PutDown");
			_toChest = Enum.Parse(_phase.FieldType, "ToChest");
			_opening = Enum.Parse(_phase.FieldType, "Opening");
			Type type3 = Type("CoglingAI");
			Called = Method(type3, "Called");
			Gathered = Method(type3, "Gathered");
			_callSpot = Field(type3, "_callSpot");
			_gathered = Field(type3, "_gathered");
			if (Gathered.ReturnType != typeof(void) || Gathered.GetParameters().Length != 1 || _callSpot.FieldType != typeof(Vector3) || _gathered.FieldType != typeof(bool))
			{
				throw new NotSupportedException("Cogling antenna call signatures changed.");
			}
			string[] array = new string[8] { "Station", "View", "Item", "Wants", "Ore", "Chest", "Stack", "Makes" };
			foreach (string text in array)
			{
				_fields.Add(text, Field(_feed, text));
			}
			if (Next.ReturnType != _feed || Next.GetParameters().Length != 3 || Step.GetParameters().Length != 1 || !Step.ReturnType.IsEnum)
			{
				throw new NotSupportedException("Cogling method signatures changed.");
			}
			static FieldInfo Field(Type type4, string name)
			{
				return type4.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingFieldException(type4.FullName, name);
			}
			static MethodInfo Method(Type type4, string name)
			{
				return type4.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingMethodException(type4.FullName, name);
			}
			Type Type(string name)
			{
				return assembly.GetType("Cogling." + name, throwOnError: true);
			}
		}

		internal bool Claimed(Smelter station)
		{
			return ((HashSet<int>)_claims.GetValue(null)).Contains(((Object)station).GetInstanceID());
		}

		internal bool InArea(object network, Vector3 position)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return (bool)_area.Invoke(null, new object[2] { network, position });
		}

		internal List<Container> Stored(object network)
		{
			return (List<Container>)_stored.Invoke(null, new object[1] { network });
		}

		internal bool MayUse(Container chest)
		{
			return (bool)_mayUse.Invoke(null, new object[1] { chest });
		}

		internal object? JobFeed(object job)
		{
			return _jobFeed.GetValue(job);
		}

		internal object JobNetwork(object job)
		{
			return _jobNetwork.GetValue(job);
		}

		internal Container? JobSource(object job)
		{
			object? value = _source.GetValue(job);
			return (Container?)((value is Container) ? value : null);
		}

		internal int TakeCount(object job)
		{
			return (int)_count.GetValue(job);
		}

		internal void SetTakeCount(object job, int count)
		{
			_count.SetValue(job, count);
		}

		internal bool IsTakingNow(object job)
		{
			if (_phase.GetValue(job).ToString() == "Taking")
			{
				return Time.time >= (float)_until.GetValue(job);
			}
			return false;
		}

		internal object CancelBeforeTaking(object job)
		{
			return _finish.Invoke(job, new object[1] { "extension: supplies reserved or job no longer needed" });
		}

		internal bool IsDeliveringToChest(object job)
		{
			object value = _phase.GetValue(job);
			if (!_toChest.Equals(value))
			{
				return _opening.Equals(value);
			}
			return true;
		}

		internal object EndDelivery(object job, string reason)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			ItemData val = (ItemData)_readCarried.Invoke(null, new object[1] { _jobZdo.Invoke(job, null) });
			if (val != null)
			{
				_putDown.Invoke(job, new object[1] { val });
			}
			return _finish.Invoke(job, new object[1] { reason });
		}

		internal bool HasGathered(BaseAI ai)
		{
			return (bool)_gathered.GetValue(ai);
		}

		internal Vector3 CallSpot(BaseAI ai)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return (Vector3)_callSpot.GetValue(ai);
		}

		internal Smelter? Station(object feed)
		{
			object? value = _fields["Station"].GetValue(feed);
			return (Smelter?)((value is Smelter) ? value : null);
		}

		internal object CreateFeed(Smelter station, Container chest, ItemData stack, string item, int wants, bool ore)
		{
			object feed = Activator.CreateInstance(_feed, nonPublic: true);
			Set("Station", station);
			Set("View", ((Component)station).GetComponent<ZNetView>());
			Set("Item", item);
			Set("Wants", wants);
			Set("Ore", ore);
			Set("Chest", chest);
			Set("Stack", stack);
			return feed;
			void Set(string name, object value)
			{
				_fields[name].SetValue(feed, value);
			}
		}
	}
	internal static class LoadingPolicy
	{
		internal static int Available(int stored, int reserve)
		{
			return (int)Math.Max(0L, (long)stored - (long)Math.Max(0, reserve));
		}

		internal static int KilnLoad(int storedWood, int reserve, int storedCoal, int queuedCoal, int target, int room)
		{
			long val = Math.Max(0L, (long)target - (long)storedCoal - queuedCoal);
			return (int)Math.Min(Math.Max(0, room), Math.Min(Available(storedWood, reserve), val));
		}

		internal static string? ChooseInput(IEnumerable<string> accepted, IEnumerable<string> queued, Func<string, int> stock)
		{
			HashSet<string> hashSet = new HashSet<string>(accepted, StringComparer.Ordinal);
			IGrouping<string, string> grouping = (from x in queued.Where(hashSet.Contains)
				group x by x into g
				orderby g.Count() descending
				select g).FirstOrDefault();
			if (grouping == null)
			{
				return hashSet.Where((string x) => stock(x) > 0).OrderByDescending(stock).ThenBy<string, string>((string x) => x, StringComparer.Ordinal)
					.FirstOrDefault();
			}
			if (stock(grouping.Key) <= 0)
			{
				return null;
			}
			return grouping.Key;
		}
	}
	internal sealed class FeedContext
	{
		internal readonly Smelter Station;

		internal readonly string Item;

		internal readonly bool Input;

		internal readonly bool Kiln;

		internal FeedContext(Smelter station, string item, bool input, bool kiln)
		{
			Station = station;
			Item = item;
			Input = input;
			Kiln = kiln;
		}
	}
	internal static class MachineJobs
	{
		internal static readonly ConditionalWeakTable<object, FeedContext> Contexts = new ConditionalWeakTable<object, FeedContext>();

		private static bool IsKiln(Smelter station)
		{
			return Utils.GetPrefabName(((Component)station).gameObject) == "charcoal_kiln";
		}

		internal static bool Managed(Smelter station, Rules rules)
		{
			string prefabName = Utils.GetPrefabName(((Component)station).gameObject);
			if (!(prefabName == "charcoal_kiln"))
			{
				if (rules.Smelters)
				{
					if (!(prefabName == "smelter"))
					{
						return prefabName == "blastfurnace";
					}
					return true;
				}
				return false;
			}
			return rules.Kilns;
		}

		internal static List<Container> Supplies(object network)
		{
			return (from c in Plugin.Bridge.Stored(network)
				where (Object)(object)c != (Object)null && c.GetInventory() != null && Plugin.Bridge.MayUse(c)
				select c).ToList();
		}

		internal static int Stock(IEnumerable<Container> chests, string prefab)
		{
			long val = (from i in chests.SelectMany((Container c) => c.GetInventory().GetAllItems())
				where (Object)(object)i.m_dropPrefab != (Object)null && ((Object)i.m_dropPrefab).name == prefab && i.m_stack > 0
				select i).Sum((Func<ItemData, long>)((ItemData i) => i.m_stack));
			return (int)Math.Min(2147483647L, val);
		}

		private static IEnumerable<Smelter> Machines(object network)
		{
			return Object.FindObjectsByType<Smelter>((FindObjectsSortMode)0).Where(delegate(Smelter s)
			{
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)s != (Object)null)
				{
					ZNetView component = ((Component)s).GetComponent<ZNetView>();
					if (component != null && component.IsValid())
					{
						return Plugin.Bridge.InArea(network, ((Component)s).transform.position);
					}
				}
				return false;
			});
		}

		private static int QueuedCoal(IEnumerable<Smelter> machines)
		{
			return machines.Where(IsKiln).Sum((Smelter s) => Math.Max(0, ((Component)s).GetComponent<ZNetView>().GetZDO().GetInt(ZDOVars.s_queued, 0)));
		}

		internal static int Budget(FeedContext context, object network, Rules rules)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (!rules.Enabled || (Object)(object)context.Station == (Object)null || !Managed(context.Station, rules) || !Plugin.Bridge.TendingEnabled)
			{
				return 0;
			}
			ZNetView component = ((Component)context.Station).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !Plugin.Bridge.InArea(network, ((Component)context.Station).transform.position))
			{
				return 0;
			}
			if (!context.Kiln)
			{
				return int.MaxValue;
			}
			if (!rules.Woods.Contains(context.Item))
			{
				return 0;
			}
			List<Container> chests = Supplies(network);
			return LoadingPolicy.KilnLoad(Stock(chests, context.Item), rules.Reserve, Stock(chests, "Coal"), QueuedCoal(Machines(network)), rules.CoalTarget, context.Station.m_maxOre - component.GetZDO().GetInt(ZDOVars.s_queued, 0));
		}

		internal static bool ContinueFeeding(FeedContext context, object network, Rules rules)
		{
			if (!rules.Enabled || (Object)(object)context.Station == (Object)null || !Managed(context.Station, rules) || !Plugin.Bridge.TendingEnabled)
			{
				return false;
			}
			if (!context.Kiln)
			{
				return true;
			}
			if (!rules.Woods.Contains(context.Item))
			{
				return false;
			}
			return (long)Stock(Supplies(network), "Coal") + (long)QueuedCoal(Machines(network)) < rules.CoalTarget;
		}

		internal static object? Find(object network, Vector3 from, List<Container> usable, Rules rules)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			List<Smelter> list = Machines(network).ToList();
			List<Container> chests = Supplies(network);
			int storedCoal = Stock(chests, "Coal");
			int queuedCoal = QueuedCoal(list);
			foreach (Smelter item in list.Where((Smelter s) => Managed(s, rules)).OrderBy(delegate(Smelter s)
			{
				//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)
				Vector3 val = ((Component)s).transform.position - from;
				return ((Vector3)(ref val)).sqrMagnitude;
			}))
			{
				if (Plugin.Bridge.Claimed(item))
				{
					continue;
				}
				ZDO zdo = ((Component)item).GetComponent<ZNetView>().GetZDO();
				int num = Math.Max(0, zdo.GetInt(ZDOVars.s_queued, 0));
				bool kiln = IsKiln(item);
				string text = LoadingPolicy.ChooseInput((from c in item.m_conversion
					where (Object)(object)c?.m_from != (Object)null && (!kiln || rules.Woods.Contains(((Object)c.m_from).name))
					select ((Object)c.m_from).name).Distinct().ToArray(), from i in Enumerable.Range(0, Math.Min(num, item.m_maxOre))
					select zdo.GetString("item" + i, ""), (string name) => Stock(usable, name));
				if (!kiln && (Object)(object)item.m_fuelItem != (Object)null && (num > 0 || text != null))
				{
					int wants = Mathf.FloorToInt((float)item.m_maxFuel - zdo.GetFloat(ZDOVars.s_fuel, 0f));
					object obj = FindStack(item, ((Object)item.m_fuelItem).name, wants, input: false, kiln: false, usable);
					if (obj != null)
					{
						return obj;
					}
				}
				if (text != null && num < item.m_maxOre)
				{
					int num2 = item.m_maxOre - num;
					if (kiln)
					{
						num2 = LoadingPolicy.KilnLoad(Stock(chests, text), rules.Reserve, storedCoal, queuedCoal, rules.CoalTarget, num2);
					}
					object obj2 = FindStack(item, text, num2, input: true, kiln, usable);
					if (obj2 != null)
					{
						return obj2;
					}
				}
			}
			return null;
		}

		private static object? FindStack(Smelter station, string item, int wants, bool input, bool kiln, List<Container> usable)
		{
			if (wants <= 0)
			{
				return null;
			}
			foreach (Container item2 in usable.Where((Container c) => (Object)(object)c != (Object)null && c.GetInventory() != null).OrderBy(delegate(Container 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 val2 = ((Component)c).transform.position - ((Component)station).transform.position;
				return ((Vector3)(ref val2)).sqrMagnitude;
			}))
			{
				ItemData val = (from i in item2.GetInventory().GetAllItems()
					where (Object)(object)i.m_dropPrefab != (Object)null && ((Object)i.m_dropPrefab).name == item && i.m_stack > 0
					orderby i.m_stack descending
					select i).FirstOrDefault();
				if (val != null)
				{
					object obj = Plugin.Bridge.CreateFeed(station, item2, val, item, Math.Min(wants, val.m_stack), input);
					Contexts.Add(obj, new FeedContext(station, item, input, kiln));
					return obj;
				}
			}
			return null;
		}
	}
	internal static class WorkPatches
	{
		public static void AfterNext(object __0, Vector3 __1, List<Container> __2, ref object? __result)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			Rules activeRules = Plugin.ActiveRules;
			if (activeRules == null || !activeRules.Enabled || !Plugin.Bridge.TendingEnabled)
			{
				return;
			}
			try
			{
				if (__result != null)
				{
					Smelter val = Plugin.Bridge.Station(__result);
					if ((Object)(object)val == (Object)null || !MachineJobs.Managed(val, activeRules))
					{
						return;
					}
					__result = null;
				}
				__result = MachineJobs.Find(__0, __1, __2, activeRules);
			}
			catch (Exception error)
			{
				Plugin.Report(error);
			}
		}

		public static bool BeforeStillWanted(object __0, object __1, ref bool __result)
		{
			if (!MachineJobs.Contexts.TryGetValue(__0, out FeedContext value))
			{
				return true;
			}
			try
			{
				Rules activeRules = Plugin.ActiveRules;
				__result = activeRules != null && MachineJobs.ContinueFeeding(value, __1, activeRules);
			}
			catch (Exception error)
			{
				Plugin.Report(error);
				__result = false;
			}
			return false;
		}

		public static bool BeforeStep(object __instance, ref object? __result)
		{
			CoglingBridge bridge = Plugin.Bridge;
			object obj = bridge.JobFeed(__instance);
			if (obj == null || !MachineJobs.Contexts.TryGetValue(obj, out FeedContext value) || !bridge.IsTakingNow(__instance))
			{
				return true;
			}
			Rules activeRules = Plugin.ActiveRules;
			int num;
			try
			{
				num = ((activeRules != null) ? MachineJobs.Budget(value, bridge.JobNetwork(__instance), activeRules) : 0);
			}
			catch (Exception error)
			{
				Plugin.Report(error);
				num = 0;
			}
			if (num <= 0)
			{
				__result = bridge.CancelBeforeTaking(__instance);
				return false;
			}
			bridge.SetTakeCount(__instance, Math.Min(bridge.TakeCount(__instance), num));
			return true;
		}
	}
	[BepInPlugin("matt321998.CoglingReimagined", "Cogling Reimagined", "0.1.2")]
	[BepInDependency("nick.Cogling", "1.0.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "matt321998.CoglingReimagined";

		public const string Version = "0.1.2";

		internal static Plugin Instance;

		internal static CoglingBridge Bridge;

		private Harmony? _harmony;

		private SettingsSync? _sync;

		private ConfigEntry<bool> _enabled;

		private ConfigEntry<bool> _smelters;

		private ConfigEntry<bool> _kilns;

		private ConfigEntry<int> _reserve;

		private ConfigEntry<int> _coal;

		private ConfigEntry<string> _woods;

		private float _reloadAt;

		private float _reportAt;

		internal static Rules? ActiveRules => Instance._sync?.Current;

		private void Awake()
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Expected O, but got Unknown
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Expected O, but got Unknown
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Expected O, but got Unknown
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Expected O, but got Unknown
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Expected O, but got Unknown
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Expected O, but got Unknown
			Instance = this;
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable this extension. Original Cogling is unchanged when disabled. Host controlled.");
			_smelters = ((BaseUnityPlugin)this).Config.Bind<bool>("Machines", "Auto start smelters", true, "Load idle vanilla smelters and blast furnaces. Requires Cogling's Tend smelters setting. Host controlled.");
			_kilns = ((BaseUnityPlugin)this).Config.Bind<bool>("Machines", "Auto start kilns", true, "Load idle charcoal kilns and manage their supply using the reserve and coal target. Host controlled.");
			_reserve = ((BaseUnityPlugin)this).Config.Bind<int>("Kilns", "Wood reserve", 50, new ConfigDescription("Leave at least this many of EACH allowed wood prefab in accessible network chests. Does not recover wood already queued. Host controlled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000), Array.Empty<object>()));
			_coal = ((BaseUnityPlugin)this).Config.Bind<int>("Kilns", "Coal target", 100, new ConfigDescription("Stop adding kiln input when coal in accessible network chests plus queued kiln output reaches this target. Coal already being carried or on the ground may cause overshoot. Host controlled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000), Array.Empty<object>()));
			_woods = ((BaseUnityPlugin)this).Config.Bind<string>("Kilns", "Allowed wood", "Wood", "Comma-separated kiln input prefab names. Default uses only ordinary Wood, preserving FineWood and RoundLog. Host controlled.");
			_sync = new SettingsSync(ReadRules, ((BaseUnityPlugin)this).Logger);
			try
			{
				Bridge = new CoglingBridge();
				_harmony = new Harmony("matt321998.CoglingReimagined");
				_harmony.Patch((MethodBase)Bridge.Next, (HarmonyMethod)null, new HarmonyMethod(typeof(WorkPatches), "AfterNext", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.StillWanted, new HarmonyMethod(typeof(WorkPatches), "BeforeStillWanted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.Step, new HarmonyMethod(typeof(WorkPatches), "BeforeStep", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.Step, new HarmonyMethod(typeof(ChestDelivery), "BeforeStep", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.Reroute, new HarmonyMethod(typeof(ChestDelivery), "BeforeReroute", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.Abandon, (HarmonyMethod)null, new HarmonyMethod(typeof(ChestDelivery), "Reset", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.Gathered, new HarmonyMethod(typeof(AntennaCall), "BeforeGathered", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)Bridge.Called, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AntennaCall), "FixLandingHeight", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Cogling Reimagined 0.1.2 ready. Gameplay settings are host controlled.");
			}
			catch (Exception ex)
			{
				Harmony? harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				_harmony = null;
				((BaseUnityPlugin)this).Logger.LogError((object)("Extension disabled: Cogling's expected methods could not be patched. Original Cogling remains active. " + ex));
			}
		}

		private Rules ReadRules()
		{
			return new Rules(_enabled.Value, _smelters.Value, _kilns.Value, _reserve.Value, _coal.Value, _woods.Value);
		}

		private void Update()
		{
			if (Time.unscaledTime >= _reloadAt)
			{
				_reloadAt = Time.unscaledTime + 5f;
				try
				{
					((BaseUnityPlugin)this).Config.Reload();
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not reload config; keeping current settings: " + ex.Message));
				}
			}
			_sync?.Update();
		}

		internal static void Report(Exception error)
		{
			if (!(Time.unscaledTime < Instance._reportAt))
			{
				Instance._reportAt = Time.unscaledTime + 10f;
				((BaseUnityPlugin)Instance).Logger.LogError((object)("Cogling Reimagined job patch failed: " + error));
			}
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal sealed class Rules
	{
		internal readonly bool Enabled;

		internal readonly bool Smelters;

		internal readonly bool Kilns;

		internal readonly int Reserve;

		internal readonly int CoalTarget;

		internal readonly string WoodList;

		internal readonly HashSet<string> Woods;

		internal Rules(bool enabled, bool smelters, bool kilns, int reserve, int coal, string woods)
		{
			Enabled = enabled;
			Smelters = smelters;
			Kilns = kilns;
			Reserve = Math.Max(0, Math.Min(1000000, reserve));
			CoalTarget = Math.Max(0, Math.Min(1000000, coal));
			WoodList = woods ?? "";
			Woods = new HashSet<string>(from s in WoodList.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s, StringComparer.Ordinal);
		}
	}
	internal sealed class SettingsSync
	{
		private const string Rpc = "matt321998.CoglingReimagined.Settings.v1";

		private readonly Func<Rules> _local;

		private readonly ManualLogSource _log;

		private ZRoutedRpc? _router;

		private Rules? _remote;

		private float _requestAt;

		private float _lastReply;

		private bool _logged;

		internal Rules? Current
		{
			get
			{
				if (!((Object)(object)ZNet.instance == (Object)null))
				{
					if (!ZNet.instance.IsServer())
					{
						if (!(Time.unscaledTime - _lastReply < 30f))
						{
							return null;
						}
						return _remote;
					}
					return _local();
				}
				return null;
			}
		}

		internal SettingsSync(Func<Rules> local, ManualLogSource log)
		{
			_local = local;
			_log = log;
		}

		internal void Update()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			if (_router != ZRoutedRpc.instance)
			{
				_router = ZRoutedRpc.instance;
				_remote = null;
				_logged = false;
				_requestAt = 0f;
				ZRoutedRpc? router = _router;
				if (router != null)
				{
					router.Register<ZPackage>("matt321998.CoglingReimagined.Settings.v1", (Action<long, ZPackage>)Receive);
				}
			}
			if (_router != null && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && ZNet.instance.GetServerPeer() != null && !(Time.unscaledTime < _requestAt))
			{
				_requestAt = Time.unscaledTime + 5f;
				ZPackage val = new ZPackage();
				val.Write(1);
				val.Write(false);
				_router.InvokeRoutedRPC("matt321998.CoglingReimagined.Settings.v1", new object[1] { val });
			}
		}

		private void Receive(long sender, ZPackage package)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			try
			{
				if ((Object)(object)ZNet.instance == (Object)null || _router == null || package.ReadInt() != 1)
				{
					return;
				}
				bool flag = package.ReadBool();
				if (ZNet.instance.IsServer())
				{
					if (!flag && ZNet.instance.GetPeers().Any((ZNetPeer p) => p.m_uid == sender && p.IsReady()))
					{
						Rules rules = _local();
						ZPackage val = new ZPackage();
						val.Write(1);
						val.Write(true);
						val.Write(rules.Enabled);
						val.Write(rules.Smelters);
						val.Write(rules.Kilns);
						val.Write(rules.Reserve);
						val.Write(rules.CoalTarget);
						val.Write(rules.WoodList);
						_router.InvokeRoutedRPC(sender, "matt321998.CoglingReimagined.Settings.v1", new object[1] { val });
					}
				}
				else
				{
					if (!flag)
					{
						return;
					}
					ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
					if (serverPeer != null && serverPeer.m_uid == sender)
					{
						_remote = new Rules(package.ReadBool(), package.ReadBool(), package.ReadBool(), package.ReadInt(), package.ReadInt(), package.ReadString());
						_lastReply = Time.unscaledTime;
						if (!_logged)
						{
							_logged = true;
							_log.LogInfo((object)"Received Cogling Reimagined settings from the host.");
						}
					}
				}
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Ignored invalid extension settings message: " + ex.Message));
			}
		}
	}
}