Decompiled source of OhMyGrid v1.1.0

OhMyGrid.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("cgaggino")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Plant crops in circular/donut grids in Valheim.")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+a4e455e874afad7ddf8e3247dfdcef6acd56a425")]
[assembly: AssemblyProduct("OhMyGrid")]
[assembly: AssemblyTitle("OhMyGrid")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace OhMyGrid
{
	public readonly struct GridPoint
	{
		public readonly float X;

		public readonly float Z;

		public GridPoint(float x, float z)
		{
			X = x;
			Z = z;
		}

		public override string ToString()
		{
			return $"({X:0.##}, {Z:0.##})";
		}
	}
	public static class GridGenerator
	{
		public static IEnumerable<GridPoint> Donut(float centerX, float centerZ, float innerRadius, float outerRadius, float spacing)
		{
			if (spacing <= 0f)
			{
				throw new ArgumentOutOfRangeException("spacing");
			}
			if (innerRadius < 0f)
			{
				throw new ArgumentOutOfRangeException("innerRadius");
			}
			if (outerRadius < innerRadius)
			{
				throw new ArgumentOutOfRangeException("outerRadius");
			}
			for (float r = innerRadius; r <= outerRadius + 0.0001f; r += spacing)
			{
				if (r <= 0.0001f)
				{
					yield return new GridPoint(centerX, centerZ);
					continue;
				}
				int n = Math.Max(1, (int)Math.Round(Math.PI * 2.0 * (double)r / (double)spacing));
				for (int i = 0; i < n; i++)
				{
					double num = Math.PI * 2.0 * (double)i / (double)n;
					float x = centerX + (float)((double)r * Math.Cos(num));
					float z = centerZ + (float)((double)r * Math.Sin(num));
					yield return new GridPoint(x, z);
				}
			}
		}

		public static IEnumerable<GridPoint> Wedge(float centerX, float centerZ, float innerRadius, float outerRadius, float spacing, float headingDeg, float sweepDeg)
		{
			if (sweepDeg <= 0f)
			{
				throw new ArgumentOutOfRangeException("sweepDeg");
			}
			bool fullCircle = sweepDeg >= 359.9999f;
			double start = (double)headingDeg - (double)sweepDeg / 2.0;
			foreach (GridPoint item in Donut(centerX, centerZ, innerRadius, outerRadius, spacing))
			{
				if (fullCircle)
				{
					yield return item;
					continue;
				}
				float num = item.X - centerX;
				float num2 = item.Z - centerZ;
				double num3 = ((((num * num + num2 * num2 <= 9.999999E-09f) ? 0.0 : (Math.Atan2(num, num2) * 180.0 / Math.PI)) - start) % 360.0 + 360.0) % 360.0;
				if (num3 > 359.999)
				{
					num3 = 0.0;
				}
				if (num3 < (double)sweepDeg - 0.001)
				{
					yield return item;
				}
			}
		}
	}
	[BepInPlugin("cgaggino.OhMyGrid", "OhMyGrid", "1.1.0")]
	public class OhMyGridPlugin : BaseUnityPlugin
	{
		public enum CenterMode
		{
			Player,
			Fixed,
			Cursor,
			CursorSnap
		}

		public enum GeometryMode
		{
			Off,
			Donut,
			Wedge
		}

		[HarmonyPatch(typeof(Player), "TryPlacePiece")]
		private static class TryPlacePiecePatch
		{
			[HarmonyPrefix]
			private static bool Prefix(Player __instance, Piece piece, ref bool __result)
			{
				if (_inDonutPlace)
				{
					return true;
				}
				if ((Object)(object)Instance == (Object)null)
				{
					return true;
				}
				if (Instance._geometryMode.Value == GeometryMode.Off)
				{
					return true;
				}
				GameObject val = PlacementGhostRef.Invoke(__instance);
				if ((Object)(object)val == (Object)null || (Object)(object)val.GetComponent<Plant>() == (Object)null)
				{
					return true;
				}
				__result = Instance.PlaceDonut(__instance, piece, val);
				return false;
			}
		}

		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private static class UpdatePlacementPatch
		{
			private static readonly FieldInfo PlaceRotationField = AccessTools.Field(typeof(Player), "m_placeRotation");

			private static bool Active(Player player)
			{
				if ((Object)(object)Instance == (Object)null || !Instance._wedgeMouseWheel.Value)
				{
					return false;
				}
				if (Instance._geometryMode.Value != GeometryMode.Wedge)
				{
					return false;
				}
				if (PlaceRotationField == null || PlaceRotationField.FieldType != typeof(int))
				{
					return false;
				}
				if ((Object)(object)player != (Object)(object)Player.m_localPlayer)
				{
					return false;
				}
				GameObject val = PlacementGhostRef.Invoke(player);
				if ((Object)(object)val != (Object)null)
				{
					return (Object)(object)val.GetComponent<Plant>() != (Object)null;
				}
				return false;
			}

			[HarmonyPrefix]
			private static void Prefix(Player __instance, out int __state)
			{
				__state = (Active(__instance) ? ((int)PlaceRotationField.GetValue(__instance)) : int.MinValue);
			}

			[HarmonyPostfix]
			private static void Postfix(Player __instance, int __state)
			{
				if (__state != int.MinValue)
				{
					int num = (int)PlaceRotationField.GetValue(__instance);
					if (num != __state)
					{
						PlaceRotationField.SetValue(__instance, __state);
						Instance.RotateWedge((float)(num - __state) * Mathf.Max(Instance._wedgeAngleStep.Value, 1f));
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "Interact")]
		private static class InteractPatch
		{
			[HarmonyPrefix]
			private static bool Prefix(Player __instance, GameObject go, bool hold, bool alt)
			{
				if ((Object)(object)Instance == (Object)null || !Instance._massInteractEnabled.Value)
				{
					return true;
				}
				if (hold || alt)
				{
					return true;
				}
				if (!Input.GetKey((KeyCode)304) && !Input.GetKey((KeyCode)303))
				{
					return true;
				}
				Instance.MassInteract(__instance);
				return false;
			}
		}

		public const string PluginGuid = "cgaggino.OhMyGrid";

		public const string PluginName = "OhMyGrid";

		public const string PluginVersion = "1.1.0";

		private const float MinRadius = 0f;

		private const float MaxRadius = 32f;

		internal static ManualLogSource Log;

		private readonly Harmony _harmony = new Harmony("cgaggino.OhMyGrid");

		private ConfigEntry<float> _innerRadius;

		private ConfigEntry<float> _outerRadius;

		private ConfigEntry<float> _spacing;

		private ConfigEntry<bool> _ignoreReach;

		private ConfigEntry<float> _wedgeHeading;

		private ConfigEntry<float> _wedgeSweep;

		private ConfigEntry<float> _wedgeAngleStep;

		private ConfigEntry<bool> _wedgeAutoAdvance;

		private ConfigEntry<bool> _wedgeMouseWheel;

		private ConfigEntry<string> _anchorsConfig;

		private ConfigEntry<float> _autoSnapRadius;

		private ConfigEntry<CenterMode> _centerMode;

		private ConfigEntry<GeometryMode> _geometryMode;

		private ConfigEntry<bool> _showCostOverlay;

		private ConfigEntry<bool> _massInteractEnabled;

		private ConfigEntry<float> _massInteractRadius;

		private ConfigEntry<KeyboardShortcut> _dumpGridHotkey;

		private ConfigEntry<KeyboardShortcut> _cycleModeHotkey;

		private ConfigEntry<KeyboardShortcut> _cycleGeometryHotkey;

		private ConfigEntry<KeyboardShortcut> _increaseOuterHotkey;

		private ConfigEntry<KeyboardShortcut> _decreaseOuterHotkey;

		private ConfigEntry<KeyboardShortcut> _increaseInnerHotkey;

		private ConfigEntry<KeyboardShortcut> _decreaseInnerHotkey;

		private ConfigEntry<KeyboardShortcut> _rotateWedgeCwHotkey;

		private ConfigEntry<KeyboardShortcut> _rotateWedgeCcwHotkey;

		private ConfigEntry<KeyboardShortcut> _widenWedgeHotkey;

		private ConfigEntry<KeyboardShortcut> _narrowWedgeHotkey;

		private ConfigEntry<KeyboardShortcut> _massInteractHotkey;

		private Vector3 _fixedCenter;

		private string _snapSource;

		private const int MaxAnchors = 16;

		private const float AnchorMergeDistance = 0.5f;

		private readonly List<Vector3> _anchors = new List<Vector3>();

		private readonly List<GameObject> _ghostClones = new List<GameObject>();

		private readonly List<Piece> _ghostClonePieces = new List<Piece>();

		private GameObject _lastSourceGhost;

		private Requirement[] _activeResources;

		private GameObject[] _activeGrownPrefabs;

		private string _activePieceLabel;

		private int _validPointsCount;

		private int _totalPointsCount;

		private int _outOfReachCount;

		private int _affordableCount = int.MaxValue;

		private bool _cloneFailedForGhost;

		private readonly StringBuilder _overlaySb = new StringBuilder(256);

		private GUIStyle _overlayStyle;

		private static OhMyGridPlugin Instance;

		private static bool _inDonutPlace;

		private static readonly FieldRef<Player, GameObject> PlacementGhostRef = AccessTools.FieldRefAccess<Player, GameObject>("m_placementGhost");

		private static readonly Func<Plant, bool> HaveGrowSpaceCall = AccessTools.MethodDelegate<Func<Plant, bool>>(AccessTools.Method(typeof(Plant), "HaveGrowSpace", (Type[])null, (Type[])null), (object)null, true);

		private void Awake()
		{
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_042d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0462: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			_innerRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Grid", "InnerRadius", 2f, "Inner radius (m) of the donut. Points inside this radius are skipped.");
			_outerRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Grid", "OuterRadius", 6f, "Outer radius (m) of the donut.");
			_spacing = ((BaseUnityPlugin)this).Config.Bind<float>("Grid", "Spacing", 1f, "Spacing (m) between rings and target spacing along each ring.");
			_ignoreReach = ((BaseUnityPlugin)this).Config.Bind<bool>("Grid", "IgnoreReach", false, "Plant points farther than your build reach (Player.m_maxPlaceDistance) too. Off = like vanilla: out-of-reach points are red and skipped.");
			_wedgeHeading = ((BaseUnityPlugin)this).Config.Bind<float>("Wedge", "Heading", 0f, "Compass direction (degrees, 0 = north, clockwise) the wedge points at, measured from the center.");
			_wedgeSweep = ((BaseUnityPlugin)this).Config.Bind<float>("Wedge", "Sweep", 90f, "Angular width (degrees) of the wedge. 90 = quarter circle, 180 = half, 360 = full donut.");
			_wedgeAngleStep = ((BaseUnityPlugin)this).Config.Bind<float>("Wedge", "AngleStep", 15f, "Degrees per rotate/widen hotkey press. 15 reaches 1/2, 1/3, 1/4, 1/6, 1/8 and 1/12 of a circle.");
			_wedgeAutoAdvance = ((BaseUnityPlugin)this).Config.Bind<bool>("Wedge", "AutoAdvance", true, "After planting a wedge, rotate the heading by one sweep so the next wedge continues the circle right where the last one ended.");
			_wedgeMouseWheel = ((BaseUnityPlugin)this).Config.Bind<bool>("Wedge", "MouseWheelRotates", true, "In Wedge mode, the mouse wheel (vanilla's rotate-piece input) rotates the wedge by one AngleStep instead of spinning the plant.");
			_autoSnapRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Center", "AutoSnapRadius", 12f, "Search radius (m) for CursorSnap. The center snaps to the nearest remembered planting center (see Anchors) within this radius from the cursor; if there is none, to the CENTROID of all Plants in range. Should be ≥ the outer radius of the donut/wedge you're aligning to.");
			_anchorsConfig = ((BaseUnityPlugin)this).Config.Bind<string>("Center", "Anchors", "", "Managed by the mod: centers of your last plantings (x,y,z;...), used by CursorSnap. Clear it to forget them.");
			LoadAnchors();
			_centerMode = ((BaseUnityPlugin)this).Config.Bind<CenterMode>("Center", "Mode", CenterMode.Player, "Current center mode. F7 cycles. Persists across sessions; if the saved value is Fixed it resets to Player on load (no persisted fixed center).");
			if (_centerMode.Value == CenterMode.Fixed)
			{
				_centerMode.Value = CenterMode.Player;
			}
			_geometryMode = ((BaseUnityPlugin)this).Config.Bind<GeometryMode>("Geometry", "Mode", GeometryMode.Donut, "Active geometry. Off = vanilla single-plant (mod disabled). Donut = circular ring(s). Wedge = a slice of the donut (see [Wedge]). F6 cycles. Persists.");
			_showCostOverlay = ((BaseUnityPlugin)this).Config.Bind<bool>("Overlay", "ShowCostOverlay", true, "Show an on-screen overlay with valid-point count, required seeds and expected yield while a plant ghost is active.");
			_massInteractEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("MassInteract", "Enabled", true, "Shift+E interacts with all Pickable / Fireplace / Smelter switches within MassInteractRadius.");
			_massInteractRadius = ((BaseUnityPlugin)this).Config.Bind<float>("MassInteract", "Radius", 5f, "Search radius (m) for Shift+E mass interact.");
			_dumpGridHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "DumpGrid", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Dump donut grid points around the donut center to the log.");
			_cycleModeHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "CycleCenterMode", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Cycle the donut center mode: Player → Fixed → Cursor → CursorSnap → Player.");
			_cycleGeometryHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "CycleGeometry", new KeyboardShortcut((KeyCode)287, Array.Empty<KeyCode>()), "Cycle the geometry: Off → Donut → Wedge → Off.");
			_increaseOuterHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "IncreaseOuter", new KeyboardShortcut((KeyCode)93, Array.Empty<KeyCode>()), "Increase outer radius by one Spacing step.");
			_decreaseOuterHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "DecreaseOuter", new KeyboardShortcut((KeyCode)91, Array.Empty<KeyCode>()), "Decrease outer radius by one Spacing step.");
			_increaseInnerHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "IncreaseInner", new KeyboardShortcut((KeyCode)93, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Increase inner radius by one Spacing step.");
			_decreaseInnerHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "DecreaseInner", new KeyboardShortcut((KeyCode)91, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Decrease inner radius by one Spacing step.");
			_rotateWedgeCwHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "RotateWedgeClockwise", new KeyboardShortcut((KeyCode)46, Array.Empty<KeyCode>()), "Rotate the wedge clockwise by one AngleStep.");
			_rotateWedgeCcwHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "RotateWedgeCounterClockwise", new KeyboardShortcut((KeyCode)44, Array.Empty<KeyCode>()), "Rotate the wedge counter-clockwise by one AngleStep.");
			_widenWedgeHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "WidenWedge", new KeyboardShortcut((KeyCode)46, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Widen the wedge by one AngleStep.");
			_narrowWedgeHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "NarrowWedge", new KeyboardShortcut((KeyCode)44, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Narrow the wedge by one AngleStep.");
			_massInteractHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "MassInteract", new KeyboardShortcut((KeyCode)101, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Mass-interact with all Pickable / Fireplace / Smelter switches in range.");
			Log.LogInfo((object)"OhMyGrid v1.1.0 loaded — hello from the grid.");
			_harmony.PatchAll();
		}

		private void Update()
		{
			HandleHotkeys();
			UpdateGhostClones();
		}

		private void HandleHotkeys()
		{
			//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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = _dumpGridHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				DumpGrid();
			}
			value = _cycleModeHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				CycleMode();
			}
			value = _cycleGeometryHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				CycleGeometry();
			}
			float num = Mathf.Max(_spacing.Value, 0.01f);
			bool flag = false;
			value = _increaseInnerHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				AdjustRadius(_innerRadius, num);
				flag = true;
			}
			else
			{
				value = _decreaseInnerHotkey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					AdjustRadius(_innerRadius, 0f - num);
					flag = true;
				}
			}
			if (!flag)
			{
				value = _increaseOuterHotkey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					AdjustRadius(_outerRadius, num);
				}
				else
				{
					value = _decreaseOuterHotkey.Value;
					if (((KeyboardShortcut)(ref value)).IsDown())
					{
						AdjustRadius(_outerRadius, 0f - num);
					}
				}
			}
			float num2 = Mathf.Max(_wedgeAngleStep.Value, 1f);
			value = _widenWedgeHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				AdjustSweep(num2);
			}
			else
			{
				value = _narrowWedgeHotkey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					AdjustSweep(0f - num2);
				}
				else
				{
					value = _rotateWedgeCwHotkey.Value;
					if (((KeyboardShortcut)(ref value)).IsDown())
					{
						RotateWedge(num2);
					}
					else
					{
						value = _rotateWedgeCcwHotkey.Value;
						if (((KeyboardShortcut)(ref value)).IsDown())
						{
							RotateWedge(0f - num2);
						}
					}
				}
			}
			if (!_massInteractEnabled.Value)
			{
				return;
			}
			value = _massInteractHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null)
				{
					MassInteract(localPlayer);
				}
			}
		}

		private void CycleMode()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				GameObject ghost = PlacementGhostRef.Invoke(localPlayer);
				Vector3 donutCenter = GetDonutCenter(localPlayer, ghost);
				_centerMode.Value = NextMode(_centerMode.Value);
				string text;
				if (_centerMode.Value == CenterMode.Fixed)
				{
					_fixedCenter = donutCenter;
					text = $"Mode: Fixed @ ({_fixedCenter.x:0.##}, {_fixedCenter.z:0.##})";
				}
				else
				{
					text = $"Mode: {_centerMode.Value}";
				}
				Log.LogInfo((object)text);
				ShowHudMessage(text);
			}
		}

		private static void ShowHudMessage(string text)
		{
			MessageHud instance = MessageHud.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				instance.ShowMessage((MessageType)1, text, 0, (Sprite)null, false, true);
			}
		}

		private static CenterMode NextMode(CenterMode m)
		{
			return m switch
			{
				CenterMode.Player => CenterMode.Fixed, 
				CenterMode.Fixed => CenterMode.Cursor, 
				CenterMode.Cursor => CenterMode.CursorSnap, 
				CenterMode.CursorSnap => CenterMode.Player, 
				_ => CenterMode.Player, 
			};
		}

		private void CycleGeometry()
		{
			Log.LogInfo((object)$"Geometry: {NextGeometry(_geometryMode.Value)}");
			_geometryMode.Value = NextGeometry(_geometryMode.Value);
			string text = $"Geometry: {_geometryMode.Value}";
			Log.LogInfo((object)text);
			ShowHudMessage(text);
		}

		private static GeometryMode NextGeometry(GeometryMode g)
		{
			return g switch
			{
				GeometryMode.Off => GeometryMode.Donut, 
				GeometryMode.Donut => GeometryMode.Wedge, 
				GeometryMode.Wedge => GeometryMode.Off, 
				_ => GeometryMode.Donut, 
			};
		}

		private void AdjustRadius(ConfigEntry<float> entry, float delta)
		{
			entry.Value = Mathf.Clamp(entry.Value + delta, 0f, 32f);
			Log.LogInfo((object)($"{((ConfigEntryBase)entry).Definition.Key} = {entry.Value:0.##}m " + $"(inner={_innerRadius.Value:0.##} outer={_outerRadius.Value:0.##})"));
		}

		private void RotateWedge(float delta)
		{
			_wedgeHeading.Value = Mathf.Repeat(_wedgeHeading.Value + delta, 360f);
			string text = $"Wedge heading: {_wedgeHeading.Value:0.#}°";
			Log.LogInfo((object)text);
			if (_geometryMode.Value == GeometryMode.Wedge)
			{
				ShowHudMessage(text);
			}
		}

		private void AdjustSweep(float delta)
		{
			float num = Mathf.Max(_wedgeAngleStep.Value, 1f);
			_wedgeSweep.Value = Mathf.Clamp(_wedgeSweep.Value + delta, num, 360f);
			string text = "Wedge sweep: " + FormatSweep(_wedgeSweep.Value);
			Log.LogInfo((object)text);
			if (_geometryMode.Value == GeometryMode.Wedge)
			{
				ShowHudMessage(text);
			}
		}

		private static string FormatSweep(float sweep)
		{
			float num = 360f / sweep;
			float num2 = Mathf.Round(num);
			if (!(Mathf.Abs(num - num2) < 0.01f) || !(num2 > 1f))
			{
				return $"{sweep:0.#}°";
			}
			return $"{sweep:0.#}° (1/{num2:0})";
		}

		private IEnumerable<GridPoint> GeneratePoints(Vector3 center)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (_geometryMode.Value == GeometryMode.Wedge)
			{
				return GridGenerator.Wedge(center.x, center.z, _innerRadius.Value, _outerRadius.Value, _spacing.Value, _wedgeHeading.Value, Mathf.Clamp(_wedgeSweep.Value, 1f, 360f));
			}
			return GridGenerator.Donut(center.x, center.z, _innerRadius.Value, _outerRadius.Value, _spacing.Value);
		}

		private Vector3 GetDonutCenter(Player player, GameObject ghost)
		{
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_00bc: 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)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if (_centerMode.Value != CenterMode.CursorSnap)
			{
				_snapSource = null;
			}
			switch (_centerMode.Value)
			{
			case CenterMode.Fixed:
				return _fixedCenter;
			case CenterMode.Cursor:
				if (!((Object)(object)ghost != (Object)null))
				{
					return ((Component)player).transform.position;
				}
				return ghost.transform.position;
			case CenterMode.CursorSnap:
			{
				Vector3 val = (((Object)(object)ghost != (Object)null) ? ghost.transform.position : ((Component)player).transform.position);
				Vector3? val2 = FindNearestAnchor(val, _autoSnapRadius.Value);
				if (val2.HasValue)
				{
					SetSnapSource("anchor", val2.Value);
					return val2.Value;
				}
				Vector3? val3 = FindPlantCentroid(val, _autoSnapRadius.Value);
				if (val3.HasValue)
				{
					SetSnapSource("centroid", val3.Value);
					return val3.Value;
				}
				if (_snapSource != null)
				{
					Log.LogInfo((object)"AutoSnap: no plants in range.");
					ShowHudMessage("AutoSnap: lost");
					_snapSource = null;
				}
				return val;
			}
			default:
				return ((Component)player).transform.position;
			}
		}

		private void SetSnapSource(string source, Vector3 c)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (!(_snapSource == source))
			{
				_snapSource = source;
				Log.LogInfo((object)$"AutoSnap → {source} ({c.x:0.##}, {c.z:0.##}).");
				ShowHudMessage("AutoSnap: " + source);
			}
		}

		private Vector3? FindNearestAnchor(Vector3 from, float radius)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			Vector3? result = null;
			float num = radius * radius;
			for (int i = 0; i < _anchors.Count; i++)
			{
				float num2 = _anchors[i].x - from.x;
				float num3 = _anchors[i].z - from.z;
				float num4 = num2 * num2 + num3 * num3;
				if (num4 <= num)
				{
					num = num4;
					result = _anchors[i];
				}
			}
			return result;
		}

		private void RememberAnchor(Vector3 center)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			for (int num = _anchors.Count - 1; num >= 0; num--)
			{
				float num2 = _anchors[num].x - center.x;
				float num3 = _anchors[num].z - center.z;
				if (num2 * num2 + num3 * num3 <= 0.25f)
				{
					_anchors.RemoveAt(num);
				}
			}
			_anchors.Insert(0, center);
			if (_anchors.Count > 16)
			{
				_anchors.RemoveRange(16, _anchors.Count - 16);
			}
			StringBuilder stringBuilder = new StringBuilder();
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			for (int i = 0; i < _anchors.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(';');
				}
				Vector3 val = _anchors[i];
				stringBuilder.Append(val.x.ToString("0.###", invariantCulture)).Append(',').Append(val.y.ToString("0.###", invariantCulture))
					.Append(',')
					.Append(val.z.ToString("0.###", invariantCulture));
			}
			_anchorsConfig.Value = stringBuilder.ToString();
		}

		private void LoadAnchors()
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			_anchors.Clear();
			string value = _anchorsConfig.Value;
			if (string.IsNullOrEmpty(value))
			{
				return;
			}
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			string[] array = value.Split(new char[1] { ';' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(new char[1] { ',' });
				if (array2.Length == 3 && float.TryParse(array2[0], NumberStyles.Float, invariantCulture, out var result) && float.TryParse(array2[1], NumberStyles.Float, invariantCulture, out var result2) && float.TryParse(array2[2], NumberStyles.Float, invariantCulture, out var result3))
				{
					_anchors.Add(new Vector3(result, result2, result3));
					if (_anchors.Count == 16)
					{
						break;
					}
				}
			}
		}

		private static Vector3? FindPlantCentroid(Vector3 from, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(from, radius);
			Vector3 val = Vector3.zero;
			int num = 0;
			HashSet<int> hashSet = new HashSet<int>();
			for (int i = 0; i < array.Length; i++)
			{
				Plant componentInParent = ((Component)array[i]).GetComponentInParent<Plant>();
				if (!((Object)(object)componentInParent == (Object)null))
				{
					int instanceID = ((Object)componentInParent).GetInstanceID();
					if (hashSet.Add(instanceID))
					{
						val += ((Component)componentInParent).transform.position;
						num++;
					}
				}
			}
			if (num == 0)
			{
				return null;
			}
			return val / (float)num;
		}

		private void DumpGrid()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				Log.LogInfo((object)"DumpGrid: no local player (in menu?).");
				return;
			}
			Vector3 donutCenter = GetDonutCenter(localPlayer, PlacementGhostRef.Invoke(localPlayer));
			Log.LogInfo((object)($"{_geometryMode.Value} grid @ ({donutCenter.x:0.##}, {donutCenter.z:0.##}) " + $"inner={_innerRadius.Value} outer={_outerRadius.Value} spacing={_spacing.Value}" + ((_geometryMode.Value == GeometryMode.Wedge) ? $" heading={_wedgeHeading.Value} sweep={_wedgeSweep.Value}" : "")));
			int num = 0;
			foreach (GridPoint item in GeneratePoints(donutCenter))
			{
				Log.LogInfo((object)$"  [{num++}] {item}");
			}
			Log.LogInfo((object)$"{_geometryMode.Value} grid: {num} points.");
		}

		private void UpdateGhostClones()
		{
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0481: Unknown result type (might be due to invalid IL or missing references)
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				HideAllClones();
				return;
			}
			if (_geometryMode.Value == GeometryMode.Off)
			{
				HideAllClones();
				_lastSourceGhost = null;
				_activeResources = null;
				_activeGrownPrefabs = null;
				_activePieceLabel = null;
				_validPointsCount = 0;
				_totalPointsCount = 0;
				return;
			}
			GameObject val = PlacementGhostRef.Invoke(localPlayer);
			Plant val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Plant>() : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				HideAllClones();
				_lastSourceGhost = null;
				_activeResources = null;
				_activeGrownPrefabs = null;
				_activePieceLabel = null;
				_validPointsCount = 0;
				_totalPointsCount = 0;
				return;
			}
			if ((Object)(object)val != (Object)(object)_lastSourceGhost)
			{
				DestroyAllClones();
				_lastSourceGhost = val;
				_cloneFailedForGhost = false;
				Piece component = val.GetComponent<Piece>();
				_activeResources = (((Object)(object)component != (Object)null) ? component.m_resources : null);
				_activeGrownPrefabs = val2.m_grownPrefabs;
				_activePieceLabel = (((Object)(object)component != (Object)null) ? LocalizeOrRaw(component.m_name) : ((Object)val).name);
			}
			Vector3 donutCenter = GetDonutCenter(localPlayer, val);
			List<GridPoint> list = new List<GridPoint>();
			foreach (GridPoint item in GeneratePoints(donutCenter))
			{
				list.Add(item);
			}
			_totalPointsCount = list.Count;
			if (_cloneFailedForGhost)
			{
				HideAllClones();
				_validPointsCount = 0;
				return;
			}
			if (_ghostClones.Count < list.Count)
			{
				int count = _ghostClones.Count;
				try
				{
					while (_ghostClones.Count < list.Count)
					{
						GameObject val3 = CreateGhostClone(val);
						_ghostClones.Add(val3);
						_ghostClonePieces.Add(val3.GetComponent<Piece>());
					}
					Log.LogDebug((object)$"Ghost clones: {count} → {_ghostClones.Count} for '{((Object)val).name}' (active={val.activeSelf})");
				}
				catch (Exception ex)
				{
					_cloneFailedForGhost = true;
					Log.LogError((object)("Ghost preview disabled for '" + ((Object)val).name + "': cloning threw " + ex.GetType().Name + ": " + ex.Message));
					HideAllClones();
					_validPointsCount = 0;
					return;
				}
			}
			Vector3 position = val.transform.position;
			Quaternion rotation = val.transform.rotation;
			Vector2 val4 = default(Vector2);
			((Vector2)(ref val4))..ctor(((Component)localPlayer).transform.position.x, ((Component)localPlayer).transform.position.z);
			float num = localPlayer.m_maxPlaceDistance * localPlayer.m_maxPlaceDistance;
			bool needCultivatedGround = val2.m_needCultivatedGround;
			Piece component2 = val.GetComponent<Piece>();
			int num2 = CountAffordable(localPlayer, component2);
			int num3 = 0;
			int num4 = 0;
			Vector3 val6 = default(Vector3);
			for (int i = 0; i < list.Count; i++)
			{
				GridPoint gridPoint = list[i];
				GameObject val5 = _ghostClones[i];
				float num5 = SampleGroundY(gridPoint.X, gridPoint.Z, position.y);
				((Vector3)(ref val6))..ctor(gridPoint.X, num5, gridPoint.Z);
				val5.transform.position = val6;
				val5.transform.rotation = rotation;
				if (!val5.activeSelf)
				{
					val5.SetActive(true);
				}
				float num6 = gridPoint.X - val4.x;
				float num7 = gridPoint.Z - val4.y;
				int num8;
				if (!_ignoreReach.Value)
				{
					num8 = ((num6 * num6 + num7 * num7 > num) ? 1 : 0);
					if (num8 != 0)
					{
						num4++;
					}
				}
				else
				{
					num8 = 0;
				}
				bool flag = needCultivatedGround && !IsCultivatedAt(val6);
				val.transform.position = val6;
				bool flag2 = !HaveGrowSpaceCall(val2);
				bool flag3 = (byte)((uint)num8 | (flag2 ? 1u : 0u) | (flag ? 1u : 0u)) != 0;
				bool flag4 = !flag3 && num3 >= num2;
				if (!flag3)
				{
					num3++;
				}
				Piece val7 = _ghostClonePieces[i];
				if ((Object)(object)val7 != (Object)null)
				{
					val7.SetInvalidPlacementHeightlight(flag3 || flag4);
				}
			}
			val.transform.position = position;
			val.transform.rotation = rotation;
			_validPointsCount = num3;
			_outOfReachCount = num4;
			_affordableCount = num2;
			for (int j = list.Count; j < _ghostClones.Count; j++)
			{
				if (_ghostClones[j].activeSelf)
				{
					_ghostClones[j].SetActive(false);
				}
			}
		}

		private static GameObject CreateGhostClone(GameObject ghost)
		{
			Piece component = ghost.GetComponent<Piece>();
			if ((Object)(object)component != (Object)null)
			{
				component.SetInvalidPlacementHeightlight(false);
			}
			bool activeSelf = ghost.activeSelf;
			ghost.SetActive(false);
			GameObject val;
			try
			{
				val = Object.Instantiate<GameObject>(ghost);
			}
			finally
			{
				ghost.SetActive(activeSelf);
			}
			((Object)val).name = ((Object)ghost).name + " (OhMyGrid ghost)";
			Plant[] componentsInChildren = val.GetComponentsInChildren<Plant>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			ZNetView[] componentsInChildren2 = val.GetComponentsInChildren<ZNetView>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			Collider[] componentsInChildren3 = val.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				componentsInChildren3[i].enabled = false;
			}
			val.SetActive(true);
			return val;
		}

		private static bool IsFreeBuild(Player player, Piece piece)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (player.NoCostCheat())
			{
				return true;
			}
			ZoneSystem instance = ZoneSystem.instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)piece != (Object)null)
			{
				return instance.GetGlobalKey(piece.FreeBuildKey());
			}
			return false;
		}

		private static int CountAffordable(Player player, Piece piece)
		{
			if ((Object)(object)piece == (Object)null || IsFreeBuild(player, piece))
			{
				return int.MaxValue;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return 0;
			}
			int num = int.MaxValue;
			Requirement[] resources = piece.m_resources;
			if (resources == null)
			{
				return int.MaxValue;
			}
			foreach (Requirement val in resources)
			{
				if (val != null && !((Object)(object)val.m_resItem == (Object)null) && val.m_amount > 0)
				{
					SharedData val2 = val.m_resItem.m_itemData?.m_shared;
					if (val2 != null)
					{
						int num2 = inventory.CountItems(val2.m_name, -1, true);
						num = Mathf.Min(num, num2 / val.m_amount);
					}
				}
			}
			return num;
		}

		private static string DescribeStock(Player player, Piece piece)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null || (Object)(object)piece == (Object)null || piece.m_resources == null)
			{
				return "?";
			}
			List<string> list = new List<string>();
			Requirement[] resources = piece.m_resources;
			foreach (Requirement val in resources)
			{
				SharedData val2 = val?.m_resItem?.m_itemData?.m_shared;
				if (val2 != null && val.m_amount > 0)
				{
					list.Add($"{val2.m_name}×{val.m_amount} have {inventory.CountItems(val2.m_name, -1, true)}");
				}
			}
			return string.Join(", ", list);
		}

		private static float SampleGroundY(float x, float z, float fallback)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			ZoneSystem instance = ZoneSystem.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return fallback;
			}
			float result = default(float);
			if (instance.GetGroundHeight(new Vector3(x, 1000f, z), ref result))
			{
				return result;
			}
			return fallback;
		}

		private void HideAllClones()
		{
			for (int i = 0; i < _ghostClones.Count; i++)
			{
				GameObject val = _ghostClones[i];
				if ((Object)(object)val != (Object)null && val.activeSelf)
				{
					val.SetActive(false);
				}
			}
		}

		private void DestroyAllClones()
		{
			for (int i = 0; i < _ghostClones.Count; i++)
			{
				if ((Object)(object)_ghostClones[i] != (Object)null)
				{
					Object.Destroy((Object)(object)_ghostClones[i]);
				}
			}
			_ghostClones.Clear();
			_ghostClonePieces.Clear();
		}

		private bool PlaceDonut(Player player, Piece piece, GameObject ghost)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 donutCenter = GetDonutCenter(player, ghost);
			Vector3 position = ghost.transform.position;
			Quaternion rotation = ghost.transform.rotation;
			Plant component = ghost.GetComponent<Plant>();
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(((Component)player).transform.position.x, ((Component)player).transform.position.z);
			float num = player.m_maxPlaceDistance * player.m_maxPlaceDistance;
			bool flag = (Object)(object)component != (Object)null && component.m_needCultivatedGround;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			bool flag2 = false;
			bool flag3 = IsFreeBuild(player, piece);
			int num6 = 0;
			int num7 = CountAffordable(player, piece);
			string text = DescribeStock(player, piece);
			_inDonutPlace = true;
			try
			{
				Vector3 val2 = default(Vector3);
				foreach (GridPoint item in GeneratePoints(donutCenter))
				{
					if (!flag3 && CountAffordable(player, piece) < num6 + 1)
					{
						flag2 = true;
						break;
					}
					float num8 = item.X - val.x;
					float num9 = item.Z - val.y;
					if (!_ignoreReach.Value && num8 * num8 + num9 * num9 > num)
					{
						num4++;
						continue;
					}
					float num10 = SampleGroundY(item.X, item.Z, position.y);
					((Vector3)(ref val2))..ctor(item.X, num10, item.Z);
					if (flag && !IsCultivatedAt(val2))
					{
						num5++;
						continue;
					}
					Vector3 val3 = val2;
					if ((Object)(object)component != (Object)null)
					{
						ghost.transform.position = val3;
						if (!HaveGrowSpaceCall(component))
						{
							num3++;
							continue;
						}
					}
					try
					{
						player.PlacePiece(piece, val3, rotation, false, false);
						num2++;
						if (!flag3)
						{
							if (num6 > 0)
							{
								player.ConsumeResources(piece.m_resources, 0, -1, 1);
							}
							num6 = 1;
						}
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)$"PlacePiece failed at ({item.X:0.##}, {item.Z:0.##}): {ex.Message}");
					}
				}
			}
			finally
			{
				_inDonutPlace = false;
				ghost.transform.position = position;
				ghost.transform.rotation = rotation;
			}
			Log.LogInfo((object)($"Donut plant: planted={num2} noSpace={num3} tooFar={num4} notCultivated={num5}" + " | cost: affordableBefore=" + ((num7 == int.MaxValue) ? "∞" : num7.ToString()) + " stockBefore=[" + text + "] stockAfterMod=[" + DescribeStock(player, piece) + "]" + $" paidHere={((!flag3) ? Mathf.Max(num2 - 1, 0) : 0)} paidByVanilla={((num2 > 0 && !flag3) ? 1 : 0)}" + (flag3 ? " (free build)" : "") + (flag2 ? " (out of resources)" : "")));
			if (num2 > 0)
			{
				RememberAnchor(donutCenter);
				if (_geometryMode.Value == GeometryMode.Wedge && _wedgeAutoAdvance.Value && _wedgeSweep.Value < 360f)
				{
					_wedgeHeading.Value = Mathf.Repeat(_wedgeHeading.Value + _wedgeSweep.Value, 360f);
					string text2 = $"Next wedge → heading {_wedgeHeading.Value:0.#}°";
					Log.LogInfo((object)text2);
					ShowHudMessage(text2);
				}
			}
			return num2 > 0;
		}

		private static bool IsCultivatedAt(Vector3 pos)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Heightmap val = Heightmap.FindHeightmap(pos);
			if ((Object)(object)val != (Object)null)
			{
				return val.IsCultivated(pos);
			}
			return false;
		}

		private void OnGUI()
		{
			//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e7: Expected O, but got Unknown
			//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0391: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bf: Expected O, but got Unknown
			//IL_03c4: Expected O, but got Unknown
			//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
			if (!_showCostOverlay.Value || _totalPointsCount == 0 || (_activeResources == null && _activeGrownPrefabs == null))
			{
				return;
			}
			StringBuilder overlaySb = _overlaySb;
			overlaySb.Length = 0;
			int num = Mathf.Min(_validPointsCount, _affordableCount);
			overlaySb.Append(_activePieceLabel ?? "Plant").Append(" · valid ").Append(_validPointsCount)
				.Append('/')
				.Append(_totalPointsCount);
			if (num < _validPointsCount)
			{
				overlaySb.Append(" · can afford ").Append(num);
			}
			if (_outOfReachCount > 0)
			{
				overlaySb.Append(" · out of reach ").Append(_outOfReachCount).Append(" (get closer)");
			}
			overlaySb.Append('\n').Append(_geometryMode.Value).Append(" · inner ")
				.Append(_innerRadius.Value.ToString("0.##"))
				.Append("m · outer ")
				.Append(_outerRadius.Value.ToString("0.##"))
				.Append("m · spacing ")
				.Append(_spacing.Value.ToString("0.##"))
				.Append('m');
			if (_geometryMode.Value == GeometryMode.Wedge)
			{
				overlaySb.Append("\nHeading ").Append(_wedgeHeading.Value.ToString("0.#")).Append("° · sweep ")
					.Append(FormatSweep(_wedgeSweep.Value));
			}
			if (_activeResources != null)
			{
				for (int i = 0; i < _activeResources.Length; i++)
				{
					Requirement val = _activeResources[i];
					if (val == null || (Object)(object)val.m_resItem == (Object)null || val.m_amount <= 0)
					{
						continue;
					}
					SharedData val2 = val.m_resItem.m_itemData?.m_shared;
					if (val2 != null)
					{
						overlaySb.Append('\n').Append("Need: ").Append(LocalizeOrRaw(val2.m_name))
							.Append(" × ")
							.Append(val.m_amount * num);
						Inventory val3 = (((Object)(object)Player.m_localPlayer != (Object)null) ? ((Humanoid)Player.m_localPlayer).GetInventory() : null);
						if (val3 != null)
						{
							overlaySb.Append(" (have ").Append(val3.CountItems(val2.m_name, -1, true)).Append(')');
						}
					}
				}
			}
			if (_activeGrownPrefabs != null && _activeGrownPrefabs.Length != 0)
			{
				GameObject val4 = _activeGrownPrefabs[0];
				Pickable val5 = (((Object)(object)val4 != (Object)null) ? val4.GetComponent<Pickable>() : null);
				if ((Object)(object)val5 != (Object)null && (Object)(object)val5.m_itemPrefab != (Object)null)
				{
					ItemDrop component = val5.m_itemPrefab.GetComponent<ItemDrop>();
					SharedData val6 = ((!((Object)(object)component != (Object)null)) ? null : component.m_itemData?.m_shared);
					if (val6 != null)
					{
						overlaySb.Append('\n').Append("Yield: ~").Append(val5.m_amount * num)
							.Append(' ')
							.Append(LocalizeOrRaw(val6.m_name));
					}
				}
			}
			if (_overlayStyle == null)
			{
				_overlayStyle = new GUIStyle(GUI.skin.box)
				{
					fontStyle = (FontStyle)1,
					fontSize = 14,
					alignment = (TextAnchor)4,
					wordWrap = false,
					padding = new RectOffset(12, 12, 8, 8)
				};
				_overlayStyle.normal.textColor = Color.white;
			}
			string text = overlaySb.ToString();
			GUIContent val7 = new GUIContent(text);
			float num2 = _overlayStyle.CalcSize(val7).x + 8f;
			float num3 = _overlayStyle.CalcHeight(val7, num2);
			float num4 = ((float)Screen.width - num2) * 0.5f;
			float num5 = 10f;
			GUI.Box(new Rect(num4, num5, num2, num3), text, _overlayStyle);
		}

		private static string LocalizeOrRaw(string key)
		{
			if (string.IsNullOrEmpty(key))
			{
				return string.Empty;
			}
			Localization instance = Localization.instance;
			if (instance == null)
			{
				return key;
			}
			return instance.Localize(key);
		}

		private static string TryGetItemDisplayName(GameObject itemPrefab)
		{
			if ((Object)(object)itemPrefab == (Object)null)
			{
				return null;
			}
			ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
			SharedData val = ((!((Object)(object)component != (Object)null)) ? null : component.m_itemData?.m_shared);
			if (val == null || string.IsNullOrEmpty(val.m_name))
			{
				return ((Object)itemPrefab).name;
			}
			return LocalizeOrRaw(val.m_name);
		}

		private void MassInteract(Player player)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			GameObject hoverObject = ((Humanoid)player).GetHoverObject();
			if ((Object)(object)hoverObject == (Object)null)
			{
				ShowHudMessage("Shift+E: no target");
				return;
			}
			float value = _massInteractRadius.Value;
			Collider[] array = Physics.OverlapSphere(((Component)player).transform.position, value);
			HashSet<int> hashSet = new HashSet<int>();
			int num = 0;
			Pickable componentInParent = hoverObject.GetComponentInParent<Pickable>();
			string arg;
			if ((Object)(object)componentInParent != (Object)null)
			{
				GameObject itemPrefab = componentInParent.m_itemPrefab;
				string text = TryGetItemDisplayName(itemPrefab);
				arg = "picked " + (text ?? "items");
				Log.LogInfo((object)string.Format("Shift+E target: pickable '{0}' radius={1}", ((Object)(object)itemPrefab != (Object)null) ? ((Object)itemPrefab).name : "?", value));
				for (int i = 0; i < array.Length; i++)
				{
					Pickable componentInParent2 = ((Component)array[i]).GetComponentInParent<Pickable>();
					if ((Object)(object)componentInParent2 == (Object)null || !hashSet.Add(((Object)componentInParent2).GetInstanceID()) || (Object)(object)componentInParent2.m_itemPrefab != (Object)(object)itemPrefab)
					{
						continue;
					}
					try
					{
						if (componentInParent2.Interact((Humanoid)(object)player, false, false))
						{
							num++;
						}
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("MassInteract pickable: " + ex.Message));
					}
				}
			}
			else
			{
				Fireplace fire = hoverObject.GetComponentInParent<Fireplace>();
				if (fire != null)
				{
					arg = "fueled " + LocalizeOrRaw(fire.m_name);
					num = FeedUntilRefused(() => fire.Interact((Humanoid)(object)player, false, true), "fireplace");
					Log.LogInfo((object)$"Shift+E target: fireplace '{fire.m_name}' fuel={fire.m_fuelItem?.m_itemData?.m_shared?.m_name} added={num}");
				}
				else
				{
					Smelter componentInParent3 = hoverObject.GetComponentInParent<Smelter>();
					if (componentInParent3 == null)
					{
						ShowHudMessage("Shift+E: target not supported");
						return;
					}
					arg = "fed " + LocalizeOrRaw(componentInParent3.m_name);
					Switch componentInParent4 = hoverObject.GetComponentInParent<Switch>();
					bool flag = (Object)(object)componentInParent4 != (Object)null && (Object)(object)componentInParent4 == (Object)(object)componentInParent3.m_addOreSwitch;
					bool flag2 = (Object)(object)componentInParent4 != (Object)null && (Object)(object)componentInParent4 == (Object)(object)componentInParent3.m_addWoodSwitch;
					int num2 = 0;
					int num3 = 0;
					if ((Object)(object)componentInParent3.m_addOreSwitch != (Object)null && !flag2)
					{
						Switch sw = componentInParent3.m_addOreSwitch;
						num2 = FeedUntilRefused(() => sw.Interact((Humanoid)(object)player, false, false), "smelter ore");
					}
					if ((Object)(object)componentInParent3.m_addWoodSwitch != (Object)null && !flag)
					{
						Switch sw2 = componentInParent3.m_addWoodSwitch;
						num3 = FeedUntilRefused(() => sw2.Interact((Humanoid)(object)player, false, false), "smelter fuel");
					}
					num = num2 + num3;
					Log.LogInfo((object)string.Format("Shift+E target: smelter '{0}' slot={1} oreAdded={2} fuelAdded={3} fuel={4}", componentInParent3.m_name, flag ? "ore" : (flag2 ? "fuel" : "both"), num2, num3, componentInParent3.m_fuelItem?.m_itemData?.m_shared?.m_name));
				}
			}
			string text2 = $"Shift+E: {arg} × {num}";
			Log.LogInfo((object)text2);
			ShowHudMessage(text2);
		}

		private static int FeedUntilRefused(Func<bool> feedOnce, string what)
		{
			int i = 0;
			try
			{
				for (; i < 64; i++)
				{
					if (!feedOnce())
					{
						break;
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("MassInteract " + what + ": " + ex.Message));
			}
			return i;
		}

		private void OnDestroy()
		{
			DestroyAllClones();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
}