Decompiled source of LGTuner v1.0.4

LGTuner.dll

Decompiled a month ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json;
using System.Text.Json.Serialization;
using AssetShards;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Expedition;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LGTuner.Configs;
using LGTuner.Manager;
using LGTuner.Utils;
using LevelGeneration;
using LevelGeneration.Core;
using Microsoft.CodeAnalysis;
using UnityEngine;
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("LGTuner")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+git32ee113-dirty-master.32ee113f774f28578bd63131db5298640efafe36")]
[assembly: AssemblyProduct("LGTuner")]
[assembly: AssemblyTitle("LGTuner")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LGTuner
{
	public static class BuilderInfo
	{
		private static readonly List<Complex> _extraComplexResourceToLoad = new List<Complex>();

		public static IEnumerable<Complex> ExtraComplexResourceToLoad => _extraComplexResourceToLoad;

		public static ComplexResourceSetDataBlock ComplexResourceSet { get; private set; }

		public static int GridSize { get; private set; }

		public static int GridCenter { get; private set; }

		public static int GridZeroOffset { get; private set; }

		public static float AltitudeOffset { get; private set; }

		public static LayoutConfig MainLayer { get; private set; }

		public static LayoutConfig SecondaryLayer { get; private set; }

		public static LayoutConfig ThirdLayer { get; private set; }

		public static LayoutConfig[] DimensionLayer { get; private set; } = Array.Empty<LayoutConfig>();


		internal static void OnResourceSetSelected()
		{
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			ComplexResourceSet = Builder.ComplexResourceSetBlock;
			GridSize = ComplexResourceSet.LevelGenConfig.GridSize;
			GridCenter = GridSize / 2;
			GridZeroOffset = -GridCenter;
			AltitudeOffset = ComplexResourceSet.LevelGenConfig.AltitudeOffset;
			MainLayer = null;
			SecondaryLayer = null;
			ThirdLayer = null;
			DimensionLayer = new LayoutConfig[Enum.GetValues(typeof(eDimensionIndex)).Length];
			_extraComplexResourceToLoad.Clear();
			ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition;
			if (ConfigManager.TryGetConfig(activeExpedition.LevelLayoutData, out var config))
			{
				MainLayer = config;
			}
			if (activeExpedition.SecondaryLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.SecondaryLayout, out var config2))
			{
				SecondaryLayer = config2;
			}
			if (activeExpedition.ThirdLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.ThirdLayout, out var config3))
			{
				ThirdLayer = config3;
			}
			Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dimension current = enumerator.Current;
				if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension)
				{
					LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData);
					if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config4))
					{
						Logger.Info("loysimme dimension ja levellayoutin");
						config4.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX);
						DimensionLayer[current.DimensionIndex] = config4;
					}
				}
			}
			MainLayer?.Reset(GridSize);
			SecondaryLayer?.Reset(GridSize);
			ThirdLayer?.Reset(GridSize);
			AddExtraShard(MainLayer);
			AddExtraShard(SecondaryLayer);
			AddExtraShard(ThirdLayer);
			Array.ForEach(DimensionLayer, delegate(LayoutConfig x)
			{
				AddExtraShard(x);
			});
		}

		private static void AddExtraShard(LayoutConfig layerConfig)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (layerConfig == null)
			{
				return;
			}
			Complex[] extraComplexResourceToLoad = layerConfig.ExtraComplexResourceToLoad;
			foreach (Complex item in extraComplexResourceToLoad)
			{
				if (!_extraComplexResourceToLoad.Contains(item))
				{
					_extraComplexResourceToLoad.Add(item);
				}
			}
		}

		public static bool TryGetConfig(LG_Zone zone, out LayoutConfig config)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected I4, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			Dimension val = default(Dimension);
			if (!Dimension.GetDimension(zone.DimensionIndex, ref val))
			{
				Logger.Info("dimension getter failed");
				config = null;
				return false;
			}
			if (val.IsMainDimension)
			{
				LG_LayerType type = zone.Layer.m_type;
				switch ((int)type)
				{
				case 0:
					config = MainLayer;
					return MainLayer != null;
				case 1:
					config = SecondaryLayer;
					return SecondaryLayer != null;
				case 2:
					config = ThirdLayer;
					return ThirdLayer != null;
				}
			}
			else if (!val.DimensionData.IsStaticDimension)
			{
				Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Dimension current = enumerator.Current;
					if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension)
					{
						LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData);
						if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config2))
						{
							Logger.Info("found a dimension + levellayout");
							config2.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX);
							DimensionLayer[current.DimensionIndex] = config2;
						}
					}
				}
				config = DimensionLayer[zone.DimensionIndex];
				return config != null;
			}
			config = null;
			return false;
		}

		public static GameObject GetRandomPlug(uint seed, int plugHeight, SubComplex subcomplex, bool withGate)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			ComplexResourceSetDataBlock complexResourceSet = ComplexResourceSet;
			return (GameObject)(plugHeight switch
			{
				0 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_straightPlugsWithGates : complexResourceSet.m_straightPlugsNoGates, subcomplex), 
				1 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_singleDropPlugsWithGates : complexResourceSet.m_singleDropPlugsNoGates, subcomplex), 
				2 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_doubleDropPlugsWithGates : complexResourceSet.m_doubleDropPlugsNoGates, subcomplex), 
				_ => null, 
			});
		}

		public static uint GetLayoutIdOfZone(LG_Zone zone)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected I4, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			Dimension dimension = zone.Dimension;
			if (dimension.IsMainDimension)
			{
				LG_LayerType type = zone.Layer.m_type;
				ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition;
				return (int)type switch
				{
					0 => activeExpedition.LevelLayoutData, 
					1 => activeExpedition.SecondaryLayout, 
					2 => activeExpedition.ThirdLayout, 
					_ => throw new NotSupportedException($"LayerType: {type} is not supported!"), 
				};
			}
			return dimension.DimensionData.LevelLayoutData;
		}
	}
	[BepInPlugin("LGTuner", "LGTuner", "1.0.3")]
	[BepInProcess("GTFO.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class EntryPoint : BasePlugin
	{
		public Harmony HarmonyInstance { get; private set; }

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			HarmonyInstance = new Harmony("LGTuner");
			HarmonyInstance.PatchAll();
			ConfigManager.Init();
		}
	}
	public static class LGExtensions
	{
		public static bool IsSame(this LG_GridPosition position, LG_GridPosition other)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (position.x == other.x)
			{
				return position.z == other.z;
			}
			return false;
		}

		public static LG_GridPosition ToNormalGrid(this LG_Tile tile, int gridSize)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return tile.m_shape.m_gridPosition.GetNormal(gridSize);
		}

		public static LG_GridPosition GetNormal(this LG_GridPosition position, int gridSize)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			LG_GridPosition result;
			if (gridSize < 0)
			{
				result = default(LG_GridPosition);
				result.x = position.x + BuilderInfo.GridZeroOffset;
				result.z = position.z + BuilderInfo.GridZeroOffset;
				return result;
			}
			int num = gridSize / 2;
			result = default(LG_GridPosition);
			result.x = position.x - num;
			result.z = position.z - num;
			return result;
		}

		public static Vector3 GetPositionNormal(this LG_Grid grid, int x, int z, int gridSize)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (gridSize < 0)
			{
				return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x - BuilderInfo.GridZeroOffset, z - BuilderInfo.GridZeroOffset);
			}
			int num = gridSize / 2;
			return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x + num, z + num);
		}

		public static int GetGridSize(this Dimension dimension)
		{
			return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX;
		}

		public static bool TryGetDimension(this LG_Floor floor, int dimensionIndex, out Dimension dimension)
		{
			if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex))
			{
				return floor.GetDimension((eDimensionIndex)dimensionIndex, ref dimension);
			}
			dimension = null;
			return false;
		}

		public static bool TryGetDimension(this LG_Floor floor, eDimensionIndex dimensionIndex, out Dimension dimension)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex))
			{
				return floor.GetDimension(dimensionIndex, ref dimension);
			}
			dimension = null;
			return false;
		}
	}
	public static class RandomExtensions
	{
		public static uint NextUint(this Random random)
		{
			int num = random.Next(1073741824);
			uint num2 = (uint)random.Next(4);
			return (uint)(num << 2) | num2;
		}

		public static float NextFloat(this Random random)
		{
			return Mathf.Clamp01((float)random.NextDouble());
		}

		public static int ToSeed(this uint seed)
		{
			return (int)seed;
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource _logger;

		static Logger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_logger = new ManualLogSource("LGTuner");
			Logger.Sources.Add((ILogSource)(object)_logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(object data)
		{
			_logger.LogMessage((object)Format(data));
		}

		public static void Verbose(object data)
		{
		}

		public static void Debug(object data)
		{
			_logger.LogDebug((object)Format(data));
		}

		public static void Error(object data)
		{
			_logger.LogError((object)Format(data));
		}
	}
	public enum DirectionType
	{
		Unknown,
		Forward,
		Backward,
		Left,
		Right
	}
	public enum RotateType
	{
		None,
		Flip,
		MoveTo_Left,
		MoveTo_Right,
		Towards_Random,
		Towards_Forward,
		Towards_Backward,
		Towards_Left,
		Towards_Right
	}
	public struct LG_PlugInfo
	{
		public static readonly Quaternion NoRotation = Quaternion.AngleAxis(0f, Vector3.up);

		public static readonly Quaternion RightRotation = Quaternion.AngleAxis(90f, Vector3.up);

		public static readonly Quaternion BackwardRotation = Quaternion.AngleAxis(180f, Vector3.up);

		public static readonly Quaternion LeftRotation = Quaternion.AngleAxis(270f, Vector3.up);

		public static readonly Vector3 FrontPlugPosition = Vector3.forward * 32f;

		public static readonly Vector3 BackPlugPosition = Vector3.back * 32f;

		public static readonly Vector3 LeftPlugPosition = Vector3.left * 32f;

		public static readonly Vector3 RightPlugPosition = Vector3.right * 32f;

		public bool IsValid { get; private set; }

		public DirectionType StartDirection { get; private set; }

		public int Count { get; private set; }

		public bool HasFront { get; private set; }

		public bool HasBack { get; private set; }

		public bool HasLeft { get; private set; }

		public bool HasRight { get; private set; }

		public bool TryGetNewRotation(uint seed, RotateType rotate, out Quaternion rotation)
		{
			//IL_0062: 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)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			DirectionType newDirection = GetNewDirection(seed, StartDirection, rotate);
			if (Count >= 4)
			{
				rotation = GetRotationOfDirection(newDirection);
				return true;
			}
			Logger.Info($"You are rotating {Count} side Geomorph, this could lead to level gen crash!");
			rotation = GetRotationOfDirection(newDirection);
			return true;
		}

		public bool HasPlug(DirectionType direction)
		{
			if (!IsValid)
			{
				return false;
			}
			if (Count >= 4)
			{
				return true;
			}
			return direction switch
			{
				DirectionType.Forward => HasFront, 
				DirectionType.Backward => HasBack, 
				DirectionType.Left => HasLeft, 
				DirectionType.Right => HasRight, 
				_ => false, 
			};
		}

		public static LG_PlugInfo BuildPlugInfo(GameObject geoObject, Quaternion rotation)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected I4, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)geoObject.GetComponent<LG_Geomorph>() == (Object)null)
			{
				return default(LG_PlugInfo);
			}
			Il2CppArrayBase<LG_Plug> componentsInChildren = geoObject.GetComponentsInChildren<LG_Plug>();
			if (componentsInChildren == null)
			{
				return default(LG_PlugInfo);
			}
			if (componentsInChildren.Length < 1)
			{
				return default(LG_PlugInfo);
			}
			LG_PlugInfo result = default(LG_PlugInfo);
			foreach (LG_Plug item in componentsInChildren)
			{
				LG_PlugDir dir = item.m_dir;
				switch (dir - 2)
				{
				case 0:
					result.HasBack = true;
					result.Count++;
					break;
				case 2:
					result.HasFront = true;
					result.Count++;
					break;
				case 3:
					result.HasLeft = true;
					result.Count++;
					break;
				case 1:
					result.HasRight = true;
					result.Count++;
					break;
				}
			}
			result.IsValid = result.Count > 0;
			float num = Mathf.Round(((Quaternion)(ref rotation)).eulerAngles.y);
			Logger.Verbose($"angle: {num}");
			num = Mathf.Repeat(num, 360f);
			result.StartDirection = Mathf.RoundToInt(num / 90f) switch
			{
				0 => DirectionType.Forward, 
				1 => DirectionType.Right, 
				2 => DirectionType.Backward, 
				3 => DirectionType.Left, 
				_ => DirectionType.Unknown, 
			};
			return result;
		}

		public static DirectionType GetNewDirection(uint seed, DirectionType direction, RotateType rotate)
		{
			if (direction == DirectionType.Unknown)
			{
				return DirectionType.Unknown;
			}
			if (rotate == RotateType.Towards_Random)
			{
				rotate = new Random(seed.ToSeed()).Next(4) switch
				{
					0 => RotateType.Towards_Forward, 
					1 => RotateType.Towards_Backward, 
					2 => RotateType.Towards_Left, 
					3 => RotateType.Towards_Right, 
					_ => throw new IndexOutOfRangeException("Towards_Random: nextIndex was out of range?!"), 
				};
			}
			return rotate switch
			{
				RotateType.None => direction, 
				RotateType.Flip => direction switch
				{
					DirectionType.Forward => DirectionType.Backward, 
					DirectionType.Backward => DirectionType.Forward, 
					DirectionType.Left => DirectionType.Right, 
					DirectionType.Right => DirectionType.Left, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.MoveTo_Left => direction switch
				{
					DirectionType.Forward => DirectionType.Left, 
					DirectionType.Backward => DirectionType.Right, 
					DirectionType.Left => DirectionType.Backward, 
					DirectionType.Right => DirectionType.Forward, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.MoveTo_Right => direction switch
				{
					DirectionType.Forward => DirectionType.Right, 
					DirectionType.Backward => DirectionType.Left, 
					DirectionType.Left => DirectionType.Forward, 
					DirectionType.Right => DirectionType.Backward, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.Towards_Forward => DirectionType.Forward, 
				RotateType.Towards_Backward => DirectionType.Backward, 
				RotateType.Towards_Left => DirectionType.Left, 
				RotateType.Towards_Right => DirectionType.Right, 
				_ => throw new ArgumentOutOfRangeException("direction"), 
			};
		}

		public static Quaternion GetRotationOfDirection(DirectionType direction)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			return (Quaternion)(direction switch
			{
				DirectionType.Forward => NoRotation, 
				DirectionType.Backward => BackwardRotation, 
				DirectionType.Left => LeftRotation, 
				DirectionType.Right => RightRotation, 
				_ => throw new ArgumentOutOfRangeException("direction"), 
			});
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "LGTuner";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "git32ee113-dirty-master";

		public const string SemVer = "1.0.0+git32ee113-dirty-master";

		public const string GitRevShort = "32ee113-dirty";

		public const string GitRevLong = "32ee113f774f28578bd63131db5298640efafe36-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}
namespace LGTuner.Utils
{
	internal static class JSON
	{
		private static readonly JsonSerializerOptions _setting;

		static JSON()
		{
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = false,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				_setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				Logger.Info("PartialData Support Found!");
			}
		}

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static object Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize(object value, Type type)
		{
			return JsonSerializer.Serialize(value, type, _setting);
		}
	}
	public static class MTFOPartialDataUtil
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static JsonConverter PersistentIDConverter { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool Initialized { get; private set; }

		public static string PartialDataPath { get; private set; }

		public static string ConfigPath { get; private set; }

		static MTFOPartialDataUtil()
		{
			PersistentIDConverter = null;
			IsLoaded = false;
			Initialized = false;
			PartialDataPath = string.Empty;
			ConfigPath = string.Empty;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = obj.GetTypes();
				Type type = types.First((Type t) => t.Name == "PersistentIDConverter");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find PersistentIDConverter Class");
				}
				Type obj2 = types.First((Type t) => t.Name == "PartialDataManager") ?? throw new Exception("Unable to Find PartialDataManager Class");
				PropertyInfo property = obj2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property2 = obj2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo? property3 = obj2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public);
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: Initialized");
				}
				if ((object)property2 == null)
				{
					throw new Exception("Unable to Find Property: PartialDataPath");
				}
				if ((object)property3 == null)
				{
					throw new Exception("Unable to Find Field: ConfigPath");
				}
				Initialized = (bool)property.GetValue(null);
				PartialDataPath = (string)property2.GetValue(null);
				ConfigPath = (string)property3.GetValue(null);
				PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}");
			}
		}
	}
	public static class MTFOUtil
	{
		public const string PLUGIN_GUID = "com.dak.MTFO";

		public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public;

		public static string GameDataPath { get; private set; }

		public static string CustomPath { get; private set; }

		public static bool HasCustomContent { get; private set; }

		public static bool IsLoaded { get; private set; }

		static MTFOUtil()
		{
			GameDataPath = string.Empty;
			CustomPath = string.Empty;
			HasCustomContent = false;
			IsLoaded = false;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class");
				FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace LGTuner.Manager
{
	public static class ConfigManager
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LiveEditEventHandler <0>__LiveEdit_FileChanged;
		}

		private static readonly List<LayoutConfig> _layouts = new List<LayoutConfig>();

		private static readonly Dictionary<uint, LayoutConfig> _lookup = new Dictionary<uint, LayoutConfig>();

		private static readonly Dictionary<string, LayoutConfig> _fileNameLookup = new Dictionary<string, LayoutConfig>();

		public static IEnumerable<LayoutConfig> Layouts => _layouts;

		public static void Init()
		{
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			if (!MTFOUtil.HasCustomContent)
			{
				return;
			}
			string text = Path.Combine(MTFOUtil.CustomPath, "LGTuner");
			FileInfo[] files = Directory.CreateDirectory(text).GetFiles();
			foreach (FileInfo fileInfo in files)
			{
				string extension = fileInfo.Extension;
				bool flag = extension.Equals(".json", StringComparison.InvariantCultureIgnoreCase);
				bool flag2 = extension.Equals(".jsonc", StringComparison.InvariantCultureIgnoreCase);
				if (flag || flag2)
				{
					LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(File.ReadAllText(fileInfo.FullName));
					if (_lookup.ContainsKey(layoutConfig.LevelLayoutID))
					{
						Logger.Error($"Duplicated ID found!: {fileInfo.Name}, {layoutConfig.LevelLayoutID}");
					}
					else
					{
						_layouts.Add(layoutConfig);
						_lookup.Add(layoutConfig.LevelLayoutID, layoutConfig);
						_fileNameLookup.Add(fileInfo.Name.ToLowerInvariant(), layoutConfig);
					}
				}
			}
			LiveEditListener obj = LiveEdit.CreateListener(text, "*.*", true);
			object obj2 = <>O.<0>__LiveEdit_FileChanged;
			if (obj2 == null)
			{
				LiveEditEventHandler val = LiveEdit_FileChanged;
				<>O.<0>__LiveEdit_FileChanged = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
			obj.StartListen();
		}

		private static void LiveEdit_FileChanged(LiveEditEventArgs e)
		{
			string key = Path.GetFileName(e.FullPath).ToLowerInvariant();
			string extension = Path.GetExtension(e.FullPath);
			if (!extension.Equals(".json", StringComparison.InvariantCulture) && !extension.Equals(".jsonc", StringComparison.InvariantCulture))
			{
				return;
			}
			Logger.Error($"File Edited: '{key}' '{e.FullPath}'");
			try
			{
				LayoutConfig data = _fileNameLookup[key];
				uint oldID = data.LevelLayoutID;
				LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string json)
				{
					try
					{
						LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(json);
						layoutConfig.LevelLayoutID = oldID;
						_fileNameLookup.Remove(key);
						_lookup.Remove(oldID);
						_layouts.Remove(data);
						_layouts.Add(layoutConfig);
						_lookup.Add(oldID, layoutConfig);
						_fileNameLookup.Add(key, layoutConfig);
					}
					catch (Exception value2)
					{
						Logger.Error($"Error while reading LGTuner Config: {value2}");
					}
				});
			}
			catch (Exception value)
			{
				Logger.Error($"Error while reading LGTuner Config: {value}");
			}
		}

		private static void DumpLevel()
		{
		}

		private static void DumpLayerToConfig()
		{
		}

		public static bool TryGetConfig(uint layoutID, out LayoutConfig config)
		{
			return _lookup.TryGetValue(layoutID, out config);
		}
	}
}
namespace LGTuner.Inject
{
	[HarmonyPatch(typeof(LG_BuildPlugBaseJob), "SpawnPlug")]
	internal static class Inject_BuildPlug
	{
		private static void Prefix(LG_Plug plug, ref GameObject prefab)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0111: 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)
			//IL_012a: Expected I4, but got Unknown
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			Logger.Info($"found plug for zone: {((LG_ZoneExpander)plug).m_linksFrom.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksFrom).name}->{((LG_ZoneExpander)plug).m_linksTo.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksTo).name}");
			if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config))
			{
				return;
			}
			LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize);
			if (!config.TryGetTileData(normal, out var overrideData))
			{
				return;
			}
			ZoneOverrideData zoneData = overrideData.ZoneData;
			if (zoneData != null && zoneData.OverridePlugs && TryGetPlugPrefab(overrideData.ZoneData.GetNextPlug(), out var prefab2))
			{
				Logger.Info(" - Prefab Replaced by Zone OverridePlugs! " + ((Object)prefab2).name);
				prefab = prefab2;
			}
			LG_PlugDir dir = plug.m_dir;
			GameObject prefab3;
			switch (dir - 2)
			{
			case 0:
				if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 2:
				if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 3:
				if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 1:
				if (TryGetPlugPrefab(overrideData.RightPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			}
			if (overrideData.OverridePlugWithNoGateChance)
			{
				Random random = new Random(((LG_ZoneExpander)plug).m_linksFrom.AreaSeed.ToSeed());
				bool withGate = ((LG_ZoneExpander)plug).m_isZoneSource || (!(overrideData.PlugWithNoGateChance >= 1f) && (overrideData.PlugWithNoGateChance <= 0f || random.NextFloat() >= overrideData.PlugWithNoGateChance));
				int dropHeight = GetDropHeight(plug);
				GameObject randomPlug = BuilderInfo.GetRandomPlug(random.NextUint(), dropHeight, GetSubComplexOfPlug(plug), withGate);
				if ((Object)(object)randomPlug == (Object)null)
				{
					Logger.Error($"Plug was null! - Height: {dropHeight}");
				}
				else
				{
					prefab = randomPlug;
				}
			}
		}

		private static SubComplex GetSubComplexOfPlug(LG_Plug plug)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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)
			SubComplex result = ((LG_ZoneExpander)plug).m_subComplex;
			if (((LG_ZoneExpander)plug).m_subComplex != ((LG_ZoneExpander)plug.m_pariedWith).m_subComplex)
			{
				result = (SubComplex)8;
			}
			return result;
		}

		private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab)
		{
			if (string.IsNullOrEmpty(prefabPath))
			{
				prefab = null;
				return false;
			}
			prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>();
			return (Object)(object)prefab != (Object)null;
		}

		private static int GetDropHeight(LG_Plug plug)
		{
			//IL_0006: 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)
			return Mathf.RoundToInt(Mathf.Abs(((Component)plug).transform.position.y - ((Component)plug.m_pariedWith).transform.position.y) / BuilderInfo.AltitudeOffset);
		}
	}
	[HarmonyPatch(typeof(LG_BuildPlugJob), "Build")]
	internal class Inject_BuildPlugJob
	{
		[HarmonyWrapSafe]
		private static bool Prefix(LG_BuildPlugJob __instance)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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: Invalid comparison between Unknown and I4
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Expected I4, but got Unknown
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			LG_Plug plug = __instance.m_plug;
			Logger.Info($"buildplugjob plug in complex {((LG_ZoneExpander)plug).m_subComplex} plug status {((LG_ZoneExpander)plug).ExpanderStatus} plug direction {plug.m_dir} ..");
			if ((int)((LG_ZoneExpander)plug).ExpanderStatus == 1)
			{
				return true;
			}
			if (((LG_ZoneExpander)plug).m_isZoneSource)
			{
				return true;
			}
			if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config))
			{
				return true;
			}
			LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize);
			if (!config.TryGetTileData(normal, out var overrideData))
			{
				return true;
			}
			LG_PlugDir dir = plug.m_dir;
			GameObject prefab;
			switch (dir - 2)
			{
			case 0:
				if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 2:
				if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 3:
				if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 1:
				if (TryGetPlugPrefab(overrideData.RightPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			}
			if ((Object)(object)val != (Object)null)
			{
				Logger.Info($"we shall replace a cap going {plug.m_dir}");
				Vector3 position = ((Component)plug).transform.position;
				Quaternion rotation = ((Component)plug).transform.rotation;
				GameObject val2 = Object.Instantiate<GameObject>(val, position, rotation);
				val2.transform.SetParent(((Component)plug).transform, true);
				LG_Factory.FindAndBuildSelectorsAndSpawners(val2, RandomExtensions.NextSubSeed(__instance.m_rnd.Random), false);
				__instance.ProcessDivider(plug, val2, false, RandomExtensions.NextSubSeed(__instance.m_rnd.Random));
				((LG_ZoneExpander)plug).m_wasProcessed = true;
			}
			return true;
		}

		private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab)
		{
			if (string.IsNullOrEmpty(prefabPath))
			{
				prefab = null;
				return false;
			}
			prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>();
			return (Object)(object)prefab != (Object)null;
		}
	}
	[HarmonyPatch(typeof(LG_LevelBuilder), "PlaceRoot")]
	internal static class Inject_BuildGeomorph
	{
		private static LayoutConfig _configContext;

		private static RotateType _nextRotateType;

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("BuildFloor")]
		private static void Post_BuildFloor()
		{
			BuilderInfo.OnResourceSetSelected();
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Pre_PlaceRoot(LG_Tile tile, ref GameObject tilePrefab, ref bool forceAlignToVector, ref Vector3 alignVector, LG_Zone zone)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			_configContext = null;
			_nextRotateType = RotateType.None;
			forceAlignToVector = alignVector != Vector3.zero;
			int gridSize = zone.Dimension.GetGridSize();
			LG_GridPosition val = tile.ToNormalGrid(gridSize);
			Logger.Info($"tile info: {val.x} {val.z} {((Object)tilePrefab).name} for {zone.LocalIndex} : {zone.DimensionIndex}");
			if (!BuilderInfo.TryGetConfig(zone, out _configContext))
			{
				return;
			}
			if (!_configContext.TryGetTileData(val, out var overrideData))
			{
				overrideData = _configContext.PopulateTileOverrideForZone(zone, val);
				if (overrideData == null)
				{
					return;
				}
			}
			if (!string.IsNullOrEmpty(overrideData.Geomorph))
			{
				Object loadedAsset = AssetAPI.GetLoadedAsset(overrideData.Geomorph);
				GameObject val2 = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
				if ((Object)(object)val2 != (Object)null)
				{
					Logger.Info(" - tile overriden! " + ((Object)val2).name);
					tilePrefab = val2;
				}
			}
			if (overrideData.Rotation != 0)
			{
				_nextRotateType = overrideData.Rotation;
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("GetTilePosition")]
		private static void Post_GetTilePosition(LG_Tile tile, LG_Floor floor, int dimensionIndex, ref Vector3 __result)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			if (_configContext != null && floor.TryGetDimension(dimensionIndex, out var dimension))
			{
				int gridSize = _configContext.GridSize;
				LG_GridPosition val = tile.ToNormalGrid(gridSize);
				if (_configContext.TryGetTileData(val, out var overrideData) && overrideData.OverrideAltitude)
				{
					Vector3 positionNormal = dimension.Grid.GetPositionNormal(val.x, val.z, gridSize);
					positionNormal += new Vector3(0f, (float)overrideData.Altitude * BuilderInfo.AltitudeOffset, 0f);
					__result = positionNormal;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Post_PlaceRoot(LG_Tile tile, LG_Zone zone, LG_Geomorph __result)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (_configContext == null)
			{
				return;
			}
			if (_nextRotateType != 0)
			{
				GameObject gameObject = ((Component)__result).gameObject;
				LG_PlugInfo lG_PlugInfo = LG_PlugInfo.BuildPlugInfo(gameObject, gameObject.transform.rotation);
				Logger.Info($" - TRYING ROTATION! PLUG COUNT: {lG_PlugInfo.Count}");
				if (lG_PlugInfo.TryGetNewRotation(zone.m_subSeed, _nextRotateType, out var rotation))
				{
					Logger.Info(" - Done!");
					gameObject.transform.rotation = rotation;
				}
				__result.SetPlaced();
			}
			int gridSize = _configContext.GridSize;
			LG_GridPosition normalGridPosition = tile.ToNormalGrid(gridSize);
			if (!_configContext.TryGetTileData(normalGridPosition, out var overrideData) || !overrideData.OverrideAreaSeeds)
			{
				return;
			}
			if (overrideData.AreaSeeds.Length == ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length)
			{
				int length = ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length;
				for (int i = 0; i < length; i++)
				{
					uint num = overrideData.AreaSeeds[i];
					if (num != 0)
					{
						((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].AreaSeed = num;
						Logger.Info($" - new area seed: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].m_navInfo}, {num}");
					}
				}
			}
			else
			{
				Logger.Error($" - Area count and AreaSeeds item count mismatched! (CFG: {overrideData.AreaSeeds.Length} != AREA: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length}) Area seed will not be applied!");
			}
		}
	}
	[HarmonyPatch(typeof(LG_LoadComplexDataSetResourcesJob), "Build")]
	internal static class Inject_LoadComplexShard
	{
		private static int _waitingShared;

		private static void Prefix(LG_LoadComplexDataSetResourcesJob __instance)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected I4, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_loadingStarted)
			{
				return;
			}
			foreach (Complex item in BuilderInfo.ExtraComplexResourceToLoad)
			{
				AssetBundleName val = (AssetBundleName)((int)item switch
				{
					0 => 2, 
					1 => 4, 
					2 => 3, 
					_ => 0, 
				});
				if ((int)val != 0)
				{
					AssetShardManager.LoadAllShardsForBundleAsync(val, Action.op_Implicit((Action)Loaded), 1, (LoadSceneMode)1);
					_waitingShared++;
				}
			}
		}

		private static void Loaded()
		{
			_waitingShared--;
		}

		[HarmonyWrapSafe]
		private static void Postfix(LG_LoadComplexDataSetResourcesJob __instance, ref bool __result)
		{
			if (_waitingShared >= 1)
			{
				__result = false;
			}
		}
	}
}
namespace LGTuner.Configs
{
	public sealed class LayoutConfig
	{
		private TileOverrideData[,] _builtTileOverrides = new TileOverrideData[0, 0];

		public uint LevelLayoutID { get; set; }

		public Complex[] ExtraComplexResourceToLoad { get; set; } = Array.Empty<Complex>();


		public ZoneOverrideData[] ZoneOverrides { get; set; } = Array.Empty<ZoneOverrideData>();


		public TileOverrideData[] TileOverrides { get; set; } = Array.Empty<TileOverrideData>();


		[JsonIgnore]
		public int GridSize { get; private set; }

		[JsonIgnore]
		public int GridSizeHalf { get; private set; }

		public void Reset(int gridSize)
		{
			Array.ForEach(ZoneOverrides, delegate(ZoneOverrideData item)
			{
				item.Clear();
			});
			Array.Clear(_builtTileOverrides, 0, _builtTileOverrides.Length);
			GridSize = gridSize;
			GridSizeHalf = gridSize / 2;
			_builtTileOverrides = new TileOverrideData[GridSize, GridSize];
			TileOverrideData[] tileOverrides = TileOverrides;
			foreach (TileOverrideData tileOverrideData in tileOverrides)
			{
				if (_builtTileOverrides[tileOverrideData.X + GridSizeHalf, tileOverrideData.Z + GridSizeHalf] == null)
				{
					PutOverrideData(tileOverrideData);
					continue;
				}
				Logger.Error($"Duplicate tile data in layout: {LevelLayoutID}, ({tileOverrideData.X}, {tileOverrideData.Z})!");
			}
		}

		public bool TryGetTileData(LG_GridPosition normalGridPosition, out TileOverrideData overrideData)
		{
			//IL_0000: 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)
			int num = normalGridPosition.x + GridSizeHalf;
			if (num >= GridSize)
			{
				Logger.Error($"TryGetTileData grid x was out of range! {num}:{GridSize}");
				overrideData = null;
				return false;
			}
			int num2 = normalGridPosition.z + GridSizeHalf;
			if (num2 >= GridSize)
			{
				Logger.Error($"TryGetTileData grid Z was out of range! {num2}:{GridSize}");
				overrideData = null;
				return false;
			}
			overrideData = _builtTileOverrides[num, num2];
			return overrideData != null;
		}

		public void PutOverrideData(TileOverrideData data)
		{
			_builtTileOverrides[data.X + GridSizeHalf, data.Z + GridSizeHalf] = data;
		}

		public TileOverrideData PopulateTileOverrideForZone(LG_Zone zone, LG_GridPosition normalGridPosition)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetZoneOverride(zone.LocalIndex, out var data))
			{
				return null;
			}
			if (TryGetTileData(normalGridPosition, out var overrideData))
			{
				overrideData.ZoneData = data;
				TryApplyOverrides(data, overrideData);
				return overrideData;
			}
			TileOverrideData tileOverrideData = new TileOverrideData
			{
				ZoneData = data,
				X = normalGridPosition.x,
				Z = normalGridPosition.z,
				OverridePlugWithNoGateChance = data.OverridePlugWithNoGateChance,
				PlugWithNoGateChance = data.PlugWithNoGateChance
			};
			TryApplyOverrides(data, tileOverrideData);
			PutOverrideData(tileOverrideData);
			return tileOverrideData;
		}

		private void TryApplyOverrides(ZoneOverrideData zoneOverrideData, TileOverrideData tileOverrideData)
		{
			if (zoneOverrideData.OverrideGeomorphs && string.IsNullOrEmpty(tileOverrideData.Geomorph))
			{
				ZoneOverrideData.GeomorphData? nextGeo = zoneOverrideData.GetNextGeo();
				if (nextGeo.HasValue)
				{
					tileOverrideData.Geomorph = nextGeo.Value.Geomorph;
					if (tileOverrideData.Rotation == RotateType.None)
					{
						tileOverrideData.Rotation = ZoneOverrideData.DirectionToRotate(nextGeo.Value.Direction);
					}
				}
			}
			if (zoneOverrideData.OverrideAltitudes && !tileOverrideData.OverrideAltitude)
			{
				int? nextAltitude = zoneOverrideData.GetNextAltitude();
				if (nextAltitude.HasValue)
				{
					tileOverrideData.OverrideAltitude = true;
					tileOverrideData.Altitude = nextAltitude.Value;
				}
			}
		}

		public bool TryGetZoneOverride(eLocalZoneIndex localIndex, out ZoneOverrideData data)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			data = ZoneOverrides.SingleOrDefault((ZoneOverrideData z) => z.LocalIndex == localIndex);
			return data != null;
		}
	}
	public sealed class TileOverrideData
	{
		public int X { get; set; }

		public int Z { get; set; }

		public bool OverrideAreaSeeds { get; set; }

		public uint[] AreaSeeds { get; set; } = Array.Empty<uint>();


		public RotateType Rotation { get; set; }

		public string Geomorph { get; set; } = string.Empty;


		public bool OverrideAltitude { get; set; }

		public int Altitude { get; set; }

		public string ForwardPlug { get; set; } = string.Empty;


		public string BackwardPlug { get; set; } = string.Empty;


		public string LeftPlug { get; set; } = string.Empty;


		public string RightPlug { get; set; } = string.Empty;


		public bool OverridePlugWithNoGateChance { get; set; }

		public float PlugWithNoGateChance { get; set; } = 0.5f;


		[JsonIgnore]
		public ZoneOverrideData ZoneData { get; set; }
	}
	public sealed class ZoneOverrideData
	{
		public enum Direction
		{
			Unchanged,
			Random,
			Forward,
			Backward,
			Left,
			Right
		}

		public struct GeomorphData
		{
			public string Geomorph { get; set; }

			public Direction Direction { get; set; }
		}

		private int _curGeomorphIndex;

		private int _curAltitudeIndex;

		private int _curPlugIndex;

		public eLocalZoneIndex LocalIndex { get; set; }

		public bool OverrideGeomorphs { get; set; }

		public GeomorphData[] Geomorphs { get; set; } = Array.Empty<GeomorphData>();


		public bool OverrideAltitudes { get; set; }

		public int[] Altitudes { get; set; } = Array.Empty<int>();


		public bool OverridePlugs { get; set; }

		public string[] Plugs { get; set; } = Array.Empty<string>();


		public bool OverridePlugWithNoGateChance { get; set; }

		public float PlugWithNoGateChance { get; set; } = 0.5f;


		public void Clear()
		{
			_curGeomorphIndex = 0;
			_curAltitudeIndex = 0;
			_curPlugIndex = 0;
		}

		public GeomorphData? GetNextGeo()
		{
			if (Geomorphs == null || Geomorphs.Length == 0)
			{
				return null;
			}
			return Geomorphs[_curGeomorphIndex++ % Geomorphs.Length];
		}

		public int? GetNextAltitude()
		{
			if (Altitudes == null || Altitudes.Length == 0)
			{
				return null;
			}
			return Altitudes[_curAltitudeIndex++ % Altitudes.Length];
		}

		public string GetNextPlug()
		{
			if (Plugs == null || Plugs.Length == 0)
			{
				return string.Empty;
			}
			return Plugs[_curPlugIndex++ % Plugs.Length];
		}

		public static RotateType DirectionToRotate(Direction direction)
		{
			return direction switch
			{
				Direction.Unchanged => RotateType.None, 
				Direction.Random => RotateType.Towards_Random, 
				Direction.Forward => RotateType.Towards_Forward, 
				Direction.Backward => RotateType.Towards_Backward, 
				Direction.Left => RotateType.Towards_Left, 
				Direction.Right => RotateType.Towards_Right, 
				_ => throw new NotImplementedException($"DirectionType: {direction} is not supported"), 
			};
		}
	}
}