Decompiled source of RuneheimQOL v1.0.7

plugins/RuneheimQOL.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using RuneheimCore;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")]
[assembly: AssemblyCompany("Daytreee")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 Daytreee. All rights reserved. Not open source: no reuse, decompiling or redistribution without permission.")]
[assembly: AssemblyFileVersion("1.0.5.0")]
[assembly: AssemblyInformationalVersion("1.0.5+1361592db6ab5574ea429f512edc2599a9ab7083")]
[assembly: AssemblyProduct("Runeheim QOL")]
[assembly: AssemblyTitle("RuneheimQOL")]
[assembly: AssemblyVersion("1.0.5.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;
		}
	}
}
internal static class RhSafe
{
	private static class Holder<F>
	{
		public static F Value;
	}

	private static ManualLogSource _log;

	private static readonly HashSet<string> _said = new HashSet<string>();

	private const int MaxReports = 300;

	private static ManualLogSource Log
	{
		get
		{
			if (_log == null)
			{
				_log = Logger.CreateLogSource(typeof(RhSafe).Assembly.GetName().Name + " (checks)");
			}
			return _log;
		}
	}

	private static void Warn(string key, string text)
	{
		try
		{
			lock (_said)
			{
				if (_said.Count >= 300 || !_said.Add(key))
				{
					return;
				}
			}
			Log.LogWarning((object)text);
		}
		catch
		{
		}
	}

	private static string Where(string file, int line)
	{
		return Path.GetFileName(file) + ":" + line;
	}

	public static void Swallowed(Exception e, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0, [CallerMemberName] string member = "")
	{
		string text = Where(file, line);
		object obj;
		if (e == null)
		{
			obj = null;
		}
		else
		{
			string? stackTrace = e.StackTrace;
			obj = ((stackTrace == null) ? null : stackTrace.Split(new char[1] { '\n' })[0]?.Trim());
		}
		if (obj == null)
		{
			obj = "";
		}
		string text2 = (string)obj;
		Warn("catch " + text, "Handled error in " + member + " (" + text + "): " + e?.GetType().Name + ": " + e?.Message + " " + text2);
	}

	private static ref F Dummy<T, F>(T instance)
	{
		return ref Holder<F>.Value;
	}

	private static ref F DummyStatic<F>()
	{
		return ref Holder<F>.Value;
	}

	public static FieldRef<T, F> FieldRef<T, F>(string name, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
	{
		try
		{
			return AccessTools.FieldRefAccess<T, F>(name);
		}
		catch (Exception ex)
		{
			Warn("field " + typeof(T).FullName + "." + name, typeof(T).Name + "." + name + " (as " + typeof(F).Name + ") can't be read (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off.");
			return Dummy<T, F>;
		}
	}

	public static FieldRef<T, F> FieldRef<T, F>(FieldInfo field, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
	{
		try
		{
			if (field != null)
			{
				return AccessTools.FieldRefAccess<T, F>(field);
			}
		}
		catch (Exception ex)
		{
			Warn("field " + field?.DeclaringType?.FullName + "." + field?.Name, field?.DeclaringType?.Name + "." + field?.Name + " can't be read (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off.");
			return Dummy<T, F>;
		}
		Warn("field null " + Where(file, line), "A field looked up at " + Where(file, line) + " wasn't found. What uses it is switched off.");
		return Dummy<T, F>;
	}

	public static FieldRef<F> StaticFieldRef<F>(Type type, string name, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
	{
		try
		{
			FieldInfo fieldInfo = ((type != null) ? AccessTools.Field(type, name) : null);
			if (fieldInfo != null)
			{
				return AccessTools.StaticFieldRefAccess<F>(fieldInfo);
			}
			Warn("static " + type?.FullName + "." + name, type?.Name + "." + name + " wasn't found (" + Where(file, line) + "). What uses it is switched off.");
		}
		catch (Exception ex)
		{
			Warn("static " + type?.FullName + "." + name, type?.Name + "." + name + " (as " + typeof(F).Name + ") can't be read (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off.");
		}
		return DummyStatic<F>;
	}

	public static D MethodDelegate<D>(MethodInfo method, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) where D : Delegate
	{
		try
		{
			if (method != null)
			{
				return AccessTools.MethodDelegate<D>(method, (object)null, true);
			}
			Warn("method null " + Where(file, line), "A method looked up at " + Where(file, line) + " wasn't found. What uses it is switched off.");
		}
		catch (Exception ex)
		{
			Warn("method " + method?.DeclaringType?.FullName + "." + method?.Name, method?.DeclaringType?.Name + "." + method?.Name + " can't be called (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off.");
		}
		return null;
	}
}
namespace RuneheimQOL
{
	public static class AwayCatchUp
	{
		[HarmonyPatch(typeof(Smelter), "UpdateSmelter")]
		private static class SmelterAway
		{
			private static void Prefix(Smelter __instance)
			{
				try
				{
					ZNetView nv = Machines.View((MonoBehaviour)(object)__instance);
					if (Eligible((MonoBehaviour)(object)__instance, nv))
					{
						Capture(nv, ZDOVars.s_startTime);
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 59, "Prefix");
				}
			}
		}

		[HarmonyPatch(typeof(Beehive), "UpdateBees")]
		private static class BeehiveAway
		{
			private static void Prefix(Beehive __instance)
			{
				try
				{
					ZNetView nv = Machines.View((MonoBehaviour)(object)__instance);
					if (Eligible((MonoBehaviour)(object)__instance, nv))
					{
						Capture(nv, ZDOVars.s_lastTime);
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 68, "Prefix");
				}
			}
		}

		[HarmonyPatch(typeof(SapCollector), "UpdateTick")]
		private static class SapAway
		{
			private static void Prefix(SapCollector __instance)
			{
				try
				{
					ZNetView nv = Machines.View((MonoBehaviour)(object)__instance);
					if (Eligible((MonoBehaviour)(object)__instance, nv))
					{
						Capture(nv, ZDOVars.s_lastTime);
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 77, "Prefix");
				}
			}
		}

		[HarmonyPatch(typeof(CookingStation), "UpdateCooking")]
		private static class OvenAway
		{
			private static void Prefix(CookingStation __instance)
			{
				try
				{
					if (__instance.m_useFuel)
					{
						ZNetView nv = Machines.View((MonoBehaviour)(object)__instance);
						if (Eligible((MonoBehaviour)(object)__instance, nv))
						{
							Capture(nv, ZDOVars.s_startTime);
						}
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 86, "Prefix");
				}
			}
		}

		private const string KAway = "rhui_away";

		private const float Threshold = 60f;

		private const int MaxPerTick = 400;

		private static readonly Dictionary<int, float> seen = new Dictionary<int, float>();

		private static readonly MethodInfo SmQueueOre = AccessTools.Method(typeof(Smelter), "QueueOre", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmQueued = AccessTools.Method(typeof(Smelter), "GetQueuedOre", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmRemove = AccessTools.Method(typeof(Smelter), "RemoveOneOre", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmProcessed = AccessTools.Method(typeof(Smelter), "QueueProcessed", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmGetFuel = AccessTools.Method(typeof(Smelter), "GetFuel", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmSetFuel = AccessTools.Method(typeof(Smelter), "SetFuel", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmGetBake = AccessTools.Method(typeof(Smelter), "GetBakeTimer", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmSetBake = AccessTools.Method(typeof(Smelter), "SetBakeTimer", (Type[])null, (Type[])null);

		private static readonly FieldRef<Smelter, bool> SmRoof = RhSafe.FieldRef<Smelter, bool>("m_haveRoof", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 153);

		private static readonly FieldRef<Smelter, bool> SmSmoke = RhSafe.FieldRef<Smelter, bool>("m_blockedSmoke", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 154);

		private static readonly MethodInfo FeTime = AccessTools.Method(typeof(Fermenter), "GetFermentationTime", (Type[])null, (Type[])null);

		private static readonly FieldRef<Fermenter, bool> FeExposed = RhSafe.FieldRef<Fermenter, bool>("m_exposed", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 209);

		private static readonly MethodInfo BhLevel = AccessTools.Method(typeof(Beehive), "GetHoneyLevel", (Type[])null, (Type[])null);

		private static readonly MethodInfo BhAdd = AccessTools.Method(typeof(Beehive), "IncreseLevel", (Type[])null, (Type[])null);

		private static readonly MethodInfo BhBiome = AccessTools.Method(typeof(Beehive), "CheckBiome", (Type[])null, (Type[])null);

		private static readonly MethodInfo BhSpace = AccessTools.Method(typeof(Beehive), "HaveFreeSpace", (Type[])null, (Type[])null);

		private static readonly MethodInfo ScLevel = AccessTools.Method(typeof(SapCollector), "GetLevel", (Type[])null, (Type[])null);

		private static readonly MethodInfo ScAdd = AccessTools.Method(typeof(SapCollector), "IncreseLevel", (Type[])null, (Type[])null);

		private static readonly FieldRef<SapCollector, ResourceRoot> ScRoot = RhSafe.FieldRef<SapCollector, ResourceRoot>("m_root", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\AwayCatchUp.cs", 258);

		private static readonly MethodInfo CsGetSlot = AccessTools.Method(typeof(CookingStation), "GetSlot", (Type[])null, (Type[])null);

		private static readonly MethodInfo CsSetSlot = AccessTools.Method(typeof(CookingStation), "SetSlot", (Type[])null, (Type[])null);

		private static readonly MethodInfo CsConv = AccessTools.Method(typeof(CookingStation), "GetItemConversion", (Type[])null, (Type[])null);

		private static readonly MethodInfo CsGetFuel = AccessTools.Method(typeof(CookingStation), "GetFuel", (Type[])null, (Type[])null);

		private static readonly MethodInfo CsSetFuel = AccessTools.Method(typeof(CookingStation), "SetFuel", (Type[])null, (Type[])null);

		private static readonly Type CsStatus = AccessTools.Inner(typeof(CookingStation), "Status");

		private static bool Allowed
		{
			get
			{
				if (Qol.AutomationOn)
				{
					return Qol.ServerCatchUp.Value;
				}
				return false;
			}
		}

		private static float Cap => Mathf.Max(1f, Qol.ServerCatchUpHours.Value) * 3600f;

		private static DateTime Now => ZNet.instance.GetTime();

		private static bool Eligible(MonoBehaviour m, ZNetView nv)
		{
			if (!Allowed || (Object)(object)nv == (Object)null || !nv.IsValid() || !nv.IsOwner() || (Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			return Machines.Get(m, inputs: false).Count > 0;
		}

		private static void Capture(ZNetView nv, int stampKey)
		{
			ZDO zDO = nv.GetZDO();
			long ticks = Now.Ticks;
			long num = zDO.GetLong(stampKey, ticks);
			double num2 = (double)(ticks - num) / 10000000.0;
			if (!(num2 <= 60.0))
			{
				zDO.Set(stampKey, ticks);
				zDO.Set("rhui_away", Mathf.Min(Cap, zDO.GetFloat("rhui_away", 0f) + (float)num2));
			}
		}

		private static bool ChestsReady(MonoBehaviour m, Vector3 pos, float range, HashSet<ZDOID> links)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)m).GetInstanceID();
			if (!seen.TryGetValue(instanceID, out var value))
			{
				seen[instanceID] = Time.time;
				return false;
			}
			float num = Time.time - value;
			if (num < 5f)
			{
				return false;
			}
			if (!(num > 30f))
			{
				return Chests.Nearby(pos, range, links).Count > 0;
			}
			return true;
		}

		public static void Run(MonoBehaviour m, ZNetView nv, HashSet<string> ins, HashSet<string> outs, Vector3 pos, float range, HashSet<ZDOID> linksIn, HashSet<ZDOID> linksOut)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if (!Allowed || outs.Count == 0 || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			ZDO zDO = nv.GetZDO();
			Fermenter val = (Fermenter)(object)((m is Fermenter) ? m : null);
			if (val != null)
			{
				if (ChestsReady(m, pos, range, linksOut))
				{
					Ferment(val, nv, ins, outs, pos, range, linksIn, linksOut);
				}
				return;
			}
			float num = zDO.GetFloat("rhui_away", 0f);
			if (num <= 0f || !ChestsReady(m, pos, range, linksOut))
			{
				return;
			}
			float num2 = 0f;
			Smelter val2 = (Smelter)(object)((m is Smelter) ? m : null);
			if (val2 != null)
			{
				num2 = Smelt(val2, nv, num, ins, outs, pos, range, linksIn, linksOut);
			}
			else
			{
				Beehive val3 = (Beehive)(object)((m is Beehive) ? m : null);
				if (val3 != null)
				{
					Honey(val3, num, outs, pos, range, linksOut);
				}
				else
				{
					SapCollector val4 = (SapCollector)(object)((m is SapCollector) ? m : null);
					if (val4 != null)
					{
						Sap(val4, num, outs, pos, range, linksOut);
					}
					else
					{
						CookingStation val5 = (CookingStation)(object)((m is CookingStation) ? m : null);
						if (val5 != null)
						{
							Oven(val5, num, ins, outs, pos, range, linksIn, linksOut);
						}
					}
				}
			}
			zDO.Set("rhui_away", num2);
		}

		private static int Put(string prefab, int count, Vector3 pos, float range, HashSet<ZDOID> links)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (count <= 0 || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return 0;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefab);
			ItemDrop val = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null)
			{
				return 0;
			}
			int num = 0;
			foreach (Container item in Chests.Nearby(pos, range, links))
			{
				if (num >= count)
				{
					break;
				}
				Inventory inventory = item.GetInventory();
				ItemData val2 = val.m_itemData.Clone();
				val2.m_dropPrefab = itemPrefab;
				val2.m_worldLevel = (byte)Game.m_worldLevel;
				val2.m_stack = 1;
				int num2 = inventory.FindFreeStackSpace(val2.m_shared.m_name, (float)val2.m_worldLevel) + inventory.GetEmptySlots() * val2.m_shared.m_maxStackSize;
				if (num2 > 0 && Chests.Claim(item))
				{
					val2.m_stack = Mathf.Min(num2, count - num);
					int stack = val2.m_stack;
					if (inventory.AddItem(val2))
					{
						num += stack;
					}
				}
			}
			Chests.Invalidate();
			return num;
		}

		private static string Shared(ItemDrop d)
		{
			return d.m_itemData.m_shared.m_name;
		}

		private static float Smelt(Smelter s, ZNetView nv, float away, HashSet<string> ins, HashSet<string> outs, Vector3 pos, float range, HashSet<ZDOID> linksIn, HashSet<ZDOID> linksOut)
		{
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			if (s.m_secPerProduct <= 0f || (s.m_requiresRoof && !SmRoof.Invoke(s)) || SmSmoke.Invoke(s))
			{
				return 0f;
			}
			float num = (Object.op_Implicit((Object)(object)s.m_windmill) ? s.m_windmill.GetPowerOutput() : 1f);
			if (num <= 0.01f)
			{
				return 0f;
			}
			float num2 = away + (float)SmGetBake.Invoke(s, null) / num;
			float num3 = s.m_secPerProduct / num;
			bool flag = s.m_maxFuel > 0 && Object.op_Implicit((Object)(object)s.m_fuelItem) && ins.Contains(((Object)s.m_fuelItem).name);
			int num4 = 0;
			while (num2 >= num3)
			{
				if (num4 >= 400)
				{
					SmSetBake.Invoke(s, new object[1] { 0f });
					return num2;
				}
				if ((int)SmQueueSize.Invoke(s, null) == 0)
				{
					bool flag2 = false;
					foreach (ItemConversion item in s.m_conversion)
					{
						if (Object.op_Implicit((Object)(object)item.m_from) && ins.Contains(((Object)item.m_from).name) && Chests.Take(Shared(item.m_from), 1, pos, range, linksIn) == 1)
						{
							SmQueueOre.Invoke(s, new object[2]
							{
								((Object)item.m_from).name,
								false
							});
							flag2 = true;
							break;
						}
					}
					if (!flag2)
					{
						break;
					}
				}
				if (s.m_maxFuel > 0)
				{
					float num5 = (float)SmGetFuel.Invoke(s, null);
					if (num5 < (float)s.m_fuelPerProduct && flag)
					{
						int amount = Mathf.CeilToInt((float)s.m_fuelPerProduct - num5);
						num5 += (float)Chests.Take(Shared(s.m_fuelItem), amount, pos, range, linksIn);
					}
					if (num5 < (float)s.m_fuelPerProduct - 0.0001f)
					{
						SmSetFuel.Invoke(s, new object[1] { num5 });
						break;
					}
					SmSetFuel.Invoke(s, new object[1] { Mathf.Max(0f, num5 - (float)s.m_fuelPerProduct) });
				}
				string text = (string)SmQueued.Invoke(s, null);
				ItemConversion val = null;
				foreach (ItemConversion item2 in s.m_conversion)
				{
					if (Object.op_Implicit((Object)(object)item2.m_from) && ((Object)item2.m_from).name == text)
					{
						val = item2;
						break;
					}
				}
				if (val != null && Object.op_Implicit((Object)(object)val.m_to) && outs.Contains(((Object)val.m_to).name))
				{
					if (Put(((Object)val.m_to).name, 1, pos, range, linksOut) != 1)
					{
						break;
					}
					SmRemove.Invoke(s, null);
				}
				else
				{
					SmRemove.Invoke(s, null);
					SmProcessed.Invoke(s, new object[1] { text });
				}
				num2 -= num3;
				num4++;
			}
			SmSetBake.Invoke(s, new object[1] { Mathf.Clamp(num2 * num, 0f, s.m_secPerProduct * 0.99f) });
			if (num4 > 0)
			{
				Plugin.Log.LogInfo((object)$"Away catch-up: {Machines.Name((MonoBehaviour)(object)s)} made {num4} while you were away.");
			}
			return 0f;
		}

		private static void Ferment(Fermenter f, ZNetView nv, HashSet<string> ins, HashSet<string> outs, Vector3 pos, float range, HashSet<ZDOID> linksIn, HashSet<ZDOID> linksOut)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = nv.GetZDO();
			int num = zDO.GetInt(ZDOVars.s_content, 0);
			float fermentationDuration = f.m_fermentationDuration;
			if (num == 0 || fermentationDuration <= 0f || FeExposed.Invoke(f))
			{
				return;
			}
			double num2 = (double)FeTime.Invoke(f, null);
			if (num2 < (double)(fermentationDuration * 2f))
			{
				return;
			}
			num2 = Math.Min(num2, Cap);
			ItemConversion val = Conv(num);
			int num3 = 0;
			while (num2 >= (double)fermentationDuration && val != null && Object.op_Implicit((Object)(object)val.m_to) && outs.Contains(((Object)val.m_to).name) && Put(((Object)val.m_to).name, val.m_producedItems, pos, range, linksOut) >= val.m_producedItems)
			{
				num2 -= (double)fermentationDuration;
				num3++;
				val = null;
				num = 0;
				foreach (ItemConversion item in f.m_conversion)
				{
					if (Object.op_Implicit((Object)(object)item.m_from) && ins.Contains(((Object)item.m_from).name) && Chests.Take(Shared(item.m_from), 1, pos, range, linksIn) == 1)
					{
						val = item;
						num = StringExtensionMethods.GetStableHashCode(((Object)item.m_from).name);
						break;
					}
				}
			}
			if (num3 != 0)
			{
				zDO.Set(ZDOVars.s_content, num, false);
				zDO.Set(ZDOVars.s_startTime, (num != 0) ? (Now.Ticks - (long)(num2 * 10000000.0)) : 0);
				Plugin.Log.LogInfo((object)$"Away catch-up: {Machines.Name((MonoBehaviour)(object)f)} finished {num3} batch(es) while you were away.");
			}
			ItemConversion Conv(int hash)
			{
				foreach (ItemConversion item2 in f.m_conversion)
				{
					if (Object.op_Implicit((Object)(object)item2.m_from) && StringExtensionMethods.GetStableHashCode(((Object)item2.m_from).name) == hash)
					{
						return item2;
					}
				}
				return null;
			}
		}

		private static void Honey(Beehive b, float away, HashSet<string> outs, Vector3 pos, float range, HashSet<ZDOID> links)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)b.m_honeyItem) && outs.Contains(((Object)b.m_honeyItem).name) && !(b.m_secPerUnit <= 0f) && (bool)BhBiome.Invoke(b, null) && (bool)BhSpace.Invoke(b, null))
			{
				int num = Mathf.FloorToInt(away / b.m_secPerUnit);
				int num2 = Put(((Object)b.m_honeyItem).name, num, pos, range, links);
				int num3 = b.m_maxHoney - (int)BhLevel.Invoke(b, null);
				int num4 = Mathf.Min(num - num2, num3);
				if (num4 > 0)
				{
					BhAdd.Invoke(b, new object[1] { num4 });
				}
				if (num2 > 0)
				{
					Plugin.Log.LogInfo((object)$"Away catch-up: {Machines.Name((MonoBehaviour)(object)b)} made {num2} while you were away.");
				}
			}
		}

		private static void Sap(SapCollector sc, float away, HashSet<string> outs, Vector3 pos, float range, HashSet<ZDOID> links)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)sc.m_spawnItem) || !outs.Contains(((Object)sc.m_spawnItem).name) || sc.m_secPerUnit <= 0f)
			{
				return;
			}
			ResourceRoot val = ScRoot.Invoke(sc);
			if (!((Object)(object)val == (Object)null) && val.CanDrain(1f))
			{
				int num = Mathf.Min(Mathf.FloorToInt(away / sc.m_secPerUnit), (int)val.GetLevel());
				int num2 = Put(((Object)sc.m_spawnItem).name, num, pos, range, links);
				int num3 = sc.m_maxLevel - (int)ScLevel.Invoke(sc, null);
				int num4 = Mathf.Min(num - num2, num3);
				if (num4 > 0)
				{
					ScAdd.Invoke(sc, new object[1] { num4 });
				}
				if (num2 + Mathf.Max(0, num4) > 0)
				{
					val.Drain((float)(num2 + Mathf.Max(0, num4)));
				}
				if (num2 > 0)
				{
					Plugin.Log.LogInfo((object)$"Away catch-up: {Machines.Name((MonoBehaviour)(object)sc)} made {num2} while you were away.");
				}
			}
		}

		private static void Oven(CookingStation cs, float away, HashSet<string> ins, HashSet<string> outs, Vector3 pos, float range, HashSet<ZDOID> linksIn, HashSet<ZDOID> linksOut)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			if (!cs.m_useFuel || cs.m_secPerFuel <= 0 || CsStatus == null)
			{
				return;
			}
			float num = (float)CsGetFuel.Invoke(cs, null);
			float num2 = away / (float)cs.m_secPerFuel;
			if (num < num2 && Object.op_Implicit((Object)(object)cs.m_fuelItem) && ins.Contains(((Object)cs.m_fuelItem).name))
			{
				num += (float)Chests.Take(Shared(cs.m_fuelItem), Mathf.Min(Mathf.CeilToInt(num2 - num), 1000), pos, range, linksIn);
			}
			float num3 = Mathf.Min(away, num * (float)cs.m_secPerFuel);
			CsSetFuel.Invoke(cs, new object[1] { Mathf.Clamp(num - num3 / (float)cs.m_secPerFuel, 0f, (float)cs.m_maxFuel) });
			object obj = Enum.ToObject(CsStatus, 0);
			object obj2 = Enum.ToObject(CsStatus, 1);
			Enum.ToObject(CsStatus, 2);
			int num4 = 0;
			for (int i = 0; i < cs.m_slots.Length; i++)
			{
				object[] array = new object[5] { i, null, 0f, null, false };
				CsGetSlot.Invoke(cs, array);
				string text = ((string)array[1]) ?? "";
				float num5 = (float)array[2];
				object obj3 = array[3] ?? obj;
				bool flag = (bool)array[4];
				float num6 = num3;
				for (int j = 0; j < 400; j++)
				{
					if (text == "")
					{
						string text2 = null;
						foreach (ItemConversion item in cs.m_conversion)
						{
							if (Object.op_Implicit((Object)(object)item.m_from) && ins.Contains(((Object)item.m_from).name) && Chests.Take(Shared(item.m_from), 1, pos, range, linksIn) == 1)
							{
								text2 = ((Object)item.m_from).name;
								break;
							}
						}
						if (text2 == null)
						{
							break;
						}
						text = text2;
						num5 = 0f;
						obj3 = obj;
					}
					if (!obj3.Equals(obj))
					{
						if (!outs.Contains(text) || Put(text, 1, pos, range, linksOut) != 1)
						{
							break;
						}
						text = "";
						num5 = 0f;
						obj3 = obj;
						num4++;
						continue;
					}
					object? obj4 = CsConv.Invoke(cs, new object[1] { text });
					ItemConversion val = (ItemConversion)((obj4 is ItemConversion) ? obj4 : null);
					if (val == null || !Object.op_Implicit((Object)(object)val.m_to))
					{
						break;
					}
					float num7 = val.m_cookTime - num5;
					if (num6 < num7)
					{
						num5 += num6;
						break;
					}
					num6 -= num7;
					if (outs.Contains(((Object)val.m_to).name) && Put(((Object)val.m_to).name, 1, pos, range, linksOut) == 1)
					{
						text = "";
						num5 = 0f;
						num4++;
						continue;
					}
					text = ((Object)val.m_to).name;
					num5 = val.m_cookTime;
					obj3 = obj2;
					break;
				}
				CsSetSlot.Invoke(cs, new object[6] { i, text, num5, obj3, flag, 0L });
			}
			if (num4 > 0)
			{
				Plugin.Log.LogInfo((object)$"Away catch-up: {Machines.Name((MonoBehaviour)(object)cs)} made {num4} while you were away.");
			}
		}
	}
	public static class BuildCam
	{
		[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
		private static class CameraPatch
		{
			private static bool Prefix(GameCamera __instance, float dt)
			{
				if (!Active)
				{
					return true;
				}
				try
				{
					Player localPlayer = Player.m_localPlayer;
					if ((Object)(object)localPlayer == (Object)null || (Object)(object)station == (Object)null)
					{
						Disable();
						return true;
					}
					if (!Console.IsVisible() && TakeInput(localPlayer) && !Hud.IsPieceSelectionVisible())
					{
						Fly(((Component)__instance).transform, localPlayer, dt);
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Freecam camera: " + ex.Message));
					Disable();
					return true;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(PlayerController), "TakeInput")]
		private static class NoWalking
		{
			private static bool Prefix(ref bool __result)
			{
				if (!Active)
				{
					return true;
				}
				__result = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		private static class PlayerUpdate
		{
			private static readonly string[] Hotbar = new string[8] { "Hotbar1", "Hotbar2", "Hotbar3", "Hotbar4", "Hotbar5", "Hotbar6", "Hotbar7", "Hotbar8" };

			private static bool Prefix(Player __instance)
			{
				if (!Active || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return true;
				}
				try
				{
					if (!Allowed || !HasTool(__instance) || ((Character)__instance).IsDead())
					{
						Disable();
						return true;
					}
					if (!TakeInput(__instance))
					{
						return false;
					}
					for (int i = 0; i < Hotbar.Length; i++)
					{
						if (Input.GetKeyDown((KeyCode)(49 + i)) || ZInput.GetButtonDown(Hotbar[i]))
						{
							__instance.UseHotbarItem(i + 1);
						}
					}
					if (ZInput.GetButtonDown("Hide") && (RightItem.Invoke((Humanoid)(object)__instance) != null || LeftItem.Invoke((Humanoid)(object)__instance) != null) && !((Character)__instance).InAttack())
					{
						((Humanoid)__instance).HideHandItems(false, true);
						Disable();
						return false;
					}
					mUpdatePlacement?.Invoke(__instance, new object[2]
					{
						true,
						Time.deltaTime
					});
					return false;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Freecam: " + ex.Message));
					Disable();
					return true;
				}
			}

			private static void Postfix(Player __instance)
			{
				try
				{
					if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !RhKeys.Fired(Qol.FreecamKey))
					{
						return;
					}
					if (Active)
					{
						if (TakeInput(__instance))
						{
							Disable();
						}
					}
					else if (Allowed && TakeInput(__instance) && HasTool(__instance))
					{
						Enable(__instance);
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Freecam key: " + ex.Message));
				}
			}
		}

		[HarmonyPatch]
		private static class PlaceDistance
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				string[] array = new string[4] { "PieceRayTest", "UpdateWearNTearHover", "CopyPiece", "RemovePiece" };
				foreach (string text in array)
				{
					MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Player), text, (Type[])null, (Type[])null);
					if (methodInfo != null)
					{
						yield return methodInfo;
					}
				}
			}

			private static void Prefix(ref float ___m_maxPlaceDistance, out float __state)
			{
				__state = ___m_maxPlaceDistance;
				if (Active && (Object)(object)station != (Object)null)
				{
					___m_maxPlaceDistance = Mathf.Max(___m_maxPlaceDistance, Range(station) * 2f + 10f);
				}
			}

			private static Exception Finalizer(Exception __exception, ref float ___m_maxPlaceDistance, float __state)
			{
				___m_maxPlaceDistance = __state;
				return __exception;
			}
		}

		[HarmonyPatch(typeof(CraftingStation), "HaveBuildStationInRange")]
		private static class StationInRange
		{
			private static void Postfix(string name, Vector3 point, ref CraftingStation __result)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__result != (Object)null || !Active)
				{
					return;
				}
				try
				{
					__result = Nearest(point, name);
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\BuildCam.cs", 221, "Postfix");
				}
			}
		}

		private static float yaw;

		private static float pitch;

		private static CraftingStation station;

		private static Vector3 lastSafe;

		private static bool haveSafe;

		private const float Clearance = 0.4f;

		private static readonly int TerrainMask = LayerMask.GetMask(new string[1] { "terrain" });

		private static readonly FieldRef<List<CraftingStation>> AllStations = RhSafe.StaticFieldRef<List<CraftingStation>>(typeof(CraftingStation), "m_allStations", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\BuildCam.cs", 26);

		private static readonly MethodInfo mUpdatePlacement = AccessTools.Method(typeof(Player), "UpdatePlacement", (Type[])null, (Type[])null);

		private static readonly MethodInfo mTakeInput = AccessTools.Method(typeof(Player), "TakeInput", (Type[])null, (Type[])null);

		private static readonly FieldRef<Humanoid, ItemData> RightItem = RhSafe.FieldRef<Humanoid, ItemData>("m_rightItem", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\BuildCam.cs", 29);

		private static readonly FieldRef<Humanoid, ItemData> LeftItem = RhSafe.FieldRef<Humanoid, ItemData>("m_leftItem", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\BuildCam.cs", 30);

		private static bool? other;

		public static bool Active { get; private set; }

		public static bool Allowed
		{
			get
			{
				if (Qol.Master.Value && Qol.Freecam.Value && Qol.ServerFreecam.Value && !OtherBuildCam)
				{
					return !PovFlies;
				}
				return false;
			}
		}

		private static bool PovFlies => PovHandover.Freecam;

		public static bool OtherBuildCam
		{
			get
			{
				if (!other.HasValue)
				{
					string text = (Chainloader.PluginInfos.ContainsKey("Azumatt.BuildCameraCHE") ? "Build Camera (Azumatt)" : ((AccessTools.TypeByName("RunicBuildCamera.Integration.BuildCameraRuntime") != null) ? "Runic Build Camera" : null));
					other = text != null;
					if (text != null)
					{
						Plugin.Log.LogWarning((object)(text + " is installed: Runeheim freecam building is off until it's removed."));
					}
				}
				return other.Value;
			}
		}

		private static bool TakeInput(Player p)
		{
			try
			{
				return mTakeInput != null && (bool)mTakeInput.Invoke(p, null);
			}
			catch
			{
				return false;
			}
		}

		private static float Range(CraftingStation s)
		{
			return Mathf.Max(s.m_rangeBuild, Qol.ServerFreecamRange.Value);
		}

		private static float Flat(Vector3 a, Vector3 b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			return num * num + num2 * num2;
		}

		private static bool HasTool(Player p)
		{
			return (Object)(object)RightItem.Invoke((Humanoid)(object)p)?.m_shared.m_buildPieces != (Object)null;
		}

		private static CraftingStation Nearest(Vector3 point, string name = null)
		{
			//IL_0043: 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)
			CraftingStation result = null;
			float num = float.MaxValue;
			foreach (CraftingStation item in AllStations.Invoke())
			{
				if (!((Object)(object)item == (Object)null) && (name == null || !(item.m_name != name)))
				{
					float num2 = Flat(((Component)item).transform.position, point);
					float num3 = Range(item);
					if (num2 <= num3 * num3 && num2 < num)
					{
						result = item;
						num = num2;
					}
				}
			}
			return result;
		}

		private static void Enable(Player p)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			station = Nearest(((Component)p).transform.position);
			if ((Object)(object)station == (Object)null)
			{
				((Character)p).Message((MessageType)2, "Freecam needs a crafting station nearby", 0, (Sprite)null, false);
				return;
			}
			Quaternion rotation = ((Character)p).m_eye.rotation;
			Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles;
			pitch = ((eulerAngles.x > 180f) ? (eulerAngles.x - 360f) : eulerAngles.x);
			yaw = eulerAngles.y;
			if ((Object)(object)GameCamera.instance != (Object)null)
			{
				lastSafe = ((Component)GameCamera.instance).transform.position;
				haveSafe = true;
			}
			Active = true;
			((Character)p).Message((MessageType)1, "Freecam building", 0, (Sprite)null, false);
		}

		public static void Disable()
		{
			if (Active)
			{
				Active = false;
				station = null;
				haveSafe = false;
			}
		}

		private static void Fly(Transform cam, Player p, float dt)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: 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_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: 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_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			yaw += PlayerController.m_mouseSens * Input.GetAxis("Mouse X") + ZInput.GetJoyRightStickX() * 110f * dt;
			float num = (PlayerController.m_invertMouse ? (-1f) : 1f);
			pitch = Mathf.Clamp(pitch - (num * PlayerController.m_mouseSens * Input.GetAxis("Mouse Y") - ZInput.GetJoyRightStickY() * 110f * dt), -89f, 89f);
			cam.rotation = Quaternion.Euler(pitch, yaw, 0f);
			Vector3 val = Vector3.zero;
			if (ZInput.GetButton("Left"))
			{
				val -= Vector3.right;
			}
			if (ZInput.GetButton("Right"))
			{
				val += Vector3.right;
			}
			if (ZInput.GetButton("Forward"))
			{
				val += Vector3.forward;
			}
			if (ZInput.GetButton("Backward"))
			{
				val -= Vector3.forward;
			}
			((Vector3)(ref val)).Normalize();
			val += Vector3.right * ZInput.GetJoyLeftStickX() - Vector3.forward * ZInput.GetJoyLeftStickY();
			val = cam.TransformVector(val);
			if (ZInput.GetButton("Jump") || ZInput.GetButton("JoyJump"))
			{
				val += Vector3.up;
			}
			if (ZInput.GetButton("Crouch") || ZInput.GetButtonPressedTimer("JoyCrouch") > 0.33f)
			{
				val -= Vector3.up;
			}
			float num2 = (ZInput.GetButton("Run") ? ((Character)p).m_runSpeed : ((Character)p).m_walkSpeed) * Qol.FreecamSpeed.Value;
			Vector3 val2 = cam.position + val * num2 * dt;
			Vector3 position = ((Component)station).transform.position;
			float num3 = Range(station);
			Vector3 val3 = val2 - position;
			if (((Vector3)(ref val3)).sqrMagnitude > num3 * num3)
			{
				val2 = position + ((Vector3)(ref val3)).normalized * num3;
			}
			cam.position = Terrain(cam.position, val2);
		}

		private static Vector3 Terrain(Vector3 from, Vector3 to)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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)
			Vector3 val = to - from;
			float magnitude = ((Vector3)(ref val)).magnitude;
			if (magnitude < 0.0001f)
			{
				return from;
			}
			RaycastHit val2 = default(RaycastHit);
			if (Physics.SphereCast(from, 0.4f, val / magnitude, ref val2, magnitude, TerrainMask, (QueryTriggerInteraction)1))
			{
				to = from + val / magnitude * Mathf.Max(0f, ((RaycastHit)(ref val2)).distance - 0.02f);
			}
			if (Physics.CheckSphere(to, 0.4f, TerrainMask, (QueryTriggerInteraction)1))
			{
				if (!haveSafe || Physics.CheckSphere(lastSafe, 0.4f, TerrainMask, (QueryTriggerInteraction)1))
				{
					return from;
				}
				return lastSafe;
			}
			lastSafe = to;
			haveSafe = true;
			return to;
		}
	}
	public static class ChestNames
	{
		private class Namer : TextReceiver
		{
			private readonly Container c;

			public Namer(Container c)
			{
				this.c = c;
			}

			public string GetText()
			{
				if (!((Object)(object)c != (Object)null))
				{
					return "";
				}
				return Get(c);
			}

			public void SetText(string text)
			{
				if ((Object)(object)c == (Object)null)
				{
					return;
				}
				ZNetView val = Chests.View(c);
				if (!((Object)(object)val == (Object)null) && val.IsValid())
				{
					text = (text ?? "").Trim();
					if (text.Length > 32)
					{
						text = text.Substring(0, 32);
					}
					if (!val.IsOwner())
					{
						val.ClaimOwnership();
					}
					val.GetZDO().Set("rhui_name", text);
				}
			}
		}

		[HarmonyPatch(typeof(Container), "GetHoverText")]
		private static class Hover
		{
			private static void Postfix(Container __instance, ref string __result)
			{
				try
				{
					if (Qol.RenameOn && !string.IsNullOrEmpty(__result) && !((Object)(object)((Component)__instance).GetComponent<TombStone>() != (Object)null) && !__result.Contains(Localization.instance.Localize("$piece_noaccess")))
					{
						string text = Get(__instance);
						if (text != "")
						{
							int num = __result.IndexOf('\n');
							string text2 = ((num >= 0) ? __result.Substring(0, num) : __result);
							string text3 = ((num >= 0) ? __result.Substring(num) : "");
							int num2 = text2.IndexOf(" (", StringComparison.Ordinal);
							__result = text + ((num2 >= 0) ? text2.Substring(num2) : "") + text3;
						}
						hint = Localization.instance.Localize("\n[<color=yellow><b>" + Pad.AltUseKeys + "</b></color>] Rename");
						__result += hint;
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\ChestNames.cs", 84, "Postfix");
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "UpdateContainer")]
		private static class Title
		{
			private static void Postfix(InventoryGui __instance)
			{
				try
				{
					if (!Qol.RenameOn || (Object)(object)__instance.m_containerName == (Object)null)
					{
						return;
					}
					Container current = Chests.Current;
					if (!((Object)(object)current == (Object)null))
					{
						string text = Get(current);
						if (text != "" && __instance.m_containerName.text != text)
						{
							__instance.m_containerName.text = text;
						}
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\ChestNames.cs", 102, "Postfix");
				}
			}
		}

		private const string Key = "rhui_name";

		private static string hint;

		public static string Get(Container c)
		{
			ZNetView val = Chests.View(c);
			if (!((Object)(object)val != (Object)null) || !val.IsValid())
			{
				return "";
			}
			return val.GetZDO().GetString("rhui_name", "");
		}

		public static string Display(Container c)
		{
			string text = Get(c);
			if (!(text != ""))
			{
				return Localization.instance.Localize(c.m_name);
			}
			return text;
		}

		private static bool MayRename(Container c, Player p)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			if (c.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)c).transform.position, 0f, true, false))
			{
				return false;
			}
			if ((int)c.m_privacy == 0)
			{
				Piece val = Chests.PieceOf(c);
				if ((Object)(object)val != (Object)null)
				{
					return val.GetCreator() == p.GetPlayerID();
				}
				return false;
			}
			return (int)c.m_privacy == 2;
		}

		public static bool TryRename(Container c, Player p)
		{
			if ((Object)(object)c == (Object)null || (Object)(object)((Component)c).GetComponent<TombStone>() != (Object)null || (Object)(object)TextInput.instance == (Object)null)
			{
				return false;
			}
			if (!MayRename(c, p))
			{
				((Character)p).Message((MessageType)2, "$msg_cantopen", 0, (Sprite)null, false);
				return true;
			}
			TextInput.instance.RequestText((TextReceiver)(object)new Namer(c), "Name this chest", 32);
			return true;
		}
	}
	public static class Chests
	{
		[HarmonyPatch(typeof(Container), "Awake")]
		private static class ContainerAwake
		{
			private static void Postfix(Container __instance)
			{
				try
				{
					if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).GetComponent<TombStone>() == (Object)null)
					{
						All.Add(__instance);
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Chests.cs", 25, "Postfix");
				}
			}
		}

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

		private static readonly FieldRef<Container, ZNetView> CView = RhSafe.FieldRef<Container, ZNetView>("m_nview", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Chests.cs", 15);

		private static readonly FieldRef<Container, Piece> CPiece = RhSafe.FieldRef<Container, Piece>("m_piece", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Chests.cs", 16);

		private static readonly MethodInfo CLoad = AccessTools.Method(typeof(Container), "Load", (Type[])null, (Type[])null);

		private static readonly FieldRef<InventoryGui, Container> Open = RhSafe.FieldRef<InventoryGui, Container>("m_currentContainer", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Chests.cs", 18);

		public static Container Current
		{
			get
			{
				if (!((Object)(object)InventoryGui.instance != (Object)null) || !InventoryGui.instance.IsContainerOpen())
				{
					return null;
				}
				return Open.Invoke(InventoryGui.instance);
			}
		}

		public static ZNetView View(Container c)
		{
			if (!((Object)(object)c != (Object)null))
			{
				return null;
			}
			return CView.Invoke(c);
		}

		public static Piece PieceOf(Container c)
		{
			if (!((Object)(object)c != (Object)null))
			{
				return null;
			}
			return CPiece.Invoke(c);
		}

		public static List<Container> Nearby(Vector3 pos, float range, ICollection<ZDOID> only = null, bool? carts = null)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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)
			List<Container> list = new List<Container>();
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return list;
			}
			long playerID = localPlayer.GetPlayerID();
			float num = range * range;
			for (int num2 = All.Count - 1; num2 >= 0; num2--)
			{
				Container val = All[num2];
				if ((Object)(object)val == (Object)null)
				{
					All.RemoveAt(num2);
				}
				else
				{
					Vector3 val2 = ((Component)val).transform.position - pos;
					if (!(((Vector3)(ref val2)).sqrMagnitude > num))
					{
						ZNetView val3 = CView.Invoke(val);
						if (!((Object)(object)val3 == (Object)null) && val3.IsValid() && (only == null || only.Count <= 0 || only.Contains(val3.GetZDO().m_uid)) && !(((Object)(object)((Component)val).GetComponentInParent<Vagon>() != (Object)null || (Object)(object)((Component)val).GetComponentInParent<Ship>() != (Object)null) ? (!(carts ?? Qol.MachineCarts.Value)) : ((Object)(object)CPiece.Invoke(val) == (Object)null)) && MayUse(val, val3, playerID))
						{
							list.Add(val);
						}
					}
				}
			}
			list.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 val4 = ((Component)a).transform.position - pos;
				float sqrMagnitude = ((Vector3)(ref val4)).sqrMagnitude;
				val4 = ((Component)b).transform.position - pos;
				return sqrMagnitude.CompareTo(((Vector3)(ref val4)).sqrMagnitude);
			});
			return list;
		}

		private static bool MayUse(Container c, ZNetView nv, long pid)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_0052: Invalid comparison between Unknown and I4
			if (!((Object)(object)Current == (Object)(object)c) && nv.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1)
			{
				return false;
			}
			if (c.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)c).transform.position, 0f, false, false))
			{
				return false;
			}
			PrivacySetting privacy = c.m_privacy;
			if ((int)privacy != 0)
			{
				if ((int)privacy == 2)
				{
					return true;
				}
				return false;
			}
			Piece val = CPiece.Invoke(c);
			if ((Object)(object)val != (Object)null)
			{
				return val.GetCreator() == pid;
			}
			return false;
		}

		public static bool Claim(Container c)
		{
			ZNetView val = CView.Invoke(c);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return false;
			}
			if (!val.IsOwner())
			{
				val.ClaimOwnership();
			}
			try
			{
				CLoad?.Invoke(c, null);
			}
			catch (Exception e)
			{
				RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Chests.cs", 79, "Claim");
			}
			return val.IsOwner();
		}

		public static void Invalidate()
		{
			Logistics.Invalidate();
		}

		public static int Take(string name, int amount, Vector3 pos, float range, ICollection<ZDOID> only = null, bool? carts = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			foreach (Container item in Nearby(pos, range, only, carts))
			{
				if (num >= amount)
				{
					break;
				}
				int num2 = item.GetInventory().CountItems(name, -1, true);
				if (num2 > 0 && Claim(item))
				{
					int num3 = Mathf.Min(num2, amount - num);
					item.GetInventory().RemoveItem(name, num3, -1, true);
					num += num3;
				}
			}
			Invalidate();
			return num;
		}
	}
	public class Discoveries : MonoBehaviour
	{
		private enum Kind
		{
			Crypt,
			Sunken,
			Cave,
			Mine,
			Copper,
			Tin,
			Silver,
			Obsidian,
			Iron,
			Marble,
			Flametal,
			Camp,
			Tar
		}

		private class Mark
		{
			public Kind K;

			public Vector3 Pos;

			public PinData Pin;

			public bool WasAway = true;

			public float ClearSince = -1f;
		}

		[HarmonyPatch(typeof(MineRock5), "Damage")]
		private static class HitRock5
		{
			private static void Postfix(MineRock5 __instance, HitData hit)
			{
				Hit((Component)(object)__instance, hit);
			}
		}

		[HarmonyPatch(typeof(MineRock), "Damage")]
		private static class HitRock
		{
			private static void Postfix(MineRock __instance, HitData hit)
			{
				Hit((Component)(object)__instance, hit);
			}
		}

		[HarmonyPatch(typeof(Destructible), "Damage")]
		private static class HitDestructible
		{
			private static void Postfix(Destructible __instance, HitData hit)
			{
				Hit((Component)(object)__instance, hit);
			}
		}

		public static ConfigEntry<bool> On;

		public static ConfigEntry<bool> Dungeons;

		public static ConfigEntry<bool> Ore;

		public static ConfigEntry<bool> Camps;

		public static ConfigEntry<bool> Server;

		public static ConfigEntry<bool> ShowOnMap;

		private static readonly List<Mark> marks = new List<Mark>();

		private static string loadedFor;

		private float next;

		private static readonly FieldRef<EnvMan, string> ForcedEnv = RhSafe.FieldRef<EnvMan, string>("m_forceEnv", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Discoveries.cs", 218);

		private static int roofMask;

		private static bool Active
		{
			get
			{
				if (Qol.Master.Value && On.Value)
				{
					return Server.Value;
				}
				return false;
			}
		}

		private static int RoofMask
		{
			get
			{
				if (roofMask == 0)
				{
					return roofMask = LayerMask.GetMask(new string[2] { "static_solid", "terrain" });
				}
				return roofMask;
			}
		}

		public static void Init(ConfigFile c)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			On = c.Bind<bool>("Discoveries", "Mark discoveries", true, "Places you have found mark themselves on your map: ore you have hit, dungeons you have been inside, camps you have walked into.");
			Dungeons = c.Bind<bool>("Discoveries", "Dungeons", true, "Burial chambers, sunken crypts, troll caves, frost caves and infested mines.");
			Ore = c.Bind<bool>("Discoveries", "Ore", true, "Copper, tin, silver, obsidian, iron scrap, black marble and flametal deposits.");
			Camps = c.Bind<bool>("Discoveries", "Camps and villages", true, "Fuling camps, draugr villages, Dvergr camps and tar pits.");
			ShowOnMap = c.Bind<bool>("Discoveries", "Show on the map", true, "Show the discovery markers (also the Discoveries chip on the large map).");
			Server = c.Bind<bool>("Server", "Allow discovery markers", true, new ConfigDescription("Server: players may have discoveries mark themselves on their map.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}

		private static Kind? OreKind(string n)
		{
			n = n.ToLowerInvariant();
			if (n.Contains("copper"))
			{
				return Kind.Copper;
			}
			if (n.Contains("minerock_tin") || n.StartsWith("tin"))
			{
				return Kind.Tin;
			}
			if (n.Contains("silvervein") || n.Contains("silver"))
			{
				return Kind.Silver;
			}
			if (n.Contains("obsidian"))
			{
				return Kind.Obsidian;
			}
			if (n.Contains("mudpile"))
			{
				return Kind.Iron;
			}
			if (n.Contains("blackmarble"))
			{
				return Kind.Marble;
			}
			if (n.Contains("meteorite") || n.Contains("flametal"))
			{
				return Kind.Flametal;
			}
			return null;
		}

		private static Kind? PlaceKind(string n)
		{
			n = n.ToLowerInvariant();
			if (n.Contains("sunkencrypt"))
			{
				return Kind.Sunken;
			}
			if (n.Contains("crypt"))
			{
				return Kind.Crypt;
			}
			if (n.Contains("trollcave") || n.Contains("mountaincave") || n.Contains("cave"))
			{
				return Kind.Cave;
			}
			if (n.Contains("dvergrtownentrance") || n.Contains("infested"))
			{
				return Kind.Mine;
			}
			if (n.Contains("goblincamp") || n.Contains("woodvillage") || n.Contains("draugrvillage") || n.Contains("dvergr"))
			{
				return Kind.Camp;
			}
			if (n.Contains("tarpit"))
			{
				return Kind.Tar;
			}
			return null;
		}

		private static bool IsDungeon(Kind k)
		{
			if (k != Kind.Crypt && k != Kind.Sunken && k != Kind.Cave)
			{
				return k == Kind.Mine;
			}
			return true;
		}

		private static bool IsOre(Kind k)
		{
			if (k >= Kind.Copper)
			{
				return k <= Kind.Flametal;
			}
			return false;
		}

		private static bool Wanted(Kind k)
		{
			if (!IsDungeon(k))
			{
				if (!IsOre(k))
				{
					return Camps.Value;
				}
				return Ore.Value;
			}
			return Dungeons.Value;
		}

		private static string Name(Kind k)
		{
			return k switch
			{
				Kind.Crypt => "Burial chamber", 
				Kind.Sunken => "Sunken crypt", 
				Kind.Cave => "Cave", 
				Kind.Mine => "Infested mine", 
				Kind.Iron => "Iron (scrap)", 
				Kind.Marble => "Black marble", 
				Kind.Camp => "Camp", 
				Kind.Tar => "Tar pit", 
				_ => k.ToString(), 
			};
		}

		private static Sprite Icon(Kind k)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			Sprite val = MarkArt.ThemeArt("mark_" + k.ToString().ToLowerInvariant());
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			return (Sprite)(k switch
			{
				Kind.Crypt => MarkArt.Mark("crypt", 30f, Color.black), 
				Kind.Sunken => MarkArt.Mark("sunken", 30f, Color.black), 
				Kind.Cave => MarkArt.Mark("cave", 30f, Color.black), 
				Kind.Mine => MarkArt.Mark("mine", 30f, Color.black), 
				Kind.Camp => MarkArt.Mark("camp", 30f, Color.black), 
				Kind.Tar => MarkArt.Mark("tar", 30f, Color.black), 
				Kind.Copper => MarkArt.Mark("ore", 30f, MarkArt.Hex("#c8743a")), 
				Kind.Tin => MarkArt.Mark("ore", 30f, MarkArt.Hex("#9aa3a8")), 
				Kind.Silver => MarkArt.Mark("ore", 30f, MarkArt.Hex("#e8eef2")), 
				Kind.Obsidian => MarkArt.Mark("ore", 30f, MarkArt.Hex("#2a2236")), 
				Kind.Iron => MarkArt.Mark("ore", 30f, MarkArt.Hex("#7a4a34")), 
				Kind.Marble => MarkArt.Mark("ore", 30f, MarkArt.Hex("#1c1d22")), 
				_ => MarkArt.Mark("ore", 30f, MarkArt.Hex("#e05a2a")), 
			});
		}

		private static string FilePath()
		{
			Player localPlayer = Player.m_localPlayer;
			ZNet instance = ZNet.instance;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null)
			{
				return null;
			}
			string text = instance.GetWorldName() ?? "world";
			string text2 = localPlayer.GetPlayerName();
			char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
			foreach (char oldChar in invalidFileNameChars)
			{
				text = text.Replace(oldChar, '_');
				text2 = text2.Replace(oldChar, '_');
			}
			string path = text + "_" + text2 + ".txt";
			string text3 = Path.Combine(Paths.ConfigPath, "RuneheimQOL", "discoveries", path);
			string text4 = Path.Combine(Paths.ConfigPath, "RuneheimUI", "discoveries", path);
			try
			{
				if (!File.Exists(text3) && File.Exists(text4))
				{
					Directory.CreateDirectory(Path.GetDirectoryName(text3));
					File.Copy(text4, text3);
				}
			}
			catch (Exception e)
			{
				RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Discoveries.cs", 122, "FilePath");
			}
			return text3;
		}

		private static void Load()
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			string text = FilePath();
			if (text == null || text == loadedFor)
			{
				return;
			}
			ClearPins();
			marks.Clear();
			loadedFor = text;
			if (!File.Exists(text))
			{
				return;
			}
			string[] array = File.ReadAllLines(text);
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(new char[1] { ';' });
				if (array2.Length >= 4 && Enum.TryParse<Kind>(array2[0], out var result) && float.TryParse(array2[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) && float.TryParse(array2[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var result3) && float.TryParse(array2[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var result4))
				{
					marks.Add(new Mark
					{
						K = result,
						Pos = new Vector3(result2, result3, result4)
					});
				}
			}
		}

		private static void Save()
		{
			string text = loadedFor;
			if (text == null)
			{
				return;
			}
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(text));
				CultureInfo invariantCulture = CultureInfo.InvariantCulture;
				List<string> list = new List<string>();
				foreach (Mark mark in marks)
				{
					list.Add(string.Format("{0};{1};{2};{3}", mark.K, mark.Pos.x.ToString("0.0", invariantCulture), mark.Pos.y.ToString("0.0", invariantCulture), mark.Pos.z.ToString("0.0", invariantCulture)));
				}
				File.WriteAllLines(text, list);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Discoveries: could not save: " + ex.Message));
			}
		}

		private static void Discover(Kind k, Vector3 pos)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || !Wanted(k))
			{
				return;
			}
			Load();
			foreach (Mark mark in marks)
			{
				if (mark.K == k && Utils.DistanceXZ(mark.Pos, pos) < 20f)
				{
					return;
				}
			}
			marks.Add(new Mark
			{
				K = k,
				Pos = pos,
				WasAway = false
			});
			Save();
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)1, "Discovered: " + Name(k), 0, (Sprite)null, false);
			}
		}

		private static void ClearPins()
		{
			foreach (Mark mark in marks)
			{
				if (mark.Pin == null)
				{
					continue;
				}
				try
				{
					Minimap instance = Minimap.instance;
					if (instance != null)
					{
						instance.RemovePin(mark.Pin);
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Discoveries.cs", 171, "ClearPins");
				}
				mark.Pin = null;
			}
		}

		private static void SyncPins()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			Minimap instance = Minimap.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			bool flag = Active && ShowOnMap.Value;
			foreach (Mark mark in marks)
			{
				bool flag2 = flag && Wanted(mark.K);
				if (flag2 && mark.Pin == null)
				{
					mark.Pin = instance.AddPin(mark.Pos, (PinType)13, "", false, false, 0L, default(PlatformUserID));
					mark.Pin.m_icon = Icon(mark.K);
					mark.Pin.m_worldSize = 0f;
					mark.Pin.m_doubleSize = false;
					if ((Object)(object)mark.Pin.m_iconElement != (Object)null)
					{
						mark.Pin.m_iconElement.sprite = mark.Pin.m_icon;
					}
				}
				else if (!flag2 && mark.Pin != null)
				{
					instance.RemovePin(mark.Pin);
					mark.Pin = null;
				}
			}
		}

		private void Update()
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)Minimap.instance == (Object)null)
			{
				if (loadedFor != null)
				{
					marks.Clear();
					loadedFor = null;
				}
				return;
			}
			if (Time.time < next)
			{
				return;
			}
			next = Time.time + 1f;
			Load();
			Vector3 position;
			Location location;
			Kind? kind;
			if (Active)
			{
				Player localPlayer = Player.m_localPlayer;
				position = ((Component)localPlayer).transform.position;
				location = Location.GetLocation(position, true);
				if ((Object)(object)location != (Object)null)
				{
					kind = PlaceKind(Utils.GetPrefabName(((Component)location).gameObject));
					if (kind.HasValue)
					{
						bool num;
						if (kind.Value != Kind.Cave)
						{
							if (!IsDungeon(kind.Value))
							{
								goto IL_00c7;
							}
							num = ((Character)localPlayer).InInterior();
						}
						else
						{
							num = InCave(localPlayer);
						}
						if (num)
						{
							goto IL_00c7;
						}
					}
				}
				goto IL_00de;
			}
			goto IL_00e3;
			IL_00de:
			ForgetMinedOut(position);
			goto IL_00e3;
			IL_00c7:
			Discover(kind.Value, ((Component)location).transform.position);
			goto IL_00de;
			IL_00e3:
			SyncPins();
		}

		private static bool InCave(Player p)
		{
			//IL_0066: 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)
			if (((Character)p).InInterior())
			{
				return true;
			}
			EnvMan instance = EnvMan.instance;
			if ((Object)(object)instance != (Object)null && !string.IsNullOrEmpty(ForcedEnv.Invoke(instance)))
			{
				return true;
			}
			EnvSetup val = (((Object)(object)instance != (Object)null) ? instance.GetCurrentEnvironment() : null);
			if (val != null && val.m_name != null && val.m_name.ToLowerInvariant().Contains("cave"))
			{
				return true;
			}
			return Physics.Raycast(((Character)p).GetHeadPoint(), Vector3.up, 40f, RoofMask);
		}

		private static void ForgetMinedOut(Vector3 pos)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			for (int num = marks.Count - 1; num >= 0; num--)
			{
				Mark mark = marks[num];
				if (IsOre(mark.K))
				{
					float num2 = Utils.DistanceXZ(mark.Pos, pos);
					if (num2 > 50f)
					{
						mark.WasAway = true;
					}
					if (!mark.WasAway || num2 > 30f || !ZoneSystem.instance.IsZoneLoaded(mark.Pos))
					{
						mark.ClearSince = -1f;
					}
					else
					{
						bool flag2 = false;
						Collider[] array = Physics.OverlapSphere(mark.Pos, 12f);
						foreach (Collider obj in array)
						{
							MineRock5 componentInParent = ((Component)obj).GetComponentInParent<MineRock5>();
							MineRock componentInParent2 = ((Component)obj).GetComponentInParent<MineRock>();
							Destructible componentInParent3 = ((Component)obj).GetComponentInParent<Destructible>();
							GameObject val = (((Object)(object)componentInParent != (Object)null) ? ((Component)componentInParent).gameObject : (((Object)(object)componentInParent2 != (Object)null) ? ((Component)componentInParent2).gameObject : (((Object)(object)componentInParent3 != (Object)null) ? ((Component)componentInParent3).gameObject : null)));
							if ((Object)(object)val != (Object)null && OreKind(Utils.GetPrefabName(val)) == mark.K)
							{
								flag2 = true;
								break;
							}
						}
						if (flag2)
						{
							mark.ClearSince = -1f;
						}
						else
						{
							if (mark.ClearSince < 0f)
							{
								mark.ClearSince = Time.time;
							}
							if (!(Time.time - mark.ClearSince < 5f))
							{
								if (mark.Pin != null)
								{
									Minimap instance = Minimap.instance;
									if (instance != null)
									{
										instance.RemovePin(mark.Pin);
									}
									mark.Pin = null;
								}
								marks.RemoveAt(num);
								flag = true;
							}
						}
					}
				}
			}
			if (flag)
			{
				Save();
			}
		}

		private static void Hit(Component rock, HitData hit)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((Object)(object)rock == (Object)null) && hit != null && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)hit.GetAttacker() != (Object)(object)Player.m_localPlayer))
				{
					Kind? kind = OreKind(Utils.GetPrefabName(rock.gameObject));
					if (kind.HasValue)
					{
						Discover(kind.Value, rock.transform.position);
					}
				}
			}
			catch (Exception e)
			{
				RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\Discoveries.cs", 276, "Hit");
			}
		}
	}
	public static class InvActions
	{
		private static readonly FieldRef<Inventory, List<ItemData>> Items = RhSafe.FieldRef<Inventory, List<ItemData>>("m_inventory", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\InvActions.cs", 20);

		private static readonly MethodInfo mChanged = AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null);

		private static readonly FieldRef<InventoryGui, Container> OpenContainer = RhSafe.FieldRef<InventoryGui, Container>("m_currentContainer", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\InvActions.cs", 66);

		private static void Changed(Inventory inv)
		{
			try
			{
				mChanged?.Invoke(inv, (mChanged.GetParameters().Length != 2) ? new object[0] : new object[2] { false, false });
			}
			catch (Exception e)
			{
				RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\InvActions.cs", 25, "Changed");
			}
		}

		private static bool Movable(Player p, ItemData it)
		{
			if (it.m_gridPos.y >= 1 && Bag.IsMain(it.m_gridPos.x, it.m_gridPos.y))
			{
				return !((Humanoid)p).IsItemEquiped(it);
			}
			return false;
		}

		private static bool Material(ItemData it)
		{
			if (it.m_shared.m_maxStackSize > 1)
			{
				return it.m_shared.m_maxQuality <= 1;
			}
			return false;
		}

		public static void Sort()
		{
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			Player p = Player.m_localPlayer;
			if ((Object)(object)p == (Object)null)
			{
				return;
			}
			try
			{
				Inventory inventory = ((Humanoid)p).GetInventory();
				List<ItemData> list = Items.Invoke(inventory);
				List<ItemData> mine = list.Where((ItemData i) => Movable(p, i)).ToList();
				foreach (IGrouping<(string, int, int, int), ItemData> item in (from i in mine
					where i.m_shared.m_maxStackSize > 1
					group i by (m_name: i.m_shared.m_name, m_quality: i.m_quality, m_variant: i.m_variant, m_worldLevel: i.m_worldLevel)).ToList())
				{
					int num = item.Sum((ItemData i) => i.m_stack);
					int maxStackSize = item.First().m_shared.m_maxStackSize;
					foreach (ItemData item2 in item)
					{
						item2.m_stack = Mathf.Min(maxStackSize, num);
						num -= item2.m_stack;
						if (item2.m_stack <= 0)
						{
							list.Remove(item2);
							mine.Remove(item2);
						}
					}
				}
				mine.Sort(delegate(ItemData a, ItemData b)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Expected I4, but got Unknown
					//IL_0014: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Expected I4, but got Unknown
					int num4 = ((int)a.m_shared.m_itemType).CompareTo((int)b.m_shared.m_itemType);
					if (num4 == 0)
					{
						num4 = string.Compare(Localization.instance.Localize(a.m_shared.m_name), Localization.instance.Localize(b.m_shared.m_name), StringComparison.CurrentCulture);
					}
					if (num4 == 0)
					{
						num4 = b.m_quality.CompareTo(a.m_quality);
					}
					return (num4 == 0) ? b.m_stack.CompareTo(a.m_stack) : num4;
				});
				HashSet<Vector2i> hashSet = new HashSet<Vector2i>(from i in list
					where !mine.Contains(i)
					select i.m_gridPos);
				int width = inventory.GetWidth();
				int num2 = 0;
				foreach (int item3 in Bag.Rows(inventory))
				{
					for (int num3 = 0; num3 < width; num3++)
					{
						if (num2 >= mine.Count)
						{
							break;
						}
						if (item3 < 1)
						{
							break;
						}
						if (Bag.IsMain(num3, item3) && !hashSet.Contains(new Vector2i(num3, item3)))
						{
							mine[num2++].m_gridPos = new Vector2i(num3, item3);
						}
					}
				}
				Changed(inventory);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Sort: " + ex.Message));
			}
		}

		public static void SortChest()
		{
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null || !Qol.Master.Value)
			{
				return;
			}
			try
			{
				Container val = OpenContainer.Invoke(instance);
				ZNetView val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<ZNetView>() : null);
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || !val2.IsValid())
				{
					return;
				}
				if (!val2.IsOwner())
				{
					((Character)localPlayer).Message((MessageType)2, "Someone else is using this chest", 0, (Sprite)null, false);
					return;
				}
				Inventory inventory = val.GetInventory();
				List<ItemData> list = Items.Invoke(inventory);
				foreach (IGrouping<(string, int, int, int), ItemData> item in (from i in list
					where i.m_shared.m_maxStackSize > 1
					group i by (m_name: i.m_shared.m_name, m_quality: i.m_quality, m_variant: i.m_variant, m_worldLevel: i.m_worldLevel)).ToList())
				{
					int num = item.Sum((ItemData i) => i.m_stack);
					int maxStackSize = item.First().m_shared.m_maxStackSize;
					foreach (ItemData item2 in item.ToList())
					{
						item2.m_stack = Mathf.Min(maxStackSize, num);
						num -= item2.m_stack;
						if (item2.m_stack <= 0)
						{
							list.Remove(item2);
						}
					}
				}
				List<ItemData> list2 = list.ToList();
				list2.Sort(delegate(ItemData a, ItemData b)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Expected I4, but got Unknown
					//IL_0014: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Expected I4, but got Unknown
					int num3 = ((int)a.m_shared.m_itemType).CompareTo((int)b.m_shared.m_itemType);
					if (num3 == 0)
					{
						num3 = string.Compare(Localization.instance.Localize(a.m_shared.m_name), Localization.instance.Localize(b.m_shared.m_name), StringComparison.CurrentCulture);
					}
					if (num3 == 0)
					{
						num3 = b.m_quality.CompareTo(a.m_quality);
					}
					return (num3 == 0) ? b.m_stack.CompareTo(a.m_stack) : num3;
				});
				int width = inventory.GetWidth();
				for (int num2 = 0; num2 < list2.Count; num2++)
				{
					list2[num2].m_gridPos = new Vector2i(num2 % width, num2 / width);
				}
				Changed(inventory);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Chest sort: " + ex.Message));
			}
		}

		public static void Pull()
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !Check(localPlayer))
			{
				return;
			}
			try
			{
				Inventory inventory = ((Humanoid)localPlayer).GetInventory();
				int num = 0;
				foreach (ItemData item in Items.Invoke(inventory).Where(Material).ToList())
				{
					int num2 = item.m_shared.m_maxStackSize - item.m_stack;
					if (num2 > 0)
					{
						int num3 = Logistics.Take(item.m_shared.m_name, num2, ((Component)localPlayer).transform.position, Logistics.Range.Value);
						if (num3 > 0)
						{
							item.m_stack += num3;
							num += num3;
						}
					}
				}
				Changed(inventory);
				((Character)localPlayer).Message((MessageType)1, (num > 0) ? $"Took {num} from nearby chests" : "Nothing to top up nearby", 0, (Sprite)null, false);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Pull: " + ex.Message));
			}
		}

		public static void Store()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Player p = Player.m_localPlayer;
			if ((Object)(object)p == (Object)null || !Check(p))
			{
				return;
			}
			try
			{
				Inventory inventory = ((Humanoid)p).GetInventory();
				int num = 0;
				List<Container> list = Logistics.Nearby(((Component)p).transform.position, Logistics.Range.Value);
				foreach (ItemData item in (from i in Items.Invoke(inventory)
					where Movable(p, i) && i.m_shared.m_maxStackSize > 1
					select i).ToList())
				{
					foreach (Container item2 in list)
					{
						Inventory inventory2 = item2.GetInventory();
						if (item.m_stack <= 0 || inventory2.CountItems(item.m_shared.m_name, -1, true) <= 0)
						{
							continue;
						}
						int num2 = Mathf.Min(inventory2.FindFreeStackSpace(item.m_shared.m_name, (float)item.m_worldLevel) + inventory2.GetEmptySlots() * item.m_shared.m_maxStackSize, item.m_stack);
						if (num2 > 0 && Logistics.Claim(item2))
						{
							ItemData val = item.Clone();
							val.m_stack = num2;
							if (inventory2.AddItem(val))
							{
								inventory.RemoveItem(item, num2);
								num += num2;
							}
						}
					}
				}
				Logistics.Invalidate();
				((Character)p).Message((MessageType)1, (num > 0) ? $"Stored {num} in nearby chests" : "No nearby chest holds those items", 0, (Sprite)null, false);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Store: " + ex.Message));
			}
		}

		private static bool Check(Player p)
		{
			if (Logistics.PullStoreOn)
			{
				return true;
			}
			((Character)p).Message((MessageType)2, (!Qol.Master.Value) ? "Runeheim QOL is switched off" : ((!Logistics.ServerPullStore.Value) ? "The server has turned this off" : "Path of Valheiman handles this (its quick stack)"), 0, (Sprite)null, false);
			return false;
		}
	}
	public static class Logistics
	{
		[HarmonyPatch(typeof(Player), "HaveRequirementItems")]
		private static class HaveRecipeItems
		{
			private static void Postfix(Player __instance, Recipe piece, bool discover, int qualityLevel, int amount, ref bool __result)
			{
				try
				{
					if (__result || discover || !CraftOn || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)piece == (Object)null)
					{
						return;
					}
					CraftingStation currentCraftingStation = __instance.GetCurrentCraftingStation();
					bool flag = false;
					Requirement[] resources = piece.m_resources;
					foreach (Requirement val in resources)
					{
						if (!Object.op_Implicit((Object)(object)val.m_resItem) || ((Object)(object)currentCraftingStation != (Object)null && currentCraftingStation.m_upgrader != val.m_upgraderResource) || ((Object)(object)currentCraftingStation == (Object)null && val.m_upgraderResource))
						{
							continue;
						}
						bool flag2 = Have(__instance, val.m_resItem.m_itemData.m_shared.m_name, craft: true) >= val.GetAmount(qualityLevel) * amount;
						if (piece.m_requireOnlyOneIngredient)
						{
							if (flag2)
							{
								flag = true;
								break;
							}
						}
						else if (!flag2)
						{
							return;
						}
					}
					__result = !piece.m_requireOnlyOneIngredient || flag;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Craft from chests: " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
		{
			typeof(Piece),
			typeof(RequirementMode)
		})]
		private static class HavePieceItems
		{
			private static void Postfix(Player __instance, Piece piece, RequirementMode mode, ref bool __result)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Invalid comparison between Unknown and I4
				//IL_0048: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Invalid comparison between Unknown and I4
				try
				{
					if (__result || (int)mode == 1 || !BuildOn || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)piece == (Object)null || (Object.op_Implicit((Object)(object)piece.m_craftingStation) && !Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, ((Component)__instance).transform.position)) && !ZoneSystem.instance.GetGlobalKey((GlobalKeys)27)) || (piece.m_dlc.Length > 0 && !DLCMan.instance.IsDLCInstalled(piece.m_dlc)))
					{
						return;
					}
					Requirement[] resources = piece.m_resources;
					foreach (Requirement val in resources)
					{
						if (Object.op_Implicit((Object)(object)val.m_resItem) && val.m_amount > 0)
						{
							int num = Have(__instance, val.m_resItem.m_itemData.m_shared.m_name, craft: false);
							if (((int)mode == 2) ? (num <= 0) : (num < val.m_amount))
							{
								return;
							}
						}
					}
					__result = true;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Build from chests: " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		private static class Consume
		{
			private static void Prefix(Player __instance, Requirement[] requirements, out Dictionary<string, int> __state)
			{
				__state = null;
				try
				{
					if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || requirements == null || !(((Character)__instance).InPlaceMode() ? BuildOn : CraftOn))
					{
						return;
					}
					__state = new Dictionary<string, int>();
					foreach (Requirement val in requirements)
					{
						if (Object.op_Implicit((Object)(object)val.m_resItem))
						{
							__state[val.m_resItem.m_itemData.m_shared.m_name] = ((Humanoid)__instance).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1, true);
						}
					}
				}
				catch (Exception ex)
				{
					__state = null;
					Plugin.Log.LogWarning((object)("Chests (before use): " + ex.Message));
				}
			}

			private static void Postfix(Player __instance, Requirement[] requirements, int qualityLevel, int multiplier, Dictionary<string, int> __state)
			{
				//IL_0023: 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_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				if (__state == null)
				{
					return;
				}
				try
				{
					CraftingStation currentCraftingStation = __instance.GetCurrentCraftingStation();
					Vector3 pos = (((Character)__instance).InPlaceMode() ? ((Component)__instance).transform.position : Origin(__instance));
					foreach (Requirement val in requirements)
					{
						if (Object.op_Implicit((Object)(object)val.m_resItem) && (!((Object)(object)currentCraftingStation != (Object)null) || currentCraftingStation.m_upgrader == val.m_upgraderResource) && (!((Object)(object)currentCraftingStation == (Object)null) || !val.m_upgraderResource))
						{
							string name = val.m_resItem.m_itemData.m_shared.m_name;
							int num = val.GetAmount(qualityLevel) * multiplier;
							int value;
							int num2 = Mathf.Min(num, __state.TryGetValue(name, out value) ? value : 0);
							__state[name] = Mathf.Max(0, value - num2);
							if (num - num2 > 0)
							{
								Take(name, num - num2, pos, Range.Value);
							}
						}
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Chests (use): " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
		private static class ShowCounts
		{
			private static void Postfix(Transform elementRoot, Requirement req, Player player, bool craft, int quality, int craftMultiplier, bool __result)
			{
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					if (!__result || req == null || (Object)(object)req.m_resItem == (Object)null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
					{
						return;
					}
					bool flag = ((Character)player).InPlaceMode();
					if (!(flag ? BuildOn : CraftOn))
					{
						return;
					}
					Transform obj = elementRoot.Find("res_amount");
					TMP_Text val = ((obj != null) ? ((Component)obj).GetComponent<TMP_Text>() : null);
					if ((Object)(object)val == (Object)null)
					{
						return;
					}
					int num = req.GetAmount(quality) * craftMultiplier;
					if (num > 0)
					{
						int num2 = Have(player, req.m_resItem.m_itemData.m_shared.m_name, !flag);
						val.text = num2 + "/" + num;
						if (num2 >= num)
						{
							((Graphic)val).color = Color.white;
						}
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Chest counts: " + ex.Message));
				}
			}
		}

		public static ConfigEntry<bool> CraftFromChests;

		public static ConfigEntry<bool> BuildFromChests;

		public static ConfigEntry<bool> IncludeCarts;

		public static ConfigEntry<float> Range;

		public static ConfigEntry<KeyboardShortcut> ToggleKey;

		public static ConfigEntry<bool> ServerCraft;

		public static ConfigEntry<bool> ServerBuild;

		public static ConfigEntry<bool> ServerPullStore;

		private static readonly MethodInfo mSync = AccessTools.Method(typeof(SynchronizationManager), "SynchronizeChangedConfig", (Type[])null, (Type[])null);

		private static float cacheTime = -1f;

		private static Vector3 cachePos;

		private static readonly Dictionary<string, int> cache = new Dictionary<string, int>();

		public static bool IsAdmin => RhServer.IsAdmin;

		public static bool CraftOn
		{
			get
			{
				if (Qol.Master.Value && CraftFromChests.Value && ServerCraft.Value)
				{
					return !PovHandover.Crafts;
				}
				return false;
			}
		}

		public static bool BuildOn
		{
			get
			{
				if (Qol.Master.Value && BuildFromChests.Value && ServerBuild.Value)
				{
					return !PovHandover.Builds;
				}
				return false;
			}
		}

		public static bool PullStoreOn
		{
			get
			{
				if (Qol.Master.Value && ServerPullStore.Value)
				{
					return !PovHandover.Stores;
				}
				return false;
			}
		}

		public static void Init(ConfigFile c)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			CraftFromChests = c.Bind<bool>("Logistics", "Craft from chests", true, "Crafting at a station also uses materials from nearby chests (your inventory first).");
			BuildFromChests = c.Bind<bool>("Logistics", "Build from chests", true, "Building with the hammer, hoe or cultivator also uses materials from nearby chests (your inventory first).");
			IncludeCarts = c.Bind<bool>("Logistics", "Use carts and ships", false, "Also take materials from carts and ship storage nearby.");
			Range = c.Bind<float>("Logistics", "Chest range", 20f, new ConfigDescription("How far (meters) from the crafting station, or from you when building, chests are used.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 50f), Array.Empty<object>()));
			ToggleKey = c.Bind<KeyboardShortcut>("Logistics", "Toggle key", new KeyboardShortcut((KeyCode)0, Array.Empty<KeyCode>()), "Turns crafting and building from chests on / off in game (none by default).");
			RhKeys.Register(ToggleKey);
			ServerCraft = c.Bind<bool>("Server", "Allow craft from chests", true, Admin("Server: players may craft with materials from nearby chests."));
			ServerBuild = c.Bind<bool>("Server", "Allow build from chests", true, Admin("Server: players may build with materials from nearby chests."));
			ServerPullStore = c.Bind<bool>("Server", "Allow inventory pull and store", true, Admin("Server: the inventory's Pull and Store buttons (taking from / putting into nearby chests)."));
			ConfigEntry<bool>[] array = new ConfigEntry<bool>[3] { ServerCraft, ServerBuild, ServerPullStore };
			for (int i = 0; i < array.Length; i++)
			{
				array[i].SettingChanged += delegate
				{
					if (IsAdmin)
					{
						Sync();
					}
				};
			}
			static ConfigDescription Admin(string d)
			{
				//IL_000a: 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)
				//IL_0017: Expected O, but got Unknown
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Expected O, but got Unknown
				return new ConfigDescription(d, (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
				{
					IsAdminOnly = true
				} });
			}
		}

		public static void Sync()
		{
			try
			{
				mSync?.Invoke(SynchronizationManager.Instance, null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Server settings sync: " + ex.Message));
			}
		}

		public static void SetServer(ConfigEntry<bool> entry, bool value)
		{
			if (!IsAdmin)
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Only a server admin can change this", 0, (Sprite)null, false);
				}
			}
			else
			{
				entry.Value = value;
			}
		}

		public static void Tick(bool typing)
		{
			if (!typing && !((Object)(object)Player.m_localPlayer == (Object)null) && RhKeys.Fired(ToggleKey))
			{
				bool flag = !CraftFromChests.Value || !BuildFromChests.Value;
				ConfigEntry<bool> craftFromChests = CraftFromChests;
				bool value = (BuildFromChests.Value = flag);
				craftFromChests.Value = value;
				((Character)Player.m_localPlayer).Message((MessageType)2, flag ? "Crafting from chests: on" : "Crafting from chests: off", 0, (Sprite)null, false);
			}
		}

		public static List<Container> Nearby(Vector3 pos, float range, ICollection<ZDOID> only = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Chests.Nearby(pos, range, only, IncludeCarts.Value);
		}

		public static bool Claim(Container c)
		{
			return Chests.Claim(c);
		}

		public static void Invalidate()
		{
			cacheTime = -1f;
		}

		public static int CountNearby(string name, Vector3 pos)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (!(Time.time - cacheTime > 0.5f))
			{
				Vector3 val = pos - cachePos;
				if (!(((Vector3)(ref val)).sqrMagnitude > 1f))
				{
					goto IL_00f6;
				}
			}
			cache.Clear();
			cacheTime = Time.time;
			cachePos = pos;
			foreach (Container item in Nearby(pos, Range.Value))
			{
				foreach (ItemData allItem in item.GetInventory().GetAllItems())
				{
					cache[allItem.m_shared.m_name] = (cache.TryGetValue(allItem.m_shared.m_name, out var value) ? value : 0) + allItem.m_stack;
				}
			}
			goto IL_00f6;
			IL_00f6:
			if (!cache.TryGetValue(name, out var value2))
			{
				return 0;
			}
			return value2;
		}

		public static int Take(string name, int amount, Vector3 pos, float range, ICollection<ZDOID> only = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return Chests.Take(name, amount, pos, range, only, IncludeCarts.Value);
		}

		public static Vector3 Origin(Player p)
		{
			//IL_0022: 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)
			CraftingStation currentCraftingStation = p.GetCurrentCraftingStation();
			if (!((Object)(object)currentCraftingStation != (Object)null))
			{
				return ((Component)p).transform.position;
			}
			return ((Component)currentCraftingStation).transform.position;
		}

		public static int NearbyForCraft(Player p, string name)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (!CraftOn)
			{
				return 0;
			}
			return CountNearby(name, Origin(p));
		}

		private static int Have(Player p, string name, bool craft)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			return ((Humanoid)p).GetInventory().CountItems(name, -1, true) + ((craft ? CraftOn : BuildOn) ? CountNearby(name, Origin(p)) : 0);
		}
	}
	public static class LootRule
	{
		[HarmonyPatch(typeof(Character), "OnDeath")]
		private static class NoStrayDrops
		{
			private static void Prefix(Character __instance)
			{
				if (!PlayerKillsOnly.Value || !Qol.WorldRulesOn)
				{
					return;
				}
				try
				{
					if ((Object)(object)__instance == (Object)null || __instance.IsPlayer() || __instance.IsBoss())
					{
						return;
					}
					HitData obj = LastHit.Invoke(__instance);
					Character val = ((obj != null) ? obj.GetAttacker() : null);
					if (!((Object)(object)val != (Object)null) || (!val.IsPlayer() && !val.IsTamed()))
					{
						CharacterDrop component = ((Component)__instance).GetComponent<CharacterDrop>();
						if (component != null)
						{
							component.SetDropsEnabled(false);
						}
					}
				}
				catch (Exception e)
				{
					RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\LootRule.cs", 37, "Prefix");
				}
			}
		}

		public static ConfigEntry<bool> PlayerKillsOnly;

		private static readonly FieldRef<Character, HitData> LastHit = RhSafe.FieldRef<Character, HitData>("m_lastHit", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimQOL\\LootRule.cs", 16);

		public static void Init(ConfigFile c)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			PlayerKillsOnly = c.Bind<bool>("Server", "Loot from player kills only", true, new ConfigDescription("Server: creatures drop loot only when a player (or a player's tamed creature) killed them. Bosses always drop.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}
	}
	public static class Machines
	{
		[HarmonyPatch(typeof(Smelter), "Awake")]
		private static class A1
		{
			private static void Po