Decompiled source of Civilisations Japon Heian v1.1.2

plugins/HeianMod/HeianMod.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ControlledRandomness;
using HarmonyLib;
using I2.Loc;
using RTM.UISystem;
using Spriteshop;
using UnityEngine;
using UnityEngine.UI;
using Voxels.TowerDefense;
using Voxels.TowerDefense.CampaignGeneration;
using Voxels.TowerDefense.HeroGeneration;
using Voxels.TowerDefense.ProfileInternals;
using Voxels.TowerDefense.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace HeianMod;

internal static class ClanBanner
{
	private static readonly string[] mons = new string[6] { "hikiryo", "uroko", "kuyo", "hanabishi", "mokko", "kikyo" };

	private static readonly FieldInfo bannerF = AccessTools.Field(typeof(MonoHero), "traitSpriteBanner");

	private static readonly FieldInfo genF = AccessTools.Field(typeof(MonoHero), "bannerSpriteGen");

	private static readonly MethodInfo drawAll = AccessTools.Method(typeof(MonoHero), "DrawAll", (Type[])null, (Type[])null);

	private static readonly Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

	private static readonly Dictionary<SpriteRenderer, Vector3> baseScale = new Dictionary<SpriteRenderer, Vector3>();

	private static readonly HashSet<GameObject> hiddenSlots = new HashSet<GameObject>();

	private static Sprite Get(string n)
	{
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Expected O, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		if (sprites.TryGetValue(n, out var value))
		{
			return value;
		}
		string path = Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", Path.Combine("clan", n + ".png")));
		if (!File.Exists(path))
		{
			sprites[n] = null;
			return null;
		}
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
		ImageConversion.LoadImage(val, File.ReadAllBytes(path));
		((Texture)val).wrapMode = (TextureWrapMode)1;
		Object.DontDestroyOnLoad((Object)(object)val);
		value = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0);
		((Object)value).name = "Kamon_" + n;
		Object.DontDestroyOnLoad((Object)(object)value);
		sprites[n] = value;
		return value;
	}

	private static PsdGroup Slot(MonoHero hero)
	{
		object? value = genF.GetValue(hero);
		Component val = (Component)((value is Component) ? value : null);
		if ((Object)(object)val == (Object)null)
		{
			return null;
		}
		PsdGroup[] componentsInChildren = val.GetComponentsInChildren<PsdGroup>(true);
		foreach (PsdGroup val2 in componentsInChildren)
		{
			if (val2.splitName != null && Array.IndexOf(val2.splitName, "IconSlot2") >= 0)
			{
				return val2;
			}
		}
		return null;
	}

	internal static void Before(MonoHero hero)
	{
		PsdGroup val = Slot(hero);
		if ((Object)(object)val != (Object)null && hiddenSlots.Remove(((Component)val).gameObject))
		{
			((Component)val).gameObject.SetActive(true);
		}
	}

	internal static void After(MonoHero hero)
	{
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: 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_012e: 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_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (HeianPlugin.CurrentCiv != Civ.Heian)
			{
				return;
			}
			object? value = bannerF.GetValue(hero);
			SpriteRenderer val = (SpriteRenderer)((value is SpriteRenderer) ? value : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val.sprite != (Object)null)
			{
				return;
			}
			PsdGroup val2 = Slot(hero);
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			Sprite val3 = Get(mons[Mathf.Abs(hero.seed) % mons.Length]);
			if (!((Object)(object)val3 == (Object)null))
			{
				if (!baseScale.TryGetValue(val, out var value2))
				{
					value2 = ((Component)val).transform.localScale;
					baseScale[val] = value2;
				}
				((Component)val).transform.localScale = value2;
				val.sprite = val3;
				float num = ((Rect)(ref val2.innerRect)).width * Mathf.Abs(((Component)val2).transform.lossyScale.x) * 0.9f;
				Bounds val4 = ((Renderer)val).bounds;
				float x = ((Bounds)(ref val4)).size.x;
				if (x > 1E-05f)
				{
					((Component)val).transform.localScale = value2 * (num / x);
				}
				Transform transform = ((Component)val2).transform;
				val4 = val2.innerBounds;
				Vector3 val5 = transform.TransformPoint(((Bounds)(ref val4)).center);
				Transform transform2 = ((Component)val).transform;
				Vector3 position = transform2.position;
				val4 = ((Renderer)val).bounds;
				transform2.position = position + (val5 - ((Bounds)(ref val4)).center);
				((Component)val2).gameObject.SetActive(false);
				hiddenSlots.Add(((Component)val2).gameObject);
				if ((object)drawAll != null)
				{
					drawAll.Invoke(hero, null);
				}
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogWarning((object)("Blason : " + ex.Message));
		}
	}
}
internal static class HouseMeshes
{
	private static readonly MeshSet set = new MeshSet("houses", new string[8] { "House_Shed_Intact", "House_Shed_Pillaged", "House_Long_Intact", "House_Long_Pillaged", "House_Big_Intact", "House_Big_Pillaged", "House_Church_Intact", "House_Church_Pillaged" });

	internal static void Apply(Civ civ)
	{
		try
		{
			int num = 0;
			House[] array = Object.FindObjectsOfType<House>();
			for (int i = 0; i < array.Length; i++)
			{
				MeshFilter[] componentsInChildren = ((Component)array[i]).GetComponentsInChildren<MeshFilter>(true);
				foreach (MeshFilter mf in componentsInChildren)
				{
					if (set.Swap(mf, civ))
					{
						num++;
					}
				}
			}
			if (num > 0)
			{
				HeianPlugin.Log.LogInfo((object)("Maisons remplacées : " + num + " (" + civ.ToString() + ")"));
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogError((object)("Maisons : " + ex));
		}
	}
}
internal class MeshSet
{
	private readonly string folder;

	private readonly string[] names;

	private Dictionary<string, Mesh> raw;

	private readonly Dictionary<string, Mesh> variants = new Dictionary<string, Mesh>();

	private readonly Dictionary<string, Mesh> originals = new Dictionary<string, Mesh>();

	internal MeshSet(string folder, string[] names)
	{
		this.folder = folder;
		this.names = names;
	}

	private static void Split(string n, out string baseName, out string suffix)
	{
		suffix = "";
		while (n.EndsWith("(Clone)"))
		{
			n = n.Substring(0, n.Length - 7);
		}
		if (n.EndsWith(" Soft"))
		{
			suffix = " Soft";
			n = n.Substring(0, n.Length - 5);
		}
		else if (n.EndsWith(" Inverted"))
		{
			suffix = " Inverted";
			n = n.Substring(0, n.Length - 9);
		}
		baseName = n;
	}

	private Mesh Variant(string baseName, string suffix)
	{
		if (variants.TryGetValue(baseName + suffix, out var value))
		{
			return value;
		}
		if (raw == null)
		{
			raw = MeshLoader.Load(folder, names, new Dictionary<Mesh, string>());
		}
		if (!raw.TryGetValue(baseName, out var value2))
		{
			return null;
		}
		value = Object.Instantiate<Mesh>(value2);
		((Object)value).name = baseName + "_Heian" + suffix;
		if (folder == "bows" || folder == "shields")
		{
			value.colors32 = (Color32[])(object)new Color32[0];
		}
		try
		{
			if (suffix.Length > 0)
			{
				Extensions.SoftNormalsInTangents(value);
			}
			if (suffix == " Inverted")
			{
				Extensions.Invert(value);
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogWarning((object)("Normales : " + ex.Message));
		}
		Object.DontDestroyOnLoad((Object)(object)value);
		variants[baseName + suffix] = value;
		return value;
	}

	internal bool Swap(MeshFilter mf, Civ civ)
	{
		Mesh sharedMesh = mf.sharedMesh;
		if ((Object)(object)sharedMesh == (Object)null)
		{
			return false;
		}
		Split(((Object)sharedMesh).name, out var baseName, out var suffix);
		bool flag = baseName.EndsWith("_Heian");
		if (civ == Civ.Heian)
		{
			if (flag || Array.IndexOf(names, baseName) < 0)
			{
				return false;
			}
			Mesh val = Variant(baseName, suffix);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if (!originals.ContainsKey(baseName + suffix))
			{
				originals[baseName + suffix] = sharedMesh;
			}
			mf.sharedMesh = val;
			return true;
		}
		if (!flag)
		{
			return false;
		}
		if (originals.TryGetValue(baseName.Substring(0, baseName.Length - 6) + suffix, out var value))
		{
			mf.sharedMesh = value;
			return true;
		}
		return false;
	}
}
internal static class WeaponMeshes
{
	private static readonly MeshSet bows = new MeshSet("bows", new string[5] { "Archer_Bow_Short_1", "Archer_Bow_Short_2", "Archer_Bow_Short_3", "Archer_Bow_Viking", "Weapons_TankArcher_Bow" });

	private static readonly MeshSet shields = new MeshSet("shields", new string[13]
	{
		"Weapons_Shield_1", "Weapons_Shield_2", "Weapons_Shield_3", "Weapons_VikingShield_1", "Weapons_VikingShield_2", "Weapons_VikingShield_3", "Weapons_VikingShield_4", "Weapons_VikingShield_6", "Weapons_VikingShield_7", "Weapons_VikingShield_8",
		"Weapons_VikingShield_9", "Weapons_VikingShield_10", "Weapons_DropShield_1"
	});

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

	private static int total;

	internal static void Apply(Civ civ)
	{
		try
		{
			int num = 0;
			MeshFilter[] array = Object.FindObjectsOfType<MeshFilter>();
			foreach (MeshFilter val in array)
			{
				Mesh sharedMesh = val.sharedMesh;
				if ((Object)(object)sharedMesh == (Object)null)
				{
					continue;
				}
				string name = ((Object)sharedMesh).name;
				if (name.IndexOf("Bow", StringComparison.Ordinal) >= 0 || name.IndexOf("Shield", StringComparison.Ordinal) >= 0)
				{
					if (seen.Add(name))
					{
						HeianPlugin.Log.LogInfo((object)("Arme vue : " + name));
					}
					if (bows.Swap(val, civ) || shields.Swap(val, civ))
					{
						num++;
					}
				}
			}
			if (num > 0)
			{
				total += num;
				if (total == num)
				{
					HeianPlugin.Log.LogInfo((object)("Armes remplacées : " + num + " (" + civ.ToString() + ")"));
				}
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogWarning((object)("Armes : " + ex.Message));
		}
	}
}
internal static class ShipMeshes
{
	private static readonly MeshSet set = new MeshSet("ships", new string[8] { "Ship_Tiny_Body", "Ship_Tiny_Lid", "Ship_Small_Body", "Ship_Small_Lid", "Ship_Long_Body", "Ship_Long_Lid", "Ship_Dragon_Body", "Ship_Dragon_Lid" });

	private static readonly Dictionary<Renderer, Material> lidMats = new Dictionary<Renderer, Material>();

	private static Material houseMat;

	internal static void Apply(Civ civ)
	{
		try
		{
			int num = 0;
			Longship[] array = Object.FindObjectsOfType<Longship>();
			for (int i = 0; i < array.Length; i++)
			{
				MeshFilter[] componentsInChildren = ((Component)array[i]).GetComponentsInChildren<MeshFilter>(true);
				foreach (MeshFilter val in componentsInChildren)
				{
					bool num2 = (Object)(object)val.sharedMesh != (Object)null && ((Object)val.sharedMesh).name.Contains("_Lid");
					if (set.Swap(val, civ))
					{
						num++;
					}
					if (!num2)
					{
						continue;
					}
					Renderer component = ((Component)val).GetComponent<Renderer>();
					if ((Object)(object)component == (Object)null)
					{
						continue;
					}
					Material value;
					if (civ == Civ.Heian)
					{
						if ((Object)(object)houseMat == (Object)null)
						{
							Material[] array2 = Resources.FindObjectsOfTypeAll<Material>();
							foreach (Material val2 in array2)
							{
								if ((Object)(object)val2 != (Object)null && ((Object)val2).name == "House")
								{
									houseMat = val2;
									break;
								}
							}
						}
						if ((Object)(object)houseMat != (Object)null && (Object)(object)component.sharedMaterial != (Object)(object)houseMat)
						{
							if (!lidMats.ContainsKey(component))
							{
								lidMats[component] = component.sharedMaterial;
							}
							component.sharedMaterial = houseMat;
						}
					}
					else if (lidMats.TryGetValue(component, out value))
					{
						component.sharedMaterial = value;
						lidMats.Remove(component);
					}
				}
			}
			if (num > 0)
			{
				HeianPlugin.Log.LogInfo((object)("Bateaux remplacés : " + num + " pièces (" + civ.ToString() + ")"));
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogError((object)("Bateaux : " + ex));
		}
	}
}
internal static class MeshLoader
{
	internal static Dictionary<string, Mesh> Load(string folder, string[] names, Dictionary<Mesh, string> reverse)
	{
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Expected O, but got Unknown
		Dictionary<string, Mesh> dictionary = new Dictionary<string, Mesh>();
		string path = Path.Combine(HeianPlugin.ModDir, folder);
		foreach (string text in names)
		{
			string text2 = Path.Combine(path, text + ".txt");
			if (!File.Exists(text2))
			{
				HeianPlugin.Log.LogWarning((object)("Maillage manquant : " + text2));
				continue;
			}
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<Color32> list3 = new List<Color32>();
			string[] array = File.ReadAllLines(text2);
			for (int j = 0; j < array.Length; j++)
			{
				string[] array2 = array[j].Split(new char[1] { ' ' });
				if (array2.Length >= 6)
				{
					list.Add(new Vector3(F(array2[0]), F(array2[1]), F(array2[2])));
					list2.Add(new Vector2(F(array2[3]), F(array2[4])));
					byte b = (byte)int.Parse(array2[5]);
					list3.Add(new Color32(b, b, b, byte.MaxValue));
				}
			}
			int[] array3 = new int[list.Count];
			for (int k = 0; k < array3.Length; k++)
			{
				array3[k] = k;
			}
			Mesh val = new Mesh
			{
				name = text + "_Heian"
			};
			val.SetVertices(list);
			val.SetUVs(0, list2);
			val.SetColors(list3);
			val.triangles = array3;
			val.RecalculateNormals();
			val.RecalculateBounds();
			try
			{
				val.RecalculateTangents();
			}
			catch
			{
			}
			Object.DontDestroyOnLoad((Object)(object)val);
			dictionary[text] = val;
			reverse[val] = text;
		}
		HeianPlugin.Log.LogInfo((object)("Maillages « " + folder + " » chargés : " + dictionary.Count));
		return dictionary;
	}

	private static float F(string s)
	{
		return float.Parse(s, CultureInfo.InvariantCulture);
	}
}
[HarmonyPatch(typeof(IslandStyle2), "ApplyShaderConstants")]
internal static class Patch_IslandStyle
{
	private static readonly FieldInfo texIdF = AccessTools.Field(typeof(IslandStyle2), "texId");

	private static readonly FieldInfo gradF = AccessTools.Field(typeof(IslandStyle2), "gradient");

	private static readonly MethodInfo makeTex = AccessTools.Method(typeof(IslandStyle2), "MaybeCreateTexture", (Type[])null, (Type[])null);

	private static readonly MethodInfo genTex = AccessTools.Method(typeof(IslandStyle2), "GenerateTexture", (Type[])null, (Type[])null);

	private static readonly Dictionary<IslandStyle2, Gradient> originals = new Dictionary<IslandStyle2, Gradient>();

	private static readonly Dictionary<IslandStyle2, Civ> state = new Dictionary<IslandStyle2, Civ>();

	private static readonly float[] times = new float[8] { 0f, 0.16f, 0.24f, 0.32f, 0.5f, 0.68f, 0.76f, 0.9f };

	private static void Prefix(IslandStyle2 __instance)
	{
		try
		{
			Civ currentCiv = HeianPlugin.CurrentCiv;
			if (state.TryGetValue(__instance, out var value) && value == currentCiv)
			{
				return;
			}
			string text = (texIdF.GetValue(__instance) as string) ?? "";
			bool flag = text.IndexOf("Tree", StringComparison.OrdinalIgnoreCase) >= 0;
			bool flag2 = text.IndexOf("Grass", StringComparison.OrdinalIgnoreCase) >= 0;
			if (!flag && !flag2)
			{
				state[__instance] = currentCiv;
				return;
			}
			if (!originals.TryGetValue(__instance, out var value2))
			{
				object? value3 = gradF.GetValue(__instance);
				value2 = (Gradient)((value3 is Gradient) ? value3 : null);
				if (value2 == null)
				{
					return;
				}
				originals[__instance] = value2;
			}
			gradF.SetValue(__instance, (currentCiv == Civ.Heian) ? Heian(value2, flag) : value2);
			makeTex.Invoke(__instance, null);
			genTex.Invoke(__instance, null);
			state[__instance] = currentCiv;
			HeianPlugin.Log.LogInfo((object)("Palette " + text + " -> " + currentCiv));
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogError((object)("Saisons : " + ex));
		}
	}

	private static float Bump(float t, float c, float w)
	{
		return Mathf.Clamp01(1f - Mathf.Abs(t - c) / w);
	}

	private static Gradient Heian(Gradient o, bool tree)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cc: Expected O, but got Unknown
		//IL_0117: 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)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: 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_017d: 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_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: 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_00ab: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: 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)
		GradientColorKey[] array = (GradientColorKey[])(object)new GradientColorKey[times.Length];
		for (int i = 0; i < times.Length; i++)
		{
			float num = times[i];
			Color val = o.Evaluate(num);
			float num2 = Mathf.Max(0.05f, val.r * 0.3f + val.g * 0.59f + val.b * 0.11f);
			float num3 = Bump(num, 0.24f, 0.09f);
			float num4 = Bump(num, 0.76f, 0.11f);
			if (tree)
			{
				Color val2 = new Color(0.98f, 0.72f, 0.8f) * Mathf.Clamp(num2 / 0.45f, 0.6f, 1.2f);
				Color val3 = new Color(0.86f, 0.28f, 0.14f) * Mathf.Clamp(num2 / 0.42f, 0.6f, 1.2f);
				val = Color.Lerp(val, val2, 0.92f);
				val = Color.Lerp(val, val3, num4 * 0.35f);
			}
			else
			{
				Color val4 = new Color(0.5f, 0.66f, 0.38f) * Mathf.Clamp(num2 / 0.55f, 0.7f, 1.2f);
				Color val5 = new Color(0.8f, 0.63f, 0.36f) * Mathf.Clamp(num2 / 0.55f, 0.7f, 1.2f);
				val = Color.Lerp(val, val4, num3 * 0.5f);
				val = Color.Lerp(val, val5, num4 * 0.75f);
			}
			val.a = 1f;
			array[i] = new GradientColorKey(val, num);
		}
		Gradient val6 = new Gradient();
		val6.SetKeys(array, o.alphaKeys);
		return val6;
	}
}
public enum Civ
{
	Nordique,
	Heian
}
[BepInPlugin("fr.natchoum.badnorth.heian", "Civilisations : Japon Heian", "1.1.2")]
public class HeianPlugin : BaseUnityPlugin
{
	internal static HeianPlugin Instance;

	internal static ManualLogSource Log;

	internal static Civ CurrentCiv = Civ.Nordique;

	internal static ConfigEntry<int> SelectedCiv;

	internal static string ModDir;

	private static string campaignsFile;

	private static readonly Dictionary<int, Civ> campaignCivs = new Dictionary<int, Civ>();

	private static readonly FieldInfo dirtyFlagsField = AccessTools.Field(typeof(HeroCustomizer), "dirtyFlags");

	private void Awake()
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: 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_0090: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		ModDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		SelectedCiv = ((BaseUnityPlugin)this).Config.Bind<int>("General", "CivilisationNouvellePartie", 0, "0 = Nordiques (jeu de base), 1 = Japon Heian. Modifiable depuis le menu Nouvelle partie.");
		SelectedCiv.Value = 0;
		campaignsFile = Path.Combine(Paths.ConfigPath, "HeianMod_campagnes.txt");
		LoadCampaigns();
		new Harmony("fr.natchoum.badnorth.heian").PatchAll();
		GameObject val = new GameObject("HeianModUI")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)val);
		val.AddComponent<HeianUI>();
		Log.LogInfo((object)("Mod Civilisations chargé (dossier : " + ModDir + ")"));
	}

	private static void LoadCampaigns()
	{
		campaignCivs.Clear();
		if (!File.Exists(campaignsFile))
		{
			return;
		}
		string[] array = File.ReadAllLines(campaignsFile);
		for (int i = 0; i < array.Length; i++)
		{
			string[] array2 = array[i].Split(new char[1] { '=' });
			if (array2.Length == 2 && int.TryParse(array2[0].Trim(), out var result) && int.TryParse(array2[1].Trim(), out var result2))
			{
				campaignCivs[result] = (Civ)result2;
			}
		}
	}

	private static void SaveCampaigns()
	{
		List<string> list = new List<string>();
		foreach (KeyValuePair<int, Civ> campaignCiv in campaignCivs)
		{
			list.Add(campaignCiv.Key + "=" + (int)campaignCiv.Value);
		}
		File.WriteAllLines(campaignsFile, list.ToArray());
	}

	internal static void RememberCampaign(int seed, Civ civ)
	{
		campaignCivs[seed] = civ;
		SaveCampaigns();
	}

	internal static Civ CivForCampaign(CampaignSave save)
	{
		if (save == null)
		{
			return (Civ)SelectedCiv.Value;
		}
		if (campaignCivs.TryGetValue(save.seed, out var value))
		{
			return value;
		}
		if (save.heroes != null)
		{
			foreach (HeroDefinition hero in save.heroes)
			{
				string text = null;
				if (hero != null && hero.propertyBank != null && hero.propertyBank.TryGetValue("HeianCiv", ref text) && text == "Heian")
				{
					return Civ.Heian;
				}
			}
		}
		return (Civ)SelectedCiv.Value;
	}

	internal static void RefreshNewGameHeroes()
	{
		try
		{
			HeroCustomizer[] array = Object.FindObjectsOfType<HeroCustomizer>();
			foreach (HeroCustomizer val in array)
			{
				if (!((Object)(object)val == (Object)null) && val.heroDef != null)
				{
					dirtyFlagsField.SetValue(val, (object)(ChangeFlags)255);
					val.Generate(false);
				}
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Rafraîchissement des héros impossible : " + ex.Message));
		}
	}

	internal static void SetCiv(Civ civ)
	{
		if (CurrentCiv != civ)
		{
			Log.LogInfo((object)("Civilisation active : " + civ));
		}
		bool num = CurrentCiv != civ;
		CurrentCiv = civ;
		TextureSwapper.Apply(civ);
		TraitIcons.Apply(civ);
		if (num)
		{
			RefreshNewGameHeroes();
		}
	}
}
public class HeianUI : MonoBehaviour
{
	private static readonly FieldInfo popupInstance = AccessTools.Field(typeof(NewGameOptionsPopup), "instance");

	private NewGameOptionsPopup popup;

	private bool wasOpen;

	private float nextPopupCheck;

	private float nextHouseCheck;

	private GUIStyle titleStyle;

	private GUIStyle btnStyle;

	private GUIStyle btnOnStyle;

	private GUIStyle boxStyle;

	private bool started;

	private bool startupPick;

	private bool startupDone;

	private readonly Dictionary<string, Texture2D> pickTex = new Dictionary<string, Texture2D>();

	private float toastUntil;

	private AccountLoader title;

	private MainMenu mainMenuRef;

	private bool inMenus;

	private readonly Sakura sakura = new Sakura();

	private static readonly FieldInfo titleLogo = AccessTools.Field(typeof(AccountLoader), "logoContainer");

	private RectTransform logo;

	private Rect logoScreen;

	private bool showBadge;

	private bool loggedLogo;

	private GUIStyle badgeStyle;

	private GUIStyle badgeShadow;

	private Texture2D titleTex;

	private bool titleTried;

	private void Update()
	{
		if (!started)
		{
			started = true;
			HeianPlugin.Log.LogInfo((object)"Interface du mod active (v1.1.2). Raccourci : F9 pour changer de civilisation.");
		}
		if (startupPick && (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)27)))
		{
			startupPick = false;
		}
		if (Input.GetKeyDown((KeyCode)290))
		{
			HeianPlugin.SelectedCiv.Value = ((HeianPlugin.SelectedCiv.Value == 0) ? 1 : 0);
			HeianPlugin.SetCiv((Civ)HeianPlugin.SelectedCiv.Value);
			toastUntil = Time.unscaledTime + 3f;
		}
		if (Time.unscaledTime >= nextPopupCheck)
		{
			nextPopupCheck = Time.unscaledTime + 0.4f;
			object? value = popupInstance.GetValue(null);
			NewGameOptionsPopup val = (NewGameOptionsPopup)((value is NewGameOptionsPopup) ? value : null);
			bool flag = (Object)(object)val != (Object)null && ((UIMenu)val).isOpen;
			if (flag != wasOpen)
			{
				wasOpen = flag;
				HeianPlugin.Log.LogInfo((object)(flag ? "Menu Nouvelle partie ouvert : affichage du choix de civilisation" : "Menu Nouvelle partie fermé"));
			}
			popup = (flag ? val : null);
			UpdateMainMenu();
			if (!startupDone && (showBadge || ((Object)(object)mainMenuRef != (Object)null && ((UIMenu)mainMenuRef).isOpen)))
			{
				startupDone = true;
				startupPick = true;
				HeianPlugin.Log.LogInfo((object)"Choix de civilisation proposé au lancement");
			}
			if (Time.unscaledTime >= nextHouseCheck)
			{
				nextHouseCheck = Time.unscaledTime + 1f;
				HouseMeshes.Apply(HeianPlugin.CurrentCiv);
				ShipMeshes.Apply(HeianPlugin.CurrentCiv);
				TextureSwapper.Apply(HeianPlugin.CurrentCiv);
				WeaponMeshes.Apply(HeianPlugin.CurrentCiv);
				CoinIcons.Apply(HeianPlugin.CurrentCiv);
			}
			if ((Object)(object)popup != (Object)null && HeianPlugin.CurrentCiv != (Civ)HeianPlugin.SelectedCiv.Value)
			{
				HeianPlugin.SetCiv((Civ)HeianPlugin.SelectedCiv.Value);
			}
		}
	}

	private Texture2D PT(string n)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Expected O, but got Unknown
		if (pickTex.TryGetValue(n, out var value))
		{
			return value;
		}
		value = null;
		try
		{
			string path = Path.Combine(HeianPlugin.ModDir, Path.Combine("picker", n + ".png"));
			if (File.Exists(path))
			{
				value = new Texture2D(2, 2, (TextureFormat)4, false);
				ImageConversion.LoadImage(value, File.ReadAllBytes(path));
				((Texture)value).wrapMode = (TextureWrapMode)1;
				Object.DontDestroyOnLoad((Object)(object)value);
			}
		}
		catch
		{
		}
		pickTex[n] = value;
		return value;
	}

	private bool DrawPicker(bool bottom, bool withButton)
	{
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: 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_0116: 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_01bd: 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_01f1: Unknown result type (might be due to invalid IL or missing references)
		int value = HeianPlugin.SelectedCiv.Value;
		string text = ((value == 1) ? "heian" : "nordique");
		Texture2D val = PT("Panneau_" + text);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		float num = Mathf.Clamp((float)Screen.height / 1080f, 0.55f, 1.5f);
		float num2 = 700f * num;
		float num3 = 372f * num;
		float num4 = ((float)Screen.width - num2) / 2f;
		float num5 = (bottom ? ((float)Screen.height - num3 - 20f * num) : (10f * num));
		GUI.DrawTexture(new Rect(num4, num5, num2, num3), (Texture)(object)val);
		Rect val2 = default(Rect);
		((Rect)(ref val2))..ctor(num4 + 40f * num, num5 + 84f * num, 300f * num, 196f * num);
		Rect val3 = new Rect(num4 + 360f * num, num5 + 84f * num, 300f * num, 196f * num);
		GUI.DrawTexture(val2, (Texture)(object)PT((value == 0) ? "Carte_nordique_on" : "Carte_nordique_off"));
		GUI.DrawTexture(val3, (Texture)(object)PT((value == 1) ? "Carte_heian_on" : "Carte_heian_off"));
		if (GUI.Button(val2, GUIContent.none, GUIStyle.none))
		{
			HeianPlugin.SelectedCiv.Value = 0;
		}
		if (GUI.Button(val3, GUIContent.none, GUIStyle.none))
		{
			HeianPlugin.SelectedCiv.Value = 1;
		}
		if (value != HeianPlugin.SelectedCiv.Value)
		{
			HeianPlugin.SetCiv((Civ)HeianPlugin.SelectedCiv.Value);
		}
		if (!withButton)
		{
			return false;
		}
		Rect val4 = default(Rect);
		((Rect)(ref val4))..ctor(num4 + 250f * num, num5 + 290f * num, 200f * num, 46f * num);
		bool flag = ((Rect)(ref val4)).Contains(Event.current.mousePosition);
		GUI.DrawTexture(val4, (Texture)(object)PT("Bouton_" + text + (flag ? "_survol" : "")));
		return GUI.Button(val4, GUIContent.none, GUIStyle.none);
	}

	private void DrawStartupPick()
	{
		if (DrawPicker(bottom: true, withButton: true))
		{
			startupPick = false;
		}
	}

	private void InitStyles()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Expected O, but got Unknown
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Expected O, but got Unknown
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Expected O, but got Unknown
		if (titleStyle == null)
		{
			titleStyle = new GUIStyle(GUI.skin.label)
			{
				fontSize = 20,
				alignment = (TextAnchor)4,
				fontStyle = (FontStyle)1
			};
			titleStyle.normal.textColor = new Color(0.95f, 0.92f, 0.85f);
			btnStyle = new GUIStyle(GUI.skin.button)
			{
				fontSize = 18
			};
			btnOnStyle = new GUIStyle(btnStyle);
			btnOnStyle.normal.textColor = new Color(1f, 0.82f, 0.3f);
			btnOnStyle.hover.textColor = btnOnStyle.normal.textColor;
			btnOnStyle.fontStyle = (FontStyle)1;
			boxStyle = new GUIStyle(GUI.skin.box);
		}
	}

	private unsafe void UpdateMainMenu()
	{
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: 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_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0187: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: 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_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bf: 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_01e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)title == (Object)null)
		{
			title = Object.FindObjectOfType<AccountLoader>();
		}
		if ((Object)(object)mainMenuRef == (Object)null)
		{
			mainMenuRef = Object.FindObjectOfType<MainMenu>();
		}
		showBadge = (Object)(object)title != (Object)null && ((UIMenu)title).isOpen && ((Behaviour)title).isActiveAndEnabled && (Object)(object)popup == (Object)null;
		inMenus = showBadge || (Object)(object)popup != (Object)null || ((Object)(object)mainMenuRef != (Object)null && ((UIMenu)mainMenuRef).isOpen);
		if (!showBadge)
		{
			return;
		}
		if ((Object)(object)logo == (Object)null)
		{
			object? value = titleLogo.GetValue(title);
			Transform val = (Transform)((value is Transform) ? value : null);
			logo = (RectTransform)(object)((val is RectTransform) ? val : null);
		}
		logoScreen = new Rect(0f, 0f, 0f, 0f);
		if ((Object)(object)logo != (Object)null)
		{
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			logo.GetWorldCorners(array);
			Canvas componentInParent = ((Component)logo).GetComponentInParent<Canvas>();
			Camera obj = (((Object)(object)componentInParent != (Object)null && (int)componentInParent.renderMode != 0) ? componentInParent.worldCamera : null);
			Vector2 val2 = RectTransformUtility.WorldToScreenPoint(obj, array[0]);
			Vector2 val3 = RectTransformUtility.WorldToScreenPoint(obj, array[2]);
			logoScreen = Rect.MinMaxRect(Mathf.Min(val2.x, val3.x), (float)Screen.height - Mathf.Max(val2.y, val3.y), Mathf.Max(val2.x, val3.x), (float)Screen.height - Mathf.Min(val2.y, val3.y));
			if (!loggedLogo)
			{
				loggedLogo = true;
				ManualLogSource log = HeianPlugin.Log;
				Rect val4 = logoScreen;
				log.LogInfo((object)("Logo du menu trouvé : " + ((object)(*(Rect*)(&val4))/*cast due to .constrained prefix*/).ToString()));
			}
		}
	}

	private Texture2D TitleTex()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Expected O, but got Unknown
		if ((Object)(object)titleTex != (Object)null || titleTried)
		{
			return titleTex;
		}
		titleTried = true;
		try
		{
			string path = Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", "Titre_Heian.png"));
			if (File.Exists(path))
			{
				titleTex = new Texture2D(2, 2, (TextureFormat)4, false);
				ImageConversion.LoadImage(titleTex, File.ReadAllBytes(path));
				((Texture)titleTex).filterMode = (FilterMode)1;
				((Texture)titleTex).wrapMode = (TextureWrapMode)1;
				Object.DontDestroyOnLoad((Object)(object)titleTex);
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogWarning((object)("Titre : " + ex.Message));
		}
		return titleTex;
	}

	private void DrawBadge(bool mainMenu)
	{
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		Texture2D val = TitleTex();
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		float num = (float)((Texture)val).width / (float)((Texture)val).height;
		Rect val2 = default(Rect);
		if (mainMenu)
		{
			float num2 = (float)Screen.height * 0.115f;
			float num3 = num2 * num;
			((Rect)(ref val2))..ctor(((float)Screen.width - num3) / 2f, (float)Screen.height * 0.004f, num3, num2);
		}
		else
		{
			float num4 = (float)Screen.height * 0.19f;
			float num5 = num4 * num;
			if (num5 > (float)Screen.width * 0.8f)
			{
				num5 = (float)Screen.width * 0.8f;
				num4 = num5 / num;
			}
			((Rect)(ref val2))..ctor(((float)Screen.width - num5) / 2f, (float)Screen.height * 0.035f, num5, num4);
		}
		GUI.DrawTexture(val2, (Texture)(object)val, (ScaleMode)2, true);
	}

	private void OnGUI()
	{
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		sakura.Draw(inMenus && HeianPlugin.SelectedCiv.Value == 1);
		if (HeianPlugin.SelectedCiv.Value == 1 && (Object)(object)popup == (Object)null)
		{
			if (showBadge)
			{
				DrawBadge(mainMenu: false);
			}
			else if ((Object)(object)mainMenuRef != (Object)null && ((UIMenu)mainMenuRef).isOpen)
			{
				DrawBadge(mainMenu: true);
			}
		}
		if (startupPick && (Object)(object)popup == (Object)null)
		{
			DrawStartupPick();
			return;
		}
		if ((Object)(object)popup == (Object)null && Time.unscaledTime < toastUntil)
		{
			InitStyles();
			Rect val = new Rect(((float)Screen.width - 460f) / 2f, 12f, 460f, 40f);
			Color color = GUI.color;
			GUI.color = new Color(0f, 0f, 0f, 0.75f);
			GUI.Box(val, GUIContent.none, boxStyle);
			GUI.color = color;
			GUI.Label(val, "Civilisation : " + ((HeianPlugin.SelectedCiv.Value == 1) ? "Japon – époque Heian" : "Nordiques (base)"), titleStyle);
		}
		if (!((Object)(object)popup == (Object)null))
		{
			DrawPicker(bottom: false, withButton: false);
		}
	}
}
[HarmonyPatch(typeof(NewGameOptionsPopup), "StartCampaign")]
internal static class Patch_StartCampaign
{
	private static void Prefix(int campaignSeed)
	{
		Civ value = (Civ)HeianPlugin.SelectedCiv.Value;
		HeianPlugin.RememberCampaign(campaignSeed, value);
		HeianPlugin.SetCiv(value);
	}
}
[HarmonyPatch(typeof(NewGameOptionsPopup), "OpenMenuInternal")]
internal static class Patch_OpenNewGame
{
	private static void Prefix()
	{
		HeianPlugin.SetCiv((Civ)HeianPlugin.SelectedCiv.Value);
	}
}
[HarmonyPatch(typeof(CampaignManager), "GenerateCampaign")]
internal static class Patch_GenerateCampaign
{
	private static void Prefix(CampaignSave campaignSave)
	{
		HeianPlugin.SetCiv(HeianPlugin.CivForCampaign(campaignSave));
	}
}
[HarmonyPatch(typeof(MetaMenuHelpers), "ExitToMainMenu")]
internal static class Patch_ExitToMenu
{
	private static void Prefix()
	{
		HeianPlugin.SetCiv((Civ)HeianPlugin.SelectedCiv.Value);
	}
}
[HarmonyPatch(typeof(MonoHero), "MakeHero")]
internal static class Patch_MakeHero
{
	private static readonly FieldInfo tagsField = AccessTools.Field(typeof(PropertyBank), "tags");

	private static readonly Color[] hairColors = (Color[])(object)new Color[4]
	{
		new Color(0.07f, 0.06f, 0.06f),
		new Color(0.1f, 0.08f, 0.07f),
		new Color(0.13f, 0.1f, 0.08f),
		new Color(0.05f, 0.05f, 0.07f)
	};

	private static void Prefix(MonoHero __instance, PropertyBank propertyBank)
	{
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0209: Unknown result type (might be due to invalid IL or missing references)
		//IL_0215: Unknown result type (might be due to invalid IL or missing references)
		TextureSwapper.Apply(HeianPlugin.CurrentCiv);
		ClanBanner.Before(__instance);
		if (HeianPlugin.CurrentCiv != Civ.Heian || propertyBank == null)
		{
			return;
		}
		propertyBank.AddTag("HeianCiv", "Heian");
		if (!(tagsField.GetValue(propertyBank) is List<Tag> list))
		{
			return;
		}
		int seed = __instance.seed;
		int num = seed;
		if (__instance.heroDef != null && !string.IsNullOrEmpty(__instance.heroDef.nameTerm))
		{
			num = 17;
			string nameTerm = __instance.heroDef.nameTerm;
			foreach (char c in nameTerm)
			{
				num = num * 31 + c;
			}
		}
		SetTag(list, "Helmet", (Mathf.Abs(num % 5) < 3) ? "Round" : "Pointy");
		SetTag(list, "SteelColor", "#FFFFFFFF");
		Color val = (Color)((__instance.heroDef != null) ? __instance.heroDef.color : new Color(0.8f, 0.12f, 0.16f));
		SetTag(list, "MailleColor", "#" + ColorUtility.ToHtmlStringRGBA(Color.Lerp(val, Color.white, 0.15f)));
		SetTag(list, "LeatherColor", "#8C2A22FF");
		SetTag(list, "PaddingColor", "#E9E2D0FF");
		SetTag(list, "GuildedColor", "#FFFFFFFF");
		SetTag(list, "HairColor", "#" + ColorUtility.ToHtmlStringRGBA(hairColors[Mathf.Abs(seed) % hairColors.Length]));
		for (int j = 0; j < list.Count; j++)
		{
			Tag val2 = list[j];
			if (((Tag)(ref val2)).key != null && ((Tag)(ref val2)).key.EndsWith("Color") && (((Tag)(ref val2)).key.IndexOf("Hair", StringComparison.OrdinalIgnoreCase) >= 0 || ((Tag)(ref val2)).key.IndexOf("Beard", StringComparison.OrdinalIgnoreCase) >= 0))
			{
				Color val3 = hairColors[Mathf.Abs(seed + j) % hairColors.Length];
				list[j] = new Tag(((Tag)(ref val2)).key, "#" + ColorUtility.ToHtmlStringRGBA(val3));
			}
		}
	}

	private static void SetTag(List<Tag> tags, string key, string value)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < tags.Count; i++)
		{
			Tag val = tags[i];
			if (((Tag)(ref val)).key == key)
			{
				tags[i] = new Tag(key, value);
				return;
			}
		}
		tags.Add(new Tag(key, value));
	}

	private static void Postfix(MonoHero __instance)
	{
		PortraitParts.Apply(__instance);
		ClanBanner.After(__instance);
		if (!HeianDebug.dumped && __instance.colorDict != null)
		{
			HeianDebug.dumped = true;
			HeianPlugin.Log.LogInfo((object)("Clés de couleur des héros : " + string.Join(", ", new List<string>(__instance.colorDict.Keys).ToArray())));
		}
	}
}
[HarmonyPatch(/*Could not decode attribute arguments.*/)]
internal static class Patch_HeroColor
{
	internal static readonly Color[] palette = (Color[])(object)new Color[8]
	{
		new Color(0.8f, 0.12f, 0.16f),
		new Color(0.93f, 0.4f, 0.18f),
		new Color(0.93f, 0.66f, 0.1f),
		new Color(0.48f, 0.62f, 0.2f),
		new Color(0.18f, 0.55f, 0.62f),
		new Color(0.16f, 0.27f, 0.55f),
		new Color(0.45f, 0.26f, 0.58f),
		new Color(0.2f, 0.19f, 0.21f)
	};

	private static void Postfix(HeroDefinition __instance, ref Color __result)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		if (HeianPlugin.CurrentCiv == Civ.Heian)
		{
			float hue = __instance.hue;
			if (!(hue < 0f) && !float.IsNaN(hue))
			{
				int num = Mathf.FloorToInt(Mathf.Repeat(hue, 1f) * (float)palette.Length) % palette.Length;
				__result = palette[num];
			}
		}
	}
}
[HarmonyPatch(typeof(LocalizationManager), "TryGetTranslation")]
internal static class Patch_Translation
{
	private static void Postfix(string Term, ref string Translation, ref bool __result)
	{
		if (HeianPlugin.CurrentCiv != Civ.Heian || Term == null)
		{
			return;
		}
		string value;
		if (Term.StartsWith("ISLAND_NAMES/"))
		{
			Translation = HeianTexts.IslandFor(Term);
			__result = true;
		}
		else if (Term.StartsWith("HERO_NAMES/MALE/") || Term.StartsWith("HERO_NAMES/FEMALE/"))
		{
			if (Term.Length > 17)
			{
				Translation = HeianTexts.NameFor(Term);
				__result = true;
			}
		}
		else if (HeianTexts.Terms.TryGetValue(Term, out value))
		{
			Translation = value;
			__result = true;
		}
		else if (__result && Translation != null && Translation.IndexOf("iking", StringComparison.Ordinal) >= 0)
		{
			Translation = Translation.Replace("Vikings", "pirates").Replace("vikings", "pirates").Replace("Viking", "pirate")
				.Replace("viking", "pirate");
			if (Translation.Length > 0)
			{
				Translation = char.ToUpper(Translation[0]) + Translation.Substring(1);
			}
		}
	}
}
internal static class HeianDebug
{
	internal static bool dumped;
}
internal static class HeianTexts
{
	internal static readonly Dictionary<string, string> Terms = new Dictionary<string, string>
	{
		{ "UPGRADES/INFANTRY/CLASS/NAME", "Bushi" },
		{ "UPGRADES/INFANTRY/CLASS/DESC", "Guerriers en armure ō-yoroi, armés du sabre courbe tachi et du bouclier tate. Solides au corps à corps et protégés des flèches." },
		{ "UPGRADES/INFANTRY/VETERAN/NAME", "Bushi aguerris" },
		{ "UPGRADES/INFANTRY/ELITE/NAME", "Gardes du palais" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/INFANTRY", "Bushi" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/VETERAN_INFANTRY", "Bushi aguerris" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/ELITE_INFANTRY", "Gardes du palais" },
		{ "UPGRADES/ARCHER/CLASS/NAME", "Yumi-shi" },
		{ "UPGRADES/ARCHER/CLASS/DESC", "Archers au grand arc asymétrique yumi, l'arme noble des premiers samouraïs. Ils frappent de loin mais craignent le corps à corps." },
		{ "UPGRADES/ARCHER/VETERAN/NAME", "Yumi-shi aguerris" },
		{ "UPGRADES/ARCHER/ELITE/NAME", "Maîtres du yumi" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/ARCHERS", "Yumi-shi" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/VETERAN_ARCHERS", "Yumi-shi aguerris" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/ELITE_ARCHERS", "Maîtres du yumi" },
		{ "UPGRADES/PIKE/CLASS/NAME", "Sōhei" },
		{ "UPGRADES/PIKE/CLASS/DESC", "Moines-guerriers des grands temples, armés de la naginata. Leur longue lame tient l'ennemi à distance." },
		{ "UPGRADES/PIKE/VETERAN/NAME", "Sōhei aguerris" },
		{ "UPGRADES/PIKE/ELITE/NAME", "Sōhei du mont Hiei" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/PIKES", "Sōhei" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/VETERAN_PIKES", "Sōhei aguerris" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/ELITE_PIKES", "Sōhei du mont Hiei" },
		{ "UPGRADES/GENERIC/LEVEL_CLASS/MILITIA", "Kondei" },
		{ "UPGRADES/ARCHER/FIRE_ARROWS/NAME", "Hiya (flèches de feu)" },
		{ "UPGRADES/ARCHER/LONGBOW/NAME", "Grand yumi" },
		{ "UPGRADES/ARCHER/SHORTBOW/NAME", "Yumi court" },
		{ "UPGRADES/ARCHER/VOLLEY/NAME", "Pluie de flèches" },
		{ "UPGRADES/INFANTRY/JAVELIN/NAME", "Uchi-ne (dards de jet)" },
		{ "UPGRADES/INFANTRY/PLUNGE/NAME", "Assaut au tachi" },
		{ "UPGRADES/INFANTRY/SHIELD_BASH/NAME", "Poussée du tate" },
		{ "UPGRADES/PIKE/CHARGE/NAME", "Charge des sōhei" },
		{ "UPGRADES/PIKE/RETREAT/NAME", "Repli ordonné" },
		{ "UPGRADES/PIKE/SHARP/NAME", "Naginata affûtées" },
		{ "UPGRADES/ITEM/BOMB/NAME", "Pot de feu" },
		{ "UPGRADES/ITEM/CORNUCOPIA/NAME", "Maillet de la fortune" },
		{ "UPGRADES/ITEM/GRAIL/NAME", "Coupe de saké sacré" },
		{ "UPGRADES/ITEM/HORN/NAME", "Horagai (conque de guerre)" },
		{ "UPGRADES/ITEM/MINE/NAME", "Makibishi (chausse-trapes)" },
		{ "UPGRADES/ITEM/PHIL_STONE/NAME", "Joyau hōju" },
		{ "UPGRADES/ITEM/RELIC/NAME", "Relique du temple" },
		{ "UPGRADES/ITEM/SIZE/NAME", "Gunbai (éventail de commandement)" },
		{ "UPGRADES/ITEM/WARHAMMER/NAME", "Kanabō" },
		{ "UPGRADES/LEVEL/MILITIA/NAME", "Kondei" },
		{ "HERO_TRAITS/EXTRA_ARMOUR/NAME", "Kikkō" },
		{ "HERO_TRAITS/BLUNT_WEAPONS/NAME", "Porteur de kanabō" },
		{ "HERO_TRAITS/CHEAPER_SKILLS/NAME", "Élève des tengu" },
		{ "HERO_TRAITS/CHEAPER_ITEMS/NAME", "Faveur de la cour" },
		{ "HERO_TRAITS/EXTRA_UNIT/NAME", "Chef de clan" },
		{ "HERO_TRAITS/ABILITY_EXTRA_USES/NAME", "Char de guerre" },
		{ "HERO_TRAITS/FAST_MOVE/NAME", "Flèche du vent" },
		{ "HERO_TRAITS/FAST_REPLENISH/NAME", "Béni du sanctuaire" },
		{ "HERO_TRAITS/GIANT/NAME", "Force de Benkei" },
		{ "HERO_TRAITS/NO_FLEE/NAME", "Flamme de Fudō" },
		{ "HERO_TRAITS/SHARP_WEAPONS/NAME", "Lame de Munechika" },
		{ "HERO_TRAITS/ABILITY_SHORT_COOLDOWN/NAME", "Esprit du sakura" },
		{ "HERO_TRAITS/STURDY/NAME", "Racines du pin" },
		{ "HERO_TRAITS/GIANT/DESC", "Ce commandant est un colosse, comme le moine Benkei, qui domine tous ses soldats" },
		{ "HERO_TRAITS/GIANT/DESC_SHORT", "Commandant colosse" }
	};

	internal static readonly string[] MaleNames = new string[48]
	{
		"Yoshitsune", "Yoritomo", "Kiyomori", "Tadanori", "Atsumori", "Masakado", "Tametomo", "Yorimitsu", "Shigemori", "Munemori",
		"Koremori", "Yoshinaka", "Naozane", "Tomomori", "Noritsune", "Yoshiie", "Yoriyoshi", "Tsunemoto", "Sumitomo", "Hidesato",
		"Michizane", "Narihira", "Yorimasa", "Kanehira", "Tadamori", "Benkei", "Kagetoki", "Shigetada", "Yoshitomo", "Tameyoshi",
		"Yasumasa", "Tsuna", "Suetake", "Sadamitsu", "Kintoki", "Yukiie", "Michinaga", "Korechika", "Tadatsune", "Kagekiyo",
		"Moritoshi", "Sanemori", "Tsunemasa", "Shigehira", "Kiyotsune", "Yoshimitsu", "Tadamasa", "Mitsunaka"
	};

	internal static readonly string[] FemaleNames = new string[32]
	{
		"Tomoe", "Shizuka", "Tokiwa", "Hangaku", "Murasaki", "Sei", "Izumi", "Akazome", "Ise", "Komachi",
		"Giō", "Hotoke", "Kogō", "Yokobue", "Senju", "Kozaishō", "Tamakazura", "Ukifune", "Fujitsubo", "Aoi",
		"Oborozuki", "Yūgao", "Akashi", "Yamabuki", "Teishi", "Shōshi", "Masako", "Tokuko", "Kenshi", "Nijō",
		"Sadako", "Ōiko"
	};

	internal static readonly string[] Islands = new string[40]
	{
		"Hiburi-jima", "Itsukushima", "Awaji", "Shōdoshima", "Naoshima", "Innoshima", "Ōmishima", "Ikuchijima", "Yashima", "Dan-no-ura",
		"Suma", "Akashi", "Tomo-no-ura", "Kurahashi", "Etajima", "Nōmijima", "Shiwaku", "Teshima", "Inujima", "Sanagi",
		"Mukaishima", "Hakatajima", "Ōshima", "Nakajima", "Gogoshima", "Yugeshima", "Iwagijima", "Ikina", "Kitagi", "Manabe",
		"Hirashima", "Kasado", "Ushimado", "Shiraishi", "Kamagari", "Tsuwajima", "Okamura", "Uoshima", "Kōjima", "Mitarai"
	};

	internal static string IslandFor(string term)
	{
		uint num = 2166136261u;
		foreach (char c in term)
		{
			num ^= c;
			num *= 16777619;
		}
		return Islands[num % (uint)Islands.Length];
	}

	internal static string NameFor(string term)
	{
		string[] array = (term.StartsWith("HERO_NAMES/FEMALE/") ? FemaleNames : MaleNames);
		uint num = 2166136261u;
		foreach (char c in term)
		{
			num ^= c;
			num *= 16777619;
		}
		return array[num % (uint)array.Length];
	}
}
internal static class PortraitParts
{
	private class Entry
	{
		public string file;

		public int padL;

		public int padB;

		public int padR;

		public int padT;
	}

	private class Saved
	{
		public Sprite sprite;

		public Vector3 pos;

		public Vector3 scale;

		public Color color;
	}

	private static Dictionary<string, Entry> entries;

	private static readonly Dictionary<Sprite, Sprite> toHeian = new Dictionary<Sprite, Sprite>();

	private static readonly Dictionary<Sprite, Sprite> toOriginal = new Dictionary<Sprite, Sprite>();

	private static bool built;

	private static readonly MethodInfo drawAll = AccessTools.Method(typeof(MonoHero), "DrawAll", (Type[])null, (Type[])null);

	private static bool loggedAgent;

	private static readonly HashSet<SpriteRenderer> hiddenCrowns = new HashSet<SpriteRenderer>();

	private static readonly string[] hiddenParts = new string[31]
	{
		"Crown", "Guilded", "Royal", "HeroGold", "EliteGold", "Noseguard", "Bolt", "bit?", "Lowbit", "Midbit",
		"#C0", "#C1", "#C2", "Cross", "Midline", "Linek", "Blobs", "GoldLines", "#N0", "#N1",
		"#ba", "#Ball", "#B0", "#B1", "#B2", "RimGold", "MaybeFlipXGold", "#RoundSteel_1", "#SquareSteel", "#BeanieSteel",
		"MaybeFlipXSteel"
	};

	private static readonly Dictionary<SpriteRenderer, Saved> headgear = new Dictionary<SpriteRenderer, Saved>();

	private static readonly Dictionary<string, Sprite> heroHelm = new Dictionary<string, Sprite>();

	private static readonly Dictionary<SpriteRenderer, Sprite> helmOrig = new Dictionary<SpriteRenderer, Sprite>();

	private static readonly HashSet<SpriteRenderer> helmHidden = new HashSet<SpriteRenderer>();

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

	private static string Dir => Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", "portrait"));

	private static void LoadEntries()
	{
		entries = new Dictionary<string, Entry>();
		string path = Path.Combine(Dir, "pieces.txt");
		if (!File.Exists(path))
		{
			HeianPlugin.Log.LogWarning((object)"pieces.txt introuvable");
			return;
		}
		string[] array = File.ReadAllLines(path);
		for (int i = 0; i < array.Length; i++)
		{
			string[] array2 = array[i].Split(new char[1] { '|' });
			if (array2.Length == 6)
			{
				entries[array2[0]] = new Entry
				{
					file = array2[1],
					padL = int.Parse(array2[2]),
					padB = int.Parse(array2[3]),
					padR = int.Parse(array2[4]),
					padT = int.Parse(array2[5])
				};
			}
		}
	}

	private static void Build()
	{
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Expected O, but got Unknown
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: 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_01b6: Unknown result type (might be due to invalid IL or missing references)
		if (built)
		{
			return;
		}
		if (entries == null)
		{
			LoadEntries();
		}
		int num = 0;
		Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
		Vector2 val3 = default(Vector2);
		Vector2 val4 = default(Vector2);
		foreach (Sprite val in array)
		{
			if ((Object)(object)val == (Object)null || (Object)(object)val.texture == (Object)null || ((Object)val.texture).name != "Heroes2_Spriteshop")
			{
				continue;
			}
			Rect rect = val.rect;
			string key = ((Object)val).name + "@" + Mathf.RoundToInt(((Rect)(ref rect)).x) + "," + Mathf.RoundToInt(((Rect)(ref rect)).y);
			if (entries.TryGetValue(key, out var value) && !toHeian.ContainsKey(val))
			{
				string path = Path.Combine(Dir, value.file);
				if (File.Exists(path))
				{
					Texture2D val2 = new Texture2D(2, 2, (TextureFormat)4, false);
					ImageConversion.LoadImage(val2, File.ReadAllBytes(path));
					((Texture)val2).wrapMode = (TextureWrapMode)1;
					((Object)val2).name = "Heian_" + value.file;
					Object.DontDestroyOnLoad((Object)(object)val2);
					((Vector2)(ref val3))..ctor(val.pivot.x + (float)value.padL, val.pivot.y + (float)value.padB);
					((Vector2)(ref val4))..ctor(val3.x / (float)((Texture)val2).width, val3.y / (float)((Texture)val2).height);
					Sprite val5 = Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), val4, val.pixelsPerUnit, 0u, (SpriteMeshType)0);
					((Object)val5).name = ((Object)val).name;
					Object.DontDestroyOnLoad((Object)(object)val5);
					toHeian[val] = val5;
					toOriginal[val5] = val;
					num++;
				}
			}
		}
		if (num > 0)
		{
			built = true;
		}
		HeianPlugin.Log.LogInfo((object)("Pièces de portrait Heian prêtes : " + num));
	}

	private static bool IsCrown(string n)
	{
		if (!n.StartsWith("Heroes2_Spriteshop") && !n.StartsWith("PartTex_Spriteshop"))
		{
			return false;
		}
		if (n.StartsWith("PartTex_Spriteshop"))
		{
			return false;
		}
		string[] array = hiddenParts;
		foreach (string value in array)
		{
			if (n.IndexOf(value, StringComparison.Ordinal) >= 0)
			{
				return true;
			}
		}
		return false;
	}

	private static Sprite HeianByName(string n)
	{
		foreach (KeyValuePair<Sprite, Sprite> item in toHeian)
		{
			if (((Object)item.Key).name == n)
			{
				return item.Value;
			}
		}
		return null;
	}

	private static bool GiveHeadgear(MonoHero hero)
	{
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		//IL_0207: 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_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0217: Unknown result type (might be due to invalid IL or missing references)
		//IL_021c: 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_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_0243: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_0285: Unknown result type (might be due to invalid IL or missing references)
		//IL_028a: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_030e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0323: Unknown result type (might be due to invalid IL or missing references)
		//IL_0328: Unknown result type (might be due to invalid IL or missing references)
		//IL_032d: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		Build();
		SpriteRenderer val = null;
		float num = 0f;
		bool flag = false;
		SpriteRenderer[] componentsInChildren = ((Component)hero).GetComponentsInChildren<SpriteRenderer>(true);
		Bounds bounds;
		foreach (SpriteRenderer val2 in componentsInChildren)
		{
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.sprite == (Object)null || !ActiveUnder(((Component)val2).transform, ((Component)hero).transform))
			{
				continue;
			}
			string name = ((Object)val2.sprite).name;
			if (!name.StartsWith("Heroes2_Spriteshop"))
			{
				continue;
			}
			if (((Renderer)val2).enabled && (name.Contains("#RoundSteel_0") || name.Contains("#PointySteel_0")))
			{
				flag = true;
			}
			if (!((Renderer)val2).enabled && hiddenCrowns.Contains(val2) && (name.Contains("Crown_0") || name.EndsWith("Guilded_0") || name.Contains("CrownPlaceholder")))
			{
				bounds = ((Renderer)val2).bounds;
				float x = ((Bounds)(ref bounds)).size.x;
				if (x > num)
				{
					num = x;
					val = val2;
				}
			}
		}
		if (flag || (Object)(object)val == (Object)null)
		{
			return false;
		}
		int seed = hero.seed;
		if (hero.heroDef != null && !string.IsNullOrEmpty(hero.heroDef.nameTerm))
		{
			seed = 17;
			string nameTerm = hero.heroDef.nameTerm;
			foreach (char c in nameTerm)
			{
				seed = seed * 31 + c;
			}
		}
		Sprite val3 = HeianByName("Heroes2_Spriteshop_#RoundSteel_0");
		if ((Object)(object)val3 == (Object)null)
		{
			return false;
		}
		if (headgear.TryGetValue(val, out var value))
		{
			((Component)val).transform.localPosition = value.pos;
			((Component)val).transform.localScale = value.scale;
		}
		else
		{
			headgear[val] = new Saved
			{
				sprite = val.sprite,
				pos = ((Component)val).transform.localPosition,
				scale = ((Component)val).transform.localScale,
				color = val.color
			};
		}
		bounds = ((Renderer)val).bounds;
		num = ((Bounds)(ref bounds)).size.x;
		Bounds bounds2 = ((Renderer)val).bounds;
		Vector3 val4 = default(Vector3);
		((Vector3)(ref val4))..ctor(((Bounds)(ref bounds2)).center.x, ((Bounds)(ref bounds2)).min.y, ((Bounds)(ref bounds2)).center.z);
		val.sprite = val3;
		val.color = Color.white;
		((Renderer)val).enabled = true;
		hiddenCrowns.Remove(val);
		bounds = ((Renderer)val).bounds;
		float x2 = ((Bounds)(ref bounds)).size.x;
		if (x2 > 1E-05f)
		{
			Transform transform = ((Component)val).transform;
			transform.localScale *= num * 1.25f / x2;
		}
		Bounds bounds3 = ((Renderer)val).bounds;
		Transform transform2 = ((Component)val).transform;
		transform2.position += val4 - new Vector3(((Bounds)(ref bounds3)).center.x, ((Bounds)(ref bounds3)).min.y, ((Bounds)(ref bounds3)).center.z) - new Vector3(0f, ((Bounds)(ref bounds2)).size.y * 0.35f, 0f);
		return true;
	}

	private static bool InHeroHelmet(Transform t, Transform root)
	{
		bool flag = false;
		bool flag2 = false;
		Transform val = t;
		while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
		{
			if (((Object)val).name == "HeroSprite")
			{
				flag = true;
			}
			if (((Object)val).name.StartsWith("Helmet #"))
			{
				flag2 = true;
			}
			val = val.parent;
		}
		return flag && flag2;
	}

	private static Sprite HeroHelmFor(Sprite orig, string kind)
	{
		//IL_0009: 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_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Expected O, but got Unknown
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		string[] array = new string[5];
		Rect rect = orig.rect;
		array[0] = ((int)((Rect)(ref rect)).x).ToString();
		array[1] = "_";
		rect = orig.rect;
		array[2] = ((int)((Rect)(ref rect)).y).ToString();
		array[3] = "_";
		array[4] = kind;
		string text = string.Concat(array);
		if (heroHelm.TryGetValue(text, out var value))
		{
			return value;
		}
		value = null;
		string path = Path.Combine(HeianPlugin.ModDir, Path.Combine("herohelm", text + ".png"));
		if (File.Exists(path))
		{
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			ImageConversion.LoadImage(val, File.ReadAllBytes(path));
			((Texture)val).filterMode = (FilterMode)0;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			Object.DontDestroyOnLoad((Object)(object)val);
			float num = ((Texture)val).width;
			rect = orig.rect;
			float num2 = (num - ((Rect)(ref rect)).width) / 2f;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor((orig.pivot.x + num2) / (float)((Texture)val).width, orig.pivot.y / (float)((Texture)val).height);
			value = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), val2, orig.pixelsPerUnit, 0u, (SpriteMeshType)0);
			((Object)value).name = "HeianChef_" + text;
			Object.DontDestroyOnLoad((Object)(object)value);
		}
		heroHelm[text] = value;
		return value;
	}

	private static bool ActiveUnder(Transform t, Transform root)
	{
		Transform val = t;
		while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
		{
			if (!((Component)val).gameObject.activeSelf)
			{
				return false;
			}
			val = val.parent;
		}
		return true;
	}

	private static string PortraitKind(MonoHero hero)
	{
		string text = null;
		SpriteRenderer[] componentsInChildren = ((Component)hero).GetComponentsInChildren<SpriteRenderer>(true);
		foreach (SpriteRenderer val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null || (Object)(object)val.sprite == (Object)null || !((Renderer)val).enabled || !ActiveUnder(((Component)val).transform, ((Component)hero).transform))
			{
				continue;
			}
			string name = ((Object)val.sprite).name;
			if (name.StartsWith("Heroes2_Spriteshop"))
			{
				if (name.Contains("#PointySteel_0"))
				{
					return "eboshi";
				}
				if (name.Contains("#RoundSteel_0"))
				{
					text = "kabuto";
				}
			}
		}
		return text ?? "kabuto";
	}

	private static bool HeroHelmets(MonoHero hero, bool heian)
	{
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
		bool result = false;
		bool flag = false;
		if (heian)
		{
			foreach (KeyValuePair<SpriteRenderer, Saved> item in headgear)
			{
				if ((Object)(object)item.Key != (Object)null && ((Renderer)item.Key).enabled && ((Component)item.Key).transform.IsChildOf(((Component)hero).transform) && ActiveUnder(((Component)item.Key).transform, ((Component)hero).transform) && (Object)(object)item.Key.sprite != (Object)null && ((Object)item.Key.sprite).name.Contains("#RoundSteel_0"))
				{
					flag = true;
					break;
				}
			}
		}
		SpriteRenderer[] componentsInChildren = ((Component)hero).GetComponentsInChildren<SpriteRenderer>(true);
		foreach (SpriteRenderer val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			if (!heian)
			{
				if (helmOrig.TryGetValue(val, out var value))
				{
					val.sprite = value;
					helmOrig.Remove(val);
					result = true;
				}
				if (helmHidden.Remove(val))
				{
					((Renderer)val).enabled = true;
					result = true;
				}
			}
			else
			{
				if ((Object)(object)val.sprite == (Object)null || !InHeroHelmet(((Component)val).transform, ((Component)hero).transform))
				{
					continue;
				}
				string name = ((Object)val.sprite).name;
				bool flag2 = false;
				Transform val2 = ((Component)val).transform;
				while ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)((Component)hero).transform)
				{
					if (((Object)val2).name.StartsWith("Helmet #Pointy"))
					{
						flag2 = true;
						break;
					}
					val2 = val2.parent;
				}
				string text = ((!flag && flag2) ? "eboshi" : "kabuto");
				if (name.StartsWith("HeianChef_"))
				{
					if (helmOrig.TryGetValue(val, out var value2))
					{
						Sprite val3 = HeroHelmFor(value2, text);
						if ((Object)(object)val3 != (Object)null && (Object)(object)val3 != (Object)(object)val.sprite)
						{
							val.sprite = val3;
							result = true;
						}
					}
				}
				else if (name == "PartTex_Spriteshop_Steel_0")
				{
					Sprite val4 = HeroHelmFor(val.sprite, text);
					string[] obj = new string[7]
					{
						(hero.heroDef != null) ? hero.heroDef.nameTerm : ((Object)hero).name,
						"/",
						text,
						"/",
						null,
						null,
						null
					};
					Rect rect = val.sprite.rect;
					obj[4] = ((int)((Rect)(ref rect)).x).ToString();
					obj[5] = "_";
					rect = val.sprite.rect;
					obj[6] = ((int)((Rect)(ref rect)).y).ToString();
					string text2 = string.Concat(obj);
					if (helmLogged.Add(text2))
					{
						HeianPlugin.Log.LogInfo((object)("Coiffe du chef : " + text2 + (((Object)(object)val4 != (Object)null) ? " -> appliquée" : " -> image introuvable")));
					}
					if ((Object)(object)val4 != (Object)null)
					{
						helmOrig[val] = val.sprite;
						val.sprite = val4;
						result = true;
					}
				}
				else if (name.StartsWith("PartTex_Spriteshop_") && ((Renderer)val).enabled && !name.StartsWith("HeianChef_"))
				{
					((Renderer)val).enabled = false;
					helmHidden.Add(val);
					result = true;
				}
			}
		}
		return result;
	}

	internal static void Apply(MonoHero hero)
	{
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			bool flag = HeianPlugin.CurrentCiv == Civ.Heian;
			bool flag2 = false;
			SpriteRenderer[] componentsInChildren = ((Component)hero).GetComponentsInChildren<SpriteRenderer>(true);
			foreach (SpriteRenderer val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					if (flag && ((Renderer)val).enabled && (Object)(object)val.sprite != (Object)null && IsCrown(((Object)val.sprite).name))
					{
						((Renderer)val).enabled = false;
						hiddenCrowns.Add(val);
						flag2 = true;
					}
					else if (!flag && !((Renderer)val).enabled && hiddenCrowns.Remove(val))
					{
						((Renderer)val).enabled = true;
						flag2 = true;
					}
					if (!flag && headgear.TryGetValue(val, out var value))
					{
						val.sprite = value.sprite;
						((Component)val).transform.localPosition = value.pos;
						((Component)val).transform.localScale = value.scale;
						val.color = value.color;
						headgear.Remove(val);
						flag2 = true;
					}
				}
			}
			if (flag && !loggedAgent)
			{
				loggedAgent = true;
				componentsInChildren = ((Component)hero).GetComponentsInChildren<SpriteRenderer>(true);
				foreach (SpriteRenderer val2 in componentsInChildren)
				{
					if ((Object)(object)val2 != (Object)null && (Object)(object)val2.sprite != (Object)null && ((Object)val2.sprite).name.StartsWith("PartTex"))
					{
						string text = ((Object)val2).name;
						Transform parent = ((Component)val2).transform.parent;
						while ((Object)(object)parent != (Object)null && (Object)(object)parent != (Object)(object)((Component)hero).transform)
						{
							text = ((Object)parent).name + "/" + text;
							parent = parent.parent;
						}
						HeianPlugin.Log.LogInfo((object)("Agent : " + text + " = " + ((Object)val2.sprite).name + ((((Renderer)val2).enabled && ((Component)val2).gameObject.activeInHierarchy) ? "" : " (caché)")));
					}
				}
			}
			if (flag)
			{
				Build();
			}
			bool flag3 = flag2;
			if (flag)
			{
				flag3 |= GiveHeadgear(hero);
			}
			if (toHeian.Count == 0)
			{
				if ((flag3 | HeroHelmets(hero, flag)) && (object)drawAll != null)
				{
					drawAll.Invoke(hero, null);
				}
				return;
			}
			componentsInChildren = ((Component)hero).GetComponentsInChildren<SpriteRenderer>(true);
			foreach (SpriteRenderer val3 in componentsInChildren)
			{
				if (!((Object)(object)val3 == (Object)null) && !((Object)(object)val3.sprite == (Object)null))
				{
					if (flag && toHeian.TryGetValue(val3.sprite, out var value2))
					{
						val3.sprite = value2;
						flag3 = true;
					}
					else if (!flag && toOriginal.TryGetValue(val3.sprite, out value2))
					{
						val3.sprite = value2;
						flag3 = true;
					}
				}
			}
			if ((flag3 | HeroHelmets(hero, flag)) && (object)drawAll != null)
			{
				drawAll.Invoke(hero, null);
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogError((object)("Portrait : " + ex));
		}
	}
}
internal class Sakura
{
	private struct Petal
	{
		public Vector2 p;

		public Vector2 v;

		public float rot;

		public float spin;

		public float size;

		public float sway;

		public float phase;

		public Color col;
	}

	private readonly List<Petal> petals = new List<Petal>();

	private Texture2D tex;

	private float alpha;

	private void Init()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: 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)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)tex != (Object)null)
		{
			return;
		}
		tex = new Texture2D(48, 48, (TextureFormat)4, false)
		{
			wrapMode = (TextureWrapMode)1
		};
		for (int i = 0; i < 48; i++)
		{
			for (int j = 0; j < 48; j++)
			{
				float num = ((float)j + 0.5f) / 48f * 2f - 1f;
				float num2 = ((float)i + 0.5f) / 48f * 2f - 1f;
				float num3 = num * num / 0.42f + num2 * num2 / 0.95f;
				float num4 = ((Mathf.Abs(num) < 0.18f - (num2 - 0.62f) * 0.5f && num2 > 0.62f) ? 1f : 0f);
				float num5 = Mathf.Clamp01((1f - num3) * 6f) * (1f - num4);
				float num6 = 0.92f + 0.08f * (1f - num2);
				Color val = Color.Lerp(new Color(1f, 0.93f, 0.95f), new Color(0.97f, 0.66f, 0.76f), Mathf.Clamp01((num2 + 1f) * 0.5f));
				tex.SetPixel(j, i, new Color(val.r * num6, val.g * num6, val.b * num6, num5));
			}
		}
		tex.Apply();
		Object.DontDestroyOnLoad((Object)(object)tex);
	}

	private Petal NewPetal(bool anywhere)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: 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)
		return new Petal
		{
			p = new Vector2(Random.Range(-0.1f, 1.1f) * (float)Screen.width, anywhere ? Random.Range(0f, (float)Screen.height) : Random.Range(-60f, -10f)),
			v = new Vector2(Random.Range(10f, 45f), Random.Range(30f, 70f)) * ((float)Screen.height / 1080f),
			rot = Random.Range(0f, 360f),
			spin = Random.Range(-90f, 90f),
			size = Random.Range(10f, 22f) * ((float)Screen.height / 1080f),
			sway = Random.Range(10f, 30f),
			phase = Random.Range(0f, 6.28f),
			col = new Color(1f, 1f, 1f, Random.Range(0.65f, 0.95f))
		};
	}

	internal void Draw(bool active)
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Invalid comparison between Unknown and I4
		//IL_00b7: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: 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_0275: 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_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: 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_01f2: 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_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		alpha = Mathf.MoveTowards(alpha, active ? 1f : 0f, Time.unscaledDeltaTime * 1.5f);
		if (alpha <= 0f)
		{
			petals.Clear();
			return;
		}
		Init();
		if ((int)Event.current.type != 7)
		{
			return;
		}
		int num = Mathf.RoundToInt(36f * ((float)Screen.width / 1920f) + 10f);
		while (petals.Count < num)
		{
			petals.Add(NewPetal(petals.Count < num / 2));
		}
		float num2 = Mathf.Min(Time.unscaledDeltaTime, 0.05f);
		Matrix4x4 matrix = GUI.matrix;
		Color color = GUI.color;
		for (int i = 0; i < petals.Count; i++)
		{
			Petal value = petals[i];
			value.phase += num2 * 1.3f;
			ref Vector2 p = ref value.p;
			p += new Vector2(value.v.x + Mathf.Sin(value.phase) * value.sway, value.v.y) * num2;
			value.rot += value.spin * num2;
			if (value.p.y > (float)(Screen.height + 40) || value.p.x > (float)(Screen.width + 60))
			{
				value = NewPetal(anywhere: false);
			}
			petals[i] = value;
			GUI.matrix = matrix;
			GUIUtility.RotateAroundPivot(value.rot, value.p);
			float num3 = 0.55f + 0.45f * Mathf.Abs(Mathf.Sin(value.phase * 1.7f));
			Rect val = new Rect(value.p.x - value.size * num3 / 2f, value.p.y - value.size / 2f, value.size * num3, value.size);
			GUI.color = new Color(1f, 1f, 1f, value.col.a * alpha);
			GUI.DrawTexture(val, (Texture)(object)tex);
		}
		GUI.matrix = matrix;
		GUI.color = color;
	}
}
internal static class StatTweaks
{
	internal static readonly HashSet<int> done = new HashSet<int>();

	internal static bool IsPlayerHeian(Component c)
	{
		if (HeianPlugin.CurrentCiv != Civ.Heian || (Object)(object)c == (Object)null)
		{
			return false;
		}
		if ((Object)(object)c.GetComponentInParent<VikingAgent>() != (Object)null)
		{
			return false;
		}
		return done.Add(((Object)c).GetInstanceID());
	}
}
[HarmonyPatch(typeof(Archery), "Setup")]
internal static class Patch_ArcherySetup
{
	private static void Postfix(Archery __instance)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		if (StatTweaks.IsPlayerHeian((Component)(object)__instance) && __instance._archerySettings != null)
		{
			for (int i = 0; i < __instance._archerySettings.Length; i++)
			{
				ArcherySettings val = __instance._archerySettings[i];
				val.cooldown *= 1.15f;
				val.spread *= 0.8f;
				val.attackSettings.damage *= 1.25f;
				__instance._archerySettings[i] = val;
			}
		}
	}
}
[HarmonyPatch(typeof(Spear), "Setup")]
internal static class Patch_SpearSetup
{
	private static void Postfix(Spear __instance)
	{
		//IL_002e: 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_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		if (!StatTweaks.IsPlayerHeian((Component)(object)__instance))
		{
			return;
		}
		__instance.spearLength *= 1.2f;
		if (__instance.attackSettings != null)
		{
			for (int i = 0; i < __instance.attackSettings.Length; i++)
			{
				AttackSettings val = __instance.attackSettings[i];
				val.damage *= 1.1f;
				val.knockback *= 0.9f;
				__instance.attackSettings[i] = val;
			}
		}
	}
}
[HarmonyPatch(typeof(Swordsman), "Setup")]
internal static class Patch_SwordSetup
{
	private static void Postfix(Swordsman __instance)
	{
		if (StatTweaks.IsPlayerHeian((Component)(object)__instance))
		{
			for (int i = 0; i < __instance.damageLevels.Length; i++)
			{
				__instance.damageLevels[i] *= 1.15f;
			}
			for (int j = 0; j < __instance.knockbackLevels.Length; j++)
			{
				__instance.knockbackLevels[j] *= 0.85f;
			}
		}
	}
}
internal static class TextureSwapper
{
	private class RefEq : IEqualityComparer<Texture2D>
	{
		public bool Equals(Texture2D a, Texture2D b)
		{
			return a == b;
		}

		public int GetHashCode(Texture2D t)
		{
			return RuntimeHelpers.GetHashCode(t);
		}
	}

	private static readonly Dictionary<string, string> heianFiles = new Dictionary<string, string>
	{
		{ "PartTex_Spriteshop", "PartTex_Spriteshop_Heian.png" },
		{ "PartTex_Median_BlurAlpha", "PartTex_Median_BlurAlpha_Heian.png" },
		{ "SpriteAtlasTexture-Sprites (Group 0)-2048x1024-fmt4", "Animations_Katana.png" },
		{ "SpriteAtlasTexture-Sprites (Group 2)-1024x2048-fmt12", "Sprites_Naginata.png" },
		{ "SpriteAtlasTexture-Sprites (Group 3)-64x64-fmt4", "Piece_Heian.png" },
		{ "CampaignDeath", "CampaignDeath_Heian.png" },
		{ "UI_Decoration", "UI_Decoration_Heian.png" },
		{ "StartMenuShields", "StartMenuShields_Heian.png" },
		{ "Palette", "Palette_Weapons_Heian.png" }
	};

	private static readonly Dictionary<string, Texture2D> backups = new Dictionary<string, Texture2D>();

	private static readonly Dictionary<string, Texture2D> heianTex = new Dictionary<string, Texture2D>();

	private static readonly Dictionary<Texture2D, Civ> applied = new Dictionary<Texture2D, Civ>(new RefEq());

	private static List<Texture2D> FindAll(string name)
	{
		List<Texture2D> list = new List<Texture2D>();
		Texture2D[] array = Resources.FindObjectsOfTypeAll<Texture2D>();
		foreach (Texture2D val in array)
		{
			if ((Object)(object)val != (Object)null && ((Object)val).name == name)
			{
				list.Add(val);
			}
		}
		return list;
	}

	internal static void Apply(Civ civ)
	{
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		foreach (KeyValuePair<string, string> heianFile in heianFiles)
		{
			foreach (Texture2D item in FindAll(heianFile.Key))
			{
				int instanceID = ((Object)item).GetInstanceID();
				if (applied.TryGetValue(item, out var value) && value == civ)
				{
					continue;
				}
				try
				{
					if (backups.ContainsKey(heianFile.Key))
					{
						goto IL_009c;
					}
					if (civ == Civ.Nordique)
					{
						applied[item] = civ;
						continue;
					}
					backups[heianFile.Key] = Backup(item, heianFile.Key);
					goto IL_009c;
					IL_009c:
					if (civ == Civ.Heian)
					{
						Texture2D heian = GetHeian(heianFile.Key, heianFile.Value, item);
						if ((Object)(object)heian == (Object)null)
						{
							continue;
						}
						Copy(heian, item, heianFile.Value);
						goto IL_011f;
					}
					Texture2D val = backups[heianFile.Key];
					if (val.format == item.format && val.mipmapCount == item.mipmapCount)
					{
						Graphics.CopyTexture((Texture)(object)val, (Texture)(object)item);
					}
					else
					{
						ImageConversion.LoadImage(item, ImageConversion.EncodeToPNG(val));
					}
					goto IL_011f;
					IL_011f:
					applied[item] = civ;
					HeianPlugin.Log.LogInfo((object)("Texture " + heianFile.Key + " #" + instanceID + " -> " + civ));
				}
				catch (Exception ex)
				{
					HeianPlugin.Log.LogError((object)("Échec du changement de texture " + heianFile.Key + " : " + ex));
					applied[item] = civ;
				}
			}
		}
	}

	private static Texture2D Backup(Texture2D target, string key)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Invalid comparison between Unknown and I4
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Invalid comparison between Unknown and I4
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		Texture2D val;
		if ((int)target.format == 10 || (int)target.format == 12 || (int)target.format == 4)
		{
			val = new Texture2D(((Texture)target).width, ((Texture)target).height, target.format, target.mipmapCount > 1);
			Graphics.CopyTexture((Texture)(object)target, (Texture)(object)val);
		}
		else
		{
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)target).width, ((Texture)target).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			Graphics.Blit((Texture)(object)target, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			val = new Texture2D(((Texture)target).width, ((Texture)target).height, (TextureFormat)4, false);
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)target).width, (float)((Texture)target).height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
		}
		((Object)val).name = key + "_Original";
		Object.DontDestroyOnLoad((Object)(object)val);
		return val;
	}

	private static Texture2D GetHeian(string key, string file, Texture2D target)
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Invalid comparison between Unknown and I4
		//IL_0129: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Invalid comparison between Unknown and I4
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Invalid comparison between Unknown and I4
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Expected O, but got Unknown
		if (heianTex.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		string text = Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", file));
		if (!File.Exists(text))
		{
			HeianPlugin.Log.LogError((object)("Texture introuvable : " + text));
			return null;
		}
		bool flag = target.mipmapCount > 1;
		value = new Texture2D(2, 2, (TextureFormat)4, flag);
		ImageConversion.LoadImage(value, File.ReadAllBytes(text));
		if (((Texture)value).width != ((Texture)target).width || ((Texture)value).height != ((Texture)target).height)
		{
			HeianPlugin.Log.LogError((object)("Taille incorrecte pour " + file + " (" + ((Texture)value).width + "x" + ((Texture)value).height + ")"));
			return null;
		}
		if (value.format != target.format && ((int)target.format == 12 || (int)target.format == 10))
		{
			value.Compress(true);
			value.Apply(false, false);
		}
		if (value.format != target.format && (int)target.format == 4)
		{
			Texture2D val = new Texture2D(((Texture)value).width, ((Texture)value).height, (TextureFormat)4, flag);
			val.SetPixels32(value.GetPixels32());
			val.Apply(true, false);
			Object.Destroy((Object)(object)value);
			value = val;
		}
		((Object)value).name = key + "_Heian";
		Object.DontDestroyOnLoad((Object)(object)value);
		heianTex[key] = value;
		return value;
	}

	private static void Copy(Texture2D src, Texture2D target, string file)
	{
		//IL_0001: 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_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		if (src.format == target.format && src.mipmapCount == target.mipmapCount)
		{
			Graphics.CopyTexture((Texture)(object)src, (Texture)(object)target);
			return;
		}
		HeianPlugin.Log.LogInfo((object)("Format " + ((object)target.format/*cast due to .constrained prefix*/).ToString() + " : chargement direct de " + file));
		ImageConversion.LoadImage(target, File.ReadAllBytes(Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", file))));
	}
}
internal static class CoinIcons
{
	private static Sprite heian;

	private static readonly Dictionary<Component, Sprite> originals = new Dictionary<Component, Sprite>();

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

	private static Sprite Get()
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected O, but got Unknown
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)heian != (Object)null)
		{
			return heian;
		}
		string path = Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", "Piece_Heian.png"));
		if (!File.Exists(path))
		{
			return null;
		}
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
		ImageConversion.LoadImage(val, File.ReadAllBytes(path));
		((Texture)val).wrapMode = (TextureWrapMode)1;
		Object.DontDestroyOnLoad((Object)(object)val);
		heian = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0);
		((Object)heian).name = "UI_Coin_BlurAlpha";
		Object.DontDestroyOnLoad((Object)(object)heian);
		return heian;
	}

	private static bool IsCoin(Sprite s)
	{
		if ((Object)(object)s != (Object)null)
		{
			return ((Object)s).name.IndexOf("Coin", StringComparison.OrdinalIgnoreCase) >= 0;
		}
		return false;
	}

	internal static void Apply(Civ civ)
	{
		try
		{
			Image[] array = Object.FindObjectsOfType<Image>();
			foreach (Image val in array)
			{
				if (!((Object)(object)val.sprite == (Object)null) && IsCoin(val.sprite) && logged.Add(((Object)val).GetInstanceID()))
				{
					Texture2D texture = val.sprite.texture;
					HeianPlugin.Log.LogInfo((object)("Pièce UI : " + ((Object)val).name + " sprite=" + ((Object)val.sprite).name + " tex=" + (Object.op_Implicit((Object)(object)texture) ? (((Object)texture).name + " #" + ((Object)texture).GetInstanceID()) : "?") + " mat=" + (Object.op_Implicit((Object)(object)((Graphic)val).material) ? ((Object)((Graphic)val).material).name : "?")));
				}
			}
		}
		catch
		{
		}
	}

	internal static void ApplyOld(Civ civ)
	{
		try
		{
			Sprite val = ((civ == Civ.Heian) ? Get() : null);
			Image[] array = Object.FindObjectsOfType<Image>();
			foreach (Image val2 in array)
			{
				if (civ == Civ.Heian && (Object)(object)val != (Object)null && IsCoin(val2.sprite) && (Object)(object)val2.sprite != (Object)(object)val)
				{
					if (!originals.ContainsKey((Component)(object)val2))
					{
						originals[(Component)(object)val2] = val2.sprite;
					}
					val2.sprite = val;
				}
				else if (civ != Civ.Heian && originals.ContainsKey((Component)(object)val2))
				{
					val2.sprite = originals[(Component)(object)val2];
					originals.Remove((Component)(object)val2);
				}
			}
			SpriteRenderer[] array2 = Object.FindObjectsOfType<SpriteRenderer>();
			foreach (SpriteRenderer val3 in array2)
			{
				if (civ == Civ.Heian && (Object)(object)val != (Object)null && IsCoin(val3.sprite) && (Object)(object)val3.sprite != (Object)(object)val)
				{
					if (!originals.ContainsKey((Component)(object)val3))
					{
						originals[(Component)(object)val3] = val3.sprite;
					}
					val3.sprite = val;
				}
				else if (civ != Civ.Heian && originals.ContainsKey((Component)(object)val3))
				{
					val3.sprite = originals[(Component)(object)val3];
					originals.Remove((Component)(object)val3);
				}
			}
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogWarning((object)("Pièces : " + ex.Message));
		}
	}
}
internal static class TraitIcons
{
	private static readonly Dictionary<HeroUpgradeDefinition, Sprite> originals = new Dictionary<HeroUpgradeDefinition, Sprite>();

	private static readonly Dictionary<string, Sprite> heian = new Dictionary<string, Sprite>();

	private static Civ applied = Civ.Nordique;

	internal static void Apply(Civ civ)
	{
		try
		{
			HeroUpgradeDefinition[] array = Resources.FindObjectsOfTypeAll<HeroUpgradeDefinition>();
			foreach (HeroUpgradeDefinition val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				if (!originals.TryGetValue(val, out var value))
				{
					if ((Object)(object)val.infoSprite == (Object)null)
					{
						continue;
					}
					string name = ((Object)val.infoSprite).name;
					if (!name.StartsWith("Traits_") && !name.StartsWith("Hero_Class_"))
					{
						continue;
					}
					value = val.infoSprite;
					originals[val] = value;
				}
				if (civ == Civ.Heian)
				{
					Sprite val2 = GetHeian(value);
					if ((Object)(object)val2 != (Object)null)
					{
						val.infoSprite = val2;
					}
				}
				else
				{
					val.infoSprite = value;
				}
			}
			if (applied != civ)
			{
				HeianPlugin.Log.LogInfo((object)("Emblèmes des traits -> " + civ.ToString() + " (" + originals.Count + " traits)"));
			}
			applied = civ;
		}
		catch (Exception ex)
		{
			HeianPlugin.Log.LogError((object)("Emblèmes : " + ex));
		}
	}

	private static Sprite GetHeian(Sprite orig)
	{
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Expected O, but got Unknown
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: 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_0124: Unknown result type (might be due to invalid IL or missing references)
		if (heian.TryGetValue(((Object)orig).name, out var value))
		{
			return value;
		}
		string path = (((Object)orig).name.StartsWith("Hero_Class_") ? "classes" : "traits");
		string text = Path.Combine(HeianPlugin.ModDir, Path.Combine("textures", Path.Combine(path, ((Object)orig).name + "_Heian.png")));
		if (!File.Exists(text))
		{
			heian[((Object)orig).name] = null;
			HeianPlugin.Log.LogWarning((object)("Emblème manquant : " + text));
			return null;
		}
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
		ImageConversion.LoadImage(val, File.ReadAllBytes(text));
		((Texture)val).wrapMode = (TextureWrapMode)1;
		((Texture)val).filterMode = (FilterMode)1;
		((Object)val).name = ((Object)orig).name + "_Heian";
		Object.DontDestroyOnLoad((Object)(object)val);
		Rect rect = orig.rect;
		Vector2 val2 = default(Vector2);
		((Vector2)(ref val2))..ctor(orig.pivot.x / ((Rect)(ref rect)).width, orig.pivot.y / ((Rect)(ref rect)).height);
		value = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), val2, orig.pixelsPerUnit * (float)((Texture)val).width / ((Rect)(ref rect)).width, 0u, (SpriteMeshType)0);
		((Object)value).name = ((Object)orig).name;
		Object.DontDestroyOnLoad((Object)(object)value);
		heian[((Object)orig).name] = value;
		return value;
	}
}