Decompiled source of LGTunerAdvanced v0.0.12

plugins/LGTunerAdvanced.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using AssetShards;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Expedition;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using LGTunerAdvanced.Data;
using LGTunerAdvanced.Render;
using LevelGeneration;
using LevelGeneration.Core;
using Microsoft.CodeAnalysis;
using Player;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("0.0.12")]
[assembly: AssemblyInformationalVersion("0.0.12")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyVersion("0.0.12.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal class ManifestInfo
{
	internal const string TSName = "LGTunerAdvanced";

	internal const string TSDescription = "Changes GTFO to use a custom level builder rather than vanilla RNG heavy system.";

	internal const string TSVersion = "0.0.12";

	internal const string TSAuthor = "Tgb03";

	internal const string TSWebsite = "https://github.com/Tgb03/LGTunerAdvanced/";
}
namespace LGTunerAdvanced
{
	[BepInPlugin("dev.Tgb03.gtfo.LGTunerAdvanced", "LGTunerAdvanced", "0.0.12")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		public const string GUID = "dev.Tgb03.gtfo.LGTunerAdvanced";

		public const string MOD_NAME = "LGTunerAdvanced";

		public const string VERSION = "0.0.12";

		internal static ManualLogSource L;

		private static readonly Harmony _harmony = new Harmony("dev.Tgb03.gtfo.LGTunerAdvanced");

		public override void Load()
		{
			L = ((BasePlugin)this).Log;
			LGTunerAdvancedConfig.Initialize(((BasePlugin)this).Config);
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			LoadLevelGenerationData.ResolveLoading();
			LG_AreaExpanderRender.Register();
			if (LGTunerAdvancedConfig.RenderExpanders.Value)
			{
				RundownManager.OnExpeditionGameplayStarted += Action.op_Implicit((Action)delegate
				{
					LG_AreaExpanderRender.AddRenderer();
				});
			}
			L.LogInfo((object)"Plugin loaded!");
		}
	}
}
namespace LGTunerAdvanced.Render
{
	internal class LG_AreaExpanderRender : MonoBehaviour
	{
		private static PlayerAgent agent;

		public LG_AreaExpanderRender(IntPtr ptr)
			: base(ptr)
		{
		}

		public LG_AreaExpanderRender()
		{
		}

		public static void Register()
		{
			ClassInjector.RegisterTypeInIl2Cpp<LG_AreaExpanderRender>();
		}

		public static void AddRenderer()
		{
			PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
			if ((Object)(object)((Component)localPlayerAgent).gameObject.GetComponent<LG_AreaExpanderRender>() == (Object)null)
			{
				((Component)localPlayerAgent).gameObject.AddComponent<LG_AreaExpanderRender>();
			}
		}

		public void Start()
		{
			agent = PlayerManager.GetLocalPlayerAgent();
		}

		public void Update()
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			if (!((Behaviour)this).enabled)
			{
				return;
			}
			LG_Area area = agent.m_courseNode.m_area;
			if ((Object)(object)area == (Object)null || area.m_zoneExpanders == null)
			{
				return;
			}
			LG_Geomorph geomorph = area.m_geomorph;
			int num = 0;
			using (IEnumerator<LG_Area> enumerator = ((Il2CppArrayBase<LG_Area>)(object)geomorph.m_areas).GetEnumerator())
			{
				while (enumerator.MoveNext() && !(((Il2CppObjectBase)enumerator.Current).Pointer == ((Il2CppObjectBase)area).Pointer))
				{
					num++;
				}
			}
			LG_GridPosition gridPosition = geomorph.m_tile.m_shape.m_gridPosition;
			Vector2Int val = default(Vector2Int);
			((Vector2Int)(ref val))..ctor(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)area.m_zone.Dimension.Grid).m_sizeX / 2, ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)area.m_zone.Dimension.Grid).m_sizeZ / 2);
			Fig.DrawText($"Position: ({gridPosition.x - ((Vector2Int)(ref val)).x}, {gridPosition.z - ((Vector2Int)(ref val)).y})\nInternalAreaID: {num}", ((Component)area).transform.position, Quaternion.LookRotation(((Component)agent).transform.position - ((Component)area).transform.position) * Quaternion.Euler(0f, 180f, 0f), new Vector3(1f, 1f, 1f), LGTunerAdvancedConfig.AreaTextColor, (TextAnchor)7, (TextAlignment)0, 1f);
			for (int i = 0; i < area.m_zoneExpanders.Count; i++)
			{
				LG_ZoneExpander val2 = area.m_zoneExpanders[i];
				if (!((Object)(object)val2 == (Object)null))
				{
					if (!val2.m_isZoneBuildBlocked)
					{
						_ = Color.white;
					}
					else
					{
						_ = Color.red;
					}
					Fig.DrawText(i.ToString(), ((Component)val2).transform.position, ((Component)val2).transform.rotation, new Vector3(5f, 5f, 5f), LGTunerAdvancedConfig.ExpanderColor, (TextAnchor)7, (TextAlignment)0, 1f);
				}
			}
		}
	}
}
namespace LGTunerAdvanced.Patches
{
	[HarmonyPatch(typeof(LG_BuildPlugBaseJob), "SpawnPlug")]
	internal class BuildPlugPatch
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		private static void Prefix(LG_Plug plug, ref GameObject prefab)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected I4, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			LG_Zone zone = ((LG_ZoneExpander)plug).m_linksFrom.m_zone;
			LG_GridPosition gridPosition = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition;
			if (!LoadLevelGenerationData.TryGrabGeoOverride(zone, gridPosition, out GeoOverride geoOverride))
			{
				return;
			}
			LG_PlugDir dir = plug.m_dir;
			string text = (dir - 2) switch
			{
				0 => geoOverride.NorthPlug, 
				1 => geoOverride.EastPlug, 
				2 => geoOverride.SouthPlug, 
				3 => geoOverride.WestPlug, 
				_ => "", 
			};
			if (!(text == ""))
			{
				GameObject val = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(text)).Cast<GameObject>();
				prefab = val;
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExMessageLogInterpolatedStringHandler val2 = new BepInExMessageLogInterpolatedStringHandler(27, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Plug prefab replaced with: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
				}
				l.LogMessage(val2);
			}
		}
	}
	[HarmonyPatch(typeof(Builder), "Build")]
	public static class BuildResetter
	{
		[HarmonyPrefix]
		public static void Prefix()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			LG_ZoneJob_CreateExpandFromDataPatch.built_geos.Clear();
			LG_ZoneJob_CreateExpandFromDataPatch.blocked_expanders.Clear();
			LG_ZoneJob_CreateExpandFromDataPatch.built_geos.Add(new LG_GridPosition(0, 0));
		}
	}
	[HarmonyPatch(typeof(LG_LevelBuilder), "PlaceRoot")]
	internal static class Inject_BuildGeomorph
	{
		[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_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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_0063: Expected O, but got Unknown
			//IL_0078: 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)
			forceAlignToVector = alignVector != Vector3.zero;
			GeoOverride geoOverride;
			if (tile == null)
			{
				Plugin.L.LogError((object)"PlaceRoot failed because tile variable is null");
			}
			else if (tile.m_shape == null)
			{
				Plugin.L.LogError((object)"PlaceRoot failed because tile.m_shape variable is null");
			}
			else if (!LoadLevelGenerationData.TryGrabGeoOverride(zone, tile.m_shape.m_gridPosition, out geoOverride))
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(58, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("PlaceRoot failed because could not find geoOverride for ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(tile.m_shape.m_gridPosition.x);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(tile.m_shape.m_gridPosition.z);
				}
				l.LogError(val);
			}
			else
			{
				Object loadedAsset = AssetAPI.GetLoadedAsset(geoOverride.Geomorph);
				GameObject val2 = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
				if ((Object)(object)val2 != (Object)null)
				{
					tilePrefab = val2;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Post_PlaceRoot(LG_Tile tile, LG_Zone zone, LG_Geomorph __result)
		{
			//IL_0039: 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_0057: Expected O, but got Unknown
			//IL_006d: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)__result).gameObject;
			GeoOverride geoOverride;
			if (tile == null)
			{
				Plugin.L.LogError((object)"PlaceRoot failed because tile variable is null");
			}
			else if (tile.m_shape == null)
			{
				Plugin.L.LogError((object)"PlaceRoot failed because tile.m_shape variable is null");
			}
			else if (!LoadLevelGenerationData.TryGrabGeoOverride(zone, tile.m_shape.m_gridPosition, out geoOverride))
			{
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(58, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("PlaceRoot failed because could not find geoOverride for ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(tile.m_shape.m_gridPosition.x);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(tile.m_shape.m_gridPosition.z);
				}
				l.LogError(val);
			}
			else
			{
				float num = geoOverride.Rotation switch
				{
					GeoRotation.Forwards => 0, 
					GeoRotation.Right => 90, 
					GeoRotation.Backwards => 180, 
					GeoRotation.Left => 270, 
					_ => 0, 
				};
				gameObject.transform.rotation = Quaternion.Euler(0f, num, 0f);
				__result.SetPlaced();
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("GetTilePosition")]
		private static void Post_GetTilePosition(LG_Tile tile, LG_Floor floor, int dimensionIndex, ref Vector3 __result)
		{
			//IL_0031: 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_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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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)
			Dimension val = default(Dimension);
			if (floor.allZones.Count != 0 && tile != null && tile.m_shape != null && floor.GetDimension((eDimensionIndex)dimensionIndex, ref val) && LoadLevelGenerationData.TryGrabLastQueried(out LevelGenerationOverride levelOverride) && levelOverride.TryGrabGeoAtPos(((CellGroupingBase<LG_Tile, LG_Cell>)(object)tile).GetGridCenterPosition(), val, out var result))
			{
				ComplexResourceSetDataBlock block = GameDataBlockBase<ComplexResourceSetDataBlock>.GetBlock(RundownManager.ActiveExpedition.Expedition.ComplexResourceData);
				Vector3 position = ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)val.Grid).GetPosition(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)val.Grid).GetCell(tile.m_shape.m_gridPosition));
				Vector3 val2 = default(Vector3);
				((Vector3)(ref val2))..ctor(__result.x, position.y + (float)result.Altitude * block.LevelGenConfig.AltitudeOffset, __result.z);
				__result = val2;
			}
		}
	}
	[HarmonyPatch(typeof(LG_ZoneJob_CreateExpandFromData), "ExpandZone")]
	public static class LG_ZoneJob_CreateExpandFromDataPatch
	{
		internal static HashSet<LG_GridPosition> built_geos = new HashSet<LG_GridPosition>();

		internal static HashSet<IntPtr> blocked_expanders = new HashSet<IntPtr>();

		[HarmonyPrefix]
		public static void Prefix(LG_Zone zone, ref LG_Area buildFromArea, ref LG_ZoneExpander buildFromExpander, uint seed)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			if (LoadLevelGenerationData.TryGrabZoneOverride(zone, out ZoneOverride zoneOverride) && GrabExpander(zone, zoneOverride, out var lgZoneExpander, out var buildFromArea2))
			{
				blocked_expanders.Add(((Il2CppObjectBase)lgZoneExpander).Pointer);
				if (zone.m_areas.Count == 0)
				{
					zone.m_sourceExpander = lgZoneExpander;
				}
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExMessageLogInterpolatedStringHandler val = new BepInExMessageLogInterpolatedStringHandler(53, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("   Succeeded in finding connection in zone ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(zone.ID);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" for area ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(zone.m_areas.Count);
				}
				l.LogMessage(val);
				buildFromExpander = lgZoneExpander;
				buildFromArea = buildFromArea2;
			}
		}

		[HarmonyPostfix]
		public static void Postfix(LG_Zone zone, LG_Area buildFromArea, LG_ZoneExpander buildFromExpander, uint seed, ref LG_Area area, ref CoverageResult __result)
		{
			if (LoadLevelGenerationData.TryGrabZoneOverride(zone, out ZoneOverride zoneOverride))
			{
				if (zone.m_areas.Count < zoneOverride.AreaOverrides.Count)
				{
					__result = (CoverageResult)1;
				}
				else
				{
					__result = (CoverageResult)4;
				}
			}
		}

		private static bool GrabExpander(LG_Zone zone, ZoneOverride zoneOverride, out LG_ZoneExpander lgZoneExpander, out LG_Area buildFromArea)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			bool flag = default(bool);
			if ((Object)(object)zone == (Object)null || zoneOverride == null)
			{
				ManualLogSource l = Plugin.L;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(49, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("   Something ended up null and could not proceed.");
				}
				l.LogError(val);
				lgZoneExpander = null;
				buildFromArea = null;
				return false;
			}
			if (zone.m_areas.Count < 0 || zone.m_areas.Count >= zoneOverride.AreaOverrides.Count)
			{
				ManualLogSource l2 = Plugin.L;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(61, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("   zone.m_areas.Count > zoneOverride.AreaOverrides.Count: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(zone.m_areas.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" > ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(zoneOverride.AreaOverrides.Count);
				}
				l2.LogError(val);
				lgZoneExpander = null;
				buildFromArea = null;
				return false;
			}
			try
			{
				AreaOverride areaOverride = zoneOverride.AreaOverrides[zone.m_areas.Count];
				LG_Area val2 = ((Il2CppArrayBase<LG_Area>)(object)((CellBase<LG_Tile, LG_Cell>)(object)((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)zone.Dimension.Grid).GetCell(GetRealPos(areaOverride.PreviousCellPosition, zone.Dimension))).m_grouping.m_geoRoot.m_areas)[areaOverride.PreviousCellInternalAreaID];
				if (areaOverride.LG_ExpanderID < 0 || areaOverride.LG_ExpanderID >= val2.m_zoneExpanders.Count)
				{
					ManualLogSource l3 = Plugin.L;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(73, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("   areaOverride.LG_ExpanderID >= previous_area.m_zoneExpanders.Count: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(areaOverride.LG_ExpanderID);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" > ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(val2.m_zoneExpanders.Count);
					}
					l3.LogError(val);
					lgZoneExpander = null;
					buildFromArea = null;
					return false;
				}
				if (blocked_expanders.Contains(((Il2CppObjectBase)val2.m_zoneExpanders[areaOverride.LG_ExpanderID]).Pointer))
				{
					ManualLogSource l4 = Plugin.L;
					bool flag2 = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(81, 0, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("   LG_ZoneExpander was already parsed and blocked. This means it cannot be reused");
					}
					l4.LogError(val);
					lgZoneExpander = null;
					buildFromArea = null;
					return false;
				}
				lgZoneExpander = val2.m_zoneExpanders[areaOverride.LG_ExpanderID];
				buildFromArea = val2;
				return true;
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)ex);
			}
			lgZoneExpander = null;
			buildFromArea = null;
			return false;
		}

		private static LG_GridPosition GetRealPos(LG_GridPosition position, Dimension dimension)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			position.x += ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX / 2;
			position.z += ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeZ / 2;
			return position;
		}
	}
	[HarmonyPatch(typeof(LG_LoadComplexDataSetResourcesJob), "Build")]
	internal class LoadComplexShard
	{
		private static int _waitingShared;

		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Prefix(LG_LoadComplexDataSetResourcesJob __instance)
		{
			//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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected I4, but got Unknown
			//IL_004d: 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_005e: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_loadingStarted)
			{
				return;
			}
			if (!LoadLevelGenerationData.TryGrabLastQueried(out LevelGenerationOverride levelOverride))
			{
				Plugin.L.LogError((object)"Failed to find levelOverride, nothing was queried");
				return;
			}
			foreach (Complex item in levelOverride.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]
		[HarmonyPostfix]
		private static void Postfix(LG_LoadComplexDataSetResourcesJob __instance, ref bool __result)
		{
			if (_waitingShared > 0)
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(RundownManager), "MasterSelectActiveExpedition")]
	internal class SelectActiveExpeditionPatch
	{
		[HarmonyPostfix]
		public static void Postfix()
		{
			LoadLevelGenerationData.SetLayoutID(RundownManager.ActiveExpedition.LevelLayoutData);
		}
	}
}
namespace LGTunerAdvanced.Data
{
	[Serializable]
	internal class LevelGenerationOverride
	{
		public uint LevelLayoutID;

		public List<ZoneOverride> ZoneOverrides = new List<ZoneOverride>();

		public List<GeoOverride> GeoOverrides = new List<GeoOverride>();

		public List<Complex> ExtraComplexResourceToLoad = new List<Complex>();

		public bool TryGrabGeoAtPos(LG_GridPosition position, Dimension dimension, out GeoOverride result)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Vector2Int cellGridCenter = default(Vector2Int);
			((Vector2Int)(ref cellGridCenter))..ctor(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX / 2, ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeZ / 2);
			return TryGrabGeoAtPos(position, cellGridCenter, out result);
		}

		public bool TryGrabGeoAtPos(LG_GridPosition position, Vector2Int cellGridCenter, out GeoOverride result)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (GeoOverride geoOverride in GeoOverrides)
			{
				if (geoOverride.Position.x == position.x - ((Vector2Int)(ref cellGridCenter)).x && geoOverride.Position.z == position.z - ((Vector2Int)(ref cellGridCenter)).y)
				{
					result = geoOverride;
					return true;
				}
			}
			result = null;
			return false;
		}
	}
	[Serializable]
	internal class ZoneOverride
	{
		public bool IgnoreZone;

		public List<AreaOverride> AreaOverrides = new List<AreaOverride>();
	}
	[Serializable]
	internal class AreaOverride
	{
		public LG_GridPosition PreviousCellPosition;

		public int PreviousCellInternalAreaID;

		public int LG_ExpanderID;
	}
	[Serializable]
	internal class GeoOverride
	{
		public LG_GridPosition Position;

		public string Geomorph;

		public GeoRotation Rotation;

		public int Altitude;

		public string NorthPlug = "";

		public string EastPlug = "";

		public string SouthPlug = "";

		public string WestPlug = "";
	}
	[Serializable]
	internal enum GeoRotation
	{
		Forwards,
		Right,
		Backwards,
		Left
	}
	internal class GeoRotationConverter : JsonConverter<GeoRotation>
	{
		public override GeoRotation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			return reader.TokenType switch
			{
				JsonTokenType.String => FromString(reader.GetString()), 
				JsonTokenType.Number => FromDegrees(reader.GetDouble()), 
				_ => throw new JsonException($"Unexpected token {reader.TokenType} when parsing {"GeoRotation"}."), 
			};
		}

		public override void Write(Utf8JsonWriter writer, GeoRotation value, JsonSerializerOptions options)
		{
			writer.WriteStringValue(value.ToString());
		}

		private static GeoRotation FromString(string text)
		{
			text = text?.Trim();
			if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return FromDegrees(result);
			}
			if (Enum.TryParse<GeoRotation>(text, ignoreCase: true, out var result2) && Enum.IsDefined(typeof(GeoRotation), result2))
			{
				return result2;
			}
			throw new JsonException($"'{text}' is not a valid {"GeoRotation"}.");
		}

		private static GeoRotation FromDegrees(double degrees)
		{
			double num = (degrees % 360.0 + 360.0) % 360.0;
			if (num != 0.0)
			{
				if (num != 1.0)
				{
					if (num != 90.0)
					{
						if (num != 180.0)
						{
							if (num != 2.0)
							{
								if (num != 270.0)
								{
									if (num == 3.0)
									{
										return GeoRotation.Left;
									}
									throw new JsonException($"{degrees} is not a valid {"GeoRotation"}; expected a multiple of 90.");
								}
								return GeoRotation.Left;
							}
							return GeoRotation.Backwards;
						}
						return GeoRotation.Backwards;
					}
					return GeoRotation.Right;
				}
				return GeoRotation.Right;
			}
			return GeoRotation.Forwards;
		}
	}
	internal class LoadLevelGenerationData
	{
		public static Dictionary<uint, LevelGenerationOverride> levelGenerationOverrides = new Dictionary<uint, LevelGenerationOverride>();

		private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
		{
			PropertyNameCaseInsensitive = true,
			IncludeFields = true,
			ReadCommentHandling = JsonCommentHandling.Skip,
			AllowTrailingCommas = true,
			Converters = 
			{
				(JsonConverter)new GeoRotationConverter(),
				(JsonConverter)new JsonStringEnumConverter()
			}
		};

		private static LevelGenerationOverride lastQueried = null;

		public static void SetLayoutID(uint id)
		{
			lastQueried = levelGenerationOverrides[id];
		}

		public static void ResolveLoading()
		{
			string gameDataPath = Paths.GameDataPath;
			string pluginPath = Paths.PluginPath;
			foreach (string item in (from d in new string[2] { gameDataPath, pluginPath }.Where(Directory.Exists).SelectMany((string p) => Directory.GetDirectories(p, "*", SearchOption.AllDirectories))
				where d.Contains(Path.Combine("Custom", "LGTunerAdvanced"), StringComparison.OrdinalIgnoreCase)
				select d).OrderBy(Path.GetDirectoryName))
			{
				LoadDictionary(item);
			}
		}

		public static void LoadDictionary(string filePath)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(39, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Loading LevelGenerationOverrides from: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(filePath);
			}
			l.LogInfo(val);
			FileInfo[] files = Directory.CreateDirectory(filePath).GetFiles();
			foreach (FileInfo fileInfo in files)
			{
				string extension = fileInfo.Extension;
				if (fileInfo.Name.EndsWith("schema.json") || (extension != ".json" && extension != ".jsonc"))
				{
					continue;
				}
				try
				{
					LevelGenerationOverride levelGenerationOverride = JsonSerializer.Deserialize<LevelGenerationOverride>(File.ReadAllText(fileInfo.FullName), _jsonOptions);
					levelGenerationOverrides[levelGenerationOverride.LevelLayoutID] = levelGenerationOverride;
					ManualLogSource l2 = Plugin.L;
					val = new BepInExInfoLogInterpolatedStringHandler(18, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("     Loaded ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(levelGenerationOverride.LevelLayoutID);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" from ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(fileInfo.FullName);
					}
					l2.LogInfo(val);
				}
				catch (Exception ex)
				{
					Plugin.L.LogError((object)ex);
				}
			}
			SafeFileSystemWatcher obj = SafeFileSystemWatcher.Create(filePath, new string[1] { "*.*" }, true);
			obj.RetryOnLocked = false;
			obj.OnRenamed += LiveEditFileChanged;
			obj.OnChanged += LiveEditFileChanged;
			obj.OnCreated += LiveEditFileChanged;
			obj.OnDeleted += LiveEditFileChanged;
			obj.Listening = true;
		}

		private static void LiveEditFileChanged(FileEventArgs e)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			string fullPath = e.FullPath;
			if (!fullPath.Contains("LGTunerAdvanced"))
			{
				return;
			}
			string text = Path.GetExtension(fullPath).ToLowerInvariant();
			if (text != ".json" && text != ".jsonc")
			{
				return;
			}
			try
			{
				LevelGenerationOverride levelGenerationOverride = JsonSerializer.Deserialize<LevelGenerationOverride>(e.ReadContent((Encoding)null), _jsonOptions);
				levelGenerationOverrides[levelGenerationOverride.LevelLayoutID] = levelGenerationOverride;
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(18, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("     Loaded ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(levelGenerationOverride.LevelLayoutID);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" from ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.FileName);
				}
				l.LogInfo(val);
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)ex);
			}
		}

		private static uint GetLayoutID(LG_Zone zone)
		{
			//IL_001f: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected I4, but got Unknown
			if (!zone.IsMainDimension)
			{
				return zone.Dimension.DimensionData.LevelLayoutData;
			}
			LG_LayerType type = zone.Layer.m_type;
			return (int)type switch
			{
				0 => Builder.LevelGenExpedition.LevelLayoutData, 
				1 => Builder.LevelGenExpedition.SecondaryLayout, 
				2 => Builder.LevelGenExpedition.ThirdLayout, 
				_ => throw new ArgumentException($"LG_LayerType of LG_Zone with id: {zone.ID} is out of bounds."), 
			};
		}

		public static bool TryGrabZoneOverride(LG_Zone zone, out ZoneOverride? zoneOverride)
		{
			uint layoutID = GetLayoutID(zone);
			if (levelGenerationOverrides.TryGetValue(layoutID, out var value))
			{
				if (zone.IDinLayer >= value.ZoneOverrides.Count)
				{
					zoneOverride = null;
					return false;
				}
				if (value.ZoneOverrides[zone.IDinLayer].IgnoreZone)
				{
					zoneOverride = null;
					return false;
				}
				zoneOverride = value.ZoneOverrides[zone.IDinLayer];
				lastQueried = value;
			}
			else
			{
				zoneOverride = null;
			}
			return zoneOverride != null;
		}

		public static bool TryGrabGeoOverride(LG_Zone zone, LG_GridPosition position, out GeoOverride? geoOverride)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			uint layoutID = GetLayoutID(zone);
			Vector2Int val = default(Vector2Int);
			((Vector2Int)(ref val))..ctor(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)zone.Dimension.Grid).m_sizeX / 2, ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)zone.Dimension.Grid).m_sizeZ / 2);
			position.x -= ((Vector2Int)(ref val)).x;
			position.z -= ((Vector2Int)(ref val)).y;
			if (levelGenerationOverrides.TryGetValue(layoutID, out var value))
			{
				foreach (GeoOverride geoOverride2 in value.GeoOverrides)
				{
					if (geoOverride2.Position.x == position.x && geoOverride2.Position.z == position.z)
					{
						geoOverride = geoOverride2;
						lastQueried = value;
						return true;
					}
				}
			}
			geoOverride = null;
			return false;
		}

		public static bool TryGrabLastQueried(out LevelGenerationOverride? levelOverride)
		{
			levelOverride = lastQueried;
			return levelOverride != null;
		}
	}
	internal class LGTunerAdvancedConfig
	{
		public static ConfigEntry<bool> RenderExpanders { get; private set; }

		public static ConfigEntry<string> ExpanderColorHex { get; private set; }

		public static ConfigEntry<string> AreaTextColorHex { get; private set; }

		public static Color ExpanderColor { get; private set; }

		public static Color AreaTextColor { get; private set; }

		internal static void Initialize(ConfigFile cfg)
		{
			//IL_0026: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			RenderExpanders = cfg.Bind<bool>("General", "RenderExpanders", false, "Show LG_AreaExpander visually when in the map.");
			ExpanderColorHex = cfg.Bind<string>("General", "ExpanderColor", ToHex(Color.white), "Color of expanders text");
			AreaTextColorHex = cfg.Bind<string>("General", "AreaTextColor", ToHex(new Color(255f, 0f, 127f)), "Color of area text");
			ExpanderColor = ParseColor(ExpanderColorHex.Value, Color.white);
			AreaTextColor = ParseColor(AreaTextColorHex.Value, new Color(255f, 0f, 127f));
		}

		private static Color ParseColor(string hex, Color fallback)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Color result = default(Color);
			if (!ColorUtility.TryParseHtmlString(hex, ref result))
			{
				return fallback;
			}
			return result;
		}

		private static string ToHex(Color color)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return "#" + ColorUtility.ToHtmlStringRGB(color);
		}
	}
	internal class SpawnDefault
	{
		public static void SpawnSchema()
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string text = null;
			string[] manifestResourceNames = executingAssembly.GetManifestResourceNames();
			foreach (string text2 in manifestResourceNames)
			{
				if (text2.EndsWith("schema.json"))
				{
					text = text2;
					break;
				}
			}
			if (text == null)
			{
				throw new FileNotFoundException("Embedded resource 'schema.json' not found.");
			}
		}
	}
}