Decompiled source of EuropeReskin v1.0.0

BepInEx/plugins/Civ.Europereskin/Civ.Europereskin.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DiceKingdoms.Game;
using DiceKingdoms.Interface;
using DiceModders.ModCore;
using DiceModders.ModCore.Tools;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DiceModders")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Half-timbered buildings and restyled units for Europe. Visual only, switchable in game.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Civ.Europereskin")]
[assembly: AssemblyTitle("Civ.Europereskin")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.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;
		}
	}
}
namespace DiceKingdoms.CivTemplate
{
	internal static class CivBuilder
	{
		private sealed record Picture(Il2CppReferenceArray<Sprite> Original, GameObject Copy, Action<Il2CppReferenceArray<Sprite>> Set, bool Unit);

		internal static ModCivilization Civ;

		internal static CivilizationSkins Skins;

		internal static int Id;

		internal static string SheetName;

		private static TechTree _tree;

		private static bool _treeTried;

		public static void Register()
		{
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			TextSet val = Texts.Load("civ.json", "texts");
			string text = (val.Has("civilization.name") ? val.Get("civilization.name", "en") : Data.Token);
			if (Data.Reskin)
			{
				Id = Data.LookId;
				Skins = Civilizations.Reskin(Id);
				if (Data.HasTree)
				{
					Civilizations.ReplaceTree(Id, (Func<TechTree>)Tree, Data.Key + ".tree", text + ": tech tree", "Uses the " + text + " tech tree layout for " + Data.LookWord + ". Only when every player has the mod.");
				}
				if (Data.HasUnitStats)
				{
					Data.W("WARN unitStats are left out in a reskin (they would change the game for one player only)");
				}
			}
			else
			{
				Civ = Civilizations.Add(Data.Key, text, Data.HasTree ? new Func<TechTree>(Tree) : null, Data.LookId);
				Id = Civ.Id;
				Skins = Civ.Skins;
				Data.ApplyUnitStats(Civ);
				string text2 = Data.Resource("build_orders.txt");
				if (text2 != null)
				{
					Data.W(Civilizations.AddBuildOrders(Civ.Id, text2) + " AI build orders read");
				}
			}
			SheetName = text + " Text";
			if (!Data.Reskin)
			{
				Civilizations.SetTexts(Id, val);
			}
			foreach (var (num, num2, val2) in Data.GroundCells)
			{
				Skins.GroundColour(num, num2, val2);
			}
			foreach (var (num3, num4, val3) in Data.NatureCells)
			{
				Skins.NatureColour(num3, num4, val3);
			}
			foreach (var (num5, num6, val4) in Data.HillCells)
			{
				Skins.HillColour(num5, num6, val4);
			}
			TextureCache.Prefetch(new string[1] { SheetName });
			DiskCache.Prefetch(DiskCache.FilesOf(Models.CacheFolder));
			Civilizations.WhenGameDataLoaded((Action)Build);
			Data.W(Data.Reskin ? ("'" + text + "' restyles " + Data.LookEnum + " (reskin, key " + Data.Key + ")") : ("'" + text + "' registered as civilization " + Civ.Id + " (key " + Data.Key + ", looks like " + Data.LookEnum + ")"));
		}

		private static TechTree Tree()
		{
			if (_treeTried)
			{
				return _tree;
			}
			_treeTried = true;
			try
			{
				_tree = CivTree.BuildCopy();
			}
			catch (Exception ex)
			{
				Data.Once("tree", "tech tree FAIL " + ex);
			}
			return _tree;
		}

		private static void Build()
		{
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Expected I4, but got Unknown
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			DateTime now = DateTime.Now;
			Il2CppArrayBase<SkinRegistry> val = Resources.FindObjectsOfTypeAll<SkinRegistry>();
			if (val.Length == 0)
			{
				Data.W("no skin registry");
				return;
			}
			PlayerSkins val2 = new PlayerSkins((Civilization)Data.LookId, val[0]);
			string value = "-" + Swapper.Kebab(Data.LookWord);
			Dictionary<IntPtr, Ragdoll> dictionary = new Dictionary<IntPtr, Ragdoll>();
			foreach (Ragdoll item in Resources.FindObjectsOfTypeAll<Ragdoll>())
			{
				Scene scene = ((Component)item).gameObject.scene;
				if (!((Scene)(ref scene)).IsValid() && ((Object)((Component)item).gameObject).name.EndsWith(value, StringComparison.Ordinal))
				{
					Ragdoll val3 = Prefabs.Copy<Ragdoll>(item, (string)null);
					Swapper.Other(((Component)val3).gameObject, "civ");
					dictionary[((Il2CppObjectBase)item).Pointer] = val3;
				}
			}
			int num = 0;
			int num2 = 0;
			Dictionary<IntPtr, BuildingVisual> dictionary2 = new Dictionary<IntPtr, BuildingVisual>();
			List<Picture> list = new List<Picture>();
			Il2CppArrayBase<BuildingTypes> val4 = Resources.FindObjectsOfTypeAll<BuildingTypes>();
			if (val4.Length == 0)
			{
				Data.W("no BuildingTypes asset");
				return;
			}
			foreach (BuildingType item2 in (Il2CppArrayBase<BuildingType>)(object)val4[0].Types)
			{
				if (item2 == null)
				{
					continue;
				}
				BuildingVisual buildingVisualPrefab;
				try
				{
					buildingVisualPrefab = val2.GetBuildingVisualPrefab(item2);
				}
				catch
				{
					continue;
				}
				if ((Object)(object)buildingVisualPrefab == (Object)null || !Swapper.BaseName(((Object)((Component)buildingVisualPrefab).gameObject).name).EndsWith(" " + Data.LookWord, StringComparison.Ordinal))
				{
					continue;
				}
				try
				{
					if (!dictionary2.TryGetValue(((Il2CppObjectBase)buildingVisualPrefab).Pointer, out var value2))
					{
						value2 = Prefabs.Copy<BuildingVisual>(buildingVisualPrefab, (string)null);
						Swapper.Building(value2, "civ");
						Relink(((Component)value2).gameObject, dictionary);
						dictionary2[((Il2CppObjectBase)buildingVisualPrefab).Pointer] = value2;
						BuildingVisual c = value2;
						if (HasModel(buildingVisualPrefab))
						{
							list.Add(new Picture(buildingVisualPrefab.icons, ((Component)value2).gameObject, delegate(Il2CppReferenceArray<Sprite> s)
							{
								c.icons = s;
							}, Unit: false));
						}
					}
					Skins.Building(item2.name, value2);
					num++;
				}
				catch (Exception ex)
				{
					Data.W("building " + ((object)item2.name/*cast due to .constrained prefix*/).ToString() + " FAIL (keeps the look-alike's): " + ex.Message);
				}
			}
			foreach (Type value3 in Enum.GetValues(typeof(Type)))
			{
				UnitVisual unitVisualPrefab;
				try
				{
					unitVisualPrefab = val2.GetUnitVisualPrefab(value3);
				}
				catch
				{
					continue;
				}
				if ((Object)(object)unitVisualPrefab == (Object)null)
				{
					continue;
				}
				try
				{
					UnitVisual copy = Prefabs.Copy<UnitVisual>(unitVisualPrefab, (string)null);
					Swapper.Other(((Component)copy).gameObject, "civ");
					Relink(((Component)copy).gameObject, dictionary);
					if (Models.Exists(Swapper.Kebab(((object)value3/*cast due to .constrained prefix*/).ToString())))
					{
						list.Add(new Picture(unitVisualPrefab.icons, ((Component)copy).gameObject, delegate(Il2CppReferenceArray<Sprite> s)
						{
							copy.icons = s;
						}, Unit: true));
					}
					Skins.Unit((int)value3, copy);
					num2++;
				}
				catch (Exception ex2)
				{
					Data.W("unit " + ((object)value3/*cast due to .constrained prefix*/).ToString() + " FAIL (keeps the look-alike's): " + ex2.Message);
				}
			}
			try
			{
				ShipVisual shipVisualPrefab = val2.GetShipVisualPrefab();
				if ((Object)(object)shipVisualPrefab != (Object)null)
				{
					ShipVisual val6 = Prefabs.Copy<ShipVisual>(shipVisualPrefab, (string)null);
					Swapper.Other(((Component)val6).gameObject, "civ");
					Skins.Ship(val6);
				}
			}
			catch (Exception ex3)
			{
				Data.W("ship FAIL " + ex3.Message);
			}
			RenderPictures(list);
			Data.W(num + " buildings, " + num2 + " units, ship, " + dictionary.Count + " ragdolls copied; " + (int)(DateTime.Now - now).TotalMilliseconds + " ms");
		}

		private static bool HasModel(BuildingVisual original)
		{
			string text = Swapper.BaseName(((Object)((Component)original).gameObject).name);
			if (text.Length <= Data.LookWord.Length)
			{
				return false;
			}
			string text2 = Swapper.Kebab(text.Substring(0, text.Length - Data.LookWord.Length - 1));
			if (!Models.Exists(text2))
			{
				return Models.Exists(text2 + "-middle");
			}
			return true;
		}

		private static void RenderPictures(List<Picture> list)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			list = list.FindAll((Picture p) => p.Original != null && ((Il2CppArrayBase<Sprite>)(object)p.Original).Length > 0 && (Object)(object)((Il2CppArrayBase<Sprite>)(object)p.Original)[0] != (Object)null);
			int left = list.Count;
			List<Entry> texts = new List<Entry>();
			List<string> names = new List<string>();
			foreach (Picture item2 in list)
			{
				Rect rect = ((Il2CppArrayBase<Sprite>)(object)item2.Original)[0].rect;
				string text = Data.Key + " " + ((Object)item2.Copy).name;
				names.Add(text);
				Picture item = item2;
				IconRenderer.PlayerColours(text, item2.Copy, item2.Unit ? IconView.Unit : IconView.Building, Mathf.RoundToInt(((Rect)(ref rect)).width), Mathf.RoundToInt(((Rect)(ref rect)).height), (Action<Sprite[]>)delegate(Sprite[] sprites)
				{
					//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
					//IL_00c9: Expected O, but got Unknown
					int num = Math.Min(sprites.Length, ((Il2CppArrayBase<Sprite>)(object)item.Original).Length);
					Il2CppReferenceArray<Sprite> val = new Il2CppReferenceArray<Sprite>((long)((Il2CppArrayBase<Sprite>)(object)item.Original).Length);
					for (int i = 0; i < ((Il2CppArrayBase<Sprite>)(object)item.Original).Length; i++)
					{
						Sprite val2 = ((Il2CppArrayBase<Sprite>)(object)item.Original)[i];
						if (i >= num || (Object)(object)val2 == (Object)null)
						{
							((Il2CppArrayBase<Sprite>)(object)val)[i] = val2;
						}
						else
						{
							Sprite s = sprites[i];
							((Object)s).name = SpriteName(((Object)val2).name);
							((Il2CppArrayBase<Sprite>)(object)val)[i] = s;
							texts.Add(new Entry(((Object)s).name, ((Object)val2).name, (Func<Texture2D>)(() => Sprites.ReadableCopy(s))));
						}
					}
					item.Set(val);
					int num2 = left - 1;
					left = num2;
					if (num2 == 0)
					{
						StringBuilder stringBuilder = new StringBuilder();
						foreach (string item3 in names)
						{
							stringBuilder.Append(IconRenderer.CacheKey(item3)).Append(';');
						}
						int num3 = TextSprites.AddLike(SheetName, (IEnumerable<Entry>)texts, StableHash(stringBuilder.ToString()));
						Data.W(list.Count + " picture sets taken in the game, " + num3 + " text pictures");
					}
				});
			}
		}

		private static string StableHash(string s)
		{
			uint num = 2166136261u;
			foreach (char c in s)
			{
				num ^= c;
				num *= 16777619;
			}
			return num.ToString("X8");
		}

		private static void Relink(GameObject go, Dictionary<IntPtr, Ragdoll> ragdolls)
		{
			foreach (ReplaceWithRagdoll componentsInChild in go.GetComponentsInChildren<ReplaceWithRagdoll>(true))
			{
				if ((Object)(object)componentsInChild.ragdollPrefab != (Object)null && ragdolls.TryGetValue(((Il2CppObjectBase)componentsInChild.ragdollPrefab).Pointer, out var value))
				{
					componentsInChild.ragdollPrefab = value;
				}
			}
		}

		internal static string SpriteName(string original)
		{
			if (original == null)
			{
				return null;
			}
			string text = "-" + Swapper.Kebab(Data.LookWord) + "-";
			int num = original.LastIndexOf(text, StringComparison.Ordinal);
			if (num >= 0)
			{
				return original.Substring(0, num) + "-" + Data.Token + "-" + original.Substring(num + text.Length);
			}
			return original + "-" + Data.Token;
		}
	}
	internal static class CivInfo
	{
		public const string Guid = "civ.dicemodders.europereskin";

		public const string Name = "Civilization: Europe Reskin";

		public const string Version = "1.0.0";
	}
	internal sealed class Model
	{
		public string Name;

		public Mesh Mesh;

		public int[] BaseTris;

		public int[] CropTris;

		public int[] SailTris;

		public int[] AllTris;

		public string[] Bones;

		public int[] VertBones;

		public float[] VertWeights;

		public Dictionary<string, float[]> BindPoses = new Dictionary<string, float[]>();

		public bool HasFlag;

		public Vector3 FlagPos;

		public float FlagYaw;

		public List<(string name, Vector3 pos, float yaw)> Anchors = new List<(string, Vector3, float)>();

		public readonly Dictionary<string, Mesh> Variants = new Dictionary<string, Mesh>();

		public Vector3[] V;

		public Vector3[] N;

		public Mesh FloatMesh;

		public Vector3 FloatPivot;

		public float FloatSpin;

		public float FloatBob;

		public float FloatPeriod;

		public bool Skinned => Bones != null;
	}
	internal static class Models
	{
		private sealed class Raw
		{
			public Vector3[] V;

			public Vector3[] N;

			public Vector2[] UV;

			public int[] T;

			public int[] VB;

			public float[] VW;

			public bool Weighted;

			public int CropStart = -1;

			public int SailStart = -1;

			public int FloatStart = -1;

			public Vector3 FloatPivot;

			public float FloatSpin;

			public float FloatBob;

			public float FloatPeriod;

			public string[] Bones;

			public Dictionary<string, float[]> BindPoses = new Dictionary<string, float[]>();

			public bool HasFlag;

			public Vector3 FlagPos;

			public float FlagYaw;

			public List<(string name, Vector3 pos, float yaw)> Anchors = new List<(string, Vector3, float)>();
		}

		private static readonly Dictionary<string, Model> Cache = new Dictionary<string, Model>();

		private static readonly Dictionary<string, bool> Files = new Dictionary<string, bool>();

		internal static readonly HashSet<IntPtr> Ours = new HashSet<IntPtr>();

		private static Mesh _empty;

		private const int BinVersion = 2;

		private static readonly Dictionary<string, float[]> Placements = new Dictionary<string, float[]>();

		internal static string CacheFolder => "civ-" + Data.Token;

		public static Mesh Empty
		{
			get
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected O, but got Unknown
				if ((Object)(object)_empty == (Object)null)
				{
					_empty = new Mesh
					{
						name = "custom-empty"
					};
					((Object)_empty).hideFlags = (HideFlags)32;
					Ours.Add(((Il2CppObjectBase)_empty).Pointer);
				}
				return _empty;
			}
		}

		private static void W(string s)
		{
			Data.W(s);
		}

		public static bool Exists(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return false;
			}
			if (!Files.TryGetValue(name, out var value))
			{
				value = (Files[name] = File.Exists(Path.Combine(Data.MeshDir, name + ".dkmesh")));
			}
			return value;
		}

		public static bool IsOurs(Mesh m)
		{
			if ((Object)(object)m != (Object)null)
			{
				return Ours.Contains(((Il2CppObjectBase)m).Pointer);
			}
			return false;
		}

		private static Mesh Keep(Mesh m)
		{
			((Object)m).hideFlags = (HideFlags)32;
			Ours.Add(((Il2CppObjectBase)m).Pointer);
			return m;
		}

		public static Model Get(string name)
		{
			if (Cache.TryGetValue(name, out var value))
			{
				return value;
			}
			value = null;
			try
			{
				value = Load(name);
			}
			catch (Exception ex)
			{
				W("LOAD FAIL " + name + ": " + ex);
			}
			Cache[name] = value;
			return value;
		}

		private static string BinPath(string name)
		{
			return DiskCache.PathFor(CacheFolder, name + ".bin");
		}

		private static Model Load(string name)
		{
			FileInfo fileInfo = new FileInfo(Path.Combine(Data.MeshDir, name + ".dkmesh"));
			string key = fileInfo.Length + ":" + fileInfo.LastWriteTimeUtc.Ticks;
			Raw raw = ReadBin(name, key);
			bool flag = raw == null;
			if (flag)
			{
				raw = Parse(fileInfo.FullName);
				WriteBin(name, key, raw);
			}
			return Build(name, raw, flag);
		}

		private static void WriteVec3(BinaryWriter w, Vector3[] a)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			w.Write(a.Length);
			foreach (Vector3 val in a)
			{
				w.Write(val.x);
				w.Write(val.y);
				w.Write(val.z);
			}
		}

		private static Vector3[] ReadVec3(BinaryReader r)
		{
			//IL_0024: 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)
			Vector3[] array = (Vector3[])(object)new Vector3[r.ReadInt32()];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
			}
			return array;
		}

		private static void WriteInts(BinaryWriter w, int[] a)
		{
			w.Write((a != null) ? a.Length : (-1));
			if (a != null)
			{
				foreach (int value in a)
				{
					w.Write(value);
				}
			}
		}

		private static int[] ReadInts(BinaryReader r)
		{
			int num = r.ReadInt32();
			if (num < 0)
			{
				return null;
			}
			int[] array = new int[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = r.ReadInt32();
			}
			return array;
		}

		private static void WriteFloats(BinaryWriter w, float[] a)
		{
			w.Write((a != null) ? a.Length : (-1));
			if (a != null)
			{
				foreach (float value in a)
				{
					w.Write(value);
				}
			}
		}

		private static float[] ReadFloats(BinaryReader r)
		{
			int num = r.ReadInt32();
			if (num < 0)
			{
				return null;
			}
			float[] array = new float[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = r.ReadSingle();
			}
			return array;
		}

		private static void WriteBin(string name, string key, Raw x)
		{
			//IL_0065: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(BinPath(name)));
				using MemoryStream memoryStream = new MemoryStream();
				using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true))
				{
					binaryWriter.Write(2);
					binaryWriter.Write(key);
					WriteVec3(binaryWriter, x.V);
					WriteVec3(binaryWriter, x.N);
					binaryWriter.Write(x.UV.Length);
					Vector2[] uV = x.UV;
					foreach (Vector2 val in uV)
					{
						binaryWriter.Write(val.x);
						binaryWriter.Write(val.y);
					}
					WriteInts(binaryWriter, x.T);
					WriteInts(binaryWriter, x.VB);
					WriteFloats(binaryWriter, x.VW);
					binaryWriter.Write(x.Weighted);
					binaryWriter.Write(x.CropStart);
					binaryWriter.Write(x.SailStart);
					binaryWriter.Write(x.FloatStart);
					binaryWriter.Write(x.FloatPivot.x);
					binaryWriter.Write(x.FloatPivot.y);
					binaryWriter.Write(x.FloatPivot.z);
					binaryWriter.Write(x.FloatSpin);
					binaryWriter.Write(x.FloatBob);
					binaryWriter.Write(x.FloatPeriod);
					string[] bones = x.Bones;
					binaryWriter.Write((bones != null) ? bones.Length : (-1));
					if (x.Bones != null)
					{
						string[] bones2 = x.Bones;
						foreach (string value in bones2)
						{
							binaryWriter.Write(value);
						}
					}
					binaryWriter.Write(x.BindPoses.Count);
					foreach (KeyValuePair<string, float[]> bindPose in x.BindPoses)
					{
						binaryWriter.Write(bindPose.Key);
						WriteFloats(binaryWriter, bindPose.Value);
					}
					binaryWriter.Write(x.HasFlag);
					binaryWriter.Write(x.FlagPos.x);
					binaryWriter.Write(x.FlagPos.y);
					binaryWriter.Write(x.FlagPos.z);
					binaryWriter.Write(x.FlagYaw);
					binaryWriter.Write(x.Anchors.Count);
					foreach (var anchor in x.Anchors)
					{
						binaryWriter.Write(anchor.name);
						binaryWriter.Write(anchor.pos.x);
						binaryWriter.Write(anchor.pos.y);
						binaryWriter.Write(anchor.pos.z);
						binaryWriter.Write(anchor.yaw);
					}
				}
				File.WriteAllBytes(BinPath(name), memoryStream.ToArray());
			}
			catch (Exception ex)
			{
				W("mesh cache write " + name + ": " + ex.Message);
			}
		}

		private static Raw ReadBin(string name, string key)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			string text = BinPath(name);
			if (!File.Exists(text))
			{
				return null;
			}
			try
			{
				using BinaryReader binaryReader = new BinaryReader(new MemoryStream(DiskCache.ReadAllBytes(text)));
				if (binaryReader.ReadInt32() != 2 || binaryReader.ReadString() != key)
				{
					return null;
				}
				Raw raw = new Raw
				{
					V = ReadVec3(binaryReader),
					N = ReadVec3(binaryReader)
				};
				raw.UV = (Vector2[])(object)new Vector2[binaryReader.ReadInt32()];
				for (int i = 0; i < raw.UV.Length; i++)
				{
					raw.UV[i] = new Vector2(binaryReader.ReadSingle(), binaryReader.ReadSingle());
				}
				raw.T = ReadInts(binaryReader);
				raw.VB = ReadInts(binaryReader);
				raw.VW = ReadFloats(binaryReader);
				raw.Weighted = binaryReader.ReadBoolean();
				raw.CropStart = binaryReader.ReadInt32();
				raw.SailStart = binaryReader.ReadInt32();
				raw.FloatStart = binaryReader.ReadInt32();
				raw.FloatPivot = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle());
				raw.FloatSpin = binaryReader.ReadSingle();
				raw.FloatBob = binaryReader.ReadSingle();
				raw.FloatPeriod = binaryReader.ReadSingle();
				int num = binaryReader.ReadInt32();
				if (num >= 0)
				{
					raw.Bones = new string[num];
					for (int j = 0; j < num; j++)
					{
						raw.Bones[j] = binaryReader.ReadString();
					}
				}
				int num2 = binaryReader.ReadInt32();
				for (int k = 0; k < num2; k++)
				{
					string key2 = binaryReader.ReadString();
					raw.BindPoses[key2] = ReadFloats(binaryReader);
				}
				raw.HasFlag = binaryReader.ReadBoolean();
				raw.FlagPos = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle());
				raw.FlagYaw = binaryReader.ReadSingle();
				int num3 = binaryReader.ReadInt32();
				for (int l = 0; l < num3; l++)
				{
					raw.Anchors.Add((binaryReader.ReadString(), new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()), binaryReader.ReadSingle()));
				}
				return raw;
			}
			catch (Exception ex)
			{
				W("mesh cache read " + name + " (rebuilding): " + ex.Message);
				return null;
			}
		}

		private static Raw Parse(string path)
		{
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04db: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0505: Unknown result type (might be due to invalid IL or missing references)
			//IL_050f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0515: Unknown result type (might be due to invalid IL or missing references)
			//IL_0524: Unknown result type (might be due to invalid IL or missing references)
			//IL_052e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0535: Unknown result type (might be due to invalid IL or missing references)
			//IL_053f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0546: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0404: Unknown result type (might be due to invalid IL or missing references)
			//IL_0467: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_065e: Unknown result type (might be due to invalid IL or missing references)
			//IL_063f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<int> list3 = new List<int>();
			List<int> list4 = new List<int>();
			List<float> list5 = new List<float>();
			int cropStart = -1;
			int sailStart = -1;
			int floatStart = -1;
			Raw raw = new Raw();
			bool weighted = false;
			foreach (string item in File.ReadLines(path))
			{
				string[] array = item.Split(' ');
				switch (array[0])
				{
				case "v":
				{
					list.Add(new Vector3(float.Parse(array[1], invariantCulture), float.Parse(array[2], invariantCulture), float.Parse(array[3], invariantCulture)));
					list2.Add(new Vector2(float.Parse(array[4], invariantCulture), float.Parse(array[5], invariantCulture)));
					int j = 0;
					if (array.Length == 7)
					{
						list4.Add(int.Parse(array[6]));
						list5.Add(1f);
						j = 1;
						weighted = true;
					}
					else if (array.Length > 7)
					{
						for (int k = 6; k + 1 < array.Length; k += 2)
						{
							if (j >= 4)
							{
								break;
							}
							list4.Add(int.Parse(array[k]));
							list5.Add(float.Parse(array[k + 1], invariantCulture));
							j++;
						}
						weighted = true;
					}
					for (; j < 4; j++)
					{
						list4.Add(0);
						list5.Add(0f);
					}
					break;
				}
				case "t":
					list3.Add(int.Parse(array[1]));
					list3.Add(int.Parse(array[2]));
					list3.Add(int.Parse(array[3]));
					break;
				case "part":
					if (array.Length > 1 && array[1] == "crops")
					{
						cropStart = list3.Count;
					}
					else if (array.Length > 1 && array[1] == "sail")
					{
						sailStart = list3.Count;
					}
					else if (array.Length > 1 && array[1] == "float")
					{
						floatStart = list3.Count;
					}
					break;
				case "bones":
					raw.Bones = array[1..];
					break;
				case "bindpose":
				{
					float[] array2 = new float[16];
					for (int i = 0; i < 16; i++)
					{
						array2[i] = float.Parse(array[2 + i], invariantCulture);
					}
					raw.BindPoses[array[1]] = array2;
					break;
				}
				case "float":
					if (array.Length >= 7)
					{
						raw.FloatPivot = new Vector3(float.Parse(array[1], invariantCulture), float.Parse(array[2], invariantCulture), float.Parse(array[3], invariantCulture));
						raw.FloatSpin = float.Parse(array[4], invariantCulture);
						raw.FloatBob = float.Parse(array[5], invariantCulture);
						raw.FloatPeriod = float.Parse(array[6], invariantCulture);
					}
					break;
				case "flag":
					raw.HasFlag = true;
					raw.FlagPos = new Vector3(float.Parse(array[1], invariantCulture), float.Parse(array[2], invariantCulture), float.Parse(array[3], invariantCulture));
					raw.FlagYaw = float.Parse(array[4], invariantCulture);
					break;
				case "anchor":
					if (array.Length >= 6)
					{
						raw.Anchors.Add((string.Join(" ", array, 1, array.Length - 5), new Vector3(float.Parse(array[^4], invariantCulture), float.Parse(array[^3], invariantCulture), float.Parse(array[^2], invariantCulture)), float.Parse(array[^1], invariantCulture)));
					}
					break;
				}
			}
			float[] array3 = new float[list.Count];
			float[] array4 = new float[list.Count];
			float[] array5 = new float[list.Count];
			for (int l = 0; l < list3.Count; l += 3)
			{
				Vector3 val = list[list3[l]];
				Vector3 val2 = list[list3[l + 1]];
				Vector3 val3 = list[list3[l + 2]];
				float num = val2.x - val.x;
				float num2 = val2.y - val.y;
				float num3 = val2.z - val.z;
				float num4 = val3.x - val.x;
				float num5 = val3.y - val.y;
				float num6 = val3.z - val.z;
				float num7 = num2 * num6 - num3 * num5;
				float num8 = num3 * num4 - num * num6;
				float num9 = num * num5 - num2 * num4;
				for (int m = 0; m < 3; m++)
				{
					int num10 = list3[l + m];
					array3[num10] += num7;
					array4[num10] += num8;
					array5[num10] += num9;
				}
			}
			Vector3[] array6 = (Vector3[])(object)new Vector3[list.Count];
			for (int n = 0; n < array6.Length; n++)
			{
				float num11 = (float)Math.Sqrt(array3[n] * array3[n] + array4[n] * array4[n] + array5[n] * array5[n]);
				array6[n] = ((num11 > 0f) ? new Vector3(array3[n] / num11, array4[n] / num11, array5[n] / num11) : new Vector3(0f, 1f, 0f));
			}
			raw.V = list.ToArray();
			raw.UV = list2.ToArray();
			raw.T = list3.ToArray();
			raw.N = array6;
			raw.VB = list4.ToArray();
			raw.VW = list5.ToArray();
			raw.Weighted = weighted;
			raw.CropStart = cropStart;
			raw.SailStart = sailStart;
			raw.FloatStart = floatStart;
			return raw;
		}

		private static Model Build(string name, Raw x, bool parsed)
		{
			//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_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			//IL_01dd: 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_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			Model model = new Model
			{
				Name = name,
				Bones = x.Bones,
				BindPoses = x.BindPoses,
				HasFlag = x.HasFlag,
				FlagPos = x.FlagPos,
				FlagYaw = x.FlagYaw,
				Anchors = x.Anchors
			};
			int[] array = x.T;
			if (x.FloatStart >= 0 && x.FloatStart < array.Length)
			{
				int[] subArray = array[x.FloatStart..];
				array = array[..x.FloatStart];
				Dictionary<int, int> dictionary = new Dictionary<int, int>();
				List<Vector3> list = new List<Vector3>();
				List<Vector3> list2 = new List<Vector3>();
				List<Vector2> list3 = new List<Vector2>();
				int[] array2 = new int[subArray.Length];
				for (int i = 0; i < subArray.Length; i++)
				{
					if (!dictionary.TryGetValue(subArray[i], out var value))
					{
						value = list.Count;
						dictionary[subArray[i]] = value;
						list.Add(x.V[subArray[i]] - x.FloatPivot);
						list2.Add(x.N[subArray[i]]);
						list3.Add(x.UV[subArray[i]]);
					}
					array2[i] = value;
				}
				Mesh val = new Mesh
				{
					name = "custom-" + name + "-float"
				};
				val.vertices = Il2CppStructArray<Vector3>.op_Implicit(list.ToArray());
				val.uv = Il2CppStructArray<Vector2>.op_Implicit(list3.ToArray());
				val.triangles = Il2CppStructArray<int>.op_Implicit(array2);
				val.normals = Il2CppStructArray<Vector3>.op_Implicit(list2.ToArray());
				val.RecalculateBounds();
				model.FloatMesh = Keep(val);
				model.FloatPivot = x.FloatPivot;
				model.FloatSpin = x.FloatSpin;
				model.FloatBob = x.FloatBob;
				model.FloatPeriod = x.FloatPeriod;
			}
			Mesh val2 = new Mesh
			{
				name = "custom-" + name,
				indexFormat = (IndexFormat)1
			};
			val2.vertices = Il2CppStructArray<Vector3>.op_Implicit(x.V);
			val2.uv = Il2CppStructArray<Vector2>.op_Implicit(x.UV);
			val2.triangles = Il2CppStructArray<int>.op_Implicit(array);
			val2.normals = Il2CppStructArray<Vector3>.op_Implicit(x.N);
			model.Mesh = Keep(val2);
			model.V = x.V;
			model.N = x.N;
			model.AllTris = array;
			int cropStart = x.CropStart;
			int sailStart = x.SailStart;
			int num = array.Length;
			if (cropStart >= 0)
			{
				num = Math.Min(num, cropStart);
			}
			if (sailStart >= 0)
			{
				num = Math.Min(num, sailStart);
			}
			if (cropStart >= 0)
			{
				model.CropTris = array[cropStart..((sailStart > cropStart) ? sailStart : array.Length)];
			}
			if (sailStart >= 0)
			{
				model.SailTris = array[sailStart..((cropStart > sailStart) ? cropStart : array.Length)];
			}
			if (num < array.Length)
			{
				model.BaseTris = array[..num];
			}
			if (model.Bones != null && x.Weighted && x.VB != null && x.VB.Length == x.V.Length * 4)
			{
				model.VertBones = x.VB;
				model.VertWeights = x.VW;
			}
			else if (model.Bones != null)
			{
				W("WARN " + name + ": 'bones' line but vertex weights do not match; loaded as a static model");
				model.Bones = null;
			}
			Vector3[] v = x.V;
			int[] t = x.T;
			W("loaded " + name + (parsed ? " (parsed text, cached)" : " (cache)") + ": " + v.Length + " verts, " + t.Length / 3 + " tris" + ((model.CropTris != null) ? (", crops " + model.CropTris.Length / 3) : "") + ((model.SailTris != null) ? (", sail " + model.SailTris.Length / 3) : "") + (model.Skinned ? (", skinned (" + model.Bones.Length + " bones, " + model.BindPoses.Count + " bind poses)") : "") + ", anchors " + model.Anchors.Count + (model.HasFlag ? ", flag" : "") + (((Object)(object)model.FloatMesh != (Object)null) ? ", floating part" : ""));
			return model;
		}

		internal static float[] Relative(Transform piece, Transform root)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_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_0033: 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_0041: 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_0056: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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_007b: 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)
			float[] array = Identity();
			bool flag = false;
			Transform val = piece;
			while ((Object)(object)val != (Object)null && ((Il2CppObjectBase)val).Pointer != ((Il2CppObjectBase)root).Pointer)
			{
				Vector3 localPosition = val.localPosition;
				Quaternion localRotation = val.localRotation;
				Vector3 localScale = val.localScale;
				if (localPosition.x * localPosition.x + localPosition.y * localPosition.y + localPosition.z * localPosition.z > 1E-08f || Math.Abs(localRotation.w) < 0.99999f || Math.Abs(localScale.x - 1f) + Math.Abs(localScale.y - 1f) + Math.Abs(localScale.z - 1f) > 0.0001f)
				{
					flag = true;
				}
				array = Mul(Trs(localPosition, localRotation, localScale), array);
				val = val.parent;
			}
			if (!flag)
			{
				return null;
			}
			return array;
		}

		public static Mesh Placed(Model model, Mesh basis, string group, float[] rel)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: 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_00c9: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			if (rel == null || model.V == null)
			{
				return basis;
			}
			string key = model.Name + "|" + group;
			if (!Placements.TryGetValue(key, out var value))
			{
				value = (Placements[key] = rel);
			}
			string key2 = "p:" + ((Object)basis).name + "|" + group;
			if (model.Variants.TryGetValue(key2, out var value2))
			{
				return value2;
			}
			float[] array2 = Inverse(value);
			if (array2 == null)
			{
				return basis;
			}
			Vector3[] array3 = (Vector3[])(object)new Vector3[model.V.Length];
			Vector3[] array4 = (Vector3[])(object)new Vector3[model.N.Length];
			for (int i = 0; i < array3.Length; i++)
			{
				Vector3 val = model.V[i];
				array3[i] = new Vector3(array2[0] * val.x + array2[4] * val.y + array2[8] * val.z + array2[12], array2[1] * val.x + array2[5] * val.y + array2[9] * val.z + array2[13], array2[2] * val.x + array2[6] * val.y + array2[10] * val.z + array2[14]);
			}
			for (int j = 0; j < array4.Length; j++)
			{
				Vector3 val2 = model.N[j];
				float num = value[0] * val2.x + value[1] * val2.y + value[2] * val2.z;
				float num2 = value[4] * val2.x + value[5] * val2.y + value[6] * val2.z;
				float num3 = value[8] * val2.x + value[9] * val2.y + value[10] * val2.z;
				float num4 = (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3);
				array4[j] = ((num4 > 0f) ? new Vector3(num / num4, num2 / num4, num3 / num4) : new Vector3(0f, 1f, 0f));
			}
			value2 = Object.Instantiate<Mesh>(basis);
			((Object)value2).name = ((Object)basis).name + "#" + group;
			value2.vertices = Il2CppStructArray<Vector3>.op_Implicit(array3);
			value2.normals = Il2CppStructArray<Vector3>.op_Implicit(array4);
			value2.RecalculateBounds();
			model.Variants[key2] = Keep(value2);
			W("placed " + model.Name + " in the space of " + group + " (scale " + Math.Sqrt(value[0] * value[0] + value[1] * value[1] + value[2] * value[2]).ToString("0.#####", CultureInfo.InvariantCulture) + ", offset " + value[12].ToString("0.###", CultureInfo.InvariantCulture) + " " + value[13].ToString("0.###", CultureInfo.InvariantCulture) + " " + value[14].ToString("0.###", CultureInfo.InvariantCulture) + ")");
			return value2;
		}

		private static float[] Identity()
		{
			return new float[16]
			{
				1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f,
				1f, 0f, 0f, 0f, 0f, 1f
			};
		}

		private static float[] Trs(Vector3 p, Quaternion q, Vector3 s)
		{
			//IL_0000: 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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: 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_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			float x = q.x;
			float y = q.y;
			float z = q.z;
			float w = q.w;
			float num = x * x;
			float num2 = y * y;
			float num3 = z * z;
			float num4 = x * y;
			float num5 = x * z;
			float num6 = y * z;
			float num7 = w * x;
			float num8 = w * y;
			float num9 = w * z;
			return new float[16]
			{
				(1f - 2f * (num2 + num3)) * s.x,
				2f * (num4 + num9) * s.x,
				2f * (num5 - num8) * s.x,
				0f,
				2f * (num4 - num9) * s.y,
				(1f - 2f * (num + num3)) * s.y,
				2f * (num6 + num7) * s.y,
				0f,
				2f * (num5 + num8) * s.z,
				2f * (num6 - num7) * s.z,
				(1f - 2f * (num + num2)) * s.z,
				0f,
				p.x,
				p.y,
				p.z,
				1f
			};
		}

		private static float[] Mul(float[] a, float[] b)
		{
			float[] array = new float[16];
			for (int i = 0; i < 4; i++)
			{
				for (int j = 0; j < 4; j++)
				{
					float num = 0f;
					for (int k = 0; k < 4; k++)
					{
						num += a[k * 4 + j] * b[i * 4 + k];
					}
					array[i * 4 + j] = num;
				}
			}
			return array;
		}

		private static float[] Inverse(float[] m)
		{
			double num = m[0];
			double num2 = m[4];
			double num3 = m[8];
			double num4 = m[1];
			double num5 = m[5];
			double num6 = m[9];
			double num7 = m[2];
			double num8 = m[6];
			double num9 = m[10];
			double num10 = num * (num5 * num9 - num6 * num8) - num2 * (num4 * num9 - num6 * num7) + num3 * (num4 * num8 - num5 * num7);
			if (Math.Abs(num10) < 1E-30)
			{
				return null;
			}
			double[] array = new double[9]
			{
				(num5 * num9 - num6 * num8) / num10,
				(num3 * num8 - num2 * num9) / num10,
				(num2 * num6 - num3 * num5) / num10,
				(num6 * num7 - num4 * num9) / num10,
				(num * num9 - num3 * num7) / num10,
				(num3 * num4 - num * num6) / num10,
				(num4 * num8 - num5 * num7) / num10,
				(num2 * num7 - num * num8) / num10,
				(num * num5 - num2 * num4) / num10
			};
			float[] array2 = new float[16];
			for (int i = 0; i < 3; i++)
			{
				for (int j = 0; j < 3; j++)
				{
					array2[j * 4 + i] = (float)array[i * 3 + j];
				}
			}
			for (int k = 0; k < 3; k++)
			{
				array2[12 + k] = 0f - (float)(array[k * 3] * (double)m[12] + array[k * 3 + 1] * (double)m[13] + array[k * 3 + 2] * (double)m[14]);
			}
			array2[15] = 1f;
			return array2;
		}

		public static Mesh ForStatic(Model model, MeshRenderer r)
		{
			if ((Object)(object)r == (Object)null)
			{
				return model.Mesh;
			}
			Il2CppReferenceArray<Material> sharedMaterials = ((Renderer)r).sharedMaterials;
			if (sharedMaterials == null || ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length <= 1)
			{
				return model.Mesh;
			}
			int num = 0;
			int num2 = -1;
			for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length; i++)
			{
				if (!((Object)(object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i] == (Object)null))
				{
					if (((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i]).name.StartsWith("Colored-Paper", StringComparison.Ordinal))
					{
						num = i;
					}
					if (((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i]).name.StartsWith("Windy-Crops", StringComparison.Ordinal))
					{
						num2 = i;
					}
				}
			}
			bool flag = model.CropTris != null && model.CropTris.Length != 0 && num2 >= 0 && num2 != num;
			if (num == 0 && !flag)
			{
				return model.Mesh;
			}
			string text = "s" + num + "/" + (flag ? num2 : (-1)) + "/" + ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length;
			if (model.Variants.TryGetValue(text, out var value))
			{
				return value;
			}
			value = Object.Instantiate<Mesh>(model.Mesh);
			((Object)value).name = ((Object)model.Mesh).name + "#" + text;
			int[] array = (flag ? (model.BaseTris ?? Array.Empty<int>()) : model.AllTris);
			value.subMeshCount = ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length;
			for (int j = 0; j < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length; j++)
			{
				value.SetTriangles(Il2CppStructArray<int>.op_Implicit((j == num) ? array : ((flag && j == num2) ? model.CropTris : new int[0])), j);
			}
			model.Variants[text] = Keep(value);
			W("material slots " + model.Name + ": body -> " + num + " (" + ((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[num]).name + ")" + (flag ? (", crops -> " + num2 + " (" + ((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[num2]).name + ")") : ""));
			return value;
		}

		public unsafe static Mesh ForSkinned(Model model, SkinnedMeshRenderer r)
		{
			if (!model.Skinned)
			{
				Data.Once("noskin:" + model.Name, "WARN " + model.Name + " goes on a skinned renderer (" + ((Object)((Component)r).gameObject).name + ") but has no bones: shown rigid");
				return model.Mesh;
			}
			Il2CppReferenceArray<Material> sharedMaterials = ((Renderer)r).sharedMaterials;
			int num = 0;
			int num2 = -1;
			for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length; i++)
			{
				if (!((Object)(object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i] == (Object)null))
				{
					if (((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i]).name.StartsWith("Colored-Paper", StringComparison.Ordinal))
					{
						num = i;
					}
					if (((Object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[i]).name.StartsWith("Sail", StringComparison.Ordinal))
					{
						num2 = i;
					}
				}
			}
			Il2CppReferenceArray<Transform> bones = r.bones;
			string[] array = new string[((Il2CppArrayBase<Transform>)(object)bones).Length];
			for (int j = 0; j < ((Il2CppArrayBase<Transform>)(object)bones).Length; j++)
			{
				array[j] = (((Object)(object)((Il2CppArrayBase<Transform>)(object)bones)[j] != (Object)null) ? ((Object)((Il2CppArrayBase<Transform>)(object)bones)[j]).name : "");
			}
			string key = "k" + num + "/" + num2 + "/" + ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length + "/" + string.Join("|", array);
			if (model.Variants.TryGetValue(key, out var value))
			{
				return value;
			}
			int[] array2 = new int[model.Bones.Length];
			List<string> list = new List<string>();
			for (int k = 0; k < model.Bones.Length; k++)
			{
				array2[k] = Array.IndexOf(array, model.Bones[k]);
				if (array2[k] < 0)
				{
					array2[k] = 0;
					list.Add(model.Bones[k]);
				}
			}
			int num3 = model.VertBones.Length / 4;
			int[] array3 = new int[num3 * 4];
			for (int l = 0; l < array3.Length; l++)
			{
				array3[l] = array2[model.VertBones[l]];
			}
			float[] array4 = new float[((Il2CppArrayBase<Transform>)(object)bones).Length * 16];
			IntPtr intPtr = IntPtr.Zero;
			try
			{
				Il2CppStructArray<Matrix4x4> val = (((Object)(object)r.sharedMesh != (Object)null) ? r.sharedMesh.bindposes : null);
				if (val != null)
				{
					intPtr = ((Il2CppObjectBase)val).Pointer;
				}
			}
			catch (Exception ex)
			{
				W("bindposes read " + model.Name + ": " + ex.Message);
			}
			int num4 = (int)((intPtr != IntPtr.Zero) ? IL2CPP.il2cpp_array_length(intPtr) : 0);
			float* ptr = (float*)((intPtr != IntPtr.Zero) ? ((byte*)(void*)intPtr + 4 * IntPtr.Size) : null);
			for (int m = 0; m < ((Il2CppArrayBase<Transform>)(object)bones).Length; m++)
			{
				for (int n = 0; n < 16; n++)
				{
					array4[m * 16 + n] = ((ptr != null && m < num4) ? ptr[m * 16 + n] : ((n % 5 == 0) ? 1f : 0f));
				}
			}
			for (int num5 = 0; num5 < model.Bones.Length; num5++)
			{
				if (!model.BindPoses.TryGetValue(model.Bones[num5], out var value2) || list.Contains(model.Bones[num5]))
				{
					continue;
				}
				for (int num6 = 0; num6 < 4; num6++)
				{
					for (int num7 = 0; num7 < 4; num7++)
					{
						array4[array2[num5] * 16 + num6 * 4 + num7] = value2[num7 * 4 + num6];
					}
				}
			}
			value = Object.Instantiate<Mesh>(model.Mesh);
			((Object)value).name = ((Object)model.Mesh).name + "#" + ((Object)((Component)r).gameObject).name;
			Skin.Set(value, array3, model.VertWeights, array4, num3, ((Il2CppArrayBase<Transform>)(object)bones).Length);
			int[] array5 = model.BaseTris ?? model.AllTris;
			value.subMeshCount = Math.Max(((Il2CppArrayBase<Material>)(object)sharedMaterials).Length, 1);
			for (int num8 = 0; num8 < value.subMeshCount; num8++)
			{
				value.SetTriangles(Il2CppStructArray<int>.op_Implicit((num8 == num) ? array5 : ((num8 == num2 && model.SailTris != null) ? model.SailTris : new int[0])), num8);
			}
			value.RecalculateBounds();
			model.Variants[key] = Keep(value);
			W("skinned " + model.Name + " on '" + ((Object)((Component)r).gameObject).name + "': " + ((Il2CppArrayBase<Transform>)(object)bones).Length + " rig bones, body -> slot " + num + ((model.SailTris != null) ? (", sail -> " + num2) : "") + ((list.Count > 0) ? (", BONES NOT IN RIG: " + string.Join(",", list)) : ""));
			return value;
		}
	}
	internal static class Skin
	{
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate void SetBoneWeightsArr(IntPtr self, IntPtr array);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate void SetBindposes(IntPtr self, IntPtr array);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate int GetBindposeCount(IntPtr self);

		private static SetBoneWeightsArr setBW;

		private static SetBindposes setBP;

		private static GetBindposeCount getBPC;

		private static IntPtr weightClass;

		private static IntPtr matrixClass;

		private unsafe static IntPtr FindClass(string ns, string name)
		{
			uint num = 0u;
			IntPtr* ptr = IL2CPP.il2cpp_domain_get_assemblies(IL2CPP.il2cpp_domain_get(), ref num);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				IntPtr intPtr = IL2CPP.il2cpp_class_from_name(IL2CPP.il2cpp_assembly_get_image(ptr[num2]), ns, name);
				if (intPtr != IntPtr.Zero)
				{
					return intPtr;
				}
			}
			return IntPtr.Zero;
		}

		private static bool Init()
		{
			if (setBW != null)
			{
				return true;
			}
			IntPtr intPtr = IL2CPP.il2cpp_resolve_icall("UnityEngine.Mesh::SetBoneWeightsImpl");
			IntPtr intPtr2 = IL2CPP.il2cpp_resolve_icall("UnityEngine.Mesh::set_bindposes");
			IntPtr intPtr3 = IL2CPP.il2cpp_resolve_icall("UnityEngine.Mesh::GetBindposeCount");
			(string, string)[] array = new(string, string)[6]
			{
				("UnityEngine", "BoneWeight"),
				("Unity.Mathematics", "float4x2"),
				("Unity.Mathematics", "float2x4"),
				("Unity.Mathematics", "double4"),
				("Unity.Mathematics", "int4x2"),
				("Unity.Mathematics", "uint4x2")
			};
			for (int i = 0; i < array.Length; i++)
			{
				(string, string) tuple = array[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				IntPtr intPtr4 = FindClass(item, item2);
				if (intPtr4 != IntPtr.Zero && IL2CPP.il2cpp_class_array_element_size(intPtr4) == 32)
				{
					weightClass = intPtr4;
					break;
				}
			}
			matrixClass = Il2CppClassPointerStore<Matrix4x4>.NativeClassPtr;
			if (matrixClass == IntPtr.Zero)
			{
				matrixClass = FindClass("UnityEngine", "Matrix4x4");
			}
			Data.W("skin init: weights icall " + intPtr + ", bindposes icall " + intPtr2 + ", 32-byte class " + weightClass + ", matrix class " + matrixClass);
			if (intPtr == IntPtr.Zero || intPtr2 == IntPtr.Zero || weightClass == IntPtr.Zero || matrixClass == IntPtr.Zero)
			{
				return false;
			}
			setBW = Marshal.GetDelegateForFunctionPointer<SetBoneWeightsArr>(intPtr);
			setBP = Marshal.GetDelegateForFunctionPointer<SetBindposes>(intPtr2);
			if (intPtr3 != IntPtr.Zero)
			{
				getBPC = Marshal.GetDelegateForFunctionPointer<GetBindposeCount>(intPtr3);
			}
			return true;
		}

		public unsafe static void Set(Mesh c, int[] bi, float[] bw, float[] bp, int nv, int nb)
		{
			if (!Init())
			{
				Data.Once("skin:init", "SKIN FAIL: engine calls not found, skinned models stay rigid");
				return;
			}
			IntPtr intPtr = IL2CPP.il2cpp_array_new(weightClass, (ulong)nv);
			byte* ptr = (byte*)(void*)intPtr + 4 * IntPtr.Size;
			for (int i = 0; i < nv; i++)
			{
				float* ptr2 = (float*)(ptr + i * 32);
				int* ptr3 = (int*)(ptr + i * 32) + 4;
				for (int j = 0; j < 4; j++)
				{
					ptr2[j] = bw[i * 4 + j];
					ptr3[j] = ((bw[i * 4 + j] > 0f) ? bi[i * 4 + j] : 0);
				}
			}
			setBW(((Il2CppObjectBase)c).Pointer, intPtr);
			if (!c.HasVertexAttribute((VertexAttribute)13))
			{
				Data.W("SKIN WARN: weights did not apply on " + ((Object)c).name);
			}
			IntPtr intPtr2 = IL2CPP.il2cpp_array_new(matrixClass, (ulong)nb);
			float* ptr4 = (float*)((byte*)(void*)intPtr2 + 4 * IntPtr.Size);
			for (int k = 0; k < nb * 16; k++)
			{
				ptr4[k] = bp[k];
			}
			setBP(((Il2CppObjectBase)c).Pointer, intPtr2);
			if (getBPC != null && getBPC(((Il2CppObjectBase)c).Pointer) != nb)
			{
				Data.W("SKIN WARN: bindpose count " + getBPC(((Il2CppObjectBase)c).Pointer) + " expected " + nb + " on " + ((Object)c).name);
			}
		}
	}
	[BepInPlugin("civ.dicemodders.europereskin", "Civilization: Europe Reskin", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Dice-Kingdoms.exe")]
	public sealed class Plugin : BasePlugin
	{
		public override void Load()
		{
			Data.Log = ((BasePlugin)this).Log;
			Data.Dir = Path.GetDirectoryName(typeof(Plugin).Assembly.Location) ?? "";
			try
			{
				Data.Read();
			}
			catch (Exception ex)
			{
				((BasePlugin)this).Log.LogError((object)("civ.json could not be read: " + ex.Message));
				return;
			}
			try
			{
				CivBuilder.Register();
			}
			catch (Exception ex2)
			{
				((BasePlugin)this).Log.LogError((object)("could not register the civilization: " + ex2));
				return;
			}
			Civilizations.AddLooksSwitch(((BasePlugin)this).Config, CivBuilder.Skins, "Reskin", "Enabled", "Show the half-timbered buildings and restyled units for Europe. Visual and on this PC only; switching works at once, also during a match.");
		}
	}
	internal static class Data
	{
		internal static ManualLogSource Log;

		internal static string Dir;

		internal static readonly JsonDocumentOptions JsonOptions = new JsonDocumentOptions
		{
			CommentHandling = JsonCommentHandling.Skip,
			AllowTrailingCommas = true
		};

		internal static string Json;

		internal static string Key;

		internal static string Token;

		internal static string LookEnum = "EUROPE";

		internal static string LookWord = "Europe";

		internal static int LookId;

		internal static bool HasTree;

		internal static bool Reskin;

		internal static readonly List<(int x, int y, Color c)> GroundCells = new List<(int, int, Color)>();

		internal static readonly List<(int x, int y, Color c)> NatureCells = new List<(int, int, Color)>();

		internal static readonly List<(int x, int y, Color c)> HillCells = new List<(int, int, Color)>();

		private static readonly Dictionary<string, UnitStatChange> UnitStats = new Dictionary<string, UnitStatChange>();

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

		internal static string MeshDir => Path.Combine(Dir, "models");

		internal static bool HasUnitStats => UnitStats.Count > 0;

		internal static string Resource(string name)
		{
			using Stream stream = typeof(Data).Assembly.GetManifestResourceStream(name);
			if (stream == null)
			{
				return null;
			}
			using StreamReader streamReader = new StreamReader(stream);
			return streamReader.ReadToEnd();
		}

		internal static void Read()
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected I4, but got Unknown
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Expected O, but got Unknown
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			Json = Resource("civ.json") ?? throw new FileNotFoundException("civ.json is not built into the DLL (build with scripts\\build.ps1)");
			using JsonDocument jsonDocument = JsonDocument.Parse(Json, JsonOptions);
			JsonElement rootElement = jsonDocument.RootElement;
			Key = rootElement.GetProperty("key").GetString();
			Token = rootElement.GetProperty("token").GetString();
			if (string.IsNullOrWhiteSpace(Key) || string.IsNullOrWhiteSpace(Token))
			{
				throw new InvalidDataException("\"key\" and \"token\" are needed");
			}
			if (rootElement.TryGetProperty("looksLike", out var value))
			{
				LookEnum = value.GetString().ToUpperInvariant();
				LookId = (int)Enum.Parse<Civilization>(LookEnum);
				LookWord = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(LookEnum.ToLowerInvariant().Replace('_', ' '));
			}
			Reskin = rootElement.TryGetProperty("mode", out var value2) && string.Equals(value2.GetString(), "reskin", StringComparison.OrdinalIgnoreCase);
			HasTree = rootElement.TryGetProperty("techTree", out var value3) && value3.ValueKind == JsonValueKind.Array && value3.GetArrayLength() > 0;
			(string, List<(int, int, Color)>)[] array = new(string, List<(int, int, Color)>)[3]
			{
				("ground", GroundCells),
				("nature", NatureCells),
				("hills", HillCells)
			};
			Color item = default(Color);
			for (int i = 0; i < array.Length; i++)
			{
				var (text, list) = array[i];
				if (!rootElement.TryGetProperty(text, out var value4) || value4.ValueKind != JsonValueKind.Object)
				{
					continue;
				}
				foreach (JsonProperty item2 in value4.EnumerateObject())
				{
					string[] array2 = item2.Name.Split(',');
					if (array2.Length == 2 && ColorUtility.TryParseHtmlString(item2.Value.GetString(), ref item))
					{
						list.Add((int.Parse(array2[0]), int.Parse(array2[1]), item));
						continue;
					}
					Log.LogWarning((object)("civ.json " + text + ": \"" + item2.Name + "\" is not \"x,y\": \"#rrggbb\""));
				}
			}
			if (!rootElement.TryGetProperty("unitStats", out var value5) || value5.ValueKind != JsonValueKind.Object)
			{
				return;
			}
			foreach (JsonProperty item3 in value5.EnumerateObject())
			{
				if (item3.Value.ValueKind != JsonValueKind.Object)
				{
					continue;
				}
				UnitStatChange val = new UnitStatChange();
				foreach (JsonProperty item4 in item3.Value.EnumerateObject())
				{
					switch (item4.Name)
					{
					case "attackPeriod":
						val.AttackPeriod = item4.Value.GetInt32();
						continue;
					case "attackDelay":
						val.AttackDelay = item4.Value.GetInt32();
						continue;
					case "aggroDistance":
						val.AggroDistance = item4.Value.GetInt32();
						continue;
					case "range":
						val.Range = item4.Value.GetInt32();
						continue;
					case "parry":
						val.Parry = Chance(item4.Value.GetString());
						continue;
					case "blockArrow":
						val.BlockArrow = Chance(item4.Value.GetString());
						continue;
					case "missChance":
						val.MissChance = Chance(item4.Value.GetString());
						continue;
					}
					Log.LogWarning((object)("civ.json unitStats." + item3.Name + ": unknown value \"" + item4.Name + "\""));
				}
				UnitStats[item3.Name.ToUpperInvariant()] = val;
			}
		}

		private static Chance Chance(string text)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			string[] array = text.Split('/');
			return new Chance(int.Parse(array[0], CultureInfo.InvariantCulture), (array.Length <= 1) ? 1 : int.Parse(array[1], CultureInfo.InvariantCulture));
		}

		internal static void ApplyUnitStats(ModCivilization civ)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<string, UnitStatChange> unitStat in UnitStats)
			{
				if (Enum.TryParse<Type>(unitStat.Key, out Type result))
				{
					Units.SetCivilizationDefaults(civ, result, unitStat.Value);
				}
				else
				{
					Log.LogWarning((object)("civ.json unitStats: unknown unit \"" + unitStat.Key + "\""));
				}
			}
		}

		internal static void W(string s)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo((object)s);
			}
		}

		internal static void Once(string key, string s)
		{
			if (OnceKeys.Add(key))
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)s);
				}
			}
		}

		internal static string F(float f)
		{
			return f.ToString("F2", CultureInfo.InvariantCulture);
		}
	}
	internal static class Swapper
	{
		private static readonly string[] Civs = new string[5] { "Europe", "Middle East", "Viking", "Ancient", "Maya" };

		private static readonly Dictionary<int, (MeshFilter mf, SkinnedMeshRenderer smr, IntPtr mesh)> Seen = new Dictionary<int, (MeshFilter, SkinnedMeshRenderer, IntPtr)>();

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

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

		internal static string Kebab(string s)
		{
			return s.ToLowerInvariant().Replace(' ', '-');
		}

		internal static string BaseName(string n)
		{
			string[] array = new string[3] { " <", " (", "(" };
			foreach (string value in array)
			{
				int num = n.IndexOf(value, StringComparison.Ordinal);
				if (num >= 0)
				{
					n = n.Substring(0, num);
				}
			}
			return n.Trim();
		}

		private static string GroupOf(string n)
		{
			if (n == null)
			{
				return null;
			}
			int num = n.IndexOf("-mesh_LOD", StringComparison.Ordinal);
			if (num > 0)
			{
				return n.Substring(0, num);
			}
			if (n.EndsWith("-mesh", StringComparison.Ordinal))
			{
				return n.Substring(0, n.Length - 5);
			}
			string text = n.Replace('_', '-').Replace('.', '-');
			int num2 = text.LastIndexOf("-mesh-", StringComparison.Ordinal);
			if (num2 > 0 && !text.Substring(num2 + 6).StartsWith("LOD", StringComparison.OrdinalIgnoreCase))
			{
				return text.Substring(0, num2).ToLowerInvariant() + "-" + text.Substring(num2 + 6).ToLowerInvariant();
			}
			return null;
		}

		private static string Piece(string group, string mainGroup, string mainModel)
		{
			if (mainModel == null || !group.StartsWith(mainGroup + "-", StringComparison.Ordinal))
			{
				return null;
			}
			string text = mainModel + "-" + group.Substring(mainGroup.Length + 1);
			if (!Models.Exists(text))
			{
				return null;
			}
			return text;
		}

		internal static string FileFor(string g)
		{
			if (g == null)
			{
				return null;
			}
			string text = "-" + Kebab(Data.LookWord);
			string text2;
			if (g.EndsWith(text, StringComparison.Ordinal))
			{
				text2 = g.Substring(0, g.Length - text.Length);
			}
			else
			{
				int num = g.IndexOf(text + "-", StringComparison.Ordinal);
				if (num <= 0)
				{
					return null;
				}
				text2 = g.Substring(0, num) + g.Substring(num + text.Length);
			}
			if (!Models.Exists(text2))
			{
				return null;
			}
			return text2;
		}

		private static bool Unchanged(GameObject go)
		{
			if (!Seen.TryGetValue(((Object)go).GetInstanceID(), out (MeshFilter, SkinnedMeshRenderer, IntPtr) value))
			{
				return false;
			}
			if ((Object)(object)value.Item1 != (Object)null)
			{
				if (!((Object)(object)value.Item1.sharedMesh != (Object)null))
				{
					return value.Item3 == IntPtr.Zero;
				}
				return ((Il2CppObjectBase)value.Item1.sharedMesh).Pointer == value.Item3;
			}
			if ((Object)(object)value.Item2 != (Object)null)
			{
				if (!((Object)(object)value.Item2.sharedMesh != (Object)null))
				{
					return value.Item3 == IntPtr.Zero;
				}
				return ((Il2CppObjectBase)value.Item2.sharedMesh).Pointer == value.Item3;
			}
			return value.Item3 == IntPtr.Zero;
		}

		public static void Building(BuildingVisual bv, string why)
		{
			if ((Object)(object)bv == (Object)null)
			{
				return;
			}
			GameObject gameObject = ((Component)bv).gameObject;
			string text = BaseName(((Object)gameObject).name);
			string lookWord = Data.LookWord;
			if (!text.EndsWith(" " + lookWord, StringComparison.Ordinal))
			{
				return;
			}
			string b = Kebab(text.Substring(0, text.Length - lookWord.Length - 1));
			string own = b + "-" + Kebab(lookWord);
			string mainName = b;
			if (Unchanged(gameObject))
			{
				return;
			}
			List<string> civPrefixes = new List<string>();
			string[] civs = Civs;
			foreach (string s in civs)
			{
				civPrefixes.Add(b + "-" + Kebab(s));
			}
			Il2CppArrayBase<MeshFilter> componentsInChildren = gameObject.GetComponentsInChildren<MeshFilter>(true);
			Il2CppArrayBase<SkinnedMeshRenderer> componentsInChildren2 = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			bool flag = false;
			foreach (MeshFilter item in componentsInChildren)
			{
				string text2 = GroupOf(((Object)(object)item.sharedMesh != (Object)null) ? ((Object)item.sharedMesh).name : null) ?? GroupOf(((Object)((Component)item).gameObject).name);
				if (text2 != null && (text2 == own || text2.StartsWith(own + "-", StringComparison.Ordinal)))
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				foreach (SkinnedMeshRenderer item2 in componentsInChildren2)
				{
					string text3 = GroupOf(((Object)(object)item2.sharedMesh != (Object)null) ? ((Object)item2.sharedMesh).name : null) ?? GroupOf(((Object)((Component)item2).gameObject).name);
					if (text3 != null && (text3 == own || text3.StartsWith(own + "-", StringComparison.Ordinal)))
					{
						flag = true;
						break;
					}
				}
			}
			string keep = (flag ? own : (b + "-europe"));
			Model main = (Models.Exists(mainName) ? Models.Get(mainName) : null);
			Root(gameObject, text, Il2CppArrayBase<MeshFilter>.op_Implicit(componentsInChildren), Il2CppArrayBase<SkinnedMeshRenderer>.op_Implicit(componentsInChildren2), ModelFor, main, why, "kept group " + keep);
			string ModelFor(string g)
			{
				if (g == null)
				{
					return null;
				}
				if (g == keep)
				{
					if (!Models.Exists(mainName))
					{
						return null;
					}
					return mainName;
				}
				if (g.StartsWith(keep + "-", StringComparison.Ordinal))
				{
					object obj = Piece(g, keep, mainName);
					if (obj == null)
					{
						if (!Models.Exists(mainName))
						{
							return null;
						}
						obj = "";
					}
					return (string)obj;
				}
				if (g != own)
				{
					string text4 = FileFor(g);
					if (text4 != null)
					{
						return text4;
					}
				}
				if (b == "sorcerer-tower" && g.StartsWith("sorcerer-", StringComparison.Ordinal) && !g.StartsWith("sorcerer-tower", StringComparison.Ordinal))
				{
					return "";
				}
				foreach (string item3 in civPrefixes)
				{
					if (g == item3 || g.StartsWith(item3 + "-", StringComparison.Ordinal))
					{
						return "";
					}
				}
				return null;
			}
		}

		public static void Other(GameObject go, string why)
		{
			if (!((Object)(object)go == (Object)null) && !Unchanged(go))
			{
				Il2CppArrayBase<MeshFilter> componentsInChildren = go.GetComponentsInChildren<MeshFilter>(true);
				Il2CppArrayBase<SkinnedMeshRenderer> componentsInChildren2 = go.GetComponentsInChildren<SkinnedMeshRenderer>(true);
				Root(go, BaseName(((Object)go).name), Il2CppArrayBase<MeshFilter>.op_Implicit(componentsInChildren), Il2CppArrayBase<SkinnedMeshRenderer>.op_Implicit(componentsInChildren2), FileFor, null, why, null);
			}
		}

		private static void Float(MeshFilter mf, Model mdl)
		{
			//IL_008b: 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_0068: 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)
			try
			{
				Transform val = null;
				for (int i = 0; i < ((Component)mf).transform.childCount; i++)
				{
					Transform child = ((Component)mf).transform.GetChild(i);
					if (((Object)((Component)child).gameObject).name.StartsWith("civ-float", StringComparison.Ordinal))
					{
						val = child;
						break;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					GameObject val2 = new GameObject("civ-float")
					{
						layer = ((Component)mf).gameObject.layer
					};
					val = val2.transform;
					val.SetParent(((Component)mf).transform, false);
					val2.AddComponent<MeshFilter>();
					val2.AddComponent<MeshRenderer>();
				}
				val.localPosition = mdl.FloatPivot;
				((Component)val).GetComponent<MeshFilter>().sharedMesh = mdl.FloatMesh;
				MeshRenderer component = ((Component)mf).GetComponent<MeshRenderer>();
				Il2CppReferenceArray<Material> val3 = (((Object)(object)component != (Object)null) ? ((Renderer)component).sharedMaterials : null);
				if (val3 != null && ((Il2CppArrayBase<Material>)(object)val3).Length > 0)
				{
					Material sharedMaterial = ((Il2CppArrayBase<Material>)(object)val3)[0];
					foreach (Material item in (Il2CppArrayBase<Material>)(object)val3)
					{
						if ((Object)(object)item != (Object)null && ((Object)item).name.StartsWith("Colored-Paper", StringComparison.Ordinal))
						{
							sharedMaterial = item;
						}
					}
					((Renderer)((Component)val).GetComponent<MeshRenderer>()).sharedMaterial = sharedMaterial;
				}
				Motion.Add(((Component)val).gameObject, mdl.FloatSpin, mdl.FloatBob, mdl.FloatPeriod);
			}
			catch (Exception ex)
			{
				Data.Once("float:" + mdl.Name, "floating part of " + mdl.Name + " FAIL: " + ex.Message);
			}
		}

		private static void Root(GameObject go, string label, MeshFilter[] filters, SkinnedMeshRenderer[] skinned, Func<string, string> modelFor, Model main, string why, string note)
		{
			//IL_00d8: 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)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			SortedSet<string> sortedSet = new SortedSet<string>();
			SortedSet<string> sortedSet2 = new SortedSet<string>();
			MeshFilter val = null;
			SkinnedMeshRenderer val2 = null;
			foreach (MeshFilter val3 in filters)
			{
				Mesh sharedMesh = val3.sharedMesh;
				if (Models.IsOurs(sharedMesh))
				{
					num4++;
					if (val == null)
					{
						val = val3;
					}
					continue;
				}
				string text = GroupOf(((Object)(object)sharedMesh != (Object)null) ? ((Object)sharedMesh).name : null) ?? GroupOf(((Object)((Component)val3).gameObject).name);
				string text2 = modelFor(text);
				if (text2 == null)
				{
					if (text != null)
					{
						sortedSet2.Add(text);
					}
					if (((Object)((Component)val3).gameObject).name == "flag-big" && main != null && main.HasFlag)
					{
						((Component)val3).transform.localPosition = main.FlagPos;
						((Component)val3).transform.localRotation = Quaternion.Euler(0f, main.FlagYaw, 0f);
						num3++;
					}
					continue;
				}
				if (text2 == "")
				{
					val3.sharedMesh = Models.Empty;
					num2++;
					continue;
				}
				Model model = Models.Get(text2);
				if (model != null)
				{
					val3.sharedMesh = Models.Placed(model, Models.ForStatic(model, ((Component)val3).GetComponent<MeshRenderer>()), text, text.StartsWith("wall-", StringComparison.Ordinal) ? null : Models.Relative(((Component)val3).transform, go.transform));
					if ((Object)(object)model.FloatMesh != (Object)null)
					{
						Float(val3, model);
					}
					if (val == null)
					{
						val = val3;
					}
					num++;
					sortedSet.Add(text + "=" + text2);
				}
			}
			foreach (SkinnedMeshRenderer val4 in skinned)
			{
				Mesh sharedMesh2 = val4.sharedMesh;
				if (Models.IsOurs(sharedMesh2))
				{
					num4++;
					if ((Object)(object)val == (Object)null && val2 == null)
					{
						val2 = val4;
					}
					continue;
				}
				string text3 = GroupOf(((Object)(object)sharedMesh2 != (Object)null) ? ((Object)sharedMesh2).name : null) ?? GroupOf(((Object)((Component)val4).gameObject).name);
				string text4 = modelFor(text3);
				if (text4 == null)
				{
					if (text3 != null)
					{
						sortedSet2.Add(text3);
					}
					continue;
				}
				if (text4 == "")
				{
					val4.sharedMesh = Models.Empty;
					num2++;
					continue;
				}
				Model model2 = Models.Get(text4);
				if (model2 != null)
				{
					val4.sharedMesh = Models.ForSkinned(model2, val4);
					if ((Object)(object)val == (Object)null && val2 == null)
					{
						val2 = val4;
					}
					num++;
					sortedSet.Add(text3 + "=" + text4 + " (skinned)");
				}
			}
			if (main != null && (num > 0 || num4 > 0))
			{
				foreach (Transform componentsInChild in go.GetComponentsInChildren<Transform>(true))
				{
					foreach (var anchor in main.Anchors)
					{
						if (((Object)((Component)componentsInChild).gameObject).name == anchor.name)
						{
							componentsInChild.localPosition = anchor.pos;
							if (anchor.yaw != 0f)
							{
								componentsInChild.localRotation = Quaternion.Euler(0f, anchor.yaw, 0f);
							}
							num3++;
						}
					}
				}
			}
			if ((Object)(object)val == (Object)null && (Object)(object)val2 == (Object)null)
			{
				if (filters.Length != 0)
				{
					val = filters[0];
				}
				else if (skinned.Length != 0)
				{
					val2 = skinned[0];
				}
			}
			Mesh val5 = (((Object)(object)val != (Object)null) ? val.sharedMesh : (((Object)(object)val2 != (Object)null) ? val2.sharedMesh : null));
			Seen[((Object)go).GetInstanceID()] = (val, val2, ((Object)(object)val5 != (Object)null) ? ((Il2CppObjectBase)val5).Pointer : IntPtr.Zero);
			if (num != 0 || num2 != 0 || num4 != 0)
			{
				Scene scene = go.scene;
				bool flag = !((Scene)(ref scene)).IsValid();
				if (Described.Add(label + (flag ? " [prefab]" : "")))
				{
					Data.W("root " + label + (flag ? " [prefab asset]" : "") + ((note != null) ? (", " + note) : "") + ": " + string.Join(", ", sortedSet) + ((sortedSet2.Count > 0) ? (" | untouched groups: " + string.Join(", ", sortedSet2)) : ""));
				}
				if (num + num2 > 0 && (Logged.Add(((Object)go).GetInstanceID()) || (why == "scan" && !flag && Logged.Count < 5000)))
				{
					Data.W("swap[" + why + "] " + ((Object)go).name + (flag ? " [prefab]" : "") + ": " + num + " swapped, " + num2 + " emptied, " + num4 + " already ours, " + num3 + " moved");
				}
			}
		}
	}
	internal static class CivTree
	{
		private sealed class SlotData
		{
			public string Name;

			public TechnologyName Tech;

			public int X;

			public int Y;

			public List<(TechnologyName to, int slot, int from, int toPort)> Links = new List<(TechnologyName, int, int, int)>();
		}

		public static TechTree BuildCopy()
		{
			List<SlotData> list = Read(Data.Json);
			if (list == null)
			{
				return null;
			}
			TechTree val = Civilizations.CloneTree(Data.LookId);
			Write(val, list);
			Data.W("tech tree: layout written into '" + ((Object)val).name + "' (" + list.Count + " slots)");
			return val;
		}

		private static void Write(TechTree tree, List<SlotData> data)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			Il2CppReferenceArray<Slot> slots = tree.slots;
			if (((Il2CppArrayBase<Slot>)(object)slots).Length != data.Count)
			{
				Data.W("tech tree WARN: the file has " + data.Count + " slots, the game " + ((Il2CppArrayBase<Slot>)(object)slots).Length);
			}
			int num = Math.Min(((Il2CppArrayBase<Slot>)(object)slots).Length, data.Count);
			for (int i = 0; i < num; i++)
			{
				Slot val = ((Il2CppArrayBase<Slot>)(object)slots)[i];
				SlotData slotData = data[i];
				val.name = slotData.Name;
				val.technology = slotData.Tech;
				int2 position = val.position;
				position.x = slotData.X;
				position.y = slotData.Y;
				val.position = position;
				Il2CppStructArray<Link> val2 = new Il2CppStructArray<Link>((long)slotData.Links.Count);
				for (int j = 0; j < slotData.Links.Count; j++)
				{
					(TechnologyName to, int slot, int from, int toPort) tuple = slotData.Links[j];
					TechnologyName item = tuple.to;
					int item2 = tuple.slot;
					int item3 = tuple.from;
					int item4 = tuple.toPort;
					((Il2CppArrayBase<Link>)(object)val2)[j] = new Link
					{
						toTechnology = item,
						toSlot = item2,
						fromPort = item3,
						toPort = item4
					};
				}
				val.links = val2;
				((Il2CppArrayBase<Slot>)(object)slots)[i] = val;
			}
			tree.dependencies?.Clear();
		}

		private static List<SlotData> Read(string json)
		{
			//IL_0097: 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)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			using JsonDocument jsonDocument = JsonDocument.Parse(json, Data.JsonOptions);
			if (!jsonDocument.RootElement.TryGetProperty("techTree", out var value) || value.ValueKind != JsonValueKind.Array)
			{
				return null;
			}
			List<SlotData> list = new List<SlotData>();
			List<string[]> list2 = new List<string[]>();
			foreach (JsonElement item in value.EnumerateArray())
			{
				string text = item.GetProperty("technology").GetString();
				JsonElement property = item.GetProperty("position");
				SlotData value2 = new SlotData
				{
					Name = text,
					Tech = Enum.Parse<TechnologyName>(text),
					X = property[0].GetInt32(),
					Y = property[1].GetInt32()
				};
				List<string> list3 = new List<string>();
				if (item.TryGetProperty("unlocks", out var value3))
				{
					foreach (JsonElement item2 in value3.EnumerateArray())
					{
						list3.Add(item2.GetString());
					}
				}
				JsonElement value4;
				int num = (item.TryGetProperty("slot", out value4) ? value4.GetInt32() : list.Count);
				while (list.Count <= num)
				{
					list.Add(null);
					list2.Add(null);
				}
				list[num] = value2;
				list2[num] = list3.ToArray();
			}
			if (list.Contains(null))
			{
				throw new InvalidDataException("slot numbers have gaps");
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			for (int i = 0; i < list.Count; i++)
			{
				dictionary[list[i].Name] = i;
			}
			int[] array = new int[list.Count];
			int[] array2 = new int[list.Count];
			for (int j = 0; j < list.Count; j++)
			{
				string[] array3 = list2[j];
				foreach (string text2 in array3)
				{
					if (dictionary.TryGetValue(text2, out var value5))
					{
						array[j]++;
						array2[value5]++;
					}
					else
					{
						Data.W("tech tree WARN: " + list[j].Name + " unlocks unknown " + text2);
					}
				}
			}
			for (int l = 0; l < list.Count; l++)
			{
				string[] array3 = list2[l];
				foreach (string key in array3)
				{
					if (dictionary.TryGetValue(key, out var value6))
					{
						int num2 = Math.Sign(list[value6].Y - list[l].Y);
						list[l].Links.Add((list[value6].Tech, value6, (array[l] > 1) ? num2 : 0, (array2[value6] > 1) ? (-num2) : 0));
					}
				}
			}
			return list;
		}
	}
}