Decompiled source of TotalTerrain v1.0.0

TotalTerrain.dll

Decompiled 3 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using AskaShared.Game;
using AskaTotalTerrain.Core;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using SSSGame;
using SSSGame.Controllers;
using SSSGame.Network;
using SSSGame.UI;
using SandSailorStudio;
using SandSailorStudio.Inventory;
using SandSailorStudio.Localization;
using SandSailorStudio.Splines;
using SandSailorStudio.Storage;
using SandSailorStudio.TerrainTools;
using SandSailorStudio.UI;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("TotalTerrain")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+afea40b0d081ff2c5d48c06b21fbc998e14808ac")]
[assembly: AssemblyProduct("Total Terrain")]
[assembly: AssemblyTitle("TotalTerrain")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte flag)
		{
			Flag = flag;
		}
	}
}
namespace AskaTotalTerrain
{
	internal static class EmbeddedSprite
	{
		private static readonly Dictionary<string, Sprite> Loaded = new Dictionary<string, Sprite>();

		internal static Sprite Load(string fileName)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			if (Loaded.TryGetValue(fileName, out Sprite value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string text = executingAssembly.GetName().Name + "." + fileName;
			using Stream stream = executingAssembly.GetManifestResourceStream(text) ?? throw new InvalidOperationException("the embedded image " + text + " is missing");
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (!ImageConversion.LoadImage(val, Il2CppStructArray<byte>.op_Implicit(memoryStream.ToArray())))
			{
				throw new InvalidOperationException("the embedded image " + text + " is not a readable PNG");
			}
			((Object)val).hideFlags = (HideFlags)61;
			Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			((Object)val2).hideFlags = (HideFlags)61;
			Loaded[fileName] = val2;
			return val2;
		}
	}
	internal sealed class EntryClone
	{
		private const string Tag = "[TotalTerrain][entry]";

		internal const string AssetPrefix = "TotalTerrain_";

		private const float GrantWindowSeconds = 5f;

		private static EntryClone[] _entries = Array.Empty<EntryClone>();

		private static bool _granting;

		private static float _grantWindowUntil;

		private static BuildItemsTabPage _lastPage;

		private static PlayerBuilder _builder;

		private static PlayerInventory _inventory;

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

		private readonly string _sourceAssetName;

		private readonly int _sourceId;

		private readonly string _sourceKeyName;

		private readonly string _cloneAssetName;

		private readonly int _cloneId;

		private readonly string _nameKey;

		private readonly string _descriptionKey;

		private readonly string _iconFile;

		private readonly string _previewFile;

		private readonly Func<ItemInfo, NodeTemplate> _instantiate;

		private NodeTemplate _clone;

		private IntPtr _clonePointer;

		private bool _granted;

		private bool _tabListed;

		private EntryClone _head;

		private static EntryClone _stackedOn;

		private int ListedBesideId
		{
			get
			{
				if (_head == null)
				{
					return _sourceId;
				}
				return _head._sourceId;
			}
		}

		internal EntryClone(string sourceAssetName, int sourceId, string cloneAssetName, int cloneId, string nameKey, string descriptionKey, string iconFile, string previewFile, Func<ItemInfo, NodeTemplate> instantiate)
		{
			_iconFile = iconFile;
			_previewFile = previewFile;
			_sourceAssetName = sourceAssetName;
			_sourceId = sourceId;
			_sourceKeyName = sourceAssetName.Substring("Item_".Length);
			_cloneAssetName = cloneAssetName;
			_cloneId = cloneId;
			_nameKey = nameKey;
			_descriptionKey = descriptionKey;
			_instantiate = instantiate;
		}

		internal bool Is(StructureTemplate template)
		{
			if ((Object)(object)template != (Object)null && _clonePointer != IntPtr.Zero)
			{
				return ((Il2CppObjectBase)template).Pointer == _clonePointer;
			}
			return false;
		}

		internal static StructureTemplate CloneWithId(int id)
		{
			EntryClone[] entries = _entries;
			foreach (EntryClone entryClone in entries)
			{
				if (entryClone._cloneId == id)
				{
					return (StructureTemplate)(object)entryClone._clone;
				}
			}
			return null;
		}

		internal static void ResetForWorld()
		{
			_builder = null;
			_inventory = null;
			_lastPage = null;
			EntryClone[] entries = _entries;
			foreach (EntryClone obj in entries)
			{
				obj._granted = false;
				obj._tabListed = false;
			}
		}

		internal static void Patch(Harmony harmony, params EntryClone[] entries)
		{
			_entries = entries;
			for (int i = 1; i < entries.Length; i++)
			{
				entries[i]._head = entries[0];
			}
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ItemInfoDatabase), "Initialize", Type.EmptyTypes, (Type[])null), Hook("BeforeDatabaseInitialize"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(BuildItemsTabPage), "Init", new Type[1] { typeof(TabButton) }, (Type[])null), Hook("BeforeTabInit"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(BuildItemsTabPage), "Show", new Type[2]
			{
				typeof(bool),
				typeof(TabButton)
			}, (Type[])null), (HarmonyMethod)null, Hook("AfterTabShow"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(BuildItemsTabPage), "_SetupNodeTemplate", new Type[1] { typeof(NodeTemplate) }, (Type[])null), Hook("BeforeSetupNode"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("AfterSetupNode"), (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(InventoryComponent), "GetItemCollection", Type.EmptyTypes, (Type[])null), (HarmonyMethod)null, Hook("AfterGetItemCollection"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(LocalizationManager), "Loc", new Type[2]
			{
				typeof(string),
				typeof(bool)
			}, (Type[])null), (HarmonyMethod)null, Hook("AfterLoc"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(StructureSerializableFactory), "_GetType", new Type[1] { typeof(Structure) }, (Type[])null), (HarmonyMethod)null, Hook("AfterGetType"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static void BeforeDatabaseInitialize(ItemInfoDatabase __instance)
		{
			EntryClone[] entries = _entries;
			foreach (EntryClone entryClone in entries)
			{
				try
				{
					entryClone.Inject(__instance.CompleteItemInfoList.itemInfoList);
				}
				catch (Exception ex)
				{
					LogError($"database entry={entryClone._cloneAssetName} threw={ex.GetType().Name} msg={ex.Message}");
				}
			}
		}

		private void Inject(List<ItemInfo> list)
		{
			int num = IndexOfId(list, _cloneId);
			if (num >= 0)
			{
				if (((Object)list[num]).name != _cloneAssetName)
				{
					LogError($"id {_cloneId} is taken by {((Object)list[num]).name}; {_cloneAssetName} is not added");
				}
			}
			else
			{
				NodeTemplate val = _instantiate(FindSource(list));
				((Object)val).name = _cloneAssetName;
				((ItemInfo)val).id = _cloneId;
				((ItemInfo)val).databaseIndex = (ushort)list.Count;
				((ItemInfo)val).Localized = false;
				((ItemInfo)val).localizedName = ModStrings.Get(_nameKey);
				val.showUnlockNotification = false;
				SetPictures(val);
				list.Add((ItemInfo)(object)val);
				_clone = val;
				_clonePointer = ((Il2CppObjectBase)val).Pointer;
				Log($"injected entry={_cloneAssetName} id={_cloneId} sourceId={_sourceId}");
			}
		}

		private void SetPictures(NodeTemplate clone)
		{
			try
			{
				Sprite icon = (Sprite)((_iconFile != null) ? ((object)EmbeddedSprite.Load(_iconFile)) : ((object)((ItemInfo)clone).icon));
				Sprite previewImage = (Sprite)((_previewFile != null) ? ((object)EmbeddedSprite.Load(_previewFile)) : ((object)((ItemInfo)clone).previewImage));
				((ItemInfo)clone).icon = icon;
				((ItemInfo)clone).previewImage = previewImage;
			}
			catch (Exception ex)
			{
				LogError($"pictures entry={_cloneAssetName} icon={_iconFile} preview={_previewFile} threw={ex.GetType().Name} msg={ex.Message}");
			}
		}

		public static void BeforeTabInit(BuildItemsTabPage __instance, TabButton button)
		{
			try
			{
				_lastPage = __instance;
				_grantWindowUntil = Time.realtimeSinceStartup + 5f;
				EntryClone[] entries = _entries;
				foreach (EntryClone entryClone in entries)
				{
					if (!entryClone._granted)
					{
						entryClone.Grant(ResolveItemCollection());
					}
					entryClone.AppendToTab(button);
				}
			}
			catch (Exception ex)
			{
				LogError("tab-init threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterTabShow(BuildItemsTabPage __instance, bool value, TabButton button)
		{
			try
			{
				_lastPage = __instance;
				if (!value)
				{
					return;
				}
				EntryClone[] entries = _entries;
				foreach (EntryClone entryClone in entries)
				{
					entryClone.AppendToTab(button);
					if (!entryClone._granted)
					{
						entryClone.Grant(ResolveItemCollection());
					}
				}
			}
			catch (Exception ex)
			{
				LogError("tab-show threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterGetItemCollection(ItemCollection __result)
		{
			if (__result == null || Time.realtimeSinceStartup > _grantWindowUntil)
			{
				return;
			}
			EntryClone[] entries = _entries;
			foreach (EntryClone entryClone in entries)
			{
				if (!entryClone._granted)
				{
					entryClone.Grant(__result);
				}
			}
		}

		public static void BeforeSetupNode(NodeTemplate node)
		{
			if ((Object)(object)node == (Object)null || _entries.Length < 2 || ((Il2CppObjectBase)node).Pointer != _entries[0]._clonePointer)
			{
				return;
			}
			try
			{
				NodeTemplate clone = _entries[0]._clone;
				if (((StructureTemplate)clone).structureUpgrades == null)
				{
					((StructureTemplate)clone).structureUpgrades = new List<StructureTemplate>();
				}
				_stackedOn = _entries[0];
				for (int i = 1; i < _entries.Length; i++)
				{
					if ((Object)(object)_entries[i]._clone != (Object)null)
					{
						((StructureTemplate)clone).structureUpgrades.Add((StructureTemplate)(object)_entries[i]._clone);
					}
				}
			}
			catch (Exception ex)
			{
				LogError("stack threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static Exception AfterSetupNode(Exception __exception)
		{
			if (_stackedOn == null)
			{
				return __exception;
			}
			try
			{
				for (int i = 1; i < _entries.Length; i++)
				{
					if ((Object)(object)_entries[i]._clone != (Object)null)
					{
						((StructureTemplate)_stackedOn._clone).structureUpgrades.Remove((StructureTemplate)(object)_entries[i]._clone);
					}
				}
			}
			catch (Exception ex)
			{
				LogError("unstack threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
			finally
			{
				_stackedOn = null;
			}
			return __exception;
		}

		private void AppendToTab(TabButton button)
		{
			TabButtonCategory val = (((Object)(object)button != (Object)null) ? ((Il2CppObjectBase)button).TryCast<TabButtonCategory>() : null);
			List<ItemInfo> val2 = (((Object)(object)val != (Object)null) ? val.additionalInfos : null);
			if (val2 == null || (Object)(object)_clone == (Object)null || IndexOfId(val2, ListedBesideId) < 0)
			{
				return;
			}
			int num = IndexOfId(val2, _cloneId);
			if (_head != null)
			{
				int num2 = IndexOfId(val2, _head._cloneId);
				if (num2 < 0)
				{
					return;
				}
				if (num >= 0 && num < num2)
				{
					val2.RemoveAt(num);
					num = -1;
				}
			}
			if (num < 0)
			{
				val2.Add((ItemInfo)(object)_clone);
			}
			else if ((Object)(object)val2[num] == (Object)null || ((Il2CppObjectBase)val2[num]).Pointer != _clonePointer)
			{
				val2[num] = (ItemInfo)(object)_clone;
			}
			if (!_tabListed)
			{
				_tabListed = true;
				Log((_head != null) ? ("listed entry=" + _cloneAssetName + " stackedUnder=" + _head._cloneAssetName) : ("listed entry=" + _cloneAssetName + " beside=" + _sourceAssetName));
			}
		}

		private void Grant(ItemCollection collection)
		{
			if (_granted || _granting || collection == null || (Object)(object)_clone == (Object)null)
			{
				return;
			}
			_granting = true;
			try
			{
				if ((Object)(object)_builder == (Object)null)
				{
					_builder = Object.FindObjectOfType<PlayerBuilder>();
				}
				ItemInfoList val = (((Object)(object)_builder != (Object)null) ? _builder.knownBlueprints : null);
				List<ItemInfo> val2 = (((Object)(object)val != (Object)null) ? val.itemInfoList : null);
				if (val2 != null)
				{
					if (collection.GetFirstItem((ItemInfo)(object)_clone) == null)
					{
						collection.AddItems((ItemInfo)(object)_clone, 1);
					}
					if (!val.Check((ItemInfo)(object)_clone))
					{
						val2.Add((ItemInfo)(object)_clone);
					}
					ItemCollection val3 = ResolveItemCollection();
					_granted = val3 != null && val3.GetFirstItem((ItemInfo)(object)_clone) != null && val.Check((ItemInfo)(object)_clone);
					if (_granted)
					{
						Log("granted entry=" + _cloneAssetName);
					}
				}
			}
			catch (Exception ex)
			{
				LogError("grant threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
			finally
			{
				_granting = false;
			}
		}

		public static void AfterLoc(LocalizationManager __instance, string key, bool fromFallbackLanguage, ref string __result)
		{
			if (key == null || key.IndexOf("TotalTerrain_", StringComparison.Ordinal) < 0)
			{
				return;
			}
			EntryClone[] entries = _entries;
			foreach (EntryClone entryClone in entries)
			{
				if (key.IndexOf(entryClone._cloneAssetName, StringComparison.Ordinal) < 0)
				{
					continue;
				}
				if (key.EndsWith("_name", StringComparison.OrdinalIgnoreCase))
				{
					__result = ModStrings.Get(entryClone._nameKey);
					break;
				}
				__result = __instance.Loc(key.Replace(entryClone._cloneAssetName, entryClone._sourceKeyName), fromFallbackLanguage);
				if (key.EndsWith("_lore", StringComparison.OrdinalIgnoreCase))
				{
					__result = __result + " " + ModStrings.Get(entryClone._descriptionKey);
				}
				break;
			}
		}

		public static void AfterGetType(ref int __result)
		{
			EntryClone[] entries = _entries;
			foreach (EntryClone entryClone in entries)
			{
				if (__result == entryClone._cloneId)
				{
					__result = entryClone._sourceId;
					break;
				}
			}
		}

		private static ItemCollection ResolveItemCollection()
		{
			PlayerInventory val = (((Object)(object)_lastPage != (Object)null) ? _lastPage._pi : null);
			if ((Object)(object)val == (Object)null)
			{
				if ((Object)(object)_inventory == (Object)null)
				{
					_inventory = Object.FindObjectOfType<PlayerInventory>();
				}
				val = _inventory;
			}
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return ((InventoryComponent)val).GetItemCollection();
		}

		private ItemInfo FindSource(List<ItemInfo> list)
		{
			for (int i = 0; i < list.Count; i++)
			{
				ItemInfo val = list[i];
				if (!((Object)(object)val == (Object)null) && !(((Object)val).name != _sourceAssetName))
				{
					if (val.id != _sourceId)
					{
						throw new InvalidOperationException($"{_sourceAssetName} has id {val.id}, expected {_sourceId}.");
					}
					return val;
				}
			}
			throw new InvalidOperationException(_sourceAssetName + " is not in the item database.");
		}

		private static int IndexOfId(List<ItemInfo> list, int id)
		{
			for (int i = 0; i < list.Count; i++)
			{
				ItemInfo val = list[i];
				if ((Object)(object)val != (Object)null && val.id == id)
				{
					return i;
				}
			}
			return -1;
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(EntryClone), name, (Type[])null, (Type[])null));
		}

		private static void Log(string message)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(1, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][entry]");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
			}
			log.LogInfo(val);
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][entry]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class HoedStrokes
	{
		private const string Tag = "[TotalTerrain][stroke]";

		private const float NodeSpacing = 0.5f;

		private static Harmony _harmony;

		private static bool _cellHooksPatched;

		private static EarthworkPlan _plan;

		private static AnimationCurve _curve;

		private static bool _overriding;

		private static bool _haveRange;

		private static TargetRange _range;

		private static readonly HashSet<int> Unmatched = new HashSet<int>();

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

		internal static void Patch(Harmony harmony)
		{
			_harmony = harmony;
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingSplineInteraction), "LevelSection", new Type[1] { typeof(int) }, (Type[])null), Hook("BeforeLevelSection"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("EndLevelSection"), (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(HeightmapTool), "TerraformSpline", new Type[7]
			{
				typeof(TerraformingToolOperation),
				typeof(HermiteSplineInterpolator),
				typeof(int),
				typeof(AnimationCurve),
				typeof(float),
				typeof(int),
				typeof(float)
			}, (Type[])null), Hook("BeforeTerraformSpline"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("EndTerraformSpline"), (HarmonyMethod)null);
		}

		internal static void ResetForWorld()
		{
			Unmatched.Clear();
		}

		public static void BeforeLevelSection(TerraformingSplineInteraction __instance)
		{
			_plan = null;
			try
			{
				NetworkStructureSplineLayoutState splineLayoutState = __instance.splineLayoutState;
				if (!((Object)(object)splineLayoutState == (Object)null))
				{
					StripKey key = default(StripKey);
					StripRecord record = default(StripRecord);
					if (StripRecordStore.IsEmpty || !StripRecordStore.TryKeyOf(splineLayoutState, out key) || !StripRecordStore.TryFind(key, out record))
					{
						NoteUnmatched(splineLayoutState);
						return;
					}
					TerrainGround.Instance.Refresh();
					EarthworkPlan earthworkPlan = EarthworkPlanner.Plan(record.Kind, new MarkerPair(record.Start, record.Finish), StripLimits.Settings(record.Width, record.SideBlend), TerrainGround.Instance);
					SplineStrokeShape? stroke = earthworkPlan.SplineStroke ?? throw new InvalidOperationException($"a side blend of {record.SideBlend} gives the stroke no curve");
					PatchCellHooks();
					_plan = earthworkPlan;
					_curve = Curve(stroke);
				}
			}
			catch (Exception ex)
			{
				LogError("strike skipped, the stroke runs as the game's: threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static Exception EndLevelSection(Exception __exception)
		{
			_plan = null;
			_curve = null;
			return __exception;
		}

		public static void BeforeTerraformSpline(TerraformingToolOperation operation, ref AnimationCurve blendCurve, ref float width, ref int sampleOverlapCount)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			_overriding = false;
			_haveRange = false;
			if (_plan == null || (int)operation != 2)
			{
				return;
			}
			try
			{
				blendCurve = _curve;
				width = _plan.SplineStroke.Width;
				sampleOverlapCount = HoeStroke.LevelOverlapFor(sampleOverlapCount);
				_overriding = true;
			}
			catch (Exception ex)
			{
				LogError("LEVEL keeps the game's stroke: threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static Exception EndTerraformSpline(Exception __exception)
		{
			_overriding = false;
			_haveRange = false;
			return __exception;
		}

		public static void AfterFillTerrainToolData(TerrainSurfaceManager __instance, TerrainToolData data)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (!_overriding)
			{
				return;
			}
			try
			{
				Vector2Int size = data.size;
				float validTerraformingDepth = data.GetValidTerraformingDepth(((Vector2Int)(ref size)).y / 2, ((Vector2Int)(ref size)).x / 2);
				_haveRange = HoeStroke.TryTargetRange(validTerraformingDepth, __instance.GetNormalizedHeight(1f), out _range);
				if (!_haveRange)
				{
					LogError($"no height is valid under this stroke (valid depth {validTerraformingDepth}), so every cell keeps its height");
				}
			}
			catch (Exception ex)
			{
				LogError("the valid depth is unread, so every cell keeps its height: threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterGetClosestPosition2D(Vector2 positionXZ, ref Vector3 curvePosition)
		{
			//IL_0009: 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)
			if (!_overriding)
			{
				return;
			}
			try
			{
				float num = MathF.Round(positionXZ.x / 0.5f) * 0.5f;
				float num2 = MathF.Round(positionXZ.y / 0.5f) * 0.5f;
				if (_haveRange && _plan.TryTargetHeightAt(num, num2, out var height))
				{
					curvePosition.y = _range.Clamp(height);
					return;
				}
				if (!TerrainGround.Instance.TryGroundHeight(num, num2, out var height2))
				{
					throw new InvalidOperationException($"no ground is loaded at x={num:F2} z={num2:F2}");
				}
				curvePosition.y = height2;
			}
			catch (Exception ex)
			{
				_overriding = false;
				LogError("cell override stopped for the rest of the stroke: threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		private static AnimationCurve Curve(SplineStrokeShape stroke)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			IReadOnlyList<CurveKey> keys = stroke.Keys;
			AnimationCurve val = new AnimationCurve();
			for (int i = 0; i < keys.Count; i++)
			{
				float num = ((i > 0) ? Slope(keys[i - 1], keys[i]) : 0f);
				float num2 = ((i < keys.Count - 1) ? Slope(keys[i], keys[i + 1]) : 0f);
				val.AddKey(new Keyframe(keys[i].Time, keys[i].Value, num, num2));
			}
			val.preWrapMode = (WrapMode)8;
			val.postWrapMode = (WrapMode)8;
			return val;
		}

		private static float Slope(CurveKey from, CurveKey to)
		{
			return (to.Value - from.Value) / (to.Time - from.Time);
		}

		private static void PatchCellHooks()
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			if (!_cellHooksPatched)
			{
				_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerrainSurfaceManager), "FillTerrainToolData", new Type[1] { typeof(TerrainToolData) }, (Type[])null), (HarmonyMethod)null, Hook("AfterFillTerrainToolData"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(HermiteSplineInterpolator), "GetClosestPosition2D", new Type[3]
				{
					typeof(Vector2),
					typeof(Vector3).MakeByRefType(),
					typeof(int).MakeByRefType()
				}, (Type[])null), (HarmonyMethod)null, Hook("AfterGetClosestPosition2D"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_cellHooksPatched = true;
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(21, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][stroke]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" cell hooks installed");
				}
				log.LogInfo(val);
			}
		}

		private static void NoteUnmatched(NetworkStructureSplineLayoutState state)
		{
			//IL_0047: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			StructureSplineLayout splineLayout = state.SplineLayout;
			StripEntry stripEntry = StripEntry.Of((StructureTemplate)(object)(((Object)(object)splineLayout != (Object)null) ? splineLayout.GetStructureTemplate() : null));
			if (stripEntry != null && Unmatched.Add(((Object)state).GetInstanceID()))
			{
				Vector3 val = ((state.GetPointCount() > 0) ? state.GetPointPosition(0) : Vector3.zero);
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(75, 5, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>("[TotalTerrain][stroke]");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" the ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<EarthworkKind>(stripEntry.Kind);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" starting at (");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.x, "F2");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.y, "F2");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.z, "F2");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") has no record, so it strikes as a vanilla Path Maker");
				}
				log.LogWarning(val2);
			}
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(HoedStrokes), name, (Type[])null, (Type[])null));
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][stroke]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class IntermediatePoints
	{
		private const string Tag = "[TotalTerrain][points]";

		private static readonly Vector3[] Between = (Vector3[])(object)new Vector3[8];

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

		internal static void Patch(Harmony harmony)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(SplineStructureTemplate), "UpdatePreview", new Type[2]
			{
				typeof(StructurePreviewData),
				typeof(Placement)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(IntermediatePoints), "AfterUpdatePreview", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static void AfterUpdatePreview(SplineStructureTemplate __instance)
		{
			//IL_0046: 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)
			StripEntry entry = PlacementMarkers.Entry;
			if (entry == null || ((Il2CppObjectBase)__instance).Pointer != ((Il2CppObjectBase)entry.Clone).Pointer || PlacementMarkers.PointCount != 2)
			{
				return;
			}
			try
			{
				NetworkStructureSplineLayoutState val = PlacementMarkers.PreviewState();
				if (!((Object)(object)val == (Object)null) && val.GetPointCount() == 2 && Add(val, PlacementMarkers.Start, PlacementMarkers.Finish) && (Object)(object)PlacementMarkers.PreviewObject != (Object)null)
				{
					PlacementMarkers.PreviewObject.RefreshValidationToolMaterials();
				}
			}
			catch (Exception ex)
			{
				LogError("update-preview threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		internal static bool Add(NetworkStructureSplineLayoutState state, Vector3 start, Vector3 finish)
		{
			//IL_0002: 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_0015: 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_004c: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			GroundPoint start2 = new GroundPoint(start.x, start.z);
			GroundPoint finish2 = new GroundPoint(finish.x, finish.z);
			int num = StripLimits.SegmentCount(start2, finish2);
			if (num < 2)
			{
				return false;
			}
			Vector3 val = default(Vector3);
			for (int i = 1; i < num; i++)
			{
				GroundPoint groundPoint = StripLimits.ControlPoint(start2, finish2, i, num);
				((Vector3)(ref val))..ctor(groundPoint.X, Mathf.Lerp(start.y, finish.y, (float)i / (float)num), groundPoint.Z);
				if (!TerrainSampler.SnapToTerrain(ref val))
				{
					LogError("points not added: no ground under a point between the markers, so the strip keeps its two markers");
					return false;
				}
				Between[i - 1] = val;
			}
			state.SetPointPosition(1, Between[0]);
			for (int j = 1; j < num - 1; j++)
			{
				state.AddPoint(Between[j]);
			}
			state.AddPoint(finish);
			state.Rebuild();
			return true;
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][points]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class LevelEntry
	{
		internal const string SourceAssetName = "Item_Structures_TerrainLevelField";

		private const string BuilderBuddyGuid = "Grymm.GrymmMods.TerrainBuddy";

		internal static readonly EntryClone Rectangle = new EntryClone("Item_Structures_TerrainLevelField", 12664862, "TotalTerrain_Rectangle", EarthworkItems.IdOf(EarthworkKind.Level, LevelShapeKind.Rectangle), "entry.rectangle.name", "entry.rectangle.description", null, "RectanglePreview.png", (ItemInfo source) => Instantiate(source, LevelShapeKind.Rectangle));

		internal static readonly EntryClone Oval = new EntryClone("Item_Structures_TerrainLevelField", 12664862, "TotalTerrain_Oval", EarthworkItems.IdOf(EarthworkKind.Level, LevelShapeKind.Oval), "entry.oval.name", "entry.oval.description", "OvalIcon.png", "OvalPreview.png", (ItemInfo source) => Instantiate(source, LevelShapeKind.Oval));

		internal static DynamicDimensionTemplate Source { get; private set; }

		internal static DynamicDimensionTemplate RectangleClone { get; private set; }

		internal static DynamicDimensionTemplate OvalClone { get; private set; }

		internal static bool Is(StructureTemplate template)
		{
			return ShapeOf(template).HasValue;
		}

		internal static LevelShapeKind? ShapeOf(StructureTemplate template)
		{
			if (Rectangle.Is(template))
			{
				return LevelShapeKind.Rectangle;
			}
			if (!Oval.Is(template))
			{
				return null;
			}
			return LevelShapeKind.Oval;
		}

		internal static bool IsOrReloaded(StructureTemplate template)
		{
			if (!Is(template))
			{
				return ((ItemInfo)template).id == 12664862;
			}
			return true;
		}

		internal static void CopyTileLimit()
		{
			int maxNumberOfTiles = LevelLimits.TileLimit(VanillaTileLimit());
			RectangleClone.maxNumberOfTiles = maxNumberOfTiles;
			OvalClone.maxNumberOfTiles = maxNumberOfTiles;
		}

		private static int VanillaTileLimit()
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("Grymm.GrymmMods.TerrainBuddy", out var value) || value.Instance == null)
			{
				return Source.maxNumberOfTiles;
			}
			Type type = value.Instance.GetType();
			FieldInfo fieldInfo = AccessTools.Field(type, "Enabled");
			FieldInfo fieldInfo2 = AccessTools.Field(type, "TerrainMaxCells");
			if (fieldInfo == null || fieldInfo2 == null)
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(92, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[TotalTerrain][level] ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Grymm.GrymmMods.TerrainBuddy");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" has no terrain cell limit to read, so a Level keeps the vanilla limit");
				}
				log.LogWarning(val);
				return Source.maxNumberOfTiles;
			}
			if (!(bool)fieldInfo.GetValue(null))
			{
				return Source.maxNumberOfTiles;
			}
			return (int)fieldInfo2.GetValue(null);
		}

		private static NodeTemplate Instantiate(ItemInfo source, LevelShapeKind shape)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			Source = ((Il2CppObjectBase)source).TryCast<DynamicDimensionTemplate>() ?? throw new InvalidOperationException("Item_Structures_TerrainLevelField is not a dynamic dimension template.");
			DynamicDimensionTemplate val = new DynamicDimensionTemplate(((Il2CppObjectBase)Object.Instantiate<DynamicDimensionTemplate>(Source)).Pointer);
			if (shape == LevelShapeKind.Oval)
			{
				OvalClone = val;
			}
			else
			{
				RectangleClone = val;
			}
			return (NodeTemplate)(object)val;
		}
	}
	internal sealed class LevelOvalCells
	{
		private static readonly Dictionary<int, LevelOvalCells> ByGrid = new Dictionary<int, LevelOvalCells>();

		private readonly LevelCellRole[] _roles;

		private readonly int[] _outside;

		private readonly GroundPoint[][] _judgedNodes;

		internal EarthworkPlan Plan { get; }

		internal bool Hidden { get; private set; }

		private LevelOvalCells(EarthworkPlan plan, LevelCellRole[] roles, int[] outside, GroundPoint[][] judgedNodes)
		{
			Plan = plan;
			_roles = roles;
			_outside = outside;
			_judgedNodes = judgedNodes;
		}

		internal static void ResetForWorld()
		{
			ByGrid.Clear();
		}

		internal static LevelOvalCells Register(TerraformingGrid grid, OvalShape oval, float blend)
		{
			if (!TryBuild(grid, oval, blend, out LevelOvalCells cells))
			{
				throw new InvalidOperationException($"the field holds {((((PlacementGrid)grid).grid != null) ? ((Il2CppArrayBase<bool>)(object)((PlacementGrid)grid).grid).Length : 0)} cells, not those of a {oval.SizeX} m by {oval.SizeZ} m Oval");
			}
			ByGrid[((Object)grid).GetInstanceID()] = cells;
			return cells;
		}

		internal static bool TryKnown(TerraformingGrid grid, out LevelOvalCells cells)
		{
			cells = null;
			if ((Object)(object)grid != (Object)null && ByGrid.TryGetValue(((Object)grid).GetInstanceID(), out cells))
			{
				return cells != null;
			}
			return false;
		}

		internal static bool TryResolve(TerraformingGrid grid, out LevelOvalCells cells)
		{
			cells = null;
			if ((Object)(object)grid == (Object)null)
			{
				return false;
			}
			if (ByGrid.TryGetValue(((Object)grid).GetInstanceID(), out cells))
			{
				return cells != null;
			}
			Structure ownerStructure = ((PlacementGrid)grid).OwnerStructure;
			StructureTemplate val = (((Object)(object)ownerStructure != (Object)null) ? ownerStructure.Template : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if (!LevelEntry.IsOrReloaded(val))
			{
				ByGrid[((Object)grid).GetInstanceID()] = null;
				return false;
			}
			if (!StripRecordStore.TryLevelKeyOf(ownerStructure, out var key))
			{
				return false;
			}
			if (!StripRecordStore.TryFind(key, out var record) || record.Kind != EarthworkKind.Level || record.Shape != LevelShapeKind.Oval)
			{
				ByGrid[((Object)grid).GetInstanceID()] = null;
				return false;
			}
			OvalShape oval = (OvalShape)LevelStrokes.ShapeOf(grid, ownerStructure, LevelShapeKind.Oval);
			if (!TryBuild(grid, oval, record.SideBlend, out cells))
			{
				return false;
			}
			ByGrid[((Object)grid).GetInstanceID()] = cells;
			return true;
		}

		private static bool TryBuild(TerraformingGrid grid, OvalShape oval, float blend, out LevelOvalCells cells)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			cells = null;
			int num = LevelLimits.CellsAlong(oval.SizeX);
			int num2 = LevelLimits.CellsAlong(oval.SizeZ);
			Il2CppStructArray<bool> grid2 = ((PlacementGrid)grid).grid;
			if (num == 0 || num2 == 0 || grid2 == null || ((Il2CppArrayBase<bool>)(object)grid2).Length != num * num2)
			{
				return false;
			}
			EarthworkPlan earthworkPlan = EarthworkPlanner.Plan(EarthworkKind.Level, oval, LevelLimits.Settings(0f, blend, oval.Centre), LevelStrokes.NoGround.Instance);
			LevelCellRole[] array = new LevelCellRole[((Il2CppArrayBase<bool>)(object)grid2).Length];
			List<int> list = new List<int>();
			GroundPoint[][] array2 = new GroundPoint[((Il2CppArrayBase<bool>)(object)grid2).Length][];
			for (int i = 0; i < ((Il2CppArrayBase<bool>)(object)grid2).Length; i++)
			{
				Vector3 cellPosition = ((DynamicPlacementGrid)grid).GetCellPosition(i);
				GroundPoint cellCentre = new GroundPoint(cellPosition.x, cellPosition.z);
				array[i] = earthworkPlan.OvalCellRole(cellCentre);
				if (array[i] == LevelCellRole.Outside)
				{
					list.Add(i);
				}
				else if (array[i] == LevelCellRole.Rim)
				{
					array2[i] = new List<GroundPoint>(earthworkPlan.OvalCellJudgedNodes(cellCentre)).ToArray();
				}
			}
			cells = new LevelOvalCells(earthworkPlan, array, list.ToArray(), array2);
			return true;
		}

		internal void ClearOutsideBits(TerraformingGrid grid)
		{
			Il2CppStructArray<bool> grid2 = ((PlacementGrid)grid).grid;
			for (int i = 0; i < _outside.Length; i++)
			{
				((Il2CppArrayBase<bool>)(object)grid2)[_outside[i]] = false;
			}
		}

		internal void HideOutsideCells(TerraformingGrid grid)
		{
			for (int i = 0; i < _outside.Length; i++)
			{
				grid.SetGridRenderer(_outside[i], false, true);
			}
			Hidden = true;
			FarmCropGridRenderer cropGridRenderer = ((DynamicPlacementGrid)grid).cropGridRenderer;
			if (!((Object)(object)cropGridRenderer == (Object)null))
			{
				cropGridRenderer.SetInvalidCells(false);
				cropGridRenderer.HideInvalidCells(true);
				PaintOutsideCells(cropGridRenderer);
			}
		}

		internal void PaintOutsideCells(FarmCropGridRenderer renderer)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Color32 borderColor = renderer.BorderColor;
			for (int i = 0; i < _outside.Length; i++)
			{
				renderer.SetTile(_outside[i], borderColor);
			}
		}

		internal bool TryRimHeight(TerraformingGrid grid, int cell, out float height)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			height = 0f;
			if (_roles[cell] != LevelCellRole.Rim || ((Il2CppArrayBase<int>)(object)grid.gridInteractMap)[cell] == 0)
			{
				return false;
			}
			GroundPoint[] array = _judgedNodes[cell];
			if (array.Length == 0)
			{
				height = grid.ReferenceLevel;
				return true;
			}
			float num = 0f;
			for (int i = 0; i < array.Length; i++)
			{
				num += TerrainSampler.SampleHeight(new Vector3(array[i].X, 0f, array[i].Z));
			}
			height = num / (float)array.Length;
			return true;
		}
	}
	internal static class LevelOverlay
	{
		private const string Tag = "[TotalTerrain][level-overlay]";

		private const float MinRedrawSeconds = 0.1f;

		private const int PostBearings = 8;

		private static readonly List<Vector3> Points = new List<Vector3>(257);

		private static readonly (float x, float z)[] CornerBuffer = new(float, float)[4];

		private static readonly List<(float X, float Z)> Inner = new List<(float, float)>(257);

		private static readonly List<(float X, float Z)> Outer = new List<(float, float)>(257);

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

		private static LinePool _lines;

		private static bool _haveKey;

		private static Vector2 _centre;

		private static Vector2 _firstPost;

		private static Vector2 _size;

		private static float _yaw;

		private static float _offset;

		private static float _blend;

		private static float _nextDraw;

		private static bool _linesShown;

		internal static void Tick()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_003f: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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)
			if (!LevelPlacement.Active)
			{
				return;
			}
			if (!LevelPlacement.TryRead(out var centre, out var size, out var yaw, out var firstPost))
			{
				Hide();
				return;
			}
			float heightOffset = LevelSettings.HeightOffset;
			float blend = LevelSettings.Blend;
			if ((_haveKey && centre == _centre && size == _size && yaw == _yaw && heightOffset == _offset && blend == _blend && firstPost == _firstPost) || Time.unscaledTime < _nextDraw)
			{
				return;
			}
			_haveKey = true;
			_firstPost = firstPost;
			_centre = centre;
			_size = size;
			_yaw = yaw;
			_offset = heightOffset;
			_blend = blend;
			_nextDraw = Time.unscaledTime + 0.1f;
			try
			{
				RectangleShape rectangle = new RectangleShape(new GroundPoint(centre.x, centre.y), size.x, size.y, yaw);
				if (LevelSettings.Shape == LevelShapeKind.Oval)
				{
					DrawOval(rectangle, heightOffset, blend);
				}
				else
				{
					Draw(rectangle, heightOffset, blend);
				}
			}
			catch (ArgumentOutOfRangeException)
			{
				HideLines();
			}
			catch (InvalidOperationException ex2)
			{
				HideLines();
				LogError("no target to show: " + ex2.Message);
			}
		}

		internal static void Hide()
		{
			_haveKey = false;
			HideLines();
		}

		internal static void ResetForWorld()
		{
			if (_lines != null)
			{
				_lines.Destroy();
			}
			_lines = null;
			_haveKey = false;
			_linesShown = false;
		}

		private static void HideLines()
		{
			if (_linesShown)
			{
				_lines.BeginFrame();
				_linesShown = false;
			}
		}

		private static float BeginDraw(EarthworkShape shape, float offset, float blend)
		{
			TerrainGround.Instance.Refresh();
			float result = EarthworkPlanner.LevelTarget(shape, LevelLimits.Settings(offset, blend, new GroundPoint(_firstPost.x, _firstPost.y)), TerrainGround.Instance);
			if (_lines == null)
			{
				_lines = new LinePool("TotalTerrainLevelOverlay", TerrainGround.Height);
			}
			_lines.BeginFrame();
			_linesShown = true;
			return result;
		}

		private static void Draw(RectangleShape rectangle, float offset, float blend)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			float num = BeginDraw(rectangle, offset, blend);
			float num2 = rectangle.SizeX / 2f;
			float num3 = rectangle.SizeZ / 2f;
			Points.Clear();
			(float, float)[] array = Corners(num2, num3);
			for (int i = 0; i < array.Length; i++)
			{
				(float, float) tuple = array[i];
				float item = tuple.Item1;
				float item2 = tuple.Item2;
				GroundPoint groundPoint = rectangle.WorldPoint(item, item2);
				Points.Add(new Vector3(groundPoint.X, num, groundPoint.Z));
				_lines.AddPost(groundPoint.X, groundPoint.Z, num, PlacementLineStyle.TargetColor, 0.05f);
			}
			Points.Add(Points[0]);
			_lines.Add(Points, PlacementLineStyle.TargetColor, 0.05f);
			CornerRing(rectangle, num2, num3, Inner);
			CornerRing(rectangle, num2 + blend, num3 + blend, Outer);
			DrawBlend();
		}

		private static void CornerRing(RectangleShape rectangle, float halfX, float halfZ, List<(float X, float Z)> ring)
		{
			ring.Clear();
			(float, float)[] array = Corners(halfX, halfZ);
			for (int i = 0; i < array.Length; i++)
			{
				(float, float) tuple = array[i];
				float item = tuple.Item1;
				float item2 = tuple.Item2;
				GroundPoint groundPoint = rectangle.WorldPoint(item, item2);
				ring.Add((groundPoint.X, groundPoint.Z));
			}
			ring.Add(ring[0]);
		}

		private static void DrawBlend()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!_lines.AddFillOnGround(Inner, Outer, PlacementLineStyle.BlendFillColor))
			{
				LogSkippedLine();
			}
			if (!_lines.AddPathOnGround(Outer, PlacementLineStyle.BlendEdgeColor, 0.02f))
			{
				LogSkippedLine();
			}
		}

		private static void DrawOval(RectangleShape rectangle, float offset, float blend)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			float num = BeginDraw(rectangle, offset, blend);
			GroundOval oval = new GroundOval(rectangle.Centre.X, rectangle.Centre.Z, rectangle.SizeX, rectangle.SizeZ, rectangle.YawDegrees);
			int num2 = oval.Segments(0f);
			Points.Clear();
			for (int i = 0; i <= num2; i++)
			{
				var (num3, num4) = oval.Point((float)i * 2f * (float)Math.PI / (float)num2, 0f);
				Points.Add(new Vector3(num3, num, num4));
			}
			_lines.Add(Points, PlacementLineStyle.TargetColor, 0.05f);
			for (int j = 0; j < 8; j++)
			{
				var (x, z) = oval.Point((float)j * 2f * (float)Math.PI / 8f, 0f);
				_lines.AddPost(x, z, num, PlacementLineStyle.TargetColor, 0.05f);
			}
			if (!_lines.AddOvalOnGround(oval, 0f, PlacementLineStyle.OutlineColor, 0.05f))
			{
				LogSkippedLine();
			}
			int num5 = oval.Segments(blend);
			Inner.Clear();
			Outer.Clear();
			for (int k = 0; k <= num5; k++)
			{
				float angle = (float)k * 2f * (float)Math.PI / (float)num5;
				Inner.Add(oval.Point(angle, 0f));
				Outer.Add(oval.Point(angle, blend));
			}
			DrawBlend();
		}

		private static void LogSkippedLine()
		{
			LogError("a line is skipped: no terrain tile is loaded under one of its points");
		}

		private static (float x, float z)[] Corners(float halfX, float halfZ)
		{
			CornerBuffer[0] = (x: 0f - halfX, z: 0f - halfZ);
			CornerBuffer[1] = (x: halfX, z: 0f - halfZ);
			CornerBuffer[2] = (x: halfX, z: halfZ);
			CornerBuffer[3] = (x: 0f - halfX, z: halfZ);
			return CornerBuffer;
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][level-overlay]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class LevelPlacement
	{
		private const string Tag = "[TotalTerrain][level]";

		private static DynamicDimensionsPlacementTool _tool;

		private static DynamicDimensionsPlacement _placement;

		private static PointPlacement _firstPoint;

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

		internal static bool Active => (Object)(object)_tool != (Object)null;

		internal static void Patch(Harmony harmony)
		{
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(DynamicDimensionsPlacementTool), "Begin", new Type[1] { typeof(StructurePreviewData) }, (Type[])null), Hook("BeforeBegin"), Hook("AfterBegin"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(DynamicDimensionsPlacementTool), "End", Type.EmptyTypes, (Type[])null), (HarmonyMethod)null, Hook("AfterEnd"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void ResetForWorld()
		{
			Clear();
		}

		internal static bool TryRead(out Vector2 centre, out Vector2 size, out float yaw, out Vector2 firstPost)
		{
			//IL_0001: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			centre = default(Vector2);
			size = default(Vector2);
			yaw = 0f;
			firstPost = default(Vector2);
			if ((Object)(object)_tool == (Object)null || (int)_tool._currentStage == 0)
			{
				return false;
			}
			if (_placement == null)
			{
				_placement = _tool._dynamicPlacement;
				if (_placement == null)
				{
					return false;
				}
				_firstPoint = ((Il2CppArrayBase<PointPlacement>)(object)((SegmentPlacement)_placement).points)[0];
			}
			Vector3 pivotPosition = ((Placement)_placement).GetPivotPosition();
			centre = new Vector2(pivotPosition.x, pivotPosition.z);
			Vector3Int gridSize = _placement.gridSize;
			float num = (float)Math.Abs(((Vector3Int)(ref gridSize)).x) * _placement.tileSize;
			gridSize = _placement.gridSize;
			size = new Vector2(num, (float)Math.Abs(((Vector3Int)(ref gridSize)).z) * _placement.tileSize);
			Quaternion pivotRotation = ((Placement)_placement).GetPivotRotation();
			yaw = ((Quaternion)(ref pivotRotation)).eulerAngles.y;
			Vector3 position = _firstPoint.position;
			firstPost = new Vector2(position.x, position.z);
			return true;
		}

		public static void BeforeBegin(DynamicDimensionsPlacementTool __instance)
		{
			try
			{
				if (SessionShape(__instance).HasValue)
				{
					LevelEntry.CopyTileLimit();
				}
			}
			catch (Exception ex)
			{
				LogError("tile limit threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterBegin(DynamicDimensionsPlacementTool __instance)
		{
			try
			{
				Clear();
				LevelShapeKind? levelShapeKind = SessionShape(__instance);
				if (levelShapeKind.HasValue)
				{
					_tool = __instance;
					LevelSettings.Begin(levelShapeKind.Value);
					PlacementReadout.Begin(() => LevelSettings.Readout);
				}
			}
			catch (Exception ex)
			{
				Clear();
				LogError("begin threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterEnd()
		{
			Clear();
		}

		private static LevelShapeKind? SessionShape(DynamicDimensionsPlacementTool tool)
		{
			PlayerBuilder builder = ((PlacementTool)tool).Builder;
			return LevelEntry.ShapeOf(((Object)(object)builder != (Object)null) ? ((StructureBuilder)builder).StructureTemplate : null);
		}

		private static void Clear()
		{
			_tool = null;
			_placement = null;
			_firstPoint = null;
			LevelOverlay.Hide();
			PlacementReadout.End();
			LevelSettings.End();
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LevelPlacement), name, (Type[])null, (Type[])null));
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][level]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class LevelSettings
	{
		private static readonly PlacementWheel Wheel = new PlacementWheel(Save);

		private static string _readout;

		private static string _settings;

		private static int _width;

		private static int _length;

		internal static float HeightOffset { get; private set; }

		internal static float Blend { get; private set; } = 0.3f;

		internal static LevelShapeKind Shape { get; private set; }

		internal static string Readout
		{
			get
			{
				//IL_0013: 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)
				int num = 0;
				int num2 = 0;
				if (LevelPlacement.TryRead(out var _, out var size, out var _, out var _))
				{
					num = LevelLimits.WholeMetres(size.x);
					num2 = LevelLimits.WholeMetres(size.y);
				}
				if (_readout == null)
				{
					_settings = ModStrings.Get("placement.height_offset", HeightOffset.ToString("+0.0;-0.0;0.0")) + "     " + ModStrings.Get("placement.blend_band", Blend.ToString("0.0"));
				}
				if (_readout == null || num != _width || num2 != _length)
				{
					_width = num;
					_length = num2;
					_readout = ((num == 0) ? _settings : (ModStrings.Get("placement.size", num, num2) + "     " + _settings));
				}
				return _readout;
			}
		}

		internal static void Begin(LevelShapeKind shape)
		{
			HeightOffset = LevelLimits.StepHeightOffset(HeightOffset, 0, Plugin.ConfigHeightLimit.Value);
			Blend = Math.Clamp(Blend, 0.1f, 3f);
			Shape = shape;
			_readout = null;
			Wheel.Begin();
		}

		internal static void End()
		{
			Wheel.End();
		}

		internal static void Tick()
		{
			if (!LevelPlacement.Active)
			{
				return;
			}
			int num = Wheel.Tick();
			if (num == 0)
			{
				return;
			}
			if (PlacementWheel.AltHeld)
			{
				float num2 = LevelLimits.StepBlend(Blend, num);
				if (num2 != Blend)
				{
					Blend = num2;
					_readout = null;
					Wheel.SaveWhenSettled();
				}
			}
			else
			{
				float num3 = LevelLimits.StepHeightOffset(HeightOffset, num, Plugin.ConfigHeightLimit.Value);
				if (num3 != HeightOffset)
				{
					HeightOffset = num3;
					_readout = null;
					Wheel.SaveWhenSettled();
				}
			}
		}

		private static void Save()
		{
		}
	}
	internal static class LevelStrokes
	{
		private readonly struct Placed
		{
			internal readonly float HeightOffset;

			internal readonly float Blend;

			internal readonly LevelShapeKind Shape;

			internal readonly GroundPoint FirstPost;

			internal Placed(float heightOffset, float blend, LevelShapeKind shape, GroundPoint firstPost)
			{
				HeightOffset = heightOffset;
				Blend = blend;
				Shape = shape;
				FirstPost = firstPost;
			}
		}

		internal sealed class NoGround : IGroundHeightReader
		{
			internal static readonly NoGround Instance = new NoGround();

			public bool TryGroundHeight(float x, float z, out float height)
			{
				height = 0f;
				return true;
			}
		}

		private const string Tag = "[TotalTerrain][level]";

		private const int BrushLengthOffset = 24;

		private const int BrushDataOffset = 32;

		private const float MinBrushBlend = 0.3f;

		private static Placed? _creating;

		private static bool _landedWhileCreating;

		private static readonly Dictionary<int, Placed> PlacedByStructure = new Dictionary<int, Placed>();

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

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

		private static readonly Dictionary<int, EarthworkPlan> BandPlans = new Dictionary<int, EarthworkPlan>();

		private static float _armedBlend = float.NaN;

		private static EarthworkPlan _armedPlan;

		private static bool _armedOval;

		private static bool _armedFirstStroke;

		private static bool _maskPending;

		private static GroundPoint _strokeAt;

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

		internal static void Patch(Harmony harmony)
		{
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Settlement), "CreateStructure", new Type[5]
			{
				typeof(StructureTemplate),
				typeof(Placement),
				typeof(Structure),
				typeof(Options),
				typeof(int)
			}, (Type[])null), Hook("BeforeCreateStructure"), Hook("AfterCreateStructure"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingGrid), "OnDynamicBuildingDimensionsChanged", new Type[1] { typeof(bool) }, (Type[])null), (HarmonyMethod)null, Hook("AfterDimensions"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingGrid), "OnDynamicBuildingDimensionsChanged", new Type[1] { typeof(bool) }, (Type[])null), (HarmonyMethod)null, HookLast("AfterDimensionsLast"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingGrid), "RefreshCellsHeights", new Type[2]
			{
				typeof(bool),
				typeof(bool)
			}, (Type[])null), HookLast("BeforeRefreshCellsHeights"), HookLast("AfterCellsRepainted"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingGrid), "SetRendererHeightData", Type.EmptyTypes, (Type[])null), (HarmonyMethod)null, HookLast("AfterCellsRepainted"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingGrid), "GetCellAverageHeight", new Type[1] { typeof(Vector3) }, (Type[])null), (HarmonyMethod)null, Hook("AfterCellAverageHeight"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(TerraformingFieldInteraction), "TryLevelTile", new Type[1] { typeof(int) }, (Type[])null), Hook("BeforeTryLevelTile"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("EndTryLevelTile"), (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(HeightmapTool), "RunOnArea", new Type[6]
			{
				typeof(TerraformingToolOperation),
				typeof(float),
				typeof(float),
				typeof(float),
				typeof(Vector3),
				typeof(float)
			}, (Type[])null), Hook("BeforeRunOnArea"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Config), "CreateData", new Type[2]
			{
				typeof(float),
				typeof(TargetFlags)
			}, (Type[])null), Hook("BeforeCreateData"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void ResetForWorld()
		{
			_creating = null;
			_landedWhileCreating = false;
			Disarm();
			PlacedByStructure.Clear();
			Targets.Clear();
			Blends.Clear();
			BandPlans.Clear();
			LevelOvalCells.ResetForWorld();
		}

		private static void Disarm()
		{
			_armedBlend = float.NaN;
			_armedPlan = null;
			_armedOval = false;
			_maskPending = false;
		}

		public static void BeforeCreateStructure(StructureTemplate s, Placement p)
		{
			//IL_0058: 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_006f: 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)
			LevelShapeKind? levelShapeKind = LevelEntry.ShapeOf(s);
			if (levelShapeKind.HasValue)
			{
				SegmentPlacement val = ((p != null) ? ((Il2CppObjectBase)p).TryCast<SegmentPlacement>() : null);
				if (val == null || val.points == null || ((Il2CppArrayBase<PointPlacement>)(object)val.points).Length == 0)
				{
					_creating = null;
					LogError("a Level was built with no first post, so it hoes as a vanilla field");
				}
				else
				{
					Vector3 position = ((Il2CppArrayBase<PointPlacement>)(object)val.points)[0].position;
					_creating = new Placed(LevelSettings.HeightOffset, LevelSettings.Blend, levelShapeKind.Value, new GroundPoint(position.x, position.z));
					_landedWhileCreating = false;
				}
			}
		}

		public static void AfterCreateStructure(StructureTemplate s, Structure __result)
		{
			if (LevelEntry.Is(s))
			{
				if ((Object)(object)__result != (Object)null && _creating.HasValue && !_landedWhileCreating)
				{
					PlacedByStructure[((Object)__result).GetInstanceID()] = _creating.Value;
				}
				_creating = null;
			}
		}

		public static void AfterDimensions(TerraformingGrid __instance, bool shouldUpdateNetworkedData)
		{
			if (!shouldUpdateNetworkedData)
			{
				return;
			}
			try
			{
				if (Targets.TryGetValue(((Object)__instance).GetInstanceID(), out var value))
				{
					Apply(__instance, value);
					return;
				}
				Structure ownerStructure = ((PlacementGrid)__instance).OwnerStructure;
				if ((Object)(object)ownerStructure == (Object)null || !LevelEntry.Is(ownerStructure.Template))
				{
					return;
				}
				Placed placed;
				if (PlacedByStructure.Remove(((Object)ownerStructure).GetInstanceID(), out var value2))
				{
					placed = value2;
				}
				else
				{
					if (!_creating.HasValue)
					{
						throw new InvalidOperationException("a Level was built with no placement settings");
					}
					placed = _creating.Value;
					_landedWhileCreating = true;
				}
				Begin(__instance, ownerStructure, placed);
			}
			catch (Exception ex)
			{
				LogError("target threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterDimensionsLast(TerraformingGrid __instance)
		{
			try
			{
				if (LevelOvalCells.TryResolve(__instance, out LevelOvalCells cells))
				{
					cells.ClearOutsideBits(__instance);
					cells.HideOutsideCells(__instance);
				}
			}
			catch (Exception ex)
			{
				LogError("oval mask threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void BeforeRefreshCellsHeights(TerraformingGrid __instance)
		{
			try
			{
				if (LevelOvalCells.TryResolve(__instance, out LevelOvalCells cells))
				{
					cells.ClearOutsideBits(__instance);
					if (!cells.Hidden)
					{
						cells.HideOutsideCells(__instance);
					}
				}
			}
			catch (Exception ex)
			{
				LogError("oval mask threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		internal static void RestoreOval(Structure structure)
		{
			try
			{
				TerraformingGrid componentInChildren = ((Component)structure).GetComponentInChildren<TerraformingGrid>(true);
				if (LevelOvalCells.TryResolve(componentInChildren, out LevelOvalCells cells))
				{
					cells.ClearOutsideBits(componentInChildren);
					cells.HideOutsideCells(componentInChildren);
				}
			}
			catch (Exception ex)
			{
				LogError("oval restore threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterCellsRepainted(TerraformingGrid __instance)
		{
			if (!LevelOvalCells.TryKnown(__instance, out LevelOvalCells cells))
			{
				return;
			}
			try
			{
				FarmCropGridRenderer cropGridRenderer = ((DynamicPlacementGrid)__instance).cropGridRenderer;
				if ((Object)(object)cropGridRenderer != (Object)null)
				{
					cells.PaintOutsideCells(cropGridRenderer);
				}
			}
			catch (Exception ex)
			{
				LogError("oval paint threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterCellAverageHeight(TerraformingGrid __instance, Vector3 Tile, ref float __result)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelOvalCells.TryKnown(__instance, out LevelOvalCells cells))
			{
				return;
			}
			try
			{
				if (cells.TryRimHeight(__instance, ((DynamicPlacementGrid)__instance).TileToIndex(Tile), out var height))
				{
					__result = height;
				}
			}
			catch (Exception ex)
			{
				LogError("rim height threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		private static void Begin(TerraformingGrid grid, Structure owner, Placed placed)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			TerrainGround.Instance.Refresh();
			EarthworkShape earthworkShape = ShapeOf(grid, owner, placed.Shape);
			float value = EarthworkPlanner.Plan(EarthworkKind.Level, earthworkShape, LevelLimits.Settings(placed.HeightOffset, placed.Blend, placed.FirstPost), TerrainGround.Instance).TargetHeight.Value;
			Targets[((Object)grid).GetInstanceID()] = value;
			Blends[((Object)grid).GetInstanceID()] = placed.Blend;
			Apply(grid, value);
			if (earthworkShape is OvalShape oval)
			{
				LevelOvalCells.Register(grid, oval, placed.Blend);
			}
			Vector3 position = ((Component)owner).transform.position;
			if (StripRecordStore.TryLevelKeyOf(owner, out var key))
			{
				StripRecordStore.Add(key, StripRecord.Level(placed.Blend, new GroundPoint(position.x, position.z), placed.Shape));
			}
			else
			{
				LogError("a Level was built before the save's session id arrived, so it has no record and hoes as a vanilla field after a reload");
			}
		}

		internal static EarthworkShape ShapeOf(TerraformingGrid grid, Structure owner, LevelShapeKind kind)
		{
			//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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)owner).transform.position;
			DynamicDimensionBuilding dynamicBuilding = ((DynamicPlacementGrid)grid).dynamicBuilding;
			GroundPoint pivot = new GroundPoint(position.x, position.z);
			Vector3Int gridSize = dynamicBuilding.GridSize;
			int x = ((Vector3Int)(ref gridSize)).x;
			gridSize = dynamicBuilding.GridSize;
			return LevelField.Shape(kind, pivot, x, ((Vector3Int)(ref gridSize)).z, dynamicBuilding.TileSize, ((Component)owner).transform.eulerAngles.y);
		}

		private static void Apply(TerraformingGrid grid, float target)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			Vector3 initialReferenceHeight = grid.initialReferenceHeight;
			grid._SetReferenceHeight(new Vector3(Math.Min(initialReferenceHeight.x, target - 0.1f), Math.Max(initialReferenceHeight.y, target + 0.1f), target));
		}

		public static void BeforeTryLevelTile(TerraformingFieldInteraction __instance, int tileIndex)
		{
			Disarm();
			try
			{
				TerraformingGrid terraformingGrid = __instance.terraformingGrid;
				_armedOval = LevelOvalCells.TryResolve(terraformingGrid, out LevelOvalCells cells);
				if (_armedOval)
				{
					cells.ClearOutsideBits(terraformingGrid);
				}
				if (TryBlendOf(terraformingGrid, out var blend))
				{
					__instance.heightmapTool.radius = 0f;
					_armedBlend = blend;
					_armedPlan = (_armedOval ? cells.Plan : BandPlanOf(terraformingGrid, blend));
					_armedFirstStroke = ((Il2CppArrayBase<int>)(object)terraformingGrid.gridInteractMap)[tileIndex] == 0;
				}
			}
			catch (Exception ex)
			{
				LogError("stroke keeps the game's blend: threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static Exception EndTryLevelTile(Exception __exception)
		{
			Disarm();
			return __exception;
		}

		public static void BeforeRunOnArea(ref float blendDistance, Vector3 position)
		{
			//IL_002c: 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)
			if (!float.IsNaN(_armedBlend))
			{
				blendDistance = Math.Max(_armedBlend, _armedOval ? 1.25f : 0.3f);
				_strokeAt = new GroundPoint(position.x, position.z);
				_maskPending = _armedPlan != null;
			}
		}

		public static void BeforeCreateData(Config __instance, float terrainTileSize)
		{
			if (!_maskPending)
			{
				return;
			}
			_maskPending = false;
			try
			{
				MaskBand(__instance, terrainTileSize);
			}
			catch (Exception ex)
			{
				LogError("stroke keeps the game's band: threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		private unsafe static void MaskBand(Config config, float spacing)
		{
			int size = config.size;
			byte* ptr = (byte*)(void*)config.brush.Pointer;
			if (((long*)ptr)[3] != (long)size * (long)size)
			{
				throw new InvalidOperationException($"the brush does not hold {size} x {size} weights");
			}
			float* ptr2 = (float*)ptr + 8;
			int num = FirstBrushNode(_strokeAt.X, size, spacing);
			int num2 = FirstBrushNode(_strokeAt.Z, size, spacing);
			for (int i = 0; i < size; i++)
			{
				for (int j = 0; j < size; j++)
				{
					GroundPoint node = new GroundPoint((float)(num + j) * spacing, (float)(num2 + i) * spacing);
					float weight;
					if (_armedOval)
					{
						ptr2[i * size + j] = _armedPlan.OvalStrokeWeight(_strokeAt, node, _armedFirstStroke);
					}
					else if (_armedPlan.TryStrokeWeight(_strokeAt, node, out weight))
					{
						ptr2[i * size + j] = (_armedFirstStroke ? weight : 0f);
					}
				}
			}
		}

		private static int FirstBrushNode(float strokeAt, int size, float spacing)
		{
			return (int)MathF.Round((strokeAt - (float)(size + 2) * spacing * 0.5f) / spacing) + 1;
		}

		private static EarthworkPlan BandPlanOf(TerraformingGrid grid, float blend)
		{
			if (!BandPlans.TryGetValue(((Object)grid).GetInstanceID(), out EarthworkPlan value))
			{
				RectangleShape rectangleShape = (RectangleShape)ShapeOf(grid, ((PlacementGrid)grid).OwnerStructure, LevelShapeKind.Rectangle);
				value = EarthworkPlanner.Plan(EarthworkKind.Level, rectangleShape, LevelLimits.Settings(0f, blend, rectangleShape.Centre), NoGround.Instance);
				BandPlans[((Object)grid).GetInstanceID()] = value;
			}
			return value;
		}

		private static bool TryBlendOf(TerraformingGrid grid, out float blend)
		{
			blend = float.NaN;
			if ((Object)(object)grid == (Object)null)
			{
				return false;
			}
			if (Blends.TryGetValue(((Object)grid).GetInstanceID(), out blend))
			{
				return !float.IsNaN(blend);
			}
			Structure ownerStructure = ((PlacementGrid)grid).OwnerStructure;
			if ((Object)(object)ownerStructure == (Object)null || !StripRecordStore.TryLevelKeyOf(ownerStructure, out var key))
			{
				return false;
			}
			blend = ((StripRecordStore.TryFind(key, out var record) && record.Kind == EarthworkKind.Level) ? record.SideBlend : float.NaN);
			Blends[((Object)grid).GetInstanceID()] = blend;
			return !float.IsNaN(blend);
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LevelStrokes), name, (Type[])null, (Type[])null));
		}

		private static HarmonyMethod HookLast(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LevelStrokes), name, (Type[])null, (Type[])null))
			{
				priority = 0
			};
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][level]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class PlacementMarkers
	{
		private const string Tag = "[TotalTerrain][markers]";

		private static SplinePlacementTool _tool;

		private static PolyLinePlacement _placement;

		private static List<PointPlacement> _points;

		private static NetworkStructureSplineLayoutState _previewState;

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

		internal static StripEntry Entry { get; private set; }

		internal static bool Active => Entry != null;

		internal static int PointCount
		{
			get
			{
				if (_points == null)
				{
					return 0;
				}
				return _points.Count;
			}
		}

		internal static Vector3 Start => _placement.GetPosition(0);

		internal static Vector3 Finish => _placement.GetPosition(PointCount - 1);

		internal static Preview PreviewObject { get; private set; }

		internal static NetworkStructureSplineLayoutState PreviewState()
		{
			if ((Object)(object)_previewState == (Object)null && (Object)(object)_tool != (Object)null)
			{
				SplineStructurePreviewData currentPreviewData = _tool._currentPreviewData;
				_previewState = ((currentPreviewData != null) ? currentPreviewData.splineLayoutState : null);
				PreviewObject = (((Object)(object)_previewState != (Object)null) ? ((NodeStructurePreviewData)currentPreviewData).preview : null);
			}
			return _previewState;
		}

		internal static void Patch(Harmony harmony)
		{
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(SplinePlacementTool), "Begin", new Type[1] { typeof(StructurePreviewData) }, (Type[])null), (HarmonyMethod)null, Hook("AfterBegin"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(SplinePlacementTool), "End", Type.EmptyTypes, (Type[])null), (HarmonyMethod)null, Hook("AfterEnd"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void ResetForWorld()
		{
			Clear();
		}

		public static void AfterBegin(SplinePlacementTool __instance)
		{
			try
			{
				Clear();
				PlayerBuilder builder = ((PlacementTool)__instance).Builder;
				StripEntry stripEntry = StripEntry.Of(((Object)(object)builder != (Object)null) ? ((StructureBuilder)builder).StructureTemplate : null);
				if (stripEntry == null)
				{
					return;
				}
				_tool = __instance;
				_placement = __instance._placement;
				_points = ((_placement != null) ? _placement.points : null);
				if (_points == null)
				{
					LogError("begin skipped: the tool has no placement");
					Clear();
					return;
				}
				Entry = stripEntry;
				StripSettings.Begin();
				PlacementReadout.Begin(() => StripSettings.Readout);
			}
			catch (Exception ex)
			{
				Clear();
				LogError("begin threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		public static void AfterEnd()
		{
			Clear();
		}

		private static void Clear()
		{
			Entry = null;
			_tool = null;
			_placement = null;
			_points = null;
			_previewState = null;
			PreviewObject = null;
			PlacementOverlay.Hide();
			PlacementReadout.End();
			StripSettings.End();
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PlacementMarkers), name, (Type[])null, (Type[])null));
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][markers]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	internal static class PlacementOverlay
	{
		private const string Tag = "[TotalTerrain][overlay]";

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

		private static readonly (float X, float Z)[] Centre = new(float, float)[2];

		private static LinePool _lines;

		private static Vector3 _start;

		private static Vector3 _finish;

		private static float _width;

		private static float _sideBlend;

		private static bool _haveKey;

		private static bool _linesShown;

		internal static void Tick()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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_007d: 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_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)
			if (!PlacementMarkers.Active || PlacementMarkers.PointCount != 2)
			{
				Hide();
				return;
			}
			Vector3 start = PlacementMarkers.Start;
			Vector3 finish = PlacementMarkers.Finish;
			float width = StripSettings.Width;
			float sideBlend = StripSettings.SideBlend;
			if (_haveKey && start == _start && finish == _finish && width == _width && sideBlend == _sideBlend)
			{
				return;
			}
			_start = start;
			_finish = finish;
			_width = width;
			_sideBlend = sideBlend;
			_haveKey = true;
			try
			{
				Draw(start, finish, width, sideBlend);
			}
			catch (Exception ex)
			{
				Hide();
				_haveKey = true;
				LogError("draw threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		internal static void Hide()
		{
			_haveKey = false;
			if (_linesShown)
			{
				_lines.BeginFrame();
				_linesShown = false;
			}
		}

		internal static void ResetForWorld()
		{
			if (_lines != null)
			{
				_lines.Destroy();
			}
			_lines = null;
			_haveKey = false;
			_linesShown = false;
		}

		private static void Draw(Vector3 start, Vector3 finish, float width, float sideBlend)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: 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_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			TerrainGround.Instance.Refresh();
			var (groundPoint, groundPoint2, _, _) = EarthworkPlanner.Ends(new GroundPoint(start.x, start.z), new GroundPoint(finish.x, finish.z), TerrainGround.Instance);
			if (MathF.Sqrt((groundPoint2.X - groundPoint.X) * (groundPoint2.X - groundPoint.X) + (groundPoint2.Z - groundPoint.Z) * (groundPoint2.Z - groundPoint.Z)) < 0.5f)
			{
				Hide();
				_haveKey = true;
				return;
			}
			if (_lines == null)
			{
				_lines = new LinePool("TotalTerrainOverlay", TerrainGround.Height);
			}
			_lines.BeginFrame();
			_linesShown = true;
			Centre[0] = (X: groundPoint.X, Z: groundPoint.Z);
			Centre[1] = (X: groundPoint2.X, Z: groundPoint2.Z);
			StripMarks stripMarks = PlacementStrip.Build(Centre, width / 2f, sideBlend, 0.5f, 0.25f, 0.15f);
			Fill(stripMarks.LeftFillInner, stripMarks.LeftFillOuter);
			Fill(stripMarks.RightFillInner, stripMarks.RightFillOuter);
			Path(stripMarks.LeftFillOuter, PlacementLineStyle.BlendEdgeColor, 0.02f);
			Path(stripMarks.RightFillOuter, PlacementLineStyle.BlendEdgeColor, 0.02f);
			Path(stripMarks.LeftSizeLine, PlacementLineStyle.SizeLineColor, 0.01f);
			Path(stripMarks.RightSizeLine, PlacementLineStyle.SizeLineColor, 0.01f);
			foreach (IReadOnlyList<(float, float)> bracket in stripMarks.Brackets)
			{
				Path(bracket, PlacementLineStyle.OutlineColor, 0.05f);
			}
			bool flag = PlacementMarkers.Entry.Kind == EarthworkKind.Ramp;
			Path(stripMarks.StartLine, flag ? PlacementLineStyle.LevelColor : PlacementLineStyle.TopColor, 0.05f);
			Path(stripMarks.EndLine, flag ? PlacementLineStyle.LevelColor : PlacementLineStyle.BottomColor, 0.05f);
		}

		private static void Path(IReadOnlyList<(float X, float Z)> path, Color color, float width)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (!_lines.AddPathOnGround(path, color, width))
			{
				LogSkipped();
			}
		}

		private static void Fill(IReadOnlyList<(float X, float Z)> inner, IReadOnlyList<(float X, float Z)> outer)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (!_lines.AddFillOnGround(inner, outer, PlacementLineStyle.BlendFillColor))
			{
				LogSkipped();
			}
		}

		private static void LogSkipped()
		{
			LogError("a line is skipped: no terrain tile is loaded under one of its points");
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("[TotalTerrain][overlay]");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				}
				log.LogError(val);
			}
		}
	}
	[BepInPlugin("mugsy33.totalterrain", "Total Terrain", "1.0.0")]
	public class Plugin : BasePlugin
	{
		public const string PluginGuid = "mugsy33.totalterrain";

		public const string PluginName = "Total Terrain";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> ConfigEnabled;

		internal static ConfigEntry<float> ConfigHeightLimit;

		internal static readonly bool DebugLogging;

		public override void Load()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BasePlugin)this).Log;
			ModStrings.Init(Log, "[TotalTerrain][strings]");
			ConfigEnabled = ((BasePlugin)this).Config.Bind<bool>("TotalTerrain", "Enabled", true, "Master on/off switch for this tool.");
			ConfigHeightLimit = ((BasePlugin)this).Config.Bind<float>("TotalTerrain", "HeightLimit", 20f, new ConfigDescription("How far in metres the mouse wheel can raise or lower a Rectangle or Oval from the ground where you click first.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>()));
			if (ConfigEnabled.Value)
			{
				Harmony harmony = new Harmony("mugsy33.totalterrain");
				EntryClone.Patch(harmony, LevelEntry.Rectangle, LevelEntry.Oval, StripEntry.Slope.Entry, StripEntry.Ramp.Entry);
				PlacementReadout.Patch(harmony, Log, "TotalTerrain");
				PlacementMarkers.Patch(harmony);
				IntermediatePoints.Patch(harmony);
				StripCapture.Patch(harmony);
				HoedStrokes.Patch(harmony);
				LevelPlacement.Patch(harmony);
				LevelStrokes.Patch(harmony);
				ClassInjector.RegisterTypeInIl2Cpp<TotalTerrainTool>();
				LocalPlayerTool.Register(Log, "TotalTerrain_Tool", Vector3.zero, typeof(TotalTerrainTool));
			}
			ManualLogSource log = Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(10, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Total Terrain");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" v");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.0.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded.");
			}
			log.LogInfo(val);
		}
	}
	internal static class Strings
	{
		internal const string SlopeName = "entry.slope.name";

		internal const string SlopeDescription = "entry.slope.description";

		internal const string RampName = "entry.ramp.name";

		internal const string RampDescription = "entry.ramp.description";

		internal const string Width = "placement.width";

		internal const string SideBlend = "placement.side_blend";

		internal const string RectangleName = "entry.rectangle.name";

		internal const string RectangleDescription = "entry.rectangle.description";

		internal const string OvalName = "entry.oval.name";

		internal const string OvalDescription = "entry.oval.description";

		internal const string HeightOffset = "placement.height_offset";

		internal const string LevelBlend = "placement.blend_band";

		internal const string Size = "placement.size";
	}
	internal static class StripCapture
	{
		private sealed class Pending
		{
			internal Structure Structure;

			internal StructureSplineLayout Layout;

			internal StripRecord Record;

			internal float Deadline;

			internal int Points;
		}

		private const string Tag = "[TotalTerrain][capture]";

		private const float ReadySeconds = 5f;

		private static readonly List<Pending> Waiting = new List<Pending>();

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

		internal static void Patch(Harmony harmony)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Settlement), "CreateStructure", new Type[5]
			{
				typeof(StructureTemplate),
				typeof(Placement),
				typeof(Structure),
				typeof(Options),
				typeof(int)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(StripCapture), "AfterCreateStructure", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void ResetForWorld()
		{
			Waiting.Clear();
		}

		public static void AfterCreateStructure(StructureTemplate s, Structure __result)
		{
			//IL_007d: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			StripEntry entry = PlacementMarkers.Entry;
			if ((Object)(object)__result == (Object)null || entry == null || StripEntry.Of(s) != entry)
			{
				return;
			}
			try
			{
				if (PlacementMarkers.PointCount != 2)
				{
					LogError($"a {entry.Kind} was built with {PlacementMarkers.PointCount} markers placed, so it has no record");
					return;
				}
				Vector3 start = PlacementMarkers.Start;
				Vector3 finish = PlacementMarkers.Finish;
				StripRecord record = new StripRecord(entry.Kind, StripSettings.Width, StripSettings.SideBlend, new GroundPoint(start.x, start.z), new GroundPoint(finish.x, finish.z));
				StructureSplineLayout componentInChildren = ((Component)__result).GetComponentInChildren<StructureSplineLayout>(true);
				if ((Object)(object)componentInChildren == (Object)null)
				{
					LogError($"a {entry.Kind} was built with no spline layout, so it has no record");
				}
				else
				{
					Expect(__result, componentInChildren, record);
				}
			}
			catch (Exception ex)
			{
				LogError("capture threw=" + ex.GetType().Name + " msg=" + ex.Message);
			}
		}

		internal static void Expect(Structure structure, StructureSplineLayout layout, StripRecord record)
		{
			Waiting.Add(new Pending
			{
				Structure = structure,
				Layout = layout,
				Record = record,
				Deadline = Time.unscaledTime + 5f,
				Points = StripLimits.ControlPoints(record.Start, record.Finish).Length
			});
		}

		internal static void Tick()
		{
			for (int num = Waiting.Count - 1; num >= 0; num--)
			{
				Pending pending = Waiting[num];
				try
				{
					if ((Object)(object)pending.Structure == (Object)null || (Object)(object)pending.Layout == (Object)null)
					{
						Waiting.RemoveAt(num);
					}
					else
					{
						NetworkStructureSplineLayoutState splineState_k__BackingField = pending.Layout._SplineState_k__BackingField;
						bool flag = Time.unscaledTime >= pending.Deadline;
						if ((((Object)(object)splineState_k__BackingField != (Object)null && splineState_k__BackingField.GetPointCount() >= pending.Points) || flag) && StripRecordStore.TryKeyOf(splineState_k__BackingField, out var key))
						{
							Waiting.RemoveAt(num);
							StripRecordStore.Add(key, pending.Record);
						}
						else if (flag)
						{
							Waiting.RemoveAt(num);
							LogError($"a {pending.Record.Kind}'s control points or the save's session id did not arrive within {5f:0} s, so it has no record");
						}
					}
				}
				catch (Exception ex)
				{
					Waiting.RemoveAt(num);
					LogError("capture threw=" + ex.GetType().Name + " msg=" + ex.Message);
				}
			}
		}

		private static void LogError(string message)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (LoggedErrors.Add(message))
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLog