Decompiled source of CivJapan v1.0.0

BepInEx/plugins/DiceModders.CivJapan/DiceModders.CivJapan.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("Japan as a new civilization for Dice Kingdoms: its own buildings, units, tech tree, texts and AI build orders.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DiceModders.CivJapan")]
[assembly: AssemblyTitle("DiceModders.CivJapan")]
[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 DiceModders.CivJapan
{
	internal static class JapanCiv
	{
		private sealed record Picture(Il2CppReferenceArray<Sprite> Original, GameObject Copy, Action<Il2CppReferenceArray<Sprite>> Set, bool Unit);

		internal static ModCivilization Civ;

		private static TechTree _tree;

		private static bool _treeTried;

		public static void Register()
		{
			//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_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: 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)
			string value;
			string text = (Japan.Names.TryGetValue("en", out value) ? value : "Japan");
			Civ = Civilizations.Add(Japan.CivKey, text, (Func<TechTree>)Tree, Japan.CivId);
			if (Japan.Names.Count > 0)
			{
				Civilizations.Rename(Civ.Id, text, (IReadOnlyDictionary<string, string>)Japan.Names);
			}
			foreach (KeyValuePair<string, Dictionary<string, string>> text2 in Japan.Texts)
			{
				Civilizations.SetText(Civ.Id, text2.Key, text2.Value.TryGetValue("en", out var value2) ? value2 : new List<string>(text2.Value.Values)[0], (IReadOnlyDictionary<string, string>)text2.Value);
			}
			foreach (var (num, num2, val) in Japan.GroundCells)
			{
				Civ.Skins.GroundColour(num, num2, val);
			}
			foreach (var (num3, num4, val2) in Japan.NatureCells)
			{
				Civ.Skins.NatureColour(num3, num4, val2);
			}
			TextureCache.Prefetch(new string[1] { Civ.Name + " Text" });
			DiskCache.Prefetch(DiskCache.FilesOf("civjapan"));
			if (File.Exists(Japan.BuildOrdersFile))
			{
				Japan.W(Civilizations.AddBuildOrders(Civ.Id, File.ReadAllText(Japan.BuildOrdersFile)) + " AI build orders read");
			}
			Civilizations.WhenGameDataLoaded((Action)Build);
			Japan.W("'" + text + "' registered as civilization " + Civ.Id + " (key " + Japan.CivKey + ", looks like " + Japan.CivEnum + ")");
		}

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

		private static void Build()
		{
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: 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_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0297: 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_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Expected I4, but got Unknown
			//IL_0209: 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)
			{
				Japan.W("no skin registry");
				return;
			}
			PlayerSkins val2 = new PlayerSkins((Civilization)Japan.CivId, val[0]);
			string text = "-" + Swapper.Kebab(Japan.CivWord);
			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(text, 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)
			{
				Japan.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(" " + Japan.CivWord, StringComparison.Ordinal))
				{
					continue;
				}
				try
				{
					if (!dictionary2.TryGetValue(((Il2CppObjectBase)buildingVisualPrefab).Pointer, out var value))
					{
						value = Prefabs.Copy<BuildingVisual>(buildingVisualPrefab, (string)null);
						Swapper.Building(value, "civ");
						Relink(((Component)value).gameObject, dictionary);
						dictionary2[((Il2CppObjectBase)buildingVisualPrefab).Pointer] = value;
						BuildingVisual c = value;
						if (HasModel(buildingVisualPrefab))
						{
							list.Add(new Picture(buildingVisualPrefab.icons, ((Component)value).gameObject, delegate(Il2CppReferenceArray<Sprite> s)
							{
								c.icons = s;
							}, Unit: false));
						}
					}
					Civ.Skins.Building(item2.name, value);
					num++;
				}
				catch (Exception ex)
				{
					Japan.W("building " + ((object)item2.name/*cast due to .constrained prefix*/).ToString() + " FAIL (keeps the look-alike's): " + ex.Message);
				}
			}
			foreach (Type value2 in Enum.GetValues(typeof(Type)))
			{
				UnitVisual unitVisualPrefab;
				try
				{
					unitVisualPrefab = val2.GetUnitVisualPrefab(value2);
				}
				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 (Japan.ModelMap.ContainsKey(Swapper.Kebab(((object)value2/*cast due to .constrained prefix*/).ToString()) + text))
					{
						list.Add(new Picture(unitVisualPrefab.icons, ((Component)copy).gameObject, delegate(Il2CppReferenceArray<Sprite> s)
						{
							copy.icons = s;
						}, Unit: true));
					}
					Civ.Skins.Unit((int)value2, copy);
					num2++;
				}
				catch (Exception ex2)
				{
					Japan.W("unit " + ((object)value2/*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");
					Civ.Skins.Ship(val6);
				}
			}
			catch (Exception ex3)
			{
				Japan.W("ship FAIL " + ex3.Message);
			}
			RenderPictures(list);
			Japan.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 <= Japan.CivWord.Length)
			{
				return false;
			}
			string key = Swapper.Kebab(text.Substring(0, text.Length - Japan.CivWord.Length - 1)) + "-" + Swapper.Kebab(Japan.CivWord);
			return Japan.ModelMap.ContainsKey(key);
		}

		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 = Japan.CivKey + " " + ((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(Civ.Name + " Text", (IEnumerable<Entry>)texts, StableHash(stringBuilder.ToString()));
						Japan.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(Japan.CivWord) + "-";
			int num = original.LastIndexOf(text, StringComparison.Ordinal);
			if (num >= 0)
			{
				return original.Substring(0, num) + "-" + Japan.Token + "-" + original.Substring(num + text.Length);
			}
			return original + "-" + Japan.Token;
		}
	}
	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 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 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;

		internal const string CacheFolder = "civjapan";

		private const int BinVersion = 1;

		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)
		{
			Japan.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(Japan.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("civjapan", name + ".bin");
		}

		private static Model Load(string name)
		{
			FileInfo fileInfo = new FileInfo(Path.Combine(Japan.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_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: 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(1);
					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);
					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_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: 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() != 1 || 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();
				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_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_0415: Unknown result type (might be due to invalid IL or missing references)
			//IL_0422: Unknown result type (might be due to invalid IL or missing references)
			//IL_0432: Unknown result type (might be due to invalid IL or missing references)
			//IL_0437: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_043f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0449: Unknown result type (might be due to invalid IL or missing references)
			//IL_044f: Unknown result type (might be due to invalid IL or missing references)
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_0480: Unknown result type (might be due to invalid IL or missing references)
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0491: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			//IL_0579: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: 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;
			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;
					}
					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 "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;
			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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: 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_0073: Expected O, but got Unknown
			Model model = new Model
			{
				Name = name,
				Bones = x.Bones,
				BindPoses = x.BindPoses,
				HasFlag = x.HasFlag,
				FlagPos = x.FlagPos,
				FlagYaw = x.FlagYaw,
				Anchors = x.Anchors
			};
			Mesh val = new Mesh
			{
				name = "custom-" + name,
				indexFormat = (IndexFormat)1
			};
			val.vertices = Il2CppStructArray<Vector3>.op_Implicit(x.V);
			val.uv = Il2CppStructArray<Vector2>.op_Implicit(x.UV);
			val.triangles = Il2CppStructArray<int>.op_Implicit(x.T);
			val.normals = Il2CppStructArray<Vector3>.op_Implicit(x.N);
			model.Mesh = Keep(val);
			int[] array = (model.AllTris = x.T);
			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" : ""));
			return model;
		}

		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)
			{
				Japan.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");
			}
			Japan.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())
			{
				Japan.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))
			{
				Japan.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)
			{
				Japan.W("SKIN WARN: bindpose count " + getBPC(((Il2CppObjectBase)c).Pointer) + " expected " + nb + " on " + ((Object)c).name);
			}
		}
	}
	[BepInPlugin("org.dicemodders.dicekingdoms.civjapan", "DiceKingdoms CivJapan", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Dice-Kingdoms.exe")]
	public sealed class Plugin : BasePlugin
	{
		public const string Guid = "org.dicemodders.dicekingdoms.civjapan";

		public const string Name = "DiceKingdoms CivJapan";

		public const string Version = "1.0.0";

		public override void Load()
		{
			Japan.Log = ((BasePlugin)this).Log;
			Japan.AssetDir = Path.Combine(Path.GetDirectoryName(typeof(Plugin).Assembly.Location) ?? "", "assets");
			try
			{
				Japan.Read(Path.Combine(Japan.AssetDir, "japan.json"));
			}
			catch (Exception ex)
			{
				((BasePlugin)this).Log.LogError((object)("could not read assets\\japan.json (install the whole folder, not only the DLL): " + ex.Message));
				return;
			}
			try
			{
				JapanCiv.Register();
			}
			catch (Exception ex2)
			{
				((BasePlugin)this).Log.LogError((object)("could not register the civilization: " + ex2));
			}
		}
	}
	internal static class Japan
	{
		internal static ManualLogSource Log;

		internal static string AssetDir;

		internal static readonly Dictionary<string, string> ModelMap = new Dictionary<string, string>();

		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 Dictionary<string, string> Names = new Dictionary<string, string>();

		internal static readonly Dictionary<string, Dictionary<string, string>> Texts = new Dictionary<string, Dictionary<string, string>>();

		internal static string CivEnum = "VIKING";

		internal static string CivWord = "Viking";

		internal static int CivId = 2;

		internal static string CivKey = "dicemodders.japan";

		internal static string Token = "japan";

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

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

		internal static string BuildOrdersFile => Path.Combine(AssetDir, "build_orders.txt");

		internal static string TechTreeJson()
		{
			using Stream stream = typeof(Japan).Assembly.GetManifestResourceStream("techtree.json");
			if (stream == null)
			{
				throw new FileNotFoundException("techtree.json is not embedded in the DLL");
			}
			using StreamReader streamReader = new StreamReader(stream);
			return streamReader.ReadToEnd();
		}

		internal static void Read(string path)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected I4, but got Unknown
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(path));
			JsonElement rootElement = jsonDocument.RootElement;
			if (rootElement.TryGetProperty("civilization", out var value))
			{
				CivEnum = value.GetString();
				CivId = (int)Enum.Parse<Civilization>(CivEnum);
				CivWord = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(CivEnum.ToLowerInvariant().Replace('_', ' '));
			}
			if (rootElement.TryGetProperty("key", out var value2))
			{
				CivKey = value2.GetString();
			}
			if (rootElement.TryGetProperty("token", out var value3))
			{
				Token = value3.GetString();
			}
			foreach (JsonProperty item2 in rootElement.GetProperty("models").EnumerateObject())
			{
				ModelMap[item2.Name] = item2.Value.GetString();
			}
			if (rootElement.TryGetProperty("ground", out var value4))
			{
				(string, List<(int, int, Color)>)[] array = new(string, List<(int, int, Color)>)[2]
				{
					("cells", GroundCells),
					("natureCells", NatureCells)
				};
				Color item = default(Color);
				for (int i = 0; i < array.Length; i++)
				{
					var (propertyName, list) = array[i];
					if (!value4.TryGetProperty(propertyName, out var value5))
					{
						continue;
					}
					foreach (JsonProperty item3 in value5.EnumerateObject())
					{
						string[] array2 = item3.Name.Split(',');
						if (ColorUtility.TryParseHtmlString(item3.Value.GetString(), ref item))
						{
							list.Add((int.Parse(array2[0]), int.Parse(array2[1]), item));
						}
					}
				}
			}
			if (rootElement.TryGetProperty("name", out var value6))
			{
				foreach (JsonProperty item4 in value6.EnumerateObject())
				{
					if (item4.Value.ValueKind == JsonValueKind.String)
					{
						Names[item4.Name] = item4.Value.GetString();
					}
				}
			}
			if (!rootElement.TryGetProperty("texts", out var value7))
			{
				return;
			}
			foreach (JsonProperty item5 in value7.EnumerateObject())
			{
				if (item5.Value.ValueKind != JsonValueKind.Object)
				{
					continue;
				}
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				foreach (JsonProperty item6 in item5.Value.EnumerateObject())
				{
					if (item6.Value.ValueKind == JsonValueKind.String)
					{
						dictionary[item6.Name] = item6.Value.GetString();
					}
				}
				if (dictionary.Count > 0)
				{
					Texts[item5.Name] = dictionary;
				}
			}
		}

		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);
			}
			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;
		}

		private static string FromMap(string g)
		{
			if (Japan.ModelMap.TryGetValue(g, out var value))
			{
				if (!Models.Exists(value))
				{
					return null;
				}
				return value;
			}
			foreach (KeyValuePair<string, string> item in Japan.ModelMap)
			{
				string text = Piece(g, item.Key, item.Value);
				if (text != null)
				{
					return text;
				}
			}
			return null;
		}

		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 civWord = Japan.CivWord;
			if (!text.EndsWith(" " + civWord, StringComparison.Ordinal))
			{
				return;
			}
			string text2 = Kebab(text.Substring(0, text.Length - civWord.Length - 1));
			string own = text2 + "-" + Kebab(civWord);
			Japan.ModelMap.TryGetValue(own, out var mainName);
			if (Unchanged(gameObject))
			{
				return;
			}
			List<string> civPrefixes = new List<string>();
			string[] civs = Civs;
			foreach (string s in civs)
			{
				civPrefixes.Add(text2 + "-" + 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 text3 = GroupOf(((Object)(object)item.sharedMesh != (Object)null) ? ((Object)item.sharedMesh).name : null) ?? GroupOf(((Object)((Component)item).gameObject).name);
				if (text3 != null && (text3 == own || text3.StartsWith(own + "-", StringComparison.Ordinal)))
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				foreach (SkinnedMeshRenderer item2 in componentsInChildren2)
				{
					string text4 = GroupOf(((Object)(object)item2.sharedMesh != (Object)null) ? ((Object)item2.sharedMesh).name : null) ?? GroupOf(((Object)((Component)item2).gameObject).name);
					if (text4 != null && (text4 == own || text4.StartsWith(own + "-", StringComparison.Ordinal)))
					{
						flag = true;
						break;
					}
				}
			}
			string keep = (flag ? own : (text2 + "-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))
				{
					return Piece(g, keep, mainName);
				}
				if (g != own)
				{
					string text5 = FromMap(g);
					if (text5 != null)
					{
						return text5;
					}
				}
				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), (string g) => (g != null) ? FromMap(g) : null, null, why, null);
			}
		}

		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_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: 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.ForStatic(model, ((Component)val3).GetComponent<MeshRenderer>());
					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]" : "")))
				{
					Japan.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)))
				{
					Japan.W("swap[" + why + "] " + ((Object)go).name + (flag ? " [prefab]" : "") + ": " + num + " swapped, " + num2 + " emptied, " + num4 + " already ours, " + num3 + " moved");
				}
			}
		}
	}
	internal static class JapanTree
	{
		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(Japan.TechTreeJson());
			if (list == null)
			{
				return null;
			}
			TechTree val = Civilizations.CloneTree(Japan.CivId);
			Write(val, list);
			Japan.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)
			{
				Japan.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_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			using JsonDocument jsonDocument = JsonDocument.Parse(json);
			JsonElement value = default(JsonElement);
			foreach (JsonProperty item in jsonDocument.RootElement.EnumerateObject())
			{
				if (item.Value.ValueKind == JsonValueKind.Object && item.Value.TryGetProperty("slots", out value))
				{
					break;
				}
			}
			if (value.ValueKind != JsonValueKind.Array)
			{
				Japan.W("tech tree: no 'slots' array");
				return null;
			}
			List<SlotData> list = new List<SlotData>();
			List<string[]> list2 = new List<string[]>();
			foreach (JsonElement item2 in value.EnumerateArray())
			{
				string text = item2.GetProperty("technology").GetString();
				JsonElement property = item2.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 (item2.TryGetProperty("unlocks", out var value3))
				{
					foreach (JsonElement item3 in value3.EnumerateArray())
					{
						list3.Add(item3.GetString());
					}
				}
				JsonElement value4;
				int num = (item2.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
					{
						Japan.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;
		}
	}
}