Decompiled source of Farming v1.0.1

meadworks.farming.dll

Decompiled 29 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using MeadWorks.Core;
using MeadWorks.UI;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("expDARE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 expDARE")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("meadworks.farming")]
[assembly: AssemblyTitle("meadworks.farming")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MeadWorks.Farming
{
	public static class AreaHarvest
	{
		private sealed class HoverHint
		{
			public string Native;

			public string Alt;

			public string Use;

			public string Text;

			public float Until;
		}

		public struct Survey
		{
			public int Ready;

			public string Prefab;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(Pickable), "Interact")]
			[HarmonyPrefix]
			private static void BeforePick(Pickable __instance, Humanoid character, bool alt, ref bool __state)
			{
				__state = AreaHarvestRules.Starts(On, alt) && !_busy && (Object)(object)character == (Object)(object)Player.m_localPlayer && Ready(__instance);
				if (__state)
				{
					AreaHarvestPickup.Expect((Component)(object)__instance, (Player)(object)((character is Player) ? character : null));
				}
			}

			[HarmonyPatch(typeof(Pickable), "Interact")]
			[HarmonyPostfix]
			private static void AfterPick(Pickable __instance, Humanoid character, bool __state)
			{
				if (__state)
				{
					Begin((Component)(object)__instance, character);
				}
			}

			[HarmonyPatch(typeof(Beehive), "Interact")]
			[HarmonyPrefix]
			private static void BeforeExtract(Beehive __instance, Humanoid character, bool repeat, bool alt, ref bool __state)
			{
				__state = AreaHarvestRules.Starts(On, alt) && !_busy && !repeat && (Object)(object)character == (Object)(object)Player.m_localPlayer && HiveReady(__instance);
				if (__state)
				{
					AreaHarvestPickup.Expect((Component)(object)__instance, (Player)(object)((character is Player) ? character : null));
				}
			}

			[HarmonyPatch(typeof(Beehive), "Interact")]
			[HarmonyPostfix]
			private static void AfterExtract(Beehive __instance, Humanoid character, bool __state)
			{
				if (__state)
				{
					Begin((Component)(object)__instance, character);
				}
			}

			[HarmonyPatch(typeof(Player), "Update")]
			[HarmonyPostfix]
			private static void AfterUpdate(Player __instance)
			{
				Drain(__instance);
			}

			[HarmonyPatch(typeof(Pickable), "GetHoverText")]
			[HarmonyPostfix]
			private static void PickHover(Pickable __instance, ref string __result)
			{
				Hover((Component)(object)__instance, ref __result);
			}

			[HarmonyPatch(typeof(Beehive), "GetHoverText")]
			[HarmonyPostfix]
			private static void HiveHover(Beehive __instance, ref string __result)
			{
				Hover((Component)(object)__instance, ref __result);
			}
		}

		private const int PerFrame = 8;

		private static Setting<bool> _on;

		private static Setting<float> _radius;

		private static Setting<string> _style;

		private static Harmony _harmony;

		private static bool _busy;

		private static int _head;

		private static int _count;

		private static HarvestNode[] _nodes = new HarvestNode[32];

		private static Component[] _things = (Component[])(object)new Component[32];

		private static readonly int[] Chosen = new int[50];

		private static readonly Component[] Queue = (Component[])(object)new Component[50];

		private static readonly List<Piece> Pieces = new List<Piece>();

		private static readonly HashSet<Component> Seen = new HashSet<Component>();

		private static readonly List<Component> Found = new List<Component>();

		private static readonly Dictionary<Component, float> Sent = new Dictionary<Component, float>();

		private static readonly List<Component> Stale = new List<Component>();

		private static readonly HashSet<string> Grown = new HashSet<string>(StringComparer.Ordinal);

		private static ZNetScene _grownScene;

		private static ConditionalWeakTable<Component, HoverHint> Hints = new ConditionalWeakTable<Component, HoverHint>();

		public static bool On
		{
			get
			{
				if (_on != null)
				{
					return _on.Value;
				}
				return false;
			}
		}

		public static float Radius
		{
			get
			{
				if (_radius != null)
				{
					return AreaHarvestRules.ClampRadius(_radius.Value);
				}
				return 5f;
			}
		}

		public static HarvestStyle Style => AreaHarvestRules.ParseStyle((_style == null) ? null : _style.Value);

		internal static int Queued => _count - _head;

		public static void Init(SettingsPage page)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			_on = page.Toggle("area_harvest", "Area harvest", true, (SettingPolicy)2, false);
			_radius = page.Slider("harvest_radius", "Harvest radius", 5f, 1f, 10f, 1f, (SettingPolicy)2, true);
			_style = page.Choice("harvest_style", "Harvest style", "Same kind", AreaHarvestRules.StyleNames, (SettingPolicy)2, true);
			page.Depends((Setting)(object)_radius, (Setting)(object)_on);
			page.Depends((Setting)(object)_style, (Setting)(object)_on);
			_harmony = new Harmony("expdare.meadworks.farming.harvest");
			LedgerTrack.Patch(_harmony, "farming area harvest");
			_harmony.PatchAll(typeof(Patches));
			_harmony.PatchAll(typeof(AreaHarvestPickup.Patches));
			Ledger.Add("farming area harvest state", (Action)delegate
			{
				ClearQueue();
				AreaHarvestPickup.Reset();
				Sent.Clear();
				Grown.Clear();
				_grownScene = null;
				Hints = new ConditionalWeakTable<Component, HoverHint>();
				_on = null;
				_radius = null;
				_style = null;
			});
		}

		public static Survey Look(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Pickable val = NearestReadyPickable(point, Radius);
			if ((Object)(object)val == (Object)null)
			{
				return new Survey
				{
					Ready = 0,
					Prefab = "none"
				};
			}
			return new Survey
			{
				Ready = Count(val),
				Prefab = PrefabName((Component)(object)val)
			};
		}

		public static int Count(Pickable source)
		{
			if ((Object)(object)source == (Object)null)
			{
				return 0;
			}
			return Fill((Component)(object)source);
		}

		public static Survey LookHives(Vector3 point)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0042: 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)
			Beehive val = null;
			float num = Radius * Radius;
			Scan(point, Radius);
			for (int i = 0; i < Found.Count; i++)
			{
				Component obj = Found[i];
				Beehive val2 = (Beehive)(object)((obj is Beehive) ? obj : null);
				if (HiveReady(val2))
				{
					Vector3 val3 = ((Component)val2).transform.position - point;
					float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
					if (!(sqrMagnitude > num))
					{
						num = sqrMagnitude;
						val = val2;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				return new Survey
				{
					Ready = 0,
					Prefab = "none"
				};
			}
			return new Survey
			{
				Ready = Fill((Component)(object)val),
				Prefab = PrefabName((Component)(object)val)
			};
		}

		private static void Begin(Component source, Humanoid who)
		{
			if (!On || _busy || (Object)(object)who != (Object)(object)Player.m_localPlayer || (Object)(object)source == (Object)null)
			{
				return;
			}
			Sent[source] = Time.time;
			int num = Fill(source);
			_head = 0;
			_count = 0;
			for (int i = 0; i < num; i++)
			{
				if (_count >= Queue.Length)
				{
					break;
				}
				Component val = _things[Chosen[i]];
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)source))
				{
					Queue[_count++] = val;
				}
			}
		}

		internal static void Drain(Player player)
		{
			if ((Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			AreaHarvestPickup.Drain(player);
			if (Sent.Count > 0)
			{
				Forget();
			}
			if (!On)
			{
				ClearQueue();
			}
			else
			{
				if (_count <= 0 || (Object)(object)player != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				if (((Character)player).IsDead() || ((Character)player).IsTeleporting())
				{
					ClearQueue();
					return;
				}
				int num = 0;
				_busy = true;
				try
				{
					while (num < 8 && _head < _count)
					{
						Component obj = Queue[_head];
						Queue[_head++] = null;
						Pickable val = (Pickable)(object)((obj is Pickable) ? obj : null);
						Beehive val2 = (Beehive)(object)((obj is Beehive) ? obj : null);
						if ((Object)(object)val != (Object)null)
						{
							if (!Ready(val))
							{
								continue;
							}
							Sent[(Component)(object)val] = Time.time;
							AreaHarvestPickup.Expect((Component)(object)val, player);
							val.Interact((Humanoid)(object)player, false, false);
						}
						else
						{
							if (!((Object)(object)val2 != (Object)null) || !HiveReady(val2))
							{
								continue;
							}
							Sent[(Component)(object)val2] = Time.time;
							AreaHarvestPickup.Expect((Component)(object)val2, player);
							val2.Interact((Humanoid)(object)player, false, false);
						}
						num++;
					}
				}
				finally
				{
					_busy = false;
				}
				if (_head >= _count)
				{
					ClearQueue();
				}
				if (Sent.Count > 0)
				{
					Forget();
				}
			}
		}

		private static void Forget()
		{
			Stale.Clear();
			foreach (KeyValuePair<Component, float> item in Sent)
			{
				if ((Object)(object)item.Key == (Object)null || Answered(item.Key) || !AreaHarvestRules.Pending(item.Value, Time.time))
				{
					Stale.Add(item.Key);
				}
			}
			for (int i = 0; i < Stale.Count; i++)
			{
				Sent.Remove(Stale[i]);
			}
			Stale.Clear();
		}

		private static bool Answered(Component thing)
		{
			Pickable val = (Pickable)(object)((thing is Pickable) ? thing : null);
			if ((Object)(object)val != (Object)null)
			{
				return val.GetPicked();
			}
			Beehive val2 = (Beehive)(object)((thing is Beehive) ? thing : null);
			if ((Object)(object)val2 != (Object)null)
			{
				return val2.GetHoneyLevel() <= 0;
			}
			return false;
		}

		private static bool Waiting(Component thing)
		{
			if (Sent.TryGetValue(thing, out var value))
			{
				return AreaHarvestRules.Pending(value, Time.time);
			}
			return false;
		}

		private static void ClearQueue()
		{
			for (int i = 0; i < _count; i++)
			{
				Queue[i] = null;
			}
			_head = 0;
			_count = 0;
		}

		private static bool Crop(Pickable pick)
		{
			if ((Object)(object)pick == (Object)null)
			{
				return false;
			}
			Piece component = ((Component)pick).GetComponent<Piece>();
			string prefab = PrefabName((Component)(object)pick);
			return AreaHarvestRules.IsCrop(IsStorage((Component)(object)pick), (Object)(object)((Component)pick).GetComponent<Plant>() != (Object)null || GrownFromPlant(prefab), (Object)(object)component != (Object)null && component.m_cultivatedGroundOnly, AreaHarvestRules.IsWildPrefab(prefab));
		}

		private static bool GrownFromPlant(string prefab)
		{
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null || string.IsNullOrEmpty(prefab))
			{
				return false;
			}
			if ((Object)(object)_grownScene != (Object)(object)instance)
			{
				_grownScene = instance;
				Grown.Clear();
				foreach (GameObject prefab2 in instance.m_prefabs)
				{
					Plant val = (((Object)(object)prefab2 == (Object)null) ? null : prefab2.GetComponent<Plant>());
					if ((Object)(object)val == (Object)null || val.m_grownPrefabs == null)
					{
						continue;
					}
					GameObject[] grownPrefabs = val.m_grownPrefabs;
					foreach (GameObject val2 in grownPrefabs)
					{
						if ((Object)(object)val2 != (Object)null && (Object)(object)val2.GetComponent<Pickable>() != (Object)null)
						{
							Grown.Add(((Object)val2).name);
						}
					}
				}
			}
			return Grown.Contains(prefab);
		}

		private static Pickable NearestReadyPickable(Vector3 point, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			Scan(point, radius);
			Pickable result = null;
			float num = radius * radius;
			for (int i = 0; i < Found.Count; i++)
			{
				Component obj = Found[i];
				Pickable val = (Pickable)(object)((obj is Pickable) ? obj : null);
				if (Ready(val))
				{
					Vector3 val2 = ((Component)val).transform.position - point;
					float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
					if (!(sqrMagnitude > num))
					{
						num = sqrMagnitude;
						result = val;
					}
				}
			}
			return result;
		}

		private static void Scan(Vector3 point, float radius)
		{
			//IL_001e: 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)
			Seen.Clear();
			Found.Clear();
			Pieces.Clear();
			Piece.GetAllPiecesInRadius(point, radius, Pieces);
			for (int i = 0; i < Pieces.Count; i++)
			{
				Piece val = Pieces[i];
				if (!((Object)(object)val == (Object)null))
				{
					Add((Component)(object)((Component)val).GetComponent<Pickable>());
					Add((Component)(object)((Component)val).GetComponent<Beehive>());
				}
			}
			Pieces.Clear();
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				Collider[] array = Physics.OverlapSphere(point, radius, localPlayer.m_interactMask);
				for (int j = 0; j < array.Length; j++)
				{
					if (!((Object)(object)array[j] == (Object)null))
					{
						Add((Component)(object)((Component)array[j]).GetComponentInParent<Pickable>());
						Add((Component)(object)((Component)array[j]).GetComponentInParent<Beehive>());
					}
				}
			}
			Seen.Clear();
		}

		private static void Add(Component thing)
		{
			if ((Object)(object)thing != (Object)null && Seen.Add(thing))
			{
				Found.Add(thing);
			}
		}

		private static int Fill(Component source)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: 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_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = source.transform.position;
			string pickedPrefab = PrefabName(source);
			Scan(position, Radius);
			int num = 0;
			for (int i = 0; i < Found.Count; i++)
			{
				Component val = Found[i];
				Pickable val2 = (Pickable)(object)((val is Pickable) ? val : null);
				Beehive val3 = (Beehive)(object)((val is Beehive) ? val : null);
				Ensure(num + 1);
				string prefab = PrefabName(val);
				Vector3 position2 = val.transform.position;
				Piece component = val.GetComponent<Piece>();
				_nodes[num] = new HarvestNode
				{
					Prefab = prefab,
					X = position2.x,
					Y = position2.y,
					Z = position2.z,
					Ready = (((Object)(object)val2 != (Object)null) ? Ready(val2) : HiveReady(val3)),
					Container = IsStorage(val),
					Planted = ((Object)(object)val2 != (Object)null && ((Object)(object)((Component)val2).GetComponent<Plant>() != (Object)null || GrownFromPlant(prefab))),
					Cultivated = ((Object)(object)val2 != (Object)null && (Object)(object)component != (Object)null && component.m_cultivatedGroundOnly),
					Wild = ((Object)(object)val2 != (Object)null && AreaHarvestRules.IsWildPrefab(prefab)),
					Hive = ((Object)(object)val3 != (Object)null),
					Self = ((Object)(object)val == (Object)(object)source)
				};
				_things[num] = val;
				num++;
			}
			Found.Clear();
			return AreaHarvestRules.Select(_nodes, num, pickedPrefab, source is Beehive, Crop((Pickable)(object)((source is Pickable) ? source : null)), Style, position.x, position.y, position.z, Radius, Chosen);
		}

		private static bool Ready(Pickable pick)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)pick == (Object)null || !((Behaviour)pick).isActiveAndEnabled || pick.GetPicked() || pick.GetEnabled != 1 || !pick.CanBePicked() || Waiting((Component)(object)pick) || Stuck(pick) || IsStorage((Component)(object)pick))
			{
				return false;
			}
			ZNetView component = ((Component)pick).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				return PrivateArea.CheckAccess(((Component)pick).transform.position, 0f, false, false);
			}
			return false;
		}

		private static bool Stuck(Pickable pick)
		{
			if (!pick.m_tarPreventsPicking)
			{
				return false;
			}
			Floating component = ((Component)pick).GetComponent<Floating>();
			if ((Object)(object)component != (Object)null)
			{
				return component.IsInTar();
			}
			return false;
		}

		private static bool HiveReady(Beehive hive)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)hive == (Object)null || !((Behaviour)hive).isActiveAndEnabled || IsStorage((Component)(object)hive))
			{
				return false;
			}
			return AreaHarvestRules.HiveReady(hive.GetHoneyLevel(), PrivateArea.CheckAccess(((Component)hive).transform.position, 0f, false, false), Waiting((Component)(object)hive));
		}

		private static bool IsStorage(Component thing)
		{
			if (!((Object)(object)thing.GetComponentInParent<Container>() != (Object)null))
			{
				return (Object)(object)thing.GetComponentInParent<ItemStand>() != (Object)null;
			}
			return true;
		}

		private static void Hover(Component target, ref string text)
		{
			if (On && !((Object)(object)target == (Object)null) && !string.IsNullOrEmpty(text) && ZInput.instance != null && Localization.instance != null)
			{
				bool flag = ZInput.IsGamepadActive();
				Localization instance = Localization.instance;
				string boundKeyString = instance.GetBoundKeyString(AreaHarvestRules.AltBinding(flag, ZInput.IsNonClassicFunctionality()), false);
				string boundKeyString2 = instance.GetBoundKeyString(flag ? "JoyUse" : "Use", false);
				HoverHint value = Hints.GetValue(target, (Component _) => new HoverHint());
				if (value.Native != text || value.Alt != boundKeyString || value.Use != boundKeyString2 || Time.unscaledTime >= value.Until)
				{
					value.Native = text;
					value.Alt = boundKeyString;
					value.Use = boundKeyString2;
					value.Until = Time.unscaledTime + 0.25f;
					Pickable val = (Pickable)(object)((target is Pickable) ? target : null);
					bool flag2 = (((Object)(object)val != (Object)null) ? Ready(val) : HiveReady((Beehive)(object)((target is Beehive) ? target : null)));
					int num = (flag2 ? AreaHarvestRules.TargetCount(Fill(target)) : 0);
					value.Text = (flag2 ? (text + "\n[<color=yellow><b>" + boundKeyString + "+" + boundKeyString2 + "</b></color>] " + (((Object)(object)val != (Object)null) ? FarmWords.Get("Pick nearby") : FarmWords.Get("Take nearby honey")) + " (" + num + "/" + 51 + ", " + Radius.ToString("0.#") + " m)") : text);
				}
				text = value.Text;
			}
		}

		private static string PrefabName(Component thing)
		{
			ZNetView component = thing.GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid() && (Object)(object)ZNetScene.instance != (Object)null)
			{
				ZDO zDO = component.GetZDO();
				if (zDO != null)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(zDO.GetPrefab());
					if ((Object)(object)prefab != (Object)null)
					{
						return ((Object)prefab).name;
					}
				}
			}
			string name = ((Object)thing.gameObject).name;
			int num = name.IndexOf('(');
			if (num >= 0)
			{
				return name.Substring(0, num).TrimEnd(Array.Empty<char>());
			}
			return name;
		}

		private static void Ensure(int n)
		{
			if (_nodes.Length < n)
			{
				int num;
				for (num = _nodes.Length; num < n; num *= 2)
				{
				}
				Array.Resize(ref _nodes, num);
				Array.Resize(ref _things, num);
			}
		}
	}
	internal static class AreaHarvestPickup
	{
		private struct SpawnScope
		{
			public ZDOID Source;

			public long Peer;

			public long Token;
		}

		private struct PendingDrop
		{
			public ItemDrop Item;

			public float Until;
		}

		internal static class Patches
		{
			[HarmonyPatch(typeof(Pickable), "Awake")]
			[HarmonyPostfix]
			private static void PickableAwake(Pickable __instance)
			{
				Register((Component)(object)__instance);
			}

			[HarmonyPatch(typeof(Beehive), "Awake")]
			[HarmonyPostfix]
			private static void HiveAwake(Beehive __instance)
			{
				Register((Component)(object)__instance);
			}

			[HarmonyPatch(typeof(Pickable), "RPC_Pick")]
			[HarmonyPrefix]
			private static void BeforePickRpc(Pickable __instance, long sender, ref SpawnScope __state)
			{
				__state = Enter((Component)(object)__instance, sender);
			}

			[HarmonyPatch(typeof(Pickable), "RPC_Pick")]
			[HarmonyFinalizer]
			private static Exception AfterPickRpc(Exception __exception, SpawnScope __state)
			{
				_scope = __state;
				return __exception;
			}

			[HarmonyPatch(typeof(Beehive), "RPC_Extract")]
			[HarmonyPrefix]
			private static void BeforeHiveRpc(Beehive __instance, long caller, ref SpawnScope __state)
			{
				__state = Enter((Component)(object)__instance, caller);
			}

			[HarmonyPatch(typeof(Beehive), "RPC_Extract")]
			[HarmonyFinalizer]
			private static Exception AfterHiveRpc(Exception __exception, SpawnScope __state)
			{
				_scope = __state;
				return __exception;
			}

			[HarmonyPatch(typeof(Pickable), "Drop")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> PickSpawn(IEnumerable<CodeInstruction> instructions)
			{
				return ReplaceSpawn(instructions, typeof(GameObject), "SpawnPickable");
			}

			[HarmonyPatch(typeof(Beehive), "RPC_Extract")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> HoneySpawn(IEnumerable<CodeInstruction> instructions)
			{
				return ReplaceSpawn(instructions, typeof(ItemDrop), "SpawnHoney");
			}

			[HarmonyPatch(typeof(ItemDrop), "Start")]
			[HarmonyPostfix]
			private static void ItemStarted(ItemDrop __instance)
			{
				Observe(__instance);
			}

			[HarmonyPatch(typeof(ItemDrop), "AutoStackItems")]
			[HarmonyPrefix]
			private static bool BeforeStack(ItemDrop __instance, bool __runOriginal = true)
			{
				if (!__runOriginal)
				{
					return false;
				}
				return !Protected(__instance);
			}

			[HarmonyPatch(typeof(ItemDrop), "AutoStackItems")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> StackTargets(IEnumerable<CodeInstruction> instructions)
			{
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0087: Expected O, but got Unknown
				List<CodeInstruction> list = new List<CodeInstruction>();
				int num = 0;
				foreach (CodeInstruction instruction in instructions)
				{
					list.Add(instruction);
					MethodInfo methodInfo = instruction.operand as MethodInfo;
					if (!(methodInfo == null) && !(methodInfo.Name != "GetComponent") && !(methodInfo.ReturnType != typeof(ItemDrop)))
					{
						list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(AreaHarvestPickup), "StackCandidate", (Type[])null, (Type[])null)));
						num++;
					}
				}
				if (num != 1)
				{
					throw new InvalidOperationException("Harvest ground-stack path changed");
				}
				return list;
			}
		}

		private const string SourceKey = "mw_harvest_source";

		private const string PeerKey = "mw_harvest_peer";

		private const string TokenKey = "mw_harvest_token";

		private const string MarkerRpc = "MW_AreaHarvest";

		private const int PerFrame = 8;

		private static readonly HarvestPickupRules<ZDOID> Claims = new HarvestPickupRules<ZDOID>();

		private static readonly Queue<PendingDrop> Drops = new Queue<PendingDrop>();

		private static readonly HarvestPickupRules<Tuple<ZDOID, long>> Markers = new HarvestPickupRules<Tuple<ZDOID, long>>();

		private static readonly List<WeakReference<ZNetView>> Views = new List<WeakReference<ZNetView>>();

		private static Player _player;

		private static SpawnScope _scope;

		private static long _nextToken;

		private static int _registrations;

		internal static void Expect(Component source, Player player)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			if ((Object)(object)_player != (Object)(object)player)
			{
				Clear();
			}
			_player = player;
			ZNetView component = source.GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid())
			{
				long num = ++_nextToken;
				if (Claims.Expect(component.GetZDO().m_uid, ZDOMan.GetSessionID(), num, Time.time))
				{
					component.InvokeRPC("MW_AreaHarvest", new object[1] { num });
				}
			}
		}

		internal static void Clear()
		{
			Claims.Clear();
			Drops.Clear();
			_player = null;
		}

		internal static void Reset()
		{
			Clear();
			Markers.Clear();
			foreach (WeakReference<ZNetView> view in Views)
			{
				if (view.TryGetTarget(out var target) && (Object)(object)target != (Object)null)
				{
					target.Unregister("MW_AreaHarvest");
				}
			}
			Views.Clear();
			_registrations = 0;
			_scope = default(SpawnScope);
		}

		internal static void Drain(Player player)
		{
			if ((Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			if (((Character)player).IsDead() || ((Character)player).IsTeleporting() || (Object)(object)_player != (Object)(object)player)
			{
				Clear();
				return;
			}
			Claims.Expire(Time.time);
			if (!AreaHarvest.On)
			{
				Drops.Clear();
				return;
			}
			int num = Math.Min(8, Drops.Count);
			for (int i = 0; i < num; i++)
			{
				PendingDrop item = Drops.Dequeue();
				ItemDrop item2 = item.Item;
				if ((Object)(object)item2 == (Object)null || Time.time >= item.Until)
				{
					continue;
				}
				ZNetView component = ((Component)item2).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				if (!item2.CanPickup(true))
				{
					item2.RequestOwn();
					Drops.Enqueue(item);
				}
				else if (item2.m_autoPickup && !item2.IsPiece() && !item2.InTar() && !((Humanoid)player).HaveUniqueKey(item2.m_itemData.m_shared.m_name))
				{
					item2.Load();
					Inventory inventory = ((Humanoid)player).GetInventory();
					if (inventory.CanAddItem(item2.m_itemData, -1) && !(item2.m_itemData.GetWeight(-1) + inventory.GetTotalWeight() > player.GetMaxCarryWeight()) && !((Humanoid)player).Pickup(((Component)item2).gameObject, true, true) && (Object)(object)item2 != (Object)null && component.IsValid() && component.IsOwner())
					{
						item2.Save();
					}
				}
			}
		}

		private static SpawnScope Enter(Component source, long peer)
		{
			//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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			SpawnScope scope = _scope;
			ZNetView component = source.GetComponent<ZNetView>();
			_scope = default(SpawnScope);
			if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
			{
				return scope;
			}
			ZDOID uid = component.GetZDO().m_uid;
			if (Markers.Take(Tuple.Create<ZDOID, long>(uid, peer), peer, Time.time, out var token))
			{
				_scope = new SpawnScope
				{
					Source = uid,
					Peer = peer,
					Token = token
				};
			}
			return scope;
		}

		private static void Register(Component source)
		{
			ZNetView view = source.GetComponent<ZNetView>();
			if ((Object)(object)view == (Object)null || !view.IsValid())
			{
				return;
			}
			if (++_registrations % 256 == 0)
			{
				Views.RemoveAll((WeakReference<ZNetView> weak) => !weak.TryGetTarget(out var target) || (Object)(object)target == (Object)null);
			}
			Views.Add(new WeakReference<ZNetView>(view));
			view.Unregister("MW_AreaHarvest");
			view.Register<long>("MW_AreaHarvest", (Action<long, long>)delegate(long peer, long token)
			{
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (view.IsValid() && view.IsOwner() && peer != 0L && token > 0)
				{
					Markers.Expect(Tuple.Create<ZDOID, long>(view.GetZDO().m_uid, peer), peer, token, Time.time);
				}
			});
		}

		private static void Mark(ItemDrop item)
		{
			//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_005e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)item == (Object)null) && _scope.Peer != 0L && !(_scope.Source == ZDOID.None))
			{
				ZNetView component = ((Component)item).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid() && component.IsOwner())
				{
					ZDO zDO = component.GetZDO();
					zDO.Set("mw_harvest_source", _scope.Source);
					zDO.Set("mw_harvest_peer", _scope.Peer);
					zDO.Set("mw_harvest_token", _scope.Token);
				}
			}
		}

		private static GameObject SpawnPickable(GameObject original, Vector3 position, Quaternion rotation)
		{
			//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)
			GameObject obj = Object.Instantiate<GameObject>(original, position, rotation);
			Mark(obj.GetComponent<ItemDrop>());
			return obj;
		}

		private static ItemDrop SpawnHoney(ItemDrop original, Vector3 position, Quaternion rotation)
		{
			//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)
			ItemDrop obj = Object.Instantiate<ItemDrop>(original, position, rotation);
			Mark(obj);
			return obj;
		}

		private static void Observe(ItemDrop item)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_player == (Object)null || (Object)(object)_player != (Object)(object)Player.m_localPlayer || ((Character)_player).IsDead() || ((Character)_player).IsTeleporting() || Drops.Count >= 4096)
			{
				return;
			}
			ZNetView component = ((Component)item).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (Claims.Claim(zDO.GetZDOID("mw_harvest_source"), zDO.GetLong("mw_harvest_peer", 0L), zDO.m_uid, zDO.GetLong("mw_harvest_token", 0L), Time.time))
			{
				CropReplant.Confirm(zDO.GetZDOID("mw_harvest_source"));
				if (AreaHarvest.On)
				{
					Drops.Enqueue(new PendingDrop
					{
						Item = item,
						Until = Time.time + 10f
					});
				}
			}
		}

		private static bool Protected(ItemDrop item)
		{
			if ((Object)(object)item == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)item).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			if (component.GetZDO().GetLong("mw_harvest_peer", 0L) == 0L)
			{
				return false;
			}
			return Time.time - item.m_spawnTime < 20f;
		}

		private static ItemDrop StackCandidate(ItemDrop item)
		{
			if (!Protected(item))
			{
				return item;
			}
			return null;
		}

		private static IEnumerable<CodeInstruction> ReplaceSpawn(IEnumerable<CodeInstruction> instructions, Type resultType, string replacement)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int num = 0;
			foreach (CodeInstruction item in list)
			{
				MethodInfo methodInfo = item.operand as MethodInfo;
				if (!(methodInfo == null) && !(methodInfo.DeclaringType != typeof(Object)) && !(methodInfo.Name != "Instantiate") && !(methodInfo.ReturnType != resultType) && methodInfo.GetParameters().Length == 3)
				{
					item.operand = AccessTools.Method(typeof(AreaHarvestPickup), replacement, (Type[])null, (Type[])null);
					num++;
				}
			}
			if (num != 1)
			{
				throw new InvalidOperationException("Harvest spawn path changed: " + replacement);
			}
			return list;
		}
	}
	public struct HarvestNode
	{
		public string Prefab;

		public float X;

		public float Y;

		public float Z;

		public bool Ready;

		public bool Container;

		public bool Planted;

		public bool Cultivated;

		public bool Wild;

		public bool Hive;

		public bool Self;
	}
	public enum HarvestStyle
	{
		SameKind,
		AllCrops
	}
	public static class AreaHarvestRules
	{
		public const int Cap = 50;

		public const float MinRadius = 1f;

		public const float MaxRadius = 10f;

		public const float DefaultRadius = 5f;

		public const string SameKindName = "Same kind";

		public const string AllCropsName = "All crops";

		public static readonly string[] StyleNames = new string[2] { "Same kind", "All crops" };

		public const float PendingSeconds = 3f;

		public static HarvestStyle ParseStyle(string name)
		{
			if (!string.Equals(name, "All crops", StringComparison.Ordinal))
			{
				return HarvestStyle.SameKind;
			}
			return HarvestStyle.AllCrops;
		}

		public static int TargetCount(int nearby)
		{
			return 1 + Math.Max(0, Math.Min(50, nearby));
		}

		public static bool Starts(bool enabled, bool alt)
		{
			return enabled && alt;
		}

		public static string AltBinding(bool gamepad, bool nonClassic)
		{
			if (gamepad)
			{
				if (!nonClassic)
				{
					return "JoyAltPlace";
				}
				return "JoyAltKeys";
			}
			return "AltPlace";
		}

		public static bool HiveReady(int honey, bool access, bool pending)
		{
			if (honey > 0 && access)
			{
				return !pending;
			}
			return false;
		}

		public static bool Pending(float sentAt, float now)
		{
			float num = now - sentAt;
			if (num >= 0f)
			{
				return num < 3f;
			}
			return false;
		}

		public static float ClampRadius(float metres)
		{
			if (float.IsNaN(metres) || metres < 1f)
			{
				return 1f;
			}
			if (metres > 10f)
			{
				return 10f;
			}
			return metres;
		}

		public static bool SamePrefab(string a, string b)
		{
			if (!string.IsNullOrEmpty(a))
			{
				return string.Equals(a, b, StringComparison.Ordinal);
			}
			return false;
		}

		public static bool IsWildPrefab(string prefab)
		{
			if (string.IsNullOrEmpty(prefab))
			{
				return false;
			}
			PlantEntry plantEntry = PlantGroupRules.Find(prefab);
			if (plantEntry != null && !plantEntry.OwnPiece)
			{
				return plantEntry.Group != "debris";
			}
			return false;
		}

		public static bool IsCrop(bool container, bool planted, bool cultivated, bool wild)
		{
			if (container)
			{
				return false;
			}
			return planted || cultivated || wild;
		}

		public static bool Qualifies(string pickedPrefab, HarvestNode node)
		{
			return Qualifies(pickedPrefab, pickedHive: false, pickedCrop: false, HarvestStyle.SameKind, node);
		}

		public static bool Qualifies(string pickedPrefab, bool pickedHive, bool pickedCrop, HarvestStyle style, HarvestNode node)
		{
			if (node.Self || !node.Ready || node.Container)
			{
				return false;
			}
			if (pickedHive || node.Hive)
			{
				if (pickedHive)
				{
					return node.Hive;
				}
				return false;
			}
			if (pickedCrop && style == HarvestStyle.AllCrops)
			{
				return IsCrop(node.Container, node.Planted, node.Cultivated, node.Wild);
			}
			return SamePrefab(pickedPrefab, node.Prefab);
		}

		public static bool InRadius(float dx, float dy, float dz, float radius)
		{
			float num = ClampRadius(radius);
			return dx * dx + dy * dy + dz * dz <= num * num;
		}

		public static int Select(HarvestNode[] nodes, int count, string pickedPrefab, float x, float y, float z, float radius, int[] chosen)
		{
			return Select(nodes, count, pickedPrefab, pickedHive: false, pickedCrop: false, HarvestStyle.SameKind, x, y, z, radius, chosen);
		}

		public static int Select(HarvestNode[] nodes, int count, string pickedPrefab, bool pickedHive, bool pickedCrop, HarvestStyle style, float x, float y, float z, float radius, int[] chosen)
		{
			if (nodes == null || chosen == null || count <= 0 || chosen.Length == 0)
			{
				return 0;
			}
			int num = ((chosen.Length < 50) ? chosen.Length : 50);
			int num2 = ((count < nodes.Length) ? count : nodes.Length);
			float[] array = new float[num];
			int num3 = 0;
			for (int i = 0; i < num2; i++)
			{
				HarvestNode node = nodes[i];
				if (!Qualifies(pickedPrefab, pickedHive, pickedCrop, style, node))
				{
					continue;
				}
				float num4 = node.X - x;
				float num5 = node.Y - y;
				float num6 = node.Z - z;
				if (!InRadius(num4, num5, num6, radius))
				{
					continue;
				}
				float num7 = num4 * num4 + num5 * num5 + num6 * num6;
				int num8 = num3;
				if (num3 == num)
				{
					if (num7 >= array[num3 - 1])
					{
						continue;
					}
					num8 = num3 - 1;
				}
				else
				{
					num3++;
				}
				while (num8 > 0 && num7 < array[num8 - 1])
				{
					array[num8] = array[num8 - 1];
					chosen[num8] = chosen[num8 - 1];
					num8--;
				}
				array[num8] = num7;
				chosen[num8] = i;
			}
			return num3;
		}
	}
	internal static class CropReplant
	{
		private sealed class Request
		{
			internal Player Player;

			internal Piece Piece;

			internal Vector3 Position;

			internal Quaternion Rotation;

			internal float Until;

			internal bool Finished;

			internal int ConfirmedFrame;

			internal GridPlanting.GridStamp Grid;
		}

		private struct Growth
		{
			internal string Crop;

			internal GridPlanting.GridStamp Grid;
		}

		private static class Patches
		{
			[HarmonyPrefix]
			[HarmonyPatch(typeof(Plant), "Grow")]
			private static void BeforeGrow(Plant __instance, out Growth __state)
			{
				__state = new Growth
				{
					Crop = Growing(__instance),
					Grid = GridPlanting.ReadGrid((Component)(object)__instance)
				};
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Plant), "Grow")]
			private static void AfterGrow(GameObject __result, Growth __state)
			{
				Grown(__state, __result);
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(Pickable), "Interact")]
			private static void BeforePick(Pickable __instance, Humanoid character, bool repeat)
			{
				Expect(__instance, character, repeat);
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Player), "Update")]
			private static void Updated(Player __instance)
			{
				Drain(__instance);
				GridPlanting.StepJob(__instance);
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Player), "SetupPlacementGhost")]
			private static void Chosen(Player __instance)
			{
				Select(__instance);
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Pickable), "GetHoverText")]
			private static void Hovered(Pickable __instance, ref string __result)
			{
				Hover(__instance, ref __result);
			}
		}

		private static readonly int CropKey = StringExtensionMethods.GetStableHashCode("mw.farming.crop");

		private static readonly Dictionary<ZDOID, Request> Pending = new Dictionary<ZDOID, Request>();

		private static readonly Queue<Request> Ready = new Queue<Request>();

		private static readonly List<ZDOID> Expired = new List<ZDOID>();

		private static readonly Dictionary<int, Piece> Crops = new Dictionary<int, Piece>();

		private static Piece _selected;

		private static PieceTable _table;

		private static int _pieceCount;

		internal static void Init(Harmony harmony)
		{
			harmony.PatchAll(typeof(Patches));
			Ledger.Add("farming crop replant", (Action)delegate
			{
				Pending.Clear();
				Ready.Clear();
				Expired.Clear();
				Crops.Clear();
				_table = null;
				_selected = null;
			});
		}

		internal static Piece Source(Pickable pick)
		{
			if ((Object)(object)pick == (Object)null || (Object)(object)pick.m_nview == (Object)null || !pick.m_nview.IsValid() || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			string text = pick.m_nview.GetZDO().GetString(CropKey, "");
			if (text.Length == 0)
			{
				return ExistingCrop(pick);
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(text);
			if (!((Object)(object)prefab == (Object)null))
			{
				return prefab.GetComponent<Piece>();
			}
			return null;
		}

		private static Piece Replacement(Pickable pick)
		{
			return ReplantRules.Crop<Piece>(ReplantRules.UsesSelected((PlantingControls.ReplantStyle == null) ? null : PlantingControls.ReplantStyle.Value), Source(pick), ((Object)(object)_selected == (Object)null) ? null : _selected);
		}

		private static void Select(Player player)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || (Object)(object)player.m_buildPieces == (Object)null || (Object)(object)player.m_buildPieces != (Object)(object)WildPlants.CultivatorTable())
			{
				return;
			}
			Piece selectedPiece = player.GetSelectedPiece();
			Plant val = (((Object)(object)selectedPiece == (Object)null) ? null : ((Component)selectedPiece).GetComponent<Plant>());
			bool flag = false;
			if ((Object)(object)val != (Object)null && val.m_grownPrefabs != null)
			{
				for (int i = 0; i < val.m_grownPrefabs.Length; i++)
				{
					if (flag)
					{
						break;
					}
					flag = (Object)(object)val.m_grownPrefabs[i] != (Object)null && (Object)(object)val.m_grownPrefabs[i].GetComponent<Pickable>() != (Object)null;
				}
			}
			if (ReplantRules.Selectable((Object)(object)val != (Object)null, (Object)(object)selectedPiece != (Object)null && (Object)(object)((Component)selectedPiece).GetComponent<WildPlant>() != (Object)null, (Object)(object)val != (Object)null && val.m_attachDistance > 0f, flag))
			{
				_selected = selectedPiece;
			}
		}

		private static Piece ExistingCrop(Pickable pick)
		{
			if (pick.m_respawnTimeMinutes > 0f || (Object)(object)pick.m_hideWhenPicked != (Object)null)
			{
				return null;
			}
			PieceTable val = WildPlants.CultivatorTable();
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if ((Object)(object)_table != (Object)(object)val || _pieceCount != val.m_pieces.Count)
			{
				_table = val;
				_pieceCount = val.m_pieces.Count;
				Crops.Clear();
				foreach (GameObject piece in val.m_pieces)
				{
					if ((Object)(object)piece == (Object)null || (Object)(object)piece.GetComponent<WildPlant>() != (Object)null)
					{
						continue;
					}
					Plant component = piece.GetComponent<Plant>();
					Piece component2 = piece.GetComponent<Piece>();
					if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null || component.m_attachDistance > 0f)
					{
						continue;
					}
					GameObject[] grownPrefabs = component.m_grownPrefabs;
					foreach (GameObject val2 in grownPrefabs)
					{
						if ((Object)(object)val2 != (Object)null && (Object)(object)val2.GetComponent<Pickable>() != (Object)null)
						{
							Crops[StringExtensionMethods.GetStableHashCode(((Object)val2).name)] = component2;
						}
					}
				}
			}
			if (!Crops.TryGetValue(pick.m_nview.GetZDO().GetPrefab(), out var value))
			{
				return null;
			}
			return value;
		}

		private static string Growing(Plant plant)
		{
			if ((Object)(object)plant == (Object)null || (Object)(object)plant.m_nview == (Object)null || !plant.m_nview.IsValid() || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(plant.m_nview.GetZDO().GetPrefab());
			if (!((Object)(object)prefab != (Object)null) || !((Object)(object)prefab.GetComponent<Piece>() != (Object)null) || !(plant.m_attachDistance <= 0f))
			{
				return null;
			}
			return ((Object)prefab).name;
		}

		private static void Grown(Growth state, GameObject grown)
		{
			if (!string.IsNullOrEmpty(state.Crop) && !((Object)(object)grown == (Object)null) && !((Object)(object)grown.GetComponent<Pickable>() == (Object)null))
			{
				ZNetView component = grown.GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid() && component.IsOwner())
				{
					component.GetZDO().Set(CropKey, state.Crop);
				}
				GiantCrops.Roll(grown);
				GridPlanting.WriteGrid((Component)(object)grown.transform, state.Grid);
			}
		}

		private static void Expect(Pickable pick, Humanoid character, bool repeat)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			if (PlantingControls.Replant == null || !PlantingControls.Replant.Value || repeat || (Object)(object)character != (Object)(object)Player.m_localPlayer || (Object)(object)pick == (Object)null || pick.GetPicked() || pick.GetEnabled == 0 || pick.m_respawnTimeMinutes > 0f || (Object)(object)pick.m_hideWhenPicked != (Object)null)
			{
				return;
			}
			Piece val = Replacement(pick);
			if (!((Object)(object)val == (Object)null) && PrivateArea.CheckAccess(((Component)pick).transform.position, 0f, false, false))
			{
				ZDOID uid = pick.m_nview.GetZDO().m_uid;
				if (!Pending.ContainsKey(uid) && Pending.Count < 128)
				{
					Pending[uid] = new Request
					{
						Player = (Player)character,
						Piece = val,
						Position = ((Component)pick).transform.position,
						Rotation = ((Component)pick).transform.rotation,
						Until = Time.time + 5f,
						Grid = GridPlanting.ReadGrid((Component)(object)pick)
					};
					AreaHarvestPickup.Expect((Component)(object)pick, (Player)character);
				}
			}
		}

		internal static void Confirm(ZDOID id)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (Pending.TryGetValue(id, out var value))
			{
				Pending.Remove(id);
				value.ConfirmedFrame = Time.frameCount;
				if (Time.time <= value.Until)
				{
					Ready.Enqueue(value);
				}
			}
		}

		private static void Drain(Player player)
		{
			//IL_0047: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			Expired.Clear();
			foreach (KeyValuePair<ZDOID, Request> item in Pending)
			{
				if (Time.time > item.Value.Until)
				{
					Expired.Add(item.Key);
				}
			}
			foreach (ZDOID item2 in Expired)
			{
				Pending.Remove(item2);
			}
			int num = Math.Min(8, Ready.Count);
			for (int i = 0; i < num; i++)
			{
				Request request = Ready.Dequeue();
				if (!(Time.time > request.Until))
				{
					if (!ReplantRules.Ready(Time.time, request.Until, Time.frameCount, request.ConfirmedFrame))
					{
						Ready.Enqueue(request);
					}
					else
					{
						Place(request);
					}
				}
			}
		}

		private static void Place(Request request)
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: 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)
			Player p = request.Player;
			Piece piece = request.Piece;
			if (request.Finished || Time.time > request.Until || (Object)(object)p == (Object)null || (Object)(object)p != (Object)(object)Player.m_localPlayer || ((Character)p).IsDead() || !((Character)p).TakeInput() || PlantingControls.Replant == null || !PlantingControls.Replant.Value || (Object)(object)piece == (Object)null)
			{
				return;
			}
			GridPlanting.PrepareReplant(p);
			if (GridPlanting.Refusal(p, piece, request.Position, request.Position, limitReach: false) != PlantRefusal.None)
			{
				return;
			}
			Vector3 origin = ((Component)p).transform.position;
			if (SeedSupply.Secure(p, piece, 1, delegate
			{
				Place(request);
			}, request, delegate
			{
				//IL_0086: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: 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)
				if (!((Object)(object)p == (Object)null) && !((Object)(object)p != (Object)(object)Player.m_localPlayer) && !((Character)p).IsDead() && ((Character)p).TakeInput() && !request.Finished && !(Time.time > request.Until))
				{
					Setting<bool> replant = PlantingControls.Replant;
					if (replant != null && replant.Value)
					{
						Vector3 val2 = ((Component)p).transform.position - origin;
						if (!(((Vector3)(ref val2)).sqrMagnitude > 1f))
						{
							return new object[3] { p, piece, request };
						}
					}
				}
				return (object[])null;
			}) != 0)
			{
				return;
			}
			Requirement[] requirements = piece.m_resources;
			if (requirements == null || requirements.Length == 0)
			{
				return;
			}
			int[] array = new int[requirements.Length];
			for (int num = 0; num < requirements.Length; num++)
			{
				Requirement val = requirements[num];
				if (val == null || (Object)(object)val.m_resItem == (Object)null || val.m_amount <= 0)
				{
					return;
				}
				array[num] = val.m_amount;
			}
			request.Finished = true;
			ReplantRules.Pay(array, delegate(int i)
			{
				string name = requirements[i].m_resItem.m_itemData.m_shared.m_name;
				return ((Humanoid)p).GetInventory().CountItems(name, -1, false) + SeedSupply.CountDirect(p, name);
			}, delegate
			{
				p.ConsumeResources(requirements, 0, -1, 1);
			}, delegate
			{
				//IL_0012: 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)
				GridPlanting.PlaceReplant(p, piece, request.Position, request.Rotation, request.Grid);
			});
		}

		private static void Hover(Pickable pick, ref string text)
		{
			if (PlantingControls.Replant != null && PlantingControls.Replant.Value && !string.IsNullOrEmpty(text))
			{
				Piece val = Replacement(pick);
				if ((Object)(object)val != (Object)null)
				{
					text = text + "\n" + FarmWords.Get("Replant") + ": " + Localization.instance.Localize(val.m_name) + " (" + FarmWords.Get("Requires seeds") + ")";
				}
			}
		}
	}
	public static class CultivatorReturn
	{
		private sealed class Loan
		{
			public PieceTable Table;

			public bool TableWas;

			public Piece Piece;

			public bool PieceWas;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(Player), "RemovePiece")]
			[HarmonyPrefix]
			private static void BeforeRemove(out bool? __state)
			{
				__state = _removing;
				_removing = _removing || On || DebrisClear.On;
			}

			[HarmonyPatch(typeof(Player), "RemovePiece")]
			[HarmonyFinalizer]
			private static void AfterRemove(bool? __state)
			{
				_accepted = null;
				if (__state.HasValue)
				{
					_removing = __state.Value;
				}
			}

			[HarmonyPatch(typeof(Player), "UpdatePlacement")]
			[HarmonyPrefix]
			private static void BeforePlacement(Player __instance, out Loan __state)
			{
				__state = null;
				if (!On || (Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				ItemData rightItem = ((Humanoid)__instance).GetRightItem();
				PieceTable val = ((rightItem == null || rightItem.m_shared == null) ? null : rightItem.m_shared.m_buildPieces);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				Piece hoveringPiece = __instance.GetHoveringPiece();
				if (!((Object)(object)hoveringPiece == (Object)null))
				{
					bool nativePlant = (Object)(object)((Component)hoveringPiece).GetComponent<Plant>() != (Object)null && (Object)(object)((Component)hoveringPiece).GetComponent<WildPlant>() == (Object)null;
					bool toolIsCultivator = (Object)(object)val == (Object)(object)WildPlants.CultivatorTable();
					if (CultivatorReturnRules.Lend(on: true, toolIsCultivator, nativePlant))
					{
						__state = new Loan
						{
							Table = val,
							TableWas = val.m_canRemovePieces,
							Piece = hoveringPiece,
							PieceWas = hoveringPiece.m_canBeRemoved
						};
						val.m_canRemovePieces = true;
						hoveringPiece.m_canBeRemoved = true;
						_cultivatorRemoving = __state;
					}
				}
			}

			[HarmonyPatch(typeof(Player), "UpdatePlacement")]
			[HarmonyFinalizer]
			private static void AfterPlacement(Loan __state)
			{
				_cultivatorRemoving = null;
				if (__state != null)
				{
					if ((Object)(object)__state.Table != (Object)null)
					{
						__state.Table.m_canRemovePieces = __state.TableWas;
					}
					if ((Object)(object)__state.Piece != (Object)null)
					{
						__state.Piece.m_canBeRemoved = __state.PieceWas;
					}
				}
			}

			[HarmonyPatch(typeof(Piece), "DropResources")]
			[HarmonyPrefix]
			private static void BeforeDrop(Piece __instance, out Requirement[] __state)
			{
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				__state = null;
				if (!_removing || (Object)(object)__instance == (Object)null)
				{
					return;
				}
				Plant component = ((Component)__instance).GetComponent<Plant>();
				bool flag = (Object)(object)((Component)__instance).GetComponent<WildPlant>() != (Object)null;
				if ((Object)(object)component == (Object)null && !flag)
				{
					return;
				}
				if ((Object)(object)component != (Object)null && DebrisClear.On)
				{
					DebrisClear.Sweep(((Component)__instance).transform.position, component.m_growRadius, __instance);
				}
				if (flag)
				{
					bool flag2 = (Object)(object)_accepted != (Object)null && (Object)(object)__instance == (Object)(object)_accepted;
					if (flag2)
					{
						_accepted = null;
					}
					if (!CultivatorReturnRules.DropRefunds(_removing, flag2))
					{
						return;
					}
				}
				else if (!CultivatorReturnRules.Refunds(On, nativePlant: true, wildPlant: false))
				{
					return;
				}
				int percent = Percent;
				Requirement[] resources = __instance.m_resources;
				if (resources != null && resources.Length != 0)
				{
					Requirement[] resources2 = Scaled(resources, percent);
					__state = resources;
					__instance.m_resources = resources2;
				}
			}

			[HarmonyPatch(typeof(Piece), "DropResources")]
			[HarmonyFinalizer]
			private static void AfterDrop(Piece __instance, Requirement[] __state)
			{
				if (__state != null && (Object)(object)__instance != (Object)null)
				{
					__instance.m_resources = __state;
				}
			}
		}

		private static class TargetPatches
		{
			[HarmonyPatch(typeof(Player), "RemovePiece")]
			[HarmonyPrefix]
			private static void BeforeTarget(Player __instance, out Piece __state)
			{
				//IL_003b: 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_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				__state = null;
				if (_cultivatorRemoving == null || (Object)(object)__instance == (Object)null || (Object)(object)GameCamera.instance == (Object)null || (Object)(object)((Character)__instance).m_eye == (Object)null)
				{
					return;
				}
				Transform transform = ((Component)GameCamera.instance).transform;
				RaycastHit val = default(RaycastHit);
				if (Physics.Raycast(transform.position, transform.forward, ref val, 50f, __instance.m_removeRayMask) && !(Vector3.Distance(((RaycastHit)(ref val)).point, ((Character)__instance).m_eye.position) >= __instance.m_maxPlaceDistance))
				{
					Piece componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Piece>();
					if (!((Object)(object)componentInParent == (Object)null) && !componentInParent.m_canBeRemoved && !((Object)(object)componentInParent == (Object)(object)_cultivatorRemoving.Piece) && !((Object)(object)((Component)componentInParent).GetComponent<Plant>() == (Object)null) && !((Object)(object)((Component)componentInParent).GetComponent<WildPlant>() != (Object)null))
					{
						componentInParent.m_canBeRemoved = true;
						__state = componentInParent;
					}
				}
			}

			[HarmonyPatch(typeof(Player), "RemovePiece")]
			[HarmonyFinalizer]
			private static void AfterTarget(Piece __state)
			{
				if ((Object)(object)__state != (Object)null)
				{
					__state.m_canBeRemoved = false;
				}
			}
		}

		private static Setting<bool> _on;

		private static Setting<bool> _wild;

		private static Setting<float> _percent;

		private static Harmony _harmony;

		private static bool _removing;

		private static Piece _accepted;

		private static Loan _cultivatorRemoving;

		public static bool On
		{
			get
			{
				if (_on != null)
				{
					return _on.Value;
				}
				return false;
			}
		}

		public static bool WildOn
		{
			get
			{
				if (_wild != null)
				{
					return _wild.Value;
				}
				return false;
			}
		}

		public static int Percent => CultivatorReturnRules.Percent((_percent == null) ? float.NaN : _percent.Value);

		public static void Init(SettingsPage page)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			_on = page.Toggle("plant_return", "Plant return", true, (SettingPolicy)2, false);
			_percent = page.Slider("plant_return_percent", "Plant return percent", 100f, 0f, 100f, 5f, (SettingPolicy)2, false);
			_wild = page.Toggle("plant_return_wild", "Wild plant return", false, (SettingPolicy)2, true);
			page.Depends((Setting)(object)_wild, (Setting)(object)_on);
			_harmony = new Harmony("expdare.meadworks.farming.plant_return");
			_harmony.PatchAll(typeof(Patches));
			_harmony.PatchAll(typeof(TargetPatches));
			LedgerTrack.Patch(_harmony, "farming plant return");
			Ledger.Add("farming plant return state", (Action)delegate
			{
				_on = null;
				_wild = null;
				_percent = null;
				_removing = false;
				_accepted = null;
				_cultivatorRemoving = null;
			});
		}

		internal static void Accepted(Component plant, ZNetView view, bool wearNTear)
		{
			_accepted = null;
			Piece val = (((Object)(object)plant == (Object)null) ? null : plant.GetComponent<Piece>());
			if (!((Object)(object)val == (Object)null) && !((Object)(object)view == (Object)null) && view.IsValid() && CultivatorReturnRules.AcceptsRefund(_removing, CultivatorReturnRules.RefundsWild(On, WildOn, wildPlant: true, WildPlants.PlacedSmall(plant))))
			{
				if (CultivatorReturnRules.ClaimsFirst(wearNTear, view.IsOwner()))
				{
					view.ClaimOwnership();
				}
				_accepted = val;
			}
		}

		internal static string Hover(Component target)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!On || (Object)(object)localPlayer == (Object)null || (Object)(object)localPlayer.m_buildPieces != (Object)(object)WildPlants.CultivatorTable() || (Object)(object)target == (Object)null)
			{
				return null;
			}
			Piece component = target.GetComponent<Piece>();
			if ((Object)(object)component == (Object)null)
			{
				return null;
			}
			bool flag = (Object)(object)target.GetComponent<WildPlant>() != (Object)null;
			bool flag2 = (Object)(object)target.GetComponent<Plant>() != (Object)null;
			if (!flag2 && !flag)
			{
				return null;
			}
			bool freeBuild = (Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGlobalKey(component.FreeBuildKey());
			List<string> list = new List<string>();
			bool placedSmall = flag && WildPlants.PlacedSmall(target);
			Requirement[] array = (Requirement[])(((object)component.m_resources) ?? ((object)new Requirement[0]));
			foreach (Requirement val in array)
			{
				if (val != null && !((Object)(object)val.m_resItem == (Object)null))
				{
					int num = (flag ? CultivatorReturnRules.PreviewWild(On, WildOn, placedSmall, freeBuild, val.m_amount, Percent) : CultivatorReturnRules.Preview(On, flag2, flag, freeBuild, component.IsPlacedByPlayer(), val.m_amount, Percent));
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					list.Add(num + " " + ((Localization.instance == null) ? name : Localization.instance.Localize(name)));
				}
			}
			string text = FarmWords.Get("Return") + ": " + ((list.Count == 0) ? "0" : string.Join(", ", list.ToArray()));
			if (!PrivateArea.CheckAccess(target.transform.position, 0f, false, false))
			{
				text = text + " — " + FarmWords.Get("Removal blocked");
			}
			return text;
		}

		private static Requirement[] Scaled(Requirement[] full, int percent)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			Requirement[] array = (Requirement[])(object)new Requirement[full.Length];
			for (int i = 0; i < full.Length; i++)
			{
				Requirement val = full[i];
				if (val != null)
				{
					array[i] = new Requirement
					{
						m_resItem = val.m_resItem,
						m_amount = CultivatorReturnRules.Count(val.m_amount, percent),
						m_extraAmountOnlyOneIngredient = val.m_extraAmountOnlyOneIngredient,
						m_amountPerLevel = val.m_amountPerLevel,
						m_upgraderResource = val.m_upgraderResource,
						m_recover = true
					};
				}
			}
			return array;
		}
	}
	public static class CultivatorReturnRules
	{
		public const int NonePercent = 0;

		public const int FullPercent = 100;

		public static int Percent(float value)
		{
			if (float.IsNaN(value) || float.IsInfinity(value))
			{
				return 100;
			}
			if (value <= 0f)
			{
				return 0;
			}
			if (value >= 100f)
			{
				return 100;
			}
			return (int)Math.Floor(value);
		}

		public static bool Lend(bool on, bool toolIsCultivator, bool nativePlant)
		{
			return on && toolIsCultivator && nativePlant;
		}

		public static bool Refunds(bool on, bool nativePlant, bool wildPlant)
		{
			if (on && nativePlant)
			{
				return !wildPlant;
			}
			return false;
		}

		public static bool RefundsWild(bool on, bool wildOn, bool wildPlant, bool placedSmall)
		{
			return on && wildOn && wildPlant && placedSmall;
		}

		public static bool AcceptsRefund(bool insideOwnRemoval, bool refundsWild)
		{
			return insideOwnRemoval && refundsWild;
		}

		public static bool ClaimsFirst(bool wearNTear, bool ownedHere)
		{
			if (wearNTear)
			{
				return !ownedHere;
			}
			return false;
		}

		public static bool DropRefunds(bool insideOwnRemoval, bool acceptedThisPlant)
		{
			return insideOwnRemoval && acceptedThisPlant;
		}

		public static int PreviewWild(bool on, bool wildOn, bool placedSmall, bool freeBuild, int full, int percent)
		{
			if (!freeBuild && RefundsWild(on, wildOn, wildPlant: true, placedSmall))
			{
				return Count(full, percent);
			}
			return 0;
		}

		public static int Preview(bool on, bool nativePlant, bool wildPlant, bool freeBuild, bool placedByPlayer, int full, int percent)
		{
			if (freeBuild || !Refunds(on, nativePlant, wildPlant))
			{
				return 0;
			}
			int num = Count(full, percent);
			if (!(num <= 0 || placedByPlayer))
			{
				return Math.Max(1, num / 3);
			}
			return num;
		}

		public static int Count(int full, int percent)
		{
			if (full <= 0 || percent <= 0)
			{
				return 0;
			}
			if (percent >= 100)
			{
				return full;
			}
			return (int)Math.Floor((double)full * (double)percent / 100.0);
		}
	}
	public static class DebrisClear
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(Player), "TryPlacePiece")]
			[HarmonyPostfix]
			private static void AfterPlace(Player __instance, Piece piece, bool __result)
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Invalid comparison between Unknown and I4
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				if (!__result || !On || (Object)(object)__instance == (Object)null || (Object)(object)piece == (Object)null)
				{
					return;
				}
				TerrainOp component = ((Component)piece).GetComponent<TerrainOp>();
				if (!((Object)(object)component == (Object)null) && component.m_settings != null && (int)component.m_settings.m_paintType == 1)
				{
					GameObject placementGhost = __instance.m_placementGhost;
					if (!((Object)(object)placementGhost == (Object)null))
					{
						Sweep(placementGhost.transform.position, component.GetRadius(), null);
					}
				}
			}
		}

		private static Setting<bool> _on;

		private static Harmony _harmony;

		private static readonly Collider[] Hits = (Collider[])(object)new Collider[64];

		private static readonly HashSet<Pickable> Seen = new HashSet<Pickable>();

		private static int _mask;

		public static bool On
		{
			get
			{
				if (_on != null)
				{
					return _on.Value;
				}
				return false;
			}
		}

		public static void Init(SettingsPage page)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			_on = page.Toggle("debris_clear", "Debris removal", true, (SettingPolicy)2, false);
			_harmony = new Harmony("expdare.meadworks.farming.debris_clear");
			_harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(_harmony, "farming debris clear");
			Ledger.Add("farming debris clear state", (Action)delegate
			{
				_on = null;
			});
		}

		public static int Sweep(Vector3 point, float radius, Piece exclude)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (!On)
			{
				return 0;
			}
			float num = DebrisClearRules.SweepRadius(radius);
			if (!(num > 0f))
			{
				return 0;
			}
			int num2 = 0;
			if (_mask == 0)
			{
				_mask = LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid" });
			}
			int num3 = Physics.OverlapSphereNonAlloc(point, num, Hits, _mask);
			Seen.Clear();
			for (int i = 0; i < num3; i++)
			{
				Pickable val = (((Object)(object)Hits[i] == (Object)null) ? null : ((Component)Hits[i]).GetComponentInParent<Pickable>());
				if (!((Object)(object)val == (Object)null) && Seen.Add(val) && (!((Object)(object)exclude != (Object)null) || !((Component)val).transform.IsChildOf(((Component)exclude).transform)) && DebrisClearRules.IsRemains(val.GetPicked(), val.m_respawnTimeMinutes) && Destroy(((Component)val).GetComponent<ZNetView>()))
				{
					num2++;
				}
			}
			return num2;
		}

		private static bool Destroy(ZNetView view)
		{
			if ((Object)(object)view == (Object)null || !view.IsValid() || !view.IsOwner() || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return false;
			}
			ZNetScene.instance.Destroy(((Component)view).gameObject);
			return true;
		}
	}
	public static class DebrisClearRules
	{
		public const float MaxRadius = 10f;

		public const int MaxObstacles = 30;

		public static bool IsRemains(bool picked, float respawnMinutes)
		{
			if (picked)
			{
				return !(respawnMinutes > 0f);
			}
			return false;
		}

		public static float SweepRadius(float radius)
		{
			if (float.IsNaN(radius) || float.IsInfinity(radius) || radius <= 0f)
			{
				return 0f;
			}
			if (!(radius > 10f))
			{
				return radius;
			}
			return 10f;
		}

		public static bool IsObstacle(bool wood, bool builtPiece, bool owned, int minToolTier)
		{
			if (wood && !builtPiece && owned)
			{
				return minToolTier <= 0;
			}
			return false;
		}

		public static bool ClearsOnOperation(bool level, bool raise, bool smooth)
		{
			return level || raise || smooth;
		}

		public static bool RoomLeft(int cleared)
		{
			return cleared < 30;
		}

		public static int HitWorldLevel(int hoeWorldLevel)
		{
			if (hoeWorldLevel < 0)
			{
				return 0;
			}
			if (hoeWorldLevel <= 255)
			{
				return hoeWorldLevel;
			}
			return 255;
		}

		public static bool TierAllows(int toolTier, int minToolTier, int itemWorldLevel, int worldLevel, bool locked, bool alwaysAllowTierZero)
		{
			if (itemWorldLevel < worldLevel && locked && (minToolTier > 0 || !alwaysAllowTierZero))
			{
				return false;
			}
			return toolTier >= minToolTier;
		}

		public static int ClearingHitWorldLevel(int hoeWorldLevel, int worldLevel, bool locked, int minToolTier)
		{
			int num = HitWorldLevel(hoeWorldLevel);
			if (TierAllows(0, minToolTier, num, worldLevel, locked, alwaysAllowTierZero: true) && !TierAllows(0, minToolTier, num, worldLevel, locked, alwaysAllowTierZero: false))
			{
				return HitWorldLevel(worldLevel);
			}
			return num;
		}
	}
	[BepInPlugin("expdare.meadworks.farming", "Meadworks: Farming", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class FarmingPlugin : BaseUnityPlugin
	{
		public const string Guid = "expdare.meadworks.farming";

		public const string DisplayName = "Meadworks: Farming";

		private void Awake()
		{
			ModuleLife.Start("farming", (Action)Init);
		}

		private void OnDisable()
		{
			ModuleLife.Leaving("farming");
		}

		private void OnDestroy()
		{
			ModuleLife.End("farming");
		}

		private void Init()
		{
			SettingsPage page = Settings.Page(((BaseUnityPlugin)this).Config, "farming", "Farming");
			GridPlanting.Init(page);
			GridPlanting.MigrateDefault(((BaseUnityPlugin)this).Config);
			WildPlants.Init(page);
			AreaHarvest.Init(page);
			GrowthTimers.Init();
			ResourceHealth.Init();
			CultivatorReturn.Init(page);
			RemovalFeedback.Init();
			DebrisClear.Init(page);
			TerrainBrush.Init(page);
			ObstacleClear.Init(page);
			PlantTuning.Init(page);
			PlantText.Init(page);
			Settings.DropRetired(((BaseUnityPlugin)this).Config, new string[4] { "plant_wither_guard", "growth_timers", "resource_health", "plant_text" });
			MwLog.Debug((object)"farming ready");
		}
	}
	public static class GridFitRules
	{
		public static bool InWater(bool noInWater, float liquidLevel, float groundY)
		{
			if (noInWater)
			{
				return liquidLevel > groundY;
			}
			return false;
		}

		public static float NormalY(float xPlus, float xMinus, float zPlus, float zMinus, float step)
		{
			if (!(step > 0f))
			{
				return 1f;
			}
			float num = (xPlus - xMinus) / (2f * step);
			float num2 = (zPlus - zMinus) / (2f * step);
			return 1f / (float)Math.Sqrt(1f + num * num + num2 * num2);
		}

		public static bool Tilted(bool notOnTiltingSurface, float normalY)
		{
			if (notOnTiltingSurface)
			{
				return normalY < 0.8f;
			}
			return false;
		}

		public static bool InteriorBlocks(bool allowedInDungeons, bool interior, bool interiorOverride, bool dungeonBuildKey)
		{
			if (!allowedInDungeons && interior && !interiorOverride)
			{
				return !dungeonBuildKey;
			}
			return false;
		}

		public static bool GrowSpaceBlocked(bool isPlant, bool healthy)
		{
			return !isPlant || healthy;
		}
	}
	public static class RemovalRules
	{
		public static bool Lend(bool toolIsCultivator, bool tableAllows, bool hoveringWildPlant)
		{
			return toolIsCultivator && !tableAllows && hoveringWildPlant;
		}

		public static bool ToolRemoves(bool wildPlant, bool toolIsCultivator)
		{
			return !wildPlant || toolIsCultivator;
		}
	}
	public static class ToolRules
	{
		public static bool Holds(bool useDurability, float durability, float reserve)
		{
			if (!useDurability)
			{
				return true;
			}
			return durability > ((reserve > 0f) ? reserve : 0f);
		}

		public static bool Broken(bool useDurability, float durability)
		{
			if (useDurability)
			{
				return durability <= 0f;
			}
			return false;
		}

		public static bool RaisesSkill(ref int removeDebt)
		{
			if (removeDebt > 0)
			{
				removeDebt--;
				return false;
			}
			return true;
		}
	}
	public static class PickStamp
	{
		public static long Sync(long zdoTicks, long fieldTicks)
		{
			if (zdoTicks <= 1)
			{
				return fieldTicks;
			}
			return zdoTicks;
		}
	}
	public static class IndexedList
	{
		public static bool SwapRemove<T>(List<T> list, int index, T item, Action<T, int> reindex) where T : class
		{
			if (list == null || index < 0 || index >= list.Count || list[index] != item)
			{
				return false;
			}
			int num = list.Count - 1;
			if (index != num)
			{
				list[index] = list[num];
				reindex?.Invoke(list[index], index);
			}
			list.RemoveAt(num);
			return true;
		}
	}
	internal static class FarmWords
	{
		internal static string Get(string english)
		{
			return Kit.Word("mwfarm_ui_" + Regex.Replace(english.ToLowerInvariant(), "[^a-z0-9]+", "_").Trim(new char[1] { '_' }), english);
		}

		internal static string Biome(string name)
		{
			string text = "$biome_" + name.ToLowerInvariant();
			if (Localization.instance != null)
			{
				return Localization.instance.Localize(text);
			}
			return name;
		}
	}
	public static class GhostParts
	{
		public static void Dress(Player player, GameObject ghost)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)ghost == (Object)null)
			{
				return;
			}
			Strip<Joint>(ghost);
			Strip<Rigidbody>(ghost);
			Strip<LightFlicker>(ghost);
			Strip<LightLod>(ghost);
			Strip<Light>(ghost);
			int num = LayerMask.NameToLayer("ghost");
			Collider[] componentsInChildren = ghost.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null && GhostRules.DisableCollider(((Component)componentsInChildren[i]).gameObject.layer, player.m_placeRayMask, num))
				{
					componentsInChildren[i].enabled = false;
				}
			}
			if (num >= 0)
			{
				Transform[] componentsInChildren2 = ghost.GetComponentsInChildren<Transform>(true);
				for (int j = 0; j < componentsInChildren2.Length; j++)
				{
					((Component)componentsInChildren2[j]).gameObject.layer = num;
				}
			}
			AudioSource[] componentsInChildren3 = ghost.GetComponentsInChildren<AudioSource>(true);
			for (int k = 0; k < componentsInChildren3.Length; k++)
			{
				((Behaviour)componentsInChildren3[k]).enabled = false;
			}
			ZSFX[] componentsInChildren4 = ghost.GetComponentsInChildren<ZSFX>(true);
			for (int l = 0; l < componentsInChildren4.Length; l++)
			{
				((Behaviour)componentsInChildren4[l]).enabled = false;
			}
			ParticleSystem[] componentsInChildren5 = ghost.GetComponentsInChildren<ParticleSystem>(true);
			for (int m = 0; m < componentsInChildren5.Length; m++)
			{
				((Component)componentsInChildren5[m]).gameObject.SetActive(false);
			}
			Unlist(ghost.GetComponent<Piece>());
		}

		internal static bool HasPlacementCollider(GameObject ghost)
		{
			Collider[] componentsInChildren = ghost.GetComponentsInChildren<Collider>();
			foreach (Collider val in componentsInChildren)
			{
				MeshCollider val2 = (MeshCollider)(object)((val is MeshCollider) ? val : null);
				if (GhostRules.UsableCollider(val.enabled, val.isTrigger, (Object)(object)val2 != (Object)null, (Object)(object)val2 != (Object)null && val2.convex))
				{
					return true;
				}
			}
			return false;
		}

		public static GameObject Clone(GameObject ghost)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("FarmingGhostHolder");
			val.SetActive(false);
			try
			{
				GameObject val2 = Object.Instantiate<GameObject>(ghost, val.transform);
				Drop<Plant>(val2);
				Drop<Pickable>(val2);
				Drop<WildPlant>(val2);
				MaterialManNotifier[] componentsInChildren = val2.GetComponentsInChildren<MaterialManNotifier>(true);
				foreach (MaterialManNotifier val3 in componentsInChildren)
				{
					MaterialMan.instance.SetValue<Color>(((Component)val3).gameObject, ShaderProps._Color, Color.white, false);
					MaterialMan.instance.ResetValue(((Component)val3).gameObject, ShaderProps._Color);
				}
				val2.transform.SetParent((Transform)null, true);
				return val2;
			}
			finally
			{
				Object.Destroy((Object)(object)val);
			}
		}

		private static void Drop<T>(GameObject root) where T : Component
		{
			T[] componentsInChildren = root.GetComponentsInChildren<T>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
				}
			}
		}

		public static void Unlist(Piece piece)
		{
			if (!((Object)(object)piece == (Object)null) && IndexedList.SwapRemove(Piece.s_allPieces, piece.m_myListIndex, piece, delegate(Piece moved, int at)
			{
				moved.m_myListIndex = at;
			}))
			{
				piece.m_myListIndex = -1;
			}
		}

		private static void Strip<T>(GameObject root) where T : Component
		{
			T[] componentsInChildren = root.GetComponentsInChildren<T>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null)
				{
					Object.Destroy((Object)(object)componentsInChildren[i]);
				}
			}
		}
	}
	public static class GhostRules
	{
		public static bool ClipGround(bool vine)
		{
			return !vine;
		}

		public static bool CanPosition(bool groundOnly, bool clipGround, bool usableCollider)
		{
			return (groundOnly && clipGround) || usableCollider;
		}

		public static bool DisableCollider(int layer, int rayMask, int ghostLayer)
		{
			if (layer != ghostLayer)
			{
				return ((1 << layer) & rayMask) == 0;
			}
			return false;
		}

		public static bool UsableCollider(bool enabled, bool trigger, bool mesh, bool convex)
		{
			if (enabled && !trigger)
			{
				return !mesh || convex;
			}
			return false;
		}
	}
	public static class GiantCropRules
	{
		public const float MaxPercent = 25f;

		public const float DefaultPercent = 5f;

		public const float Scale = 1.4f;

		public const int YieldMultiplier = 3;

		public static bool IsCrop(float respawnMinutes, bool hidesWhenPicked)
		{
			if (!(respawnMinutes > 0f))
			{
				return !hidesWhenPicked;
			}
			return false;
		}

		public static float Chance(float percent)
		{
			if (float.IsNaN(percent) || percent <= 0f)
			{
				return 0f;
			}
			return ((percent > 25f) ? 25f : percent) / 100f;
		}

		public static bool Rolls(float percent, float roll)
		{
			float num = Chance(percent);
			if (num > 0f)
			{
				return roll < num;
			}
			return false;
		}

		public static int ExtraDrops(int amount)
		{
			if (amount > 0)
			{
				return amount * 2;
			}
			return 0;
		}
	}
	internal static class GiantCrops
	{
		private static class Patches
		{
			[HarmonyPostfix]
			[HarmonyPatch(typeof(Pickable), "Awake")]
			private static void Awoke(Pickable __instance)
			{
				Loaded(__instance);
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(Pickable), "RPC_Pick")]
			private static void BeforePick(Pickable __instance, ref int bonus)
			{
				Picking(__instance, ref bonus);
			}
		}

		private static readonly int GiantKey = StringExtensionMethods.GetStableHashCode("mw.farming.giant");

		private static Setting<float> _chance;

		internal static void Init(SettingsPage page, Harmony harmony)
		{
			_chance = page.Slider("giant_crop_chance", "Giant crop chance", 5f, 0f, 25f, 1f, (SettingPolicy)2, false);
			harmony.PatchAll(typeof(Patches));
			Ledger.Add("farming giant crops state", (Action)delegate
			{
				_chance = null;
			});
		}

		private static bool IsGiant(Pickable pick)
		{
			if ((Object)(object)pick != (Object)null && (Object)(object)pick.m_nview != (Object)null && pick.m_nview.IsValid())
			{
				return pick.m_nview.GetZDO().GetInt(GiantKey, 0) == 1;
			}
			return false;
		}

		internal static void Roll(GameObject grown)
		{
			//IL_008c: 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)
			if (_chance != null && !((Object)(object)grown == (Object)null))
			{
				Pickable component = grown.GetComponent<Pickable>();
				ZNetView component2 = grown.GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null) && component2.IsValid() && component2.IsOwner() && GiantCropRules.IsCrop(component.m_respawnTimeMinutes, (Object)(object)component.m_hideWhenPicked != (Object)null) && GiantCropRules.Rolls(_chance.Value, Random.value))
				{
					component2.GetZDO().Set(GiantKey, 1, false);
					component2.SetLocalScale(((Component)component2).transform.localScale * 1.4f);
				}
			}
		}

		private static void Loaded(Pickable pick)
		{
			//IL_001d: 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)
			if (IsGiant(pick) && !pick.m_nview.m_syncInitialScale)
			{
				Transform transform = ((Component)pick).transform;
				transform.localScale *= 1.4f;
			}
		}

		private static void Picking(Pickable pick, ref int bonus)
		{
			if (IsGiant(pick) && pick.m_nview.IsOwner() && !pick.GetPicked())
			{
				int amount = (pick.m_dontScale ? pick.m_amount : Mathf.Max(pick.m_minAmountScaled, Game.instance.ScaleDrops(pick.m_itemPrefab, pick.m_amount)));
				bonus += GiantCropRules.ExtraDrops(amount);
			}
		}
	}
	public sealed class GridCellChecks
	{
		public readonly bool[] Fits;

		public readonly bool[] Checked;

		private int _cursor;

		public GridCellChecks(int capacity)
		{
			Fits = new bool[capacity];
			Checked = new bool[capacity];
		}

		public void Moved(int cells, bool fresh)
		{
			for (int i = 1; i < cells && i < Fits.Length; i++)
			{
				Checked[i] = false;
				if (fresh)
				{
					Fits[i] = true;
				}
			}
		}

		public int Sweep(int cells, bool every, Func<int, bool> check)
		{
			if (cells > Fits.Length)
			{
				cells = Fits.Length;
			}
			int num = GridBatchRules.Checks(cells, every);
			for (int i = 0; i < num; i++)
			{
				_cursor = GridBatchRules.Next(_cursor, cells);
				Fits[_cursor] = check(_cursor);
				Checked[_cursor] = true;
			}
			return num;
		}

		public bool Settled(int cells)
		{
			for (int i = 1; i < cells && i < Checked.Length; i++)
			{
				if (!Checked[i])
				{
					return false;
				}
			}
			return true;
		}
	}
	public enum PlantOutcome
	{
		Planted,
		Last,
		Stopped
	}
	public static class GridBatchRules
	{
		public const int ChecksPerFrame = 24;

		public const int GhostsPerFrame = 24;

		public const int ClickPlacements = 25;

		public const int FramePlacements = 10;

		public const float ProbeHeight = 1f;

		public static int Checks(int cells, bool all)
		{
			int num = cells - 1;
			if (num <= 0)
			{
				return 0;
			}
			if (!all && num >= 24)
			{
				return 24;
			}
			return num;
		}

		public static int Next(int cursor, int cells)
		{
			if (cells <= 1)
			{
				return 0;
			}
			int num = cursor + 1;
			if (num < cells && num >= 1)
			{
				return num;
			}
			return 1;
		}

		public static int Grow(int have, int want, bool all)
		{
			int num = want - have;
			if (num <= 0)
			{
				return 0;
			}
			if (!all && num >= 24)
			{
				return 24;
			}
			return num;
		}

		public static bool Defers(bool fromPreview, int handled)
		{
			if (fromPreview)
			{
				return handled >= 25;
			}
			return false;
		}

		public static bool JobEnds(bool playerGone, bool dead, bool toolChanged, bool pieceGone)
		{
			return playerGone || dead || toolChanged || pieceGone;
		}

		public static int Step(int next, int count, int perFrame, Func<int, bool> stillFits, Func<int, PlantOutcome> plant)
		{
			if (next < 0)
			{
				next = 0;
			}
			for (int i = 0; i < perFrame; i++)
			{
				if (next >= count)
				{
					break;
				}
				int arg = next++;
				if (stillFits(arg) && plant(arg) != PlantOutcome.Planted)
				{
					return count;
				}
			}
			return next;
		}

		public static int Frames(int cells)
		{
			if (cells <= 25)
			{
				return 1;
			}
			int num = cells - 25;
			return 1 + (num + 10 - 1) / 10;
		}
	}
	internal sealed class GridControls : MonoBehaviour
	{
		private sealed class WindowWatch : MonoBehaviour
		{
			internal Action Changed;

			private void OnRectTransformDimensionsChange()
			{
				if (Changed != null)
				{
					Changed();
				}
			}
		}

		private static class Patches
		{
			[HarmonyPostfix]
			[HarmonyPatch(typeof(BuildUi), "OpenBuildMenu")]
			private static void Opened(BuildUi __instance)
			{
				Open(__instance);
			}
		}

		private GameObject _row;

		private GameObject _spacingRow;

		private KitSlider _spacing;

		private KitPanel _fallback;

		private KitToggle _on;

		private KitStepper _rows;

		private KitStepper _columns;

		private BuildUi _ui;

		private RectTransform _plank;

		private bool _settling;

		private static readonly Vector3[] Corners = (Vector3[])(object)new Vector3[4];

		private static readonly Vector3[] Corners2 = (Vector3[])(object)new Vector3[4];

		internal static void Init(Harmony harmony)
		{
			harmony.PatchAll(typeof(Patches));
			Ledger.Add("farming grid controls", (Action)delegate
			{
				GridControls[] array = Object.FindObjectsByType<GridControls>((FindObjectsInactive)1, (FindObjectsSortMode)0);
				for (int i = 0; i < array.Length; i++)
				{
					Object.Destroy((Object)(object)array[i]);
				}
			});
		}

		private static void Open(BuildUi ui)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ui == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)Player.m_localPlayer.m_buildPieces != (Object)(object)WildPlants.CultivatorTable()))
			{
				GridControls component = ((Component)ui).GetComponent<GridControls>();
				if ((Object)(object)component != (Object)null)
				{
					component.Clear();
					Object.Destroy((Object)(object)component);
				}
				GridControls gridControls = ((Component)ui).gameObject.AddComponent<GridControls>();
				gridControls._ui = ui;
				KitPanel val = (gridControls._fallback = Kit.Panel(((Component)ui).transform, (string)null, 580f));
				RectTransform val2 = (RectTransform)((Component)val).transform;
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(0.5f, 0.5f);
				val2.anchorMax = val3;
				val2.anchorMin = val3;
				val2.pivot = new Vector2(0.5f, 0f);
				gridControls.Build((Transform)(object)val.Content);
				gridControls.Watch();
				gridControls.Again();
			}
		}

		private static RectTransform Plank(BuildUi ui)
		{
			RectTransform val = ui.m_pieceView;
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			while ((Object)(object)((Transform)val).parent != (Object)null && (Object)(object)((Transform)val).parent != (Object)(object)((Component)ui).transform)
			{
				Transform parent = ((Transform)val).parent;
				val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			}
			if (!((Object)(object)val != (Object)null) || !((Object)(object)((Transform)val).parent == (Object)(object)((Component)ui).transform))
			{
				return null;
			}
			return val;
		}

		private void Watch()
		{
			_plank = Plank(_ui);
			if (!((Object)(object)_plank == (Object)null))
			{
				(((Component)_plank).GetComponent<WindowWatch>() ?? ((Component)_plank).gameObject.AddComponent<WindowWatch>()).Changed = Again;
			}
		}

		private void Again()
		{
			if (!_settling && ((Behaviour)this).isActiveAndEnabled)
			{
				_settling = true;
				((MonoBehaviour)this).StartCoroutine(Settle());
			}
		}

		private IEnumerator Settle()
		{
			yield return null;
			yield return null;
			_settling = false;
			Place();
		}

		private void Place()
		{
			//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)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_fallback == (Object)null || (Object)(object)_ui == (Object)null)
			{
				return;
			}
			if ((Object)(object)_plank == (Object)null)
			{
				_plank = Plank(_ui);
			}
			if ((Object)(object)_plank == (Object)null)
			{
				return;
			}
			_plank.GetWorldCorners(Corners);
			float y = ((Transform)(RectTransform)((Component)_ui).transform).lossyScale.y;
			if (y <= 0f)
			{
				return;
			}
			RectTransform val = (RectTransform)((Component)_fallback).transform;
			Rect rect = val.rect;
			float height = ((Rect)(ref rect)).height * ((Transform)val).lossyScale.y / y;
			float num = float.NaN;
			RectTransform pieceButtonsContainer = _ui.m_pieceButtonsContainer;
			if ((Object)(object)pieceButtonsContainer != (Object)null)
			{
				for (int i = 0; i < ((Transform)pieceButtonsContainer).childCount; i++)
				{
					Transform child = ((Transform)pieceButtonsContainer).GetChild(i);
					RectTransform val2 = (RectTransform)(object)((child is RectTransform) ? child : null);
					if (!((Object)(object)val2 == (Object)null) && ((Component)val2).gameObject.activeSelf)
					{
						val2.GetWorldCorners(Corners2);
						num = (float.IsNaN(num) ? Corners2[0].y : Mathf.Min(num, Corners2[0].y));
					}
				}
			}
			float y2 = Corners[0].y;
			GridPanelSpot spot = GridPanelRules.Spot(float.IsNaN(num) ? ((Corners[1].y - y2) / y) : ((num - y2) / y), height);
			float num2 = (Corners[0].x + Corners[3].x) * 0.5f;
			((Transform)val).position = new Vector3(num2, GridPanelRules.PivotY(spot, y2, Corners[1].y, y), ((Transform)val).position.z);
			((Transform)val).SetAsLastSibling();
		}

		private void Build(Transform parent)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Expected O, but got Unknown
			_row = new GameObject("Farming grid controls", new Type[1] { typeof(RectTransform) });
			_row.transform.SetParent(parent, false);
			HorizontalLayoutGroup obj = _row.AddComponent<HorizontalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 8f;
			((LayoutGroup)obj).childAlignment = (TextAnchor)3;
			bool childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true);
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = childControlWidth;
			childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false);
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = childControlWidth;
			_on = Kit.Toggle(_row.transform, FarmWords.Get("Grid"), GridPlanting.On, (Action<bool>)delegate(bool value)
			{
				SettingsWindow.Write((Setting)(object)GridPlanting.EnabledSetting, value ? "true" : "false");
			});
			Kit.Label(_row.transform, "Rows", FarmWords.Get("Rows"));
			_rows = Kit.Stepper(_row.transform, GridPlanting.Rows, 1, 10, (Action<int>)delegate(int n)
			{
				SettingsWindow.Write((Setting)(object)GridPlanting.RowsSetting, n.ToString(CultureInfo.InvariantCulture));
			}, (string)null);
			Kit.Label(_row.transform, "Columns", FarmWords.Get("Columns"));
			_columns = Kit.Stepper(_row.transform, GridPlanting.Columns, 1, 10, (Action<int>)delegate(int n)
			{
				SettingsWindow.Write((Setting)(object)GridPlanting.ColumnsSetting, n.ToString(CultureInfo.InvariantCulture));
			}, (string)null);
			if (PlantSpacing.Setting != null && WildPlants.On)
			{
				_spacingRow = new GameObject("Farming spacing controls", new Type[1] { typeof(RectTransform) });
				_spacingRow.transform.SetParent(parent, false);
				HorizontalLayoutGroup obj2 = _spacingRow.AddComponent<HorizontalLayoutGroup>();
				((HorizontalOrVerticalLayoutGroup)obj2).spacing = 8f;
				((LayoutGroup)obj2).childAlignment = (TextAnchor)3;
				childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true);
				((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = childControlWidth;
				childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandHeight = false);
				((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandWidth = childControlWidth;
				Kit.Label(_spacingRow.transform, "Spacing", FarmWords.Get("Wild plant spacing"));
				_spacing = Kit.Slider(_spacingRow.transform, 0f, 3f, PlantSpacing.Value, 0.25f, (Action<float>)delegate(float v)
				{
					SettingsWindow.Write((Setting)(object)PlantSpacing.Setting, v.ToString("0.##", CultureInfo.InvariantCulture));
				});
				_spacing.ZeroLabel = FarmWords.Get("Auto");
				_spacing.Unit = "m";
			}
			Sync();
			Listen(on: true);
		}

		private void Sync()
		{
			if ((Object)(object)_row == (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			_on.SetValueWithoutNotify(GridPlanting.On);
			_rows.Value = GridPlanting.Rows;
			_columns.Value = GridPlanting.Columns;
			if ((Object)(object)_spacing != (Object)null && PlantSpacing.Setting != null)
			{
				if (Mathf.Abs(_spacing.Value - PlantSpacing.Value) > 0.001f)
				{
					_spacing.Value = PlantSpacing.Value;
				}
				bool flag = !((Setting)PlantSpacing.Setting).Editable;
				if (_spacing.Locked != flag)
				{
					_spacing.Locked = flag;
				}
			}
		}

		private void Listen(bool on)
		{
			Hear((Setting)(object)GridPlanting.EnabledSetting, on);
			Hear((Setting)(object)GridPlanting.RowsSetting, on);
			Hear((Setting)(object)GridPlanting.ColumnsSetting, on);
			Hear((Setting)(object)PlantSpacing.Setting, on);
		}

		private void Hear(Setting setting, bool on)
		{
			if (setting != null)
			{
				if (on)
				{
					setting.Changed += Sync;
				}
				else
				{
					setting.Changed -= Sync;
				}
			}
		}

		private void Clear()
		{
			Listen(on: false);
			if ((Object)(object)_plank != (Object)null)
			{
				WindowWatch component = ((Component)_plank).GetComponent<WindowWatch>();
				if ((Object)(object)component != (Object)null)
				{
					component.Changed = null;
					Object.Destroy((Object)(object)component);
				}
				_plank = null;
			}
			if ((Object)(object)_row != (Object)null)
			{
				_row.SetActive(false);
				Object.Destroy((Object)(object)_row);
			}
			if ((Object)(object)_spacingRow != (Object)null)
			{
				_spacingRow.SetActive(false);
				Object.Destroy((Object)(object)_spacingRow);
			}
			_spacing = null;
			if ((Object)(object)_fallback != (Object)null)
			{
				((Component)_fallback).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)_fallback).gameObject);
			}
		}

		private void OnDisable()
		{
			Clear();
		}

		private void OnDestroy()
		{
			Clear();
		}
	}
	public sealed class GridHeadingRules
	{
		private float _native;

		private float _written = float.NaN;

		public float Yaw => _native;

		public void Clear()
		{
			_native = 0f;
			_written = float.NaN;
		}

		public void Read(float ghostYaw)
		{
			if (float.IsNaN(_written) || Math.Abs(Delta(ghostYaw, _written)) > 0.01f)
			{
				_native = ghostYaw;
			}
		}

		public void Wrote(float yaw)
		{
			_written = yaw;
		}

		public void Direction(out float forwardX, out float forwardZ)
		{
			float num = _native * (float)Math.PI / 180f;
			forwardX = (float)Math.Sin(num);
			forwardZ = (float)Math.Cos(num);
		}

		private static float Delta(float a, float b)
		{
			float num = (a - b) % 360f;
			if (num > 180f)
			{
				num -= 360f;
			}
			if (num < -180f)
			{
				num += 360f;
			}
			return num;
		}
	}
	public static class GridDefaultRules
	{
		public const int Size = 5;

		public static bool Migrate(bool done, int rows, int columns, out int newRows, out int newColumns)
		{
			newRows = rows;
			newColumns = columns;
			if (done || rows != 1 || columns != 1)
			{
				return false;
			}
			newRows = (newColumns = 5);
			return true;
		}
	}
	public static class GridLineRules
	{
		public const int RingPoints = 24;

		public const float Lift = 0.06f;

		public const float Width = 0.035f;

		public static readonly float[] Gold = new float[4] { 0.98f, 0.8f, 0.36f, 0.95f };

		public static readonly float[] Row = new float[4] { 0.93f, 0.86f, 0.68f, 0.85f };

		public static readonly float[] Column = new float[4] { 0.66f, 0.76f, 0.58f, 0.75f };

		public const float FarAlpha = 0.25f;

		public static bool Shows(bool gridOn, int cells)
		{
			if (gridOn)
			{
				return cells > 1;
			}
			return false;
		}

		public static bool ShowsRows(int rows)
		{
			return rows > 1;
		}

		public static bool ShowsColumns(int columns)
		{
			return columns > 1;
		}

		public static float RingRadius(float spacing)
		{
			float num = spacing * 0.4f;
			if (float.IsNaN(num) || num < 0.2f)
			{
				return 0.2f;
			}
			if (!(num > 0.6f))
			{
				return num;
			}
			return 0.6f;
		}

		public static void RingPoint(int index, float