Decompiled source of MapHexApi v1.0.0

BepInEx/plugins/MapHexAPI/MapHexAPI.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using FishNet.Connection;
using FishNet.Managing;
using FishNet.Object;
using HarmonyLib;
using MapHexAPI.Utils;
using UnityEngine;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MapHexAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MapHexAPI")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("08322e6f-6f45-402b-ac42-7ba42492d22d")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace MapHexAPI
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("com.magearena.MapHexAPI", "MapHexAPI", "1.0.0")]
	public class MapHexAPIPlugin : BaseUnityPlugin
	{
		public static string modsync = "all";

		private const string MyGUID = "com.magearena.MapHexApi";

		private const string PluginName = "MapHexApi";

		private const string VersionString = "1.0.0";

		public static GameObject TemplateHexMaterial;

		private static readonly Harmony Harmony = new Harmony("com.magearena.MapHexApi");

		public static ManualLogSource Log;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Log.LogInfo((object)"MapHexAPI initializing...");
			HexRegistry.Initialize(Log);
			AssetLoader.Initialize(Log);
			Harmony.PatchAll();
			SceneManager.sceneLoaded += OnSceneLoaded;
			Log.LogInfo((object)"MapHexAPI initialized successfully");
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			Log.LogDebug((object)("Scene loaded: " + ((Scene)(ref scene)).name));
			HexRegistry.RegisterPrefabsWithNetwork();
		}

		private void OnDestroy()
		{
			AssetLoader.UnloadAllAssets();
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}
	}
	public static class HexRegistry
	{
		public class HexDefinition
		{
			public GameObject Prefab { get; set; }

			public Material MapIcon { get; set; }

			public string DisplayName { get; set; }

			public int HexType { get; set; }

			public List<MonoBehaviour> Components { get; set; } = new List<MonoBehaviour>();


			public List<NetworkBehaviour> NetworkComponents { get; set; } = new List<NetworkBehaviour>();


			public bool IsValid { get; set; }
		}

		private static readonly Dictionary<int, HexDefinition> _hexes = new Dictionary<int, HexDefinition>();

		private static ManualLogSource _log;

		private static int _nextHexType = 9;

		public static void Initialize(ManualLogSource logger)
		{
			_log = logger;
		}

		public static int RegisterHex(GameObject prefab, Material mapIcon, string displayName = null, List<MonoBehaviour> components = null, List<NetworkBehaviour> netcomponents = null)
		{
			try
			{
				int num = _nextHexType++;
				HexDefinition value = new HexDefinition
				{
					Prefab = prefab,
					MapIcon = mapIcon,
					DisplayName = (displayName ?? $"Custom Hex {num}"),
					Components = (components ?? new List<MonoBehaviour>()),
					NetworkComponents = (netcomponents ?? new List<NetworkBehaviour>()),
					HexType = num,
					IsValid = ((Object)(object)prefab != (Object)null && (Object)(object)mapIcon != (Object)null)
				};
				_hexes[num] = value;
				_log.LogInfo((object)$"Registered hex type {num}: {displayName}");
				_log.LogDebug((object)("Prefab: " + ((Object)prefab).name + ", Icon: " + (((mapIcon != null) ? ((Object)mapIcon).name : null) ?? "None")));
				return num;
			}
			catch (Exception arg)
			{
				_log.LogError((object)$"Error registering hex: {arg}");
				return -1;
			}
		}

		public static bool TryGetHex(int hexType, out HexDefinition definition)
		{
			return _hexes.TryGetValue(hexType, out definition);
		}

		public static void Reset()
		{
			_hexes.Clear();
		}

		public static IEnumerable<HexDefinition> GetAllHexes()
		{
			return _hexes.Values;
		}

		public static void RegisterPrefabsWithNetwork()
		{
			HashSet<string> hashSet = new HashSet<string>();
			foreach (HexDefinition value in _hexes.Values)
			{
				if ((Object)(object)value.Prefab != (Object)null)
				{
					string name = ((Object)value.Prefab).name;
					if (!hashSet.Contains(name))
					{
						AssetLoader.RegisterPrefabWithNetworkManager(value.Prefab);
						hashSet.Add(name);
					}
				}
			}
		}
	}
}
namespace MapHexAPI.Utils
{
	public static class AssetLoader
	{
		private static readonly Dictionary<string, AssetBundle> _bundles = new Dictionary<string, AssetBundle>();

		private static ManualLogSource _log;

		public static void Initialize(ManualLogSource logger)
		{
			_log = logger;
		}

		public static GameObject LoadPrefabFromBundle(string bundlePath, string assetName)
		{
			try
			{
				if (!File.Exists(bundlePath))
				{
					_log.LogError((object)("Bundle not found: " + bundlePath));
					return null;
				}
				if (!_bundles.TryGetValue(bundlePath, out var value))
				{
					value = AssetBundle.LoadFromFile(bundlePath);
					if ((Object)(object)value == (Object)null)
					{
						_log.LogError((object)"Failed to load bundle");
						return null;
					}
					_bundles[bundlePath] = value;
				}
				GameObject val = value.LoadAsset<GameObject>(assetName);
				if ((Object)(object)val == (Object)null)
				{
					_log.LogError((object)("Prefab '" + assetName + "' not found in bundle"));
					return null;
				}
				EnsureNetworkObject(val);
				return val;
			}
			catch (Exception arg)
			{
				_log.LogError((object)$"Error loading prefab: {arg}");
				return null;
			}
		}

		public static Texture2D LoadTexture(string path)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			try
			{
				if (!File.Exists(path))
				{
					_log.LogError((object)("Texture not found: " + path));
					return null;
				}
				byte[] array = File.ReadAllBytes(path);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, array))
				{
					_log.LogError((object)("Failed to load texture frdom file: " + path));
					return null;
				}
				((Object)val).name = Path.GetFileNameWithoutExtension(path);
				return val;
			}
			catch (Exception arg)
			{
				_log.LogError((object)$"Error loading texture: {arg}");
				return null;
			}
		}

		public static Material CreateMaterial(Texture2D texture, Shader shader = null)
		{
			//IL_001d: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			if ((Object)(object)texture == (Object)null)
			{
				return null;
			}
			shader = shader ?? Shader.Find("HDRP/Decal");
			Material val = new Material(shader)
			{
				mainTexture = (Texture)(object)texture
			};
			val.SetTexture("_BaseColor", (Texture)(object)texture);
			return val;
		}

		public static Material CreateDecalMaterial(Texture2D texture)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)texture == (Object)null)
			{
				MapHexAPIPlugin.Log.LogWarning((object)"Texture is null when creating decal material - using default white texture");
				texture = new Texture2D(2, 2);
				texture.SetPixels((Color[])(object)new Color[4]
				{
					Color.white,
					Color.white,
					Color.white,
					Color.white
				});
				texture.Apply();
			}
			Shader val = Shader.Find("HDRP/Decal");
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Universal Render Pipeline/Decal");
				if ((Object)(object)val == (Object)null)
				{
					val = Shader.Find("Standard");
					MapHexAPIPlugin.Log.LogWarning((object)"Decal shader not found! Using Standard shader as fallback");
				}
			}
			Material val2 = new Material(val ?? Shader.Find("Standard"));
			try
			{
				((Object)val2).name = ((Object)texture).name + "_Material";
				val2.mainTexture = (Texture)(object)texture;
				if ((Object)(object)val != (Object)null && ((Object)val).name.Contains("Decal"))
				{
					val2.SetTexture("_BaseColorMap", (Texture)(object)texture);
					val2.SetColor("_BaseColor", Color.white);
					val2.SetFloat("_NormalBlendSrc", 1f);
					val2.enableInstancing = true;
					val2.SetFloat("_DecalBlend", 1f);
					val2.SetInt("_DecalMeshBiasType", 1);
					val2.SetInt("_PassCount", 4);
					val2.renderQueue = 2003;
					val2.SetInt("_RawRenderQueue", 2003);
					val2.SetFloat("_EmissiveIsBlack", 1f);
					val2.EnableKeyword("_COLORMAP");
					val2.EnableKeyword("_MATERIAL_AFFECTS_ALBEDO");
					val2.EnableKeyword("_DISABLE_SSR_TRANSPARENT");
					val2.EnableKeyword("_NORMALMAP_TANGENT_SPACE");
				}
				else
				{
					val2.SetFloat("_Mode", 1f);
					val2.SetInt("_SrcBlend", 5);
					val2.SetInt("_DstBlend", 10);
					val2.SetInt("_ZWrite", 0);
					val2.EnableKeyword("_ALPHATEST_ON");
					val2.renderQueue = 2450;
				}
			}
			catch (Exception ex)
			{
				MapHexAPIPlugin.Log.LogError((object)("Error confidguring decal material: " + ex.Message));
			}
			return val2;
		}

		public static bool RegisterPrefabWithNetworkManager(GameObject prefab)
		{
			try
			{
				NetworkManager val = Object.FindFirstObjectByType<NetworkManager>();
				if ((Object)(object)val == (Object)null)
				{
					_log.LogError((object)"NetworkManager not found");
					return false;
				}
				NetworkObject component = prefab.GetComponent<NetworkObject>();
				if ((Object)(object)component == (Object)null)
				{
					_log.LogError((object)"Prefab has no NetworkObject");
					return false;
				}
				val.SpawnablePrefabs.AddObject(component, true);
				_log.LogInfo((object)("Registered prefab: " + ((Object)prefab).name));
				return true;
			}
			catch (Exception arg)
			{
				_log.LogError((object)$"Error registering prefab: {arg}");
				return false;
			}
		}

		private static void EnsureNetworkObject(GameObject prefab)
		{
			if ((Object)(object)prefab.GetComponent<NetworkObject>() == (Object)null)
			{
				prefab.AddComponent<NetworkObject>();
				_log.LogDebug((object)"Added NetworkObject to prefab");
			}
		}

		public static void UnloadAllAssets()
		{
			foreach (AssetBundle value in _bundles.Values)
			{
				value.Unload(true);
			}
			_bundles.Clear();
			_log.LogInfo((object)"Unloaded all assets");
		}
	}
	internal static class Helper
	{
		internal static Dictionary<string, Sprite> CachedSprites = new Dictionary<string, Sprite>();

		public static Sprite LoadSpriteFromDisk(string path, float pixelsPerUnit = 1f)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (CachedSprites.TryGetValue(path + pixelsPerUnit, out var value))
				{
					return value;
				}
				Texture2D val = LoadTextureFromDisk(path);
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				value = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), pixelsPerUnit);
				Sprite obj = value;
				((Object)obj).hideFlags = (HideFlags)(((Object)obj).hideFlags | 0x3D);
				return CachedSprites[path + pixelsPerUnit] = value;
			}
			catch (Exception ex)
			{
				MapHexAPIPlugin.Log.LogError((object)ex);
				return null;
			}
		}

		public static Texture2D LoadTextureFromDisk(string path)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			try
			{
				if (File.Exists(path))
				{
					Texture2D val = new Texture2D(2, 2, (TextureFormat)5, false);
					byte[] array = File.ReadAllBytes(path);
					if (ImageConversion.LoadImage(val, array, false))
					{
						return val;
					}
					MapHexAPIPlugin.Log.LogError((object)"Failed to load image data into texture.");
				}
				else
				{
					MapHexAPIPlugin.Log.LogError((object)("File does not exist: " + path));
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = MapHexAPIPlugin.Log;
				string text = "Exception while loading texture: ";
				log.LogError((object)(text + ex));
			}
			return null;
		}

		public static Sprite LoadSpriteFromResources(this Assembly assembly, string path, float pixelsPerUnit = 1f)
		{
			//IL_004d: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (CachedSprites.TryGetValue(path + pixelsPerUnit, out var value))
				{
					return value;
				}
				Texture2D val = assembly.LoadTextureFromResources(path);
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				value = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), pixelsPerUnit);
				Sprite obj = value;
				((Object)obj).hideFlags = (HideFlags)(((Object)obj).hideFlags | 0x3D);
				return CachedSprites[path + pixelsPerUnit] = value;
			}
			catch (Exception ex)
			{
				MapHexAPIPlugin.Log.LogError((object)ex);
				return null;
			}
		}

		public static Texture2D LoadTextureFromResources(this Assembly assembly, string path)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			try
			{
				Stream manifestResourceStream = assembly.GetManifestResourceStream(path);
				if (manifestResourceStream == null)
				{
					return null;
				}
				Texture2D val = new Texture2D(1, 1, (TextureFormat)5, false);
				using (MemoryStream memoryStream = new MemoryStream())
				{
					manifestResourceStream.CopyTo(memoryStream);
					if (!ImageConversion.LoadImage(val, memoryStream.ToArray(), false))
					{
						return null;
					}
				}
				return val;
			}
			catch (Exception ex)
			{
				MapHexAPIPlugin.Log.LogError((object)ex);
				return null;
			}
		}

		public static Material CreateMaterialFromPng(string pngPath, string shaderName = "HDRP/Decal")
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if (string.IsNullOrEmpty(pngPath) || !File.Exists(pngPath))
			{
				throw new ArgumentException("Ungültiger PNG-Pfad.", "pngPath");
			}
			byte[] array = File.ReadAllBytes(pngPath);
			Texture2D val = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(val, array))
			{
				throw new Exception("PNG konnte nicht als Textur geladen werden.");
			}
			Shader obj = Shader.Find(shaderName);
			if ((Object)(object)obj == (Object)null)
			{
				throw new Exception("Shader '" + shaderName + "' nicht gefunden.");
			}
			Material val2 = new Material(obj);
			val2.SetTexture("_BaseColorMap", (Texture)(object)val);
			return val2;
		}
	}
}
namespace MapHexAPI.Patches
{
	[HarmonyPatch(typeof(DungeonGenerator))]
	public static class DungeonGeneratorPatches
	{
		[CompilerGenerated]
		private sealed class <CustomGenerateMap>d__7 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public DungeonGenerator instance;

			private Traverse<bool> <prevHexSpawned>5__2;

			private Traverse<bool[]> <occupiedHexes>5__3;

			private Traverse<bool> <dungeonPlaced>5__4;

			private Traverse<bool> <hexesPlaced>5__5;

			private List<int> <hexTypes>5__6;

			private int <i>5__7;

			private bool <isDungeon>5__8;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <CustomGenerateMap>d__7(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || (uint)(num - 1) <= 1u)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<prevHexSpawned>5__2 = null;
				<occupiedHexes>5__3 = null;
				<dungeonPlaced>5__4 = null;
				<hexesPlaced>5__5 = null;
				<hexTypes>5__6 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
					{
						<>1__state = -1;
						<prevHexSpawned>5__2 = Traverse.Create((object)instance).Field<bool>("PrevHexSpawned");
						<occupiedHexes>5__3 = Traverse.Create((object)instance).Field<bool[]>("OccupiedHexes");
						<dungeonPlaced>5__4 = Traverse.Create((object)instance).Field<bool>("dungeonPlaced");
						<hexesPlaced>5__5 = Traverse.Create((object)instance).Field<bool>("HexesPlaced");
						<>1__state = -3;
						_largeMapRPC(instance);
						for (int i = 0; i < instance.ToggledDeformers.Length; i++)
						{
							instance.ToggledDeformers[i].SetActive(i < 4);
						}
						if (Random.Range(0, 100) < 33)
						{
							_placeMountain(instance);
							goto IL_0114;
						}
						goto IL_012d;
					}
					case 1:
						<>1__state = -3;
						goto IL_0114;
					case 2:
						{
							<>1__state = -3;
							goto IL_02a7;
						}
						IL_012d:
						<hexTypes>5__6 = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7 };
						foreach (HexRegistry.HexDefinition allHex in HexRegistry.GetAllHexes())
						{
							<hexTypes>5__6.Add(allHex.HexType);
						}
						for (int num = <hexTypes>5__6.Count - 1; num > 0; num--)
						{
							int num2 = Random.Range(0, num + 1);
							List<int> list = <hexTypes>5__6;
							int index = num;
							List<int> list2 = <hexTypes>5__6;
							int index2 = num2;
							int value = <hexTypes>5__6[num2];
							int value2 = <hexTypes>5__6[num];
							list[index] = value;
							list2[index2] = value2;
						}
						<i>5__7 = 0;
						goto IL_02ed;
						IL_02a7:
						if (!<prevHexSpawned>5__2.Value && (!<isDungeon>5__8 || !instance.isDungeonGenerated))
						{
							<>2__current = null;
							<>1__state = 2;
							return true;
						}
						<prevHexSpawned>5__2.Value = false;
						goto IL_02db;
						IL_0114:
						if (!<prevHexSpawned>5__2.Value)
						{
							<>2__current = null;
							<>1__state = 1;
							return true;
						}
						<prevHexSpawned>5__2.Value = false;
						goto IL_012d;
						IL_02db:
						<i>5__7++;
						goto IL_02ed;
						IL_02ed:
						if (<i>5__7 < <occupiedHexes>5__3.Value.Length)
						{
							if (!<occupiedHexes>5__3.Value[<i>5__7])
							{
								int num3 = <hexTypes>5__6[<i>5__7];
								<isDungeon>5__8 = num3 == 3;
								if (<isDungeon>5__8)
								{
									<dungeonPlaced>5__4.Value = true;
								}
								_serverPlaceHex(instance, num3, <i>5__7);
								goto IL_02a7;
							}
							goto IL_02db;
						}
						<hexesPlaced>5__5.Value = true;
						for (int j = 0; j < <occupiedHexes>5__3.Value.Length; j++)
						{
							<occupiedHexes>5__3.Value[j] = false;
						}
						<hexTypes>5__6 = null;
						<>m__Finally1();
						return false;
					}
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				activeCoroutines.Remove(instance);
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[CompilerGenerated]
		private sealed class <CustomGenerateSmallMap>d__9 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public DungeonGenerator instance;

			private Traverse<bool> <prevHexSpawned>5__2;

			private Traverse<bool[]> <occupiedHexes>5__3;

			private Traverse<bool> <dungeonPlaced>5__4;

			private Traverse<bool> <hexesPlaced>5__5;

			private int <numloothexes>5__6;

			private List<int> <hexTypes>5__7;

			private int <i>5__8;

			private bool <isDungeon>5__9;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <CustomGenerateSmallMap>d__9(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<prevHexSpawned>5__2 = null;
				<occupiedHexes>5__3 = null;
				<dungeonPlaced>5__4 = null;
				<hexesPlaced>5__5 = null;
				<hexTypes>5__7 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					int num = <>1__state;
					if (num != 0)
					{
						if (num != 1)
						{
							return false;
						}
						<>1__state = -3;
						goto IL_0303;
					}
					<>1__state = -1;
					<prevHexSpawned>5__2 = Traverse.Create((object)instance).Field<bool>("PrevHexSpawned");
					<occupiedHexes>5__3 = Traverse.Create((object)instance).Field<bool[]>("OccupiedHexes");
					<dungeonPlaced>5__4 = Traverse.Create((object)instance).Field<bool>("dungeonPlaced");
					<hexesPlaced>5__5 = Traverse.Create((object)instance).Field<bool>("HexesPlaced");
					<>1__state = -3;
					_smallMapRPC(instance);
					<numloothexes>5__6 = 0;
					<occupiedHexes>5__3.Value[0] = true;
					<occupiedHexes>5__3.Value[6] = true;
					<hexTypes>5__7 = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7 };
					foreach (HexRegistry.HexDefinition allHex in HexRegistry.GetAllHexes())
					{
						<hexTypes>5__7.Add(allHex.HexType);
					}
					for (int num2 = <hexTypes>5__7.Count - 1; num2 > 0; num2--)
					{
						int num3 = Random.Range(0, num2 + 1);
						List<int> list = <hexTypes>5__7;
						int index = num2;
						List<int> list2 = <hexTypes>5__7;
						int index2 = num3;
						int value = <hexTypes>5__7[num3];
						int value2 = <hexTypes>5__7[num2];
						list[index] = value;
						list2[index2] = value2;
					}
					<i>5__8 = 0;
					goto IL_0349;
					IL_0349:
					if (<i>5__8 < <occupiedHexes>5__3.Value.Length)
					{
						if (!<occupiedHexes>5__3.Value[<i>5__8])
						{
							int num4 = <hexTypes>5__7[<i>5__8];
							bool flag = num4 == 0 || num4 == 3 || num4 == 5;
							if (flag)
							{
								<numloothexes>5__6++;
							}
							if (<numloothexes>5__6 > 2 && flag)
							{
								foreach (int item in <hexTypes>5__7)
								{
									if (item != 0 && item != 3 && item != 5)
									{
										num4 = item;
										break;
									}
								}
							}
							else if (<numloothexes>5__6 < 2 && <i>5__8 == 5)
							{
								if (<hexTypes>5__7.Contains(5))
								{
									num4 = 5;
								}
								else if (<hexTypes>5__7.Contains(0))
								{
									num4 = 0;
								}
								else if (<hexTypes>5__7.Contains(3))
								{
									num4 = 3;
								}
							}
							<isDungeon>5__9 = num4 == 3;
							if (<isDungeon>5__9)
							{
								<dungeonPlaced>5__4.Value = true;
							}
							_serverPlaceHex(instance, num4, <i>5__8);
							goto IL_0303;
						}
						goto IL_0337;
					}
					<hexesPlaced>5__5.Value = true;
					for (int i = 0; i < <occupiedHexes>5__3.Value.Length; i++)
					{
						<occupiedHexes>5__3.Value[i] = false;
					}
					<hexTypes>5__7 = null;
					<>m__Finally1();
					return false;
					IL_0303:
					if (!<prevHexSpawned>5__2.Value && (!<isDungeon>5__9 || !instance.isDungeonGenerated))
					{
						<>2__current = null;
						<>1__state = 1;
						return true;
					}
					<prevHexSpawned>5__2.Value = false;
					goto IL_0337;
					IL_0337:
					<i>5__8++;
					goto IL_0349;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				activeCoroutines.Remove(instance);
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private static Dictionary<DungeonGenerator, IEnumerator> activeCoroutines = new Dictionary<DungeonGenerator, IEnumerator>();

		private static Action<DungeonGenerator> _largeMapRPC;

		private static Action<DungeonGenerator> _smallMapRPC;

		private static Action<DungeonGenerator> _placeMountain;

		private static Action<DungeonGenerator, int, int> _serverPlaceHex;

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void ExtendHexArrays(DungeonGenerator __instance)
		{
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			try
			{
				Traverse<bool> val = Traverse.Create((object)__instance).Field<bool>("__hexArraysExtended");
				if (val.Value)
				{
					MapHexAPIPlugin.Log.LogInfo((object)"[DEBUG] Arrays already extended for this instance. Skipping.");
					return;
				}
				FieldInfo fieldInfo = AccessTools.Field(typeof(DungeonGenerator), "Hexes");
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(DungeonGenerator), "hexmapicons");
				FieldInfo fieldInfo3 = AccessTools.Field(typeof(DungeonGenerator), "mapicons");
				GameObject[] array = (GameObject[])fieldInfo.GetValue(__instance);
				Material[] array2 = (Material[])fieldInfo2.GetValue(__instance);
				DecalProjector[] array3 = (DecalProjector[])fieldInfo3.GetValue(__instance);
				List<HexRegistry.HexDefinition> list = HexRegistry.GetAllHexes().ToList();
				int num = Math.Max(array.Length - 1, list.Max((HexRegistry.HexDefinition h) => h.HexType));
				GameObject[] array4 = (GameObject[])(object)new GameObject[num + 1];
				Material[] array5 = (Material[])(object)new Material[num + 1];
				DecalProjector[] array6 = (DecalProjector[])(object)new DecalProjector[array3.Length];
				Array.Copy(array, array4, array.Length);
				Array.Copy(array2, array5, array2.Length);
				Array.Copy(array3, array6, array3.Length);
				foreach (HexRegistry.HexDefinition item in list)
				{
					int hexType = item.HexType;
					if (hexType < array4.Length)
					{
						if ((Object)(object)array4[hexType] != (Object)null)
						{
							ManualLogSource log = MapHexAPIPlugin.Log;
							string[] obj = new string[6]
							{
								$"Overwriting existing hex at type {hexType} ",
								"(Old: ",
								null,
								null,
								null,
								null
							};
							GameObject obj2 = array4[hexType];
							obj[2] = ((obj2 != null) ? ((Object)obj2).name : null) ?? "NULL";
							obj[3] = ", New: ";
							GameObject prefab = item.Prefab;
							obj[4] = ((prefab != null) ? ((Object)prefab).name : null) ?? "NULL";
							obj[5] = ")";
							log.LogWarning((object)string.Concat(obj));
						}
						array4[hexType] = item.Prefab;
						if ((Object)(object)item.MapIcon == (Object)null)
						{
							Texture2D texture = new Texture2D(2, 2);
							item.MapIcon = AssetLoader.CreateDecalMaterial(texture);
							MapHexAPIPlugin.Log.LogWarning((object)$"Created default decal material for hex type {hexType}");
						}
						Material val2 = new Material(Shader.Find("HDRP/Decal"));
						((Object)val2).name = ((Object)item.Prefab).name + "_Icon";
						val2.CopyPropertiesFromMaterial(array5[0]);
						val2.mainTexture = item.MapIcon.mainTexture;
						array5[hexType] = val2;
					}
					else
					{
						MapHexAPIPlugin.Log.LogError((object)$"HexType {hexType} is out of bounds for array (max: {array4.Length - 1})");
					}
				}
				fieldInfo.SetValue(__instance, array4);
				fieldInfo2.SetValue(__instance, array5);
				fieldInfo3.SetValue(__instance, array6);
				val.Value = true;
				MapHexAPIPlugin.Log.LogInfo((object)$"Extended arrays to {array4.Length} hexes and {array5.Length} icons");
			}
			catch (Exception ex)
			{
				MapHexAPIPlugin.Log.LogError((object)("Array extension failed: " + ex.Message + "\n" + ex.StackTrace));
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("GenerateMap")]
		private static bool GenerateMapPrefix(DungeonGenerator __instance, ref IEnumerator __result)
		{
			if (activeCoroutines.TryGetValue(__instance, out var value))
			{
				__result = value;
				return false;
			}
			if (_largeMapRPC == null)
			{
				_largeMapRPC = AccessTools.MethodDelegate<Action<DungeonGenerator>>(AccessTools.Method(typeof(DungeonGenerator), "LargeMapRPC", (Type[])null, (Type[])null), (object)null, true);
			}
			if (_placeMountain == null)
			{
				_placeMountain = AccessTools.MethodDelegate<Action<DungeonGenerator>>(AccessTools.Method(typeof(DungeonGenerator), "PlaceMountain", (Type[])null, (Type[])null), (object)null, true);
			}
			if (_serverPlaceHex == null)
			{
				_serverPlaceHex = AccessTools.MethodDelegate<Action<DungeonGenerator, int, int>>(AccessTools.Method(typeof(DungeonGenerator), "ServerPlaceHex", (Type[])null, (Type[])null), (object)null, true);
			}
			value = CustomGenerateMap(__instance);
			activeCoroutines[__instance] = value;
			__result = value;
			return false;
		}

		[IteratorStateMachine(typeof(<CustomGenerateMap>d__7))]
		private static IEnumerator CustomGenerateMap(DungeonGenerator instance)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <CustomGenerateMap>d__7(0)
			{
				instance = instance
			};
		}

		[HarmonyPrefix]
		[HarmonyPatch("GenerateSmallMap")]
		private static bool GenerateSmallMapPrefix(DungeonGenerator __instance, ref IEnumerator __result)
		{
			if (activeCoroutines.TryGetValue(__instance, out var value))
			{
				__result = value;
				return false;
			}
			if (_smallMapRPC == null)
			{
				_smallMapRPC = AccessTools.MethodDelegate<Action<DungeonGenerator>>(AccessTools.Method(typeof(DungeonGenerator), "SmallMapRPC", (Type[])null, (Type[])null), (object)null, true);
			}
			if (_serverPlaceHex == null)
			{
				_serverPlaceHex = AccessTools.MethodDelegate<Action<DungeonGenerator, int, int>>(AccessTools.Method(typeof(DungeonGenerator), "ServerPlaceHex", (Type[])null, (Type[])null), (object)null, true);
			}
			value = CustomGenerateSmallMap(__instance);
			activeCoroutines[__instance] = value;
			__result = value;
			return false;
		}

		[IteratorStateMachine(typeof(<CustomGenerateSmallMap>d__9))]
		private static IEnumerator CustomGenerateSmallMap(DungeonGenerator instance)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <CustomGenerateSmallMap>d__9(0)
			{
				instance = instance
			};
		}

		[HarmonyPrefix]
		[HarmonyPatch("ServerPlaceHex")]
		private static bool HandleCustomHexSpawn(DungeonGenerator __instance, int HexType, int hexindex, ref bool __runOriginal)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			if (!__runOriginal)
			{
				return false;
			}
			if (!HexRegistry.TryGetHex(HexType, out var definition))
			{
				return true;
			}
			try
			{
				Transform[] array = (Transform[])AccessTools.Field(typeof(DungeonGenerator), "HexPoints").GetValue(__instance);
				if (array == null || hexindex >= array.Length)
				{
					MapHexAPIPlugin.Log.LogError((object)"Invalid hex points array or index");
					return true;
				}
				if ((Object)(object)definition.Prefab == (Object)null)
				{
					MapHexAPIPlugin.Log.LogInfo((object)$"Prefab is null for hex type {HexType}");
					return true;
				}
				if ((Object)(object)definition.MapIcon == (Object)null)
				{
					MapHexAPIPlugin.Log.LogWarning((object)$"Creating temporary decal material for hex type {HexType}");
					definition.MapIcon = AssetLoader.CreateDecalMaterial(Texture2D.whiteTexture);
				}
				GameObject val = Object.Instantiate<GameObject>(definition.Prefab, array[hexindex].position, Quaternion.identity);
				NetworkObject networkObject = ((NetworkBehaviour)__instance).NetworkObject;
				if ((Object)(object)((networkObject != null) ? networkObject.ServerManager : null) != (Object)null)
				{
					((NetworkBehaviour)__instance).NetworkObject.ServerManager.Spawn(val, (NetworkConnection)null, default(Scene));
					AccessTools.Method(typeof(DungeonGenerator), "updatemap", (Type[])null, (Type[])null).Invoke(__instance, new object[2] { HexType, hexindex });
					Traverse.Create((object)__instance).Field("PrevHexSpawned").SetValue((object)true);
					__runOriginal = false;
					return false;
				}
				Object.Destroy((Object)(object)val);
				return true;
			}
			catch (Exception arg)
			{
				MapHexAPIPlugin.Log.LogError((object)$"Error spawning custom hex: {arg}");
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(DungeonGenerator))]
	internal class MapIconPatches
	{
	}
}