Decompiled source of Dresses v1.1.0

Dresses.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Dresses")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("Dresses")]
[assembly: AssemblyTitle("Dresses")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Dresses
{
	internal sealed class BootDef
	{
		public string Id { get; set; } = "";

		public string Name { get; set; } = "";

		public string Description { get; set; } = "";

		public string CraftingStation { get; set; } = CraftingStations.Workbench;

		public List<(string Item, int Amount, int AmountPerLevel)> Recipe { get; set; } = new List<(string, int, int)>();

		public string NameToken => "item_" + Id.ToLowerInvariant();

		public string DescriptionToken => NameToken + "_description";
	}
	internal static class BootDefs
	{
		public static readonly BootDef[] All = new BootDef[1]
		{
			new BootDef
			{
				Id = "SkaBootsLaced",
				Name = "Laced Boots",
				Description = "Dark brown leather boots, laced up the front to just below the knee.",
				Recipe = 
				{
					("DeerHide", 2, 2),
					("Blueberries", 2, 0),
					("Raspberry", 2, 0)
				}
			}
		};
	}
	internal static class BootFactory
	{
		private const string BasePrefab = "ArmorLeatherLegs";

		private static readonly int LegsTex = Shader.PropertyToID("_LegsTex");

		private static readonly int LegsBumpMap = Shader.PropertyToID("_LegsBumpMap");

		private static readonly int LegsMetal = Shader.PropertyToID("_LegsMetal");

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

		private static readonly Dictionary<string, Material> ShellMaterials = new Dictionary<string, Material>();

		private static readonly Quaternion IconRotation = Quaternion.Euler(15f, 0f, 0f) * Quaternion.Euler(0f, 35f, 0f);

		private static readonly Dictionary<Mesh, Mesh> Shells = new Dictionary<Mesh, Mesh>();

		private static readonly BootShell.Shape Shape = new BootShell.Shape();

		private const string ShellName = "boot_shell";

		public static bool Shaped { get; set; } = true;

		public static void Add(BootDef def)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_011c: 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_0139: Expected O, but got Unknown
			ItemConfig val = new ItemConfig
			{
				Name = "$" + def.NameToken,
				Description = "$" + def.DescriptionToken,
				CraftingStation = def.CraftingStation
			};
			foreach (var (text, num, num2) in def.Recipe)
			{
				val.AddRequirement(text, num, num2);
			}
			CustomItem val2 = new CustomItem(def.Id, "ArmorLeatherLegs", val);
			if (!Object.op_Implicit((Object)(object)val2.ItemPrefab))
			{
				throw new InvalidOperationException("Could not clone ArmorLeatherLegs.");
			}
			SharedData shared = val2.ItemDrop.m_itemData.m_shared;
			if (!Object.op_Implicit((Object)(object)shared.m_armorMaterial))
			{
				throw new InvalidOperationException("ArmorLeatherLegs has no armour material to paint the legs with.");
			}
			if (!shared.m_armorMaterial.HasProperty(LegsTex))
			{
				throw new InvalidOperationException("ArmorLeatherLegs's armour material has no leg texture slot.");
			}
			Texture2D val3 = GownTextures.Load(def.Id + "_legs.png");
			Material val4 = new Material(shared.m_armorMaterial)
			{
				name = def.Id + "_legs"
			};
			val4.SetTexture(LegsTex, (Texture)(object)val3);
			if (val4.HasProperty(LegsBumpMap))
			{
				val4.SetTexture(LegsBumpMap, (Texture)null);
			}
			if (val4.HasProperty(LegsMetal))
			{
				val4.SetTexture(LegsMetal, (Texture)null);
			}
			shared.m_armorMaterial = val4;
			string text2 = AddShell(val2.ItemPrefab, def, val3);
			Sprite val5 = RenderIcon(def);
			if (Object.op_Implicit((Object)(object)val5))
			{
				shared.m_icons = (Sprite[])(object)new Sprite[1] { val5 };
			}
			Hashes.Add(StringExtensionMethods.GetStableHashCode(def.Id));
			if (!ItemManager.Instance.AddItem(val2))
			{
				throw new InvalidOperationException("Jotunn refused to add " + def.Id + ".");
			}
			DressesPlugin.Log.LogInfo((object)string.Format("Added {0}: cloned from {1}, leg texture {2}x{3}, shape: {4}, icon {5}", def.Id, "ArmorLeatherLegs", ((Texture)val3).width, ((Texture)val3).height, text2, Object.op_Implicit((Object)(object)val5) ? "rendered from the boot shape" : "vanilla (the trousers')"));
		}

		private static Sprite? RenderIcon(BootDef def)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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_00d3: 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_00fa: 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_0100: 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)
			//IL_011a: Expected O, but got Unknown
			GameObject val = null;
			try
			{
				if (!ShellMaterials.TryGetValue(def.Id, out Material value))
				{
					return null;
				}
				VisEquipment val2 = ((IEnumerable<VisEquipment>)Resources.FindObjectsOfTypeAll<VisEquipment>()).FirstOrDefault((Func<VisEquipment, bool>)((VisEquipment candidate) => Object.op_Implicit((Object)(object)candidate) && ((Object)((Component)candidate).gameObject).name == "Player" && Object.op_Implicit((Object)(object)candidate.m_bodyModel) && Object.op_Implicit((Object)(object)candidate.m_bodyModel.sharedMesh)));
				if (!Object.op_Implicit((Object)(object)val2))
				{
					return null;
				}
				Mesh val3 = ShellFor(val2.m_bodyModel);
				if ((Object)(object)val3 == (Object)null)
				{
					return null;
				}
				val = new GameObject(def.Id + "_icon");
				GameObject val4 = new GameObject("boots");
				val4.transform.SetParent(val.transform, false);
				val4.transform.localRotation = ((Component)val2.m_bodyModel).transform.localRotation;
				val4.transform.localScale = ((Component)val2.m_bodyModel).transform.localScale;
				val4.AddComponent<MeshFilter>().sharedMesh = val3;
				((Renderer)val4.AddComponent<MeshRenderer>()).sharedMaterial = value;
				return RenderManager.Instance.Render(new RenderRequest(val)
				{
					Rotation = IconRotation,
					DistanceMultiplier = 0.9f
				});
			}
			catch (Exception ex)
			{
				DressesPlugin.Log.LogWarning((object)("Icon render for " + def.Id + " failed: " + ex.Message));
				return null;
			}
			finally
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					Object.DestroyImmediate((Object)(object)val);
				}
			}
		}

		public static bool IsBoots(int itemHash)
		{
			return Hashes.Contains(itemHash);
		}

		private static string AddShell(GameObject prefab, BootDef def, Texture2D texture)
		{
			//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_0060: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab2 = PrefabManager.Instance.GetPrefab("ArmorDress1");
			SkinnedMeshRenderer val = (Object.op_Implicit((Object)(object)prefab2) ? prefab2.GetComponentInChildren<SkinnedMeshRenderer>(true) : null);
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)((Renderer)val).sharedMaterial))
			{
				return "paint only (no vanilla material to copy for the shell)";
			}
			Material val2 = new Material(((Renderer)val).sharedMaterial)
			{
				name = def.Id + "_shell"
			};
			val2.SetTexture("_MainTex", (Texture)(object)texture);
			if (val2.HasProperty("_BumpMap"))
			{
				val2.SetTexture("_BumpMap", (Texture)null);
			}
			if (val2.HasProperty("_MetallicGlossMap"))
			{
				val2.SetTexture("_MetallicGlossMap", (Texture)null);
			}
			GameObject val3 = new GameObject("attach_skin");
			val3.transform.SetParent(prefab.transform, false);
			val3.SetActive(false);
			GameObject val4 = new GameObject("boot_shell");
			val4.transform.SetParent(val3.transform, false);
			((Renderer)val4.AddComponent<SkinnedMeshRenderer>()).sharedMaterial = val2;
			ShellMaterials[def.Id] = val2;
			return $"a shell round the foot, {Shape.Top * 100f:0} cm high, built when worn";
		}

		public static void Fit(List<GameObject> parts, SkinnedMeshRenderer body)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			Mesh val = (Shaped ? ShellFor(body) : null);
			foreach (GameObject part in parts)
			{
				if (!Object.op_Implicit((Object)(object)part))
				{
					continue;
				}
				SkinnedMeshRenderer[] componentsInChildren = part.GetComponentsInChildren<SkinnedMeshRenderer>(true);
				foreach (SkinnedMeshRenderer val2 in componentsInChildren)
				{
					if (!(((Object)val2).name != "boot_shell"))
					{
						val2.sharedMesh = val;
						if ((Object)(object)val != (Object)null)
						{
							((Renderer)val2).localBounds = ((Renderer)body).localBounds;
						}
					}
				}
			}
		}

		private static Mesh? ShellFor(SkinnedMeshRenderer body)
		{
			//IL_0058: 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)
			Mesh sharedMesh = body.sharedMesh;
			if (!Object.op_Implicit((Object)(object)sharedMesh))
			{
				return null;
			}
			if (Shells.TryGetValue(sharedMesh, out Mesh value))
			{
				return value;
			}
			Mesh val = null;
			if (!sharedMesh.isReadable)
			{
				DressesPlugin.Log.LogWarning((object)("The body mesh " + ((Object)sharedMesh).name + " cannot be read, so boots on it are paint only."));
			}
			else
			{
				try
				{
					val = BootShell.Build(sharedMesh, ((Component)body).transform.localRotation, ((Component)body).transform.localScale, Shape);
					DressesPlugin.Log.LogInfo((object)($"Boot shell built for body mesh {((Object)sharedMesh).name}: {val.vertexCount} vertices, {val.triangles.Length / 3} triangles, " + $"{val.bindposes.Length} bind poses (the body has {body.bones.Length} bones)"));
				}
				catch (Exception ex)
				{
					DressesPlugin.Log.LogWarning((object)("The boot shell for " + ((Object)sharedMesh).name + " could not be built, so boots on it are paint only: " + ex.Message));
				}
			}
			Shells[sharedMesh] = val;
			return val;
		}
	}
	internal static class Catalogue
	{
		public sealed class Entry
		{
			public string Id = "";

			public string Name = "";
		}

		private static Entry[]? _all;

		public static Entry[] All => _all ?? (_all = GownDefs.All.Select((GownDef def) => new Entry
		{
			Id = def.Id,
			Name = def.Name
		}).Concat(BootDefs.All.Select((BootDef def) => new Entry
		{
			Id = def.Id,
			Name = def.Name
		})).ToArray());
	}
	public static class BootShell
	{
		public sealed class Shape
		{
			public float Top = 0.45f;

			public float Thickness = 0.013f;

			public float SoleThickness = 0.024f;

			public float SoleHeight = 0.04f;

			public float CuffThickness = 0.022f;

			public float CuffDepth = 0.045f;

			public float HeelHeight = 0.075f;

			public float HeelFront = -0.05f;

			public float HeelThickness = 0.04f;
		}

		public static Mesh Build(Mesh body, Quaternion rotation, Vector3 scale, Shape shape)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0423: Unknown result type (might be due to invalid IL or missing references)
			//IL_0428: Unknown result type (might be due to invalid IL or missing references)
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0456: Unknown result type (might be due to invalid IL or missing references)
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_0474: Unknown result type (might be due to invalid IL or missing references)
			//IL_0480: Unknown result type (might be due to invalid IL or missing references)
			//IL_0488: Unknown result type (might be due to invalid IL or missing references)
			//IL_048f: Expected O, but got Unknown
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0401: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] positions = body.vertices;
			Vector3[] normals = body.normals;
			Vector2[] uvs = body.uv;
			BoneWeight[] weights = body.boneWeights;
			int[] triangles = body.triangles;
			float num = 1f / Mathf.Max(1E-06f, Mathf.Abs(scale.x));
			float[] height = new float[positions.Length];
			float[] forward = new float[positions.Length];
			for (int i = 0; i < positions.Length; i++)
			{
				Vector3 val = rotation * Vector3.Scale(positions[i], scale);
				height[i] = val.y;
				forward[i] = val.z;
			}
			List<Vector3> outPositions = new List<Vector3>();
			List<Vector3> outNormals = new List<Vector3>();
			List<Vector2> outUvs = new List<Vector2>();
			List<BoneWeight> outWeights = new List<BoneWeight>();
			List<float> outHeights = new List<float>();
			List<float> outForward = new List<float>();
			List<int> list = new List<int>();
			Dictionary<int, int> kept = new Dictionary<int, int>();
			Dictionary<long, int> cuts = new Dictionary<long, int>();
			for (int j = 0; j < triangles.Length; j += 3)
			{
				int num2 = 0;
				for (int k = 0; k < 3; k++)
				{
					if (height[triangles[j + k]] <= shape.Top)
					{
						num2++;
					}
				}
				switch (num2)
				{
				case 3:
				{
					for (int m = 0; m < 3; m++)
					{
						list.Add(Keep(triangles[j + m]));
					}
					continue;
				}
				case 1:
				{
					int l;
					for (l = 0; height[triangles[j + l]] > shape.Top; l++)
					{
					}
					int num3 = triangles[j + l];
					int above = triangles[j + (l + 1) % 3];
					int above2 = triangles[j + (l + 2) % 3];
					list.Add(Keep(num3));
					list.Add(Cut(num3, above));
					list.Add(Cut(num3, above2));
					continue;
				}
				case 0:
					continue;
				}
				int n;
				for (n = 0; height[triangles[j + n]] <= shape.Top; n++)
				{
				}
				int above3 = triangles[j + n];
				int num4 = triangles[j + (n + 1) % 3];
				int num5 = triangles[j + (n + 2) % 3];
				int item = Keep(num4);
				int item2 = Keep(num5);
				int item3 = Cut(num5, above3);
				int item4 = Cut(num4, above3);
				list.Add(item);
				list.Add(item2);
				list.Add(item3);
				list.Add(item);
				list.Add(item3);
				list.Add(item4);
			}
			for (int num6 = 0; num6 < outPositions.Count; num6++)
			{
				float num7 = outHeights[num6];
				float num8 = ((num7 < shape.SoleHeight) ? shape.SoleThickness : ((num7 > shape.Top - shape.CuffDepth) ? shape.CuffThickness : shape.Thickness));
				if (num7 < shape.HeelHeight && outForward[num6] < shape.HeelFront)
				{
					num8 = shape.HeelThickness;
				}
				Vector3 val2 = outNormals[num6];
				Vector3 val3;
				if (!(((Vector3)(ref val2)).sqrMagnitude > 1E-08f))
				{
					val3 = Vector3.zero;
				}
				else
				{
					val2 = outNormals[num6];
					val3 = ((Vector3)(ref val2)).normalized;
				}
				Vector3 val4 = val3;
				if ((rotation * val4).y < -0.5f)
				{
					num8 = 0.003f;
				}
				List<Vector3> list2 = outPositions;
				int index = num6;
				list2[index] += val4 * (num8 * num);
			}
			Mesh val5 = new Mesh
			{
				name = ((Object)body).name + "_bootshell"
			};
			val5.SetVertices(outPositions);
			val5.SetNormals(outNormals);
			val5.SetUVs(0, outUvs);
			val5.boneWeights = outWeights.ToArray();
			val5.bindposes = body.bindposes;
			val5.SetTriangles(list, 0);
			val5.RecalculateBounds();
			return val5;
			int Cut(int below, int num9)
			{
				//IL_0062: 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_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
				long key = ((long)below << 32) | (uint)num9;
				if (cuts.TryGetValue(key, out var value))
				{
					return value;
				}
				float num10 = Mathf.InverseLerp(height[below], height[num9], shape.Top);
				value = outPositions.Count;
				cuts[key] = value;
				outPositions.Add(Vector3.Lerp(positions[below], positions[num9], num10));
				List<Vector3> list3 = outNormals;
				Vector3 val6 = Vector3.Lerp(normals[below], normals[num9], num10);
				list3.Add(((Vector3)(ref val6)).normalized);
				outUvs.Add(Vector2.Lerp(uvs[below], uvs[num9], num10));
				outWeights.Add(weights[below]);
				outHeights.Add(shape.Top);
				outForward.Add(Mathf.Lerp(forward[below], forward[num9], num10));
				return value;
			}
			int Keep(int num9)
			{
				//IL_0038: 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)
				//IL_0066: 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)
				if (kept.TryGetValue(num9, out var value))
				{
					return value;
				}
				value = outPositions.Count;
				kept[num9] = value;
				outPositions.Add(positions[num9]);
				outNormals.Add(normals[num9]);
				outUvs.Add(uvs[num9]);
				outWeights.Add(weights[num9]);
				outHeights.Add(height[num9]);
				outForward.Add(forward[num9]);
				return value;
			}
		}
	}
	[BepInPlugin("com.skaket.valheim.dresses", "Dresses", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class DressesPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.skaket.valheim.dresses";

		public const string PluginName = "Dresses";

		public const string PluginVersion = "1.1.0";

		internal static ManualLogSource Log;

		private Harmony? _harmony;

		private ConfigEntry<float> _glow;

		private ConfigEntry<bool> _hideLegArmour;

		private ConfigEntry<bool> _keepVanillaFoldMap;

		private ConfigEntry<bool> _diagnostics;

		private ConfigEntry<bool> _giveItems;

		private void Awake()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			_glow = ((BaseUnityPlugin)this).Config.Bind<float>("General", "GlowStrength", 1f, new ConfigDescription("How strongly the lit parts of a gown's pattern glow. 1 is as designed, 0 turns the glow off. Takes effect on the next launch.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>()));
			_hideLegArmour = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "HideLegArmourUnderGowns", true, "While a gown from this mod is worn, hide the 3D parts of the leg armour (hip plates, knee guards, boot cuffs), which otherwise poke through the skirt at the hips. The trousers and boots painted on the legs stay, and the armour still counts. Applies to every character and armour stand you see. Takes effect at once.");
			_keepVanillaFoldMap = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "KeepVanillaFoldMap", false, "Use the vanilla dress's fold map unchanged. Normally the woven hem band pressed into it is smoothed away, so it does not show under a gown's own hem. Only for comparing the two while testing. Takes effect on the next launch.");
			_diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Diagnostics", false, "Write test lines to the log: whether the items and recipes exist, and, each time the chest item changes, what the game put on the character and whether the skirt's cloth is running. Also saves each rendered icon as a PNG in BepInEx\\Dresses. Takes effect on the next launch.");
			_giveItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "GiveItemsOnSpawn", false, "On entering a world, put one of each gown this mod adds into the inventory if the character has none. For testing how a gown looks without crafting it. Takes effect on the next launch.");
			GownDiagnostics gownDiagnostics = ((Component)this).gameObject.AddComponent<GownDiagnostics>();
			gownDiagnostics.LogState = _diagnostics.Value;
			gownDiagnostics.GiveItems = _giveItems.Value;
			ConfigEntry<bool> bootShape = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BootShape", true, "Give boots from this mod their shape: a shell round the foot and lower leg, built from the character's own body. Off leaves them painted on the leg, with no thickness. Takes effect the next time boots are put on.");
			BootFactory.Shaped = bootShape.Value;
			bootShape.SettingChanged += delegate
			{
				BootFactory.Shaped = bootShape.Value;
			};
			LegArmourUnderGown.Enabled = _hideLegArmour.Value;
			_hideLegArmour.SettingChanged += delegate
			{
				LegArmourUnderGown.Enabled = _hideLegArmour.Value;
			};
			_harmony = new Harmony("com.skaket.valheim.dresses");
			if (LegArmourUnderGown.Install(_harmony))
			{
				Log.LogInfo((object)("Leg armour is " + (_hideLegArmour.Value ? "hidden" : "shown (HideLegArmourUnderGowns is off)") + " under gowns."));
			}
			AddTranslations();
			PrefabManager.OnVanillaPrefabsAvailable += AddItems;
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private static void AddTranslations()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			GownDef[] all = GownDefs.All;
			foreach (GownDef gownDef in all)
			{
				dictionary[gownDef.NameToken] = gownDef.Name;
				dictionary[gownDef.DescriptionToken] = gownDef.Description;
			}
			BootDef[] all2 = BootDefs.All;
			foreach (BootDef bootDef in all2)
			{
				dictionary[bootDef.NameToken] = bootDef.Name;
				dictionary[bootDef.DescriptionToken] = bootDef.Description;
			}
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text = "English";
			localization.AddTranslation(ref text, dictionary);
		}

		private void AddItems()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= AddItems;
			GownDef[] all = GownDefs.All;
			foreach (GownDef gownDef in all)
			{
				try
				{
					GownFactory.Add(gownDef, _glow.Value, _keepVanillaFoldMap.Value, _diagnostics.Value);
				}
				catch (Exception arg)
				{
					Log.LogError((object)$"{gownDef.Id} was not added: {arg}");
				}
			}
			BootDef[] all2 = BootDefs.All;
			foreach (BootDef bootDef in all2)
			{
				try
				{
					BootFactory.Add(bootDef);
				}
				catch (Exception arg2)
				{
					Log.LogError((object)$"{bootDef.Id} was not added: {arg2}");
				}
			}
		}
	}
	internal sealed class GownDef
	{
		private string? _textureId;

		public string Id { get; set; } = "";

		public string BasePrefab { get; set; } = "ArmorDress3";

		public string Name { get; set; } = "";

		public string Description { get; set; } = "";

		public float GlowStrength { get; set; }

		public bool Short { get; set; }

		public bool Wide { get; set; }

		public string CraftingStation { get; set; } = CraftingStations.Workbench;

		public List<(string Item, int Amount, int AmountPerLevel)> Recipe { get; set; } = new List<(string, int, int)>();

		public string TextureId
		{
			get
			{
				return _textureId ?? Id;
			}
			set
			{
				_textureId = value;
			}
		}

		public string NameToken => "item_" + Id.ToLowerInvariant();

		public string DescriptionToken => NameToken + "_description";

		public GownDef Plain()
		{
			return new GownDef
			{
				Id = Id + "Plain",
				BasePrefab = "ArmorDress1",
				Name = "Plain " + Name,
				Description = Description + " Worn plain, without the chain and bracelets.",
				GlowStrength = GlowStrength,
				Wide = Wide,
				CraftingStation = CraftingStation,
				Recipe = Recipe.ToList(),
				TextureId = TextureId
			};
		}
	}
	internal static class GownDefs
	{
		private static GownDef[]? _all;

		private static readonly GownDef[] Designs = new GownDef[30]
		{
			new GownDef
			{
				Id = "SkaDressCrimsonChevron",
				BasePrefab = "ArmorDress3",
				Name = "Crimson Chevron Gown",
				Description = "A deep red gown with layered chevrons and woven trim at the hem.",
				GlowStrength = 1.2f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressStargazerWeave",
				Name = "Stargazer Weave Gown",
				Description = "An indigo gown with geometric diamonds strung on vertical lines.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Blueberries", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressForestKnot",
				Name = "Forest Knot Gown",
				Description = "A dark green gown with an interlaced gold band down the front.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Resin", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressAuroraFall",
				Name = "Aurora Fall Gown",
				Description = "A night-dark gown with streaks of violet light rising from the hem.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Thistle", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressNorthernStar",
				Name = "Northern Star Gown",
				Description = "A cream and maroon gown with a large star and woven framing.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Dandelion", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressFrostpeakBand",
				Name = "Frostpeak Band Gown",
				Description = "A grey-blue gown with a ridge of snowy peaks and snowflakes at the hem.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Thistle", 3, 0),
					("Dandelion", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressTwilightTapestry",
				Name = "Twilight Tapestry Gown",
				Description = "A plum gown woven with branching trees over a banded hem.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Blueberries", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressSunfall",
				Name = "Sunfall Gown",
				Description = "A sleeveless gown with radiant lines and a rising sun at the hem.",
				GlowStrength = 0.9f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Dandelion", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressEmberChevron",
				Name = "Ember Chevron Gown",
				Description = "A dark crimson gown with zigzag bands of fire above the hem.",
				GlowStrength = 1f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Resin", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressArcaneChevron",
				Name = "Arcane Chevron Gown",
				Description = "A purple sleeveless gown with layered geometrics and a rising chevron.",
				GlowStrength = 1f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Blueberries", 3, 0),
					("Raspberry", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressAstralGrid",
				Name = "Astral Grid Gown",
				Description = "A purple gown ruled with gold lines and strung with diamonds.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Blueberries", 3, 0),
					("Dandelion", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressAstralVeil",
				Name = "Astral Veil Gown",
				Description = "A night-blue sleeveless gown with starlit motifs and celestial bands.",
				GlowStrength = 0.9f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Blueberries", 3, 0),
					("Thistle", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressGroveWeave",
				Name = "Grove Weave Gown",
				Description = "A green sleeveless gown with a gold tree, branches and leaf-like forms.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Dandelion", 3, 0),
					("Resin", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressMosaicTier",
				Name = "Mosaic Tier Gown",
				Description = "A sleeveless gown in layered bands with tilework patterns.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Thistle", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressEmberflame",
				Name = "Emberflame Gown",
				Description = "A black sleeveless gown with red fire rising from the hem.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Raspberry", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressVerdantflame",
				Name = "Verdantflame Gown",
				Description = "A black sleeveless gown with green fire rising from the hem.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Guck", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressFrostflame",
				Name = "Frostflame Gown",
				Description = "A black sleeveless gown with blue fire rising from the hem.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Blueberries", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressDuskflame",
				Name = "Duskflame Gown",
				Description = "A black sleeveless gown with purple fire rising from the hem.",
				GlowStrength = 0.8f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Thistle", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressEmberSwirl",
				Wide = true,
				Name = "Ember Swirl Gown",
				Description = "A red gown with one great swirl of fire sweeping across the front.",
				GlowStrength = 1f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Resin", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressAutumnVine",
				Wide = true,
				Name = "Autumn Vine Gown",
				Description = "A cream and red gown with a leafy vine climbing across the front, over a woven border.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Dandelion", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressVerdantSpiral",
				Wide = true,
				Name = "Verdant Spiral Gown",
				Description = "A green gown with a pale spiralling vine and small flowers.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Dandelion", 3, 0),
					("Resin", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressEmberScroll",
				Wide = true,
				Name = "Ember Scroll Gown",
				Description = "A dark red sleeveless gown with flowing scrollwork and a band of waves at the hem.",
				GlowStrength = 0.9f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Raspberry", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressRiverCurrent",
				Wide = true,
				Name = "River Current Gown",
				Description = "A teal sleeveless gown with curling waves winding round the skirt.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Blueberries", 3, 0),
					("Guck", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressThornBloom",
				Wide = true,
				Name = "Thorn Bloom Gown",
				Description = "A plum sleeveless gown with a gold thorned vine and red blooms.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 3, 0),
					("Thistle", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressCherryBlossom",
				Wide = true,
				Name = "Cherry Blossom Gown",
				Description = "A white gown with a gold branch in red blossom climbing across the front.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Raspberry", 5, 0),
					("Dandelion", 2, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressMidnightBlossom",
				Wide = true,
				Name = "Midnight Blossom Gown",
				Description = "A black gown with a gold branch in pink blossom climbing across the front.",
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Raspberry", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressGalaxyPink",
				Wide = true,
				Name = "Galaxy Pink Gown",
				Description = "A black gown with pink and violet nebula clouds and glowing stars drifting round the skirt.",
				GlowStrength = 0.7f,
				Recipe = 
				{
					("DeerHide", 6, 6),
					("Coal", 3, 0),
					("Raspberry", 3, 0),
					("Blueberries", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressDiamondLattice",
				BasePrefab = "ArmorTunic1",
				Short = true,
				Name = "Diamond Lattice Dress",
				Description = "A short sleeveless dress with a diamond lattice and a stepped band at the hem.",
				GlowStrength = 0.9f,
				Recipe = 
				{
					("DeerHide", 4, 4),
					("Raspberry", 3, 0),
					("Blueberries", 3, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressRitualMini",
				BasePrefab = "ArmorTunic1",
				Short = true,
				Name = "Ritual Mini Dress",
				Description = "A compact, festive short dress with bold zigzag bands.",
				GlowStrength = 1f,
				Recipe = 
				{
					("DeerHide", 4, 4),
					("Raspberry", 5, 0)
				}
			},
			new GownDef
			{
				Id = "SkaDressSolarStep",
				BasePrefab = "ArmorTunic1",
				Short = true,
				Name = "Solar Step Dress",
				Description = "A short red dress with a stepped band of fire at the hem and a sun on each hip.",
				GlowStrength = 0.9f,
				Recipe = 
				{
					("DeerHide", 4, 4),
					("Raspberry", 3, 0),
					("Dandelion", 3, 0)
				}
			}
		};

		public static GownDef[] All => _all ?? (_all = Designs.SelectMany((GownDef design) => (design.BasePrefab == "ArmorDress3") ? new GownDef[2]
		{
			design,
			design.Plain()
		} : new GownDef[1] { design }).ToArray());
	}
	internal sealed class GownDiagnostics : MonoBehaviour
	{
		private const float SettleSeconds = 3f;

		private const float CheckSeconds = 0.5f;

		private const float WornReportDelay = 2f;

		private static readonly FieldInfo? ChestInstancesField = PrivateField("m_chestItemInstances");

		private static readonly FieldInfo? ChestHashField = PrivateField("m_currentChestItemHash");

		private static readonly FieldInfo? LegInstancesField = PrivateField("m_legItemInstances");

		private static readonly FieldInfo? LegHashField = PrivateField("m_currentLegItemHash");

		private Player? _player;

		private float _readyAt;

		private float _nextCheck;

		private bool _introDone;

		private string _inventoryState = "";

		private int _wornHash = int.MinValue;

		private int _legHash = int.MinValue;

		private float _wornReportAt = float.MaxValue;

		public bool LogState { get; set; }

		public bool GiveItems { get; set; }

		private static FieldInfo? PrivateField(string name)
		{
			return typeof(VisEquipment).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
		}

		public static bool IsCloth(MonoBehaviour component)
		{
			if (Object.op_Implicit((Object)(object)component))
			{
				return ((object)component).GetType().Name == "MagicaCloth";
			}
			return false;
		}

		private void Update()
		{
			if (!LogState && !GiveItems)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < _nextCheck)
			{
				return;
			}
			_nextCheck = unscaledTime + 0.5f;
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				_player = null;
				return;
			}
			if ((Object)(object)localPlayer != (Object)(object)_player)
			{
				_player = localPlayer;
				_readyAt = unscaledTime + 3f;
				_introDone = false;
				_inventoryState = "";
				_wornHash = int.MinValue;
				_legHash = int.MinValue;
				_wornReportAt = float.MaxValue;
			}
			if (unscaledTime < _readyAt || !Object.op_Implicit((Object)(object)ObjectDB.instance))
			{
				return;
			}
			try
			{
				if (!_introDone)
				{
					_introDone = true;
					if (LogState)
					{
						ReportRegistration(localPlayer);
					}
					if (GiveItems)
					{
						Give(localPlayer);
					}
				}
				if (LogState)
				{
					ReportInventory(localPlayer);
					ReportWorn(localPlayer, unscaledTime);
				}
			}
			catch (Exception arg)
			{
				DressesPlugin.Log.LogWarning((object)$"Diagnostics stopped after an error: {arg}");
				LogState = false;
				GiveItems = false;
			}
		}

		private static void ReportRegistration(Player player)
		{
			Catalogue.Entry[] all = Catalogue.All;
			foreach (Catalogue.Entry def in all)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(def.Id);
				Recipe val = ((IEnumerable<Recipe>)ObjectDB.instance.m_recipes).FirstOrDefault((Func<Recipe, bool>)((Recipe r) => Object.op_Implicit((Object)(object)r) && Object.op_Implicit((Object)(object)r.m_item) && ((Object)r.m_item).name == def.Id));
				string text = "no recipe";
				if ((Object)(object)val != (Object)null)
				{
					string text2 = string.Join(", ", val.m_resources.Select((Requirement r) => string.Format("{0} {1}", r.m_amount, Object.op_Implicit((Object)(object)r.m_resItem) ? ((Object)r.m_resItem).name : "?")));
					string text3 = (Object.op_Implicit((Object)(object)val.m_craftingStation) ? ((Object)val.m_craftingStation).name : "no station (crafted by hand)");
					text = "recipe at " + text3 + " for " + text2;
				}
				bool flag = Object.op_Implicit((Object)(object)itemPrefab) && player.IsRecipeKnown(itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name);
				Say(def.Id + ": " + (Object.op_Implicit((Object)(object)itemPrefab) ? "in the item database" : "NOT in the item database") + ", " + text + ", " + (flag ? "known" : "not known") + " to this character. " + $"Free inventory slots: {((Humanoid)player).GetInventory().GetEmptySlots()}");
			}
		}

		private static void Give(Player player)
		{
			string text = GivenFile(player);
			HashSet<string> hashSet = new HashSet<string>(File.Exists(text) ? ((IEnumerable<string>)File.ReadAllLines(text)) : ((IEnumerable<string>)new string[0]), StringComparer.OrdinalIgnoreCase);
			int count = hashSet.Count;
			Inventory inventory = ((Humanoid)player).GetInventory();
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			Catalogue.Entry[] all = Catalogue.All;
			foreach (Catalogue.Entry entry in all)
			{
				if (Owned(inventory, entry.Id).Any())
				{
					hashSet.Add(entry.Id);
				}
				else
				{
					if (hashSet.Contains(entry.Id))
					{
						continue;
					}
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(entry.Id);
					if (Object.op_Implicit((Object)(object)itemPrefab))
					{
						if (!inventory.CanAddItem(itemPrefab, 1))
						{
							Say("GiveItemsOnSpawn: no room in the inventory for " + entry.Id);
							list2.Add(entry.Name);
							continue;
						}
						inventory.AddItem(itemPrefab, 1);
						hashSet.Add(entry.Id);
						Say("GiveItemsOnSpawn: added " + entry.Id + " to the inventory");
						list.Add(entry.Name);
					}
				}
			}
			if (hashSet.Count != count)
			{
				Directory.CreateDirectory(Path.GetDirectoryName(text));
				File.WriteAllLines(text, hashSet.OrderBy<string, string>((string id) => id, StringComparer.OrdinalIgnoreCase));
			}
			List<string> list3 = new List<string>();
			if (list.Count > 0)
			{
				list3.Add("Test items added to your inventory: " + string.Join(", ", list));
			}
			if (list2.Count > 0)
			{
				list3.Add($"No room yet for {list2.Count} more: drop gowns you have seen, then enter the world again");
			}
			if (list3.Count > 0)
			{
				((Character)player).Message((MessageType)2, string.Join("\n", list3), 0, (Sprite)null, false);
			}
			if (list2.Count > 0)
			{
				Say($"GiveItemsOnSpawn: {list2.Count} gown(s) still to give when there is room. Given so far: {hashSet.Count} of {Catalogue.All.Length}, remembered in {text}");
			}
		}

		private static string GivenFile(Player player)
		{
			string text = new string((from ch in player.GetPlayerName()
				select (!char.IsLetterOrDigit(ch)) ? '_' : ch).ToArray());
			return Path.Combine(Paths.BepInExRootPath, "Dresses", "given_" + text + ".txt");
		}

		private void ReportInventory(Player player)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			List<string> list = new List<string>();
			Catalogue.Entry[] all = Catalogue.All;
			foreach (Catalogue.Entry entry in all)
			{
				foreach (ItemData item in Owned(inventory, entry.Id))
				{
					list.Add(string.Format("{0} in slot ({1}, {2}){3}", entry.Id, item.m_gridPos.x, item.m_gridPos.y, item.m_equipped ? ", equipped" : ""));
				}
			}
			string text = ((list.Count == 0) ? "none of this mod's items" : string.Join("; ", list));
			if (!(text == _inventoryState))
			{
				_inventoryState = text;
				Say("Inventory: " + text);
			}
		}

		private void ReportWorn(Player player, float now)
		{
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			VisEquipment component = ((Component)player).GetComponent<VisEquipment>();
			if (!Object.op_Implicit((Object)(object)component) || ChestHashField == null || ChestInstancesField == null)
			{
				return;
			}
			int num = (int)ChestHashField.GetValue(component);
			int num2 = ((LegHashField != null) ? ((int)LegHashField.GetValue(component)) : 0);
			if (num != _wornHash || num2 != _legHash)
			{
				_wornHash = num;
				_legHash = num2;
				_wornReportAt = now + 2f;
			}
			else
			{
				if (now < _wornReportAt)
				{
					return;
				}
				_wornReportAt = float.MaxValue;
				Say(DescribeLegs(component, num2));
				if (num == 0)
				{
					Say("Chest slot: empty");
					return;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(num);
				string text = (Object.op_Implicit((Object)(object)itemPrefab) ? ((Object)itemPrefab).name : ("unknown item " + num));
				List<string> list = new List<string>();
				object obj = ChestInstancesField.GetValue(component) as List<GameObject>;
				int num3 = 0;
				int num4 = 0;
				if (obj == null)
				{
					obj = new List<GameObject>();
				}
				foreach (GameObject item in (List<GameObject>)obj)
				{
					if (!Object.op_Implicit((Object)(object)item))
					{
						continue;
					}
					SkinnedMeshRenderer[] componentsInChildren = item.GetComponentsInChildren<SkinnedMeshRenderer>();
					foreach (SkinnedMeshRenderer val in componentsInChildren)
					{
						Material sharedMaterial = ((Renderer)val).sharedMaterial;
						string text2 = (Object.op_Implicit((Object)(object)val.sharedMesh) ? $"{((Object)val.sharedMesh).name} ({val.sharedMesh.vertexCount} vertices)" : "no mesh");
						string text3 = "no material";
						if (Object.op_Implicit((Object)(object)sharedMaterial))
						{
							text3 = "material " + ((Object)sharedMaterial).name + ", texture " + TextureName(sharedMaterial, "_MainTex") + ", fold map " + TextureName(sharedMaterial, "_BumpMap") + ", glow map " + TextureName(sharedMaterial, "_EmissionMap") + (sharedMaterial.HasProperty("_EmissionColor") ? string.Format(", glow colour {0}", sharedMaterial.GetColor("_EmissionColor")) : "");
						}
						list.Add("mesh " + text2 + ", " + (((Renderer)val).isVisible ? "drawn" : "NOT drawn") + ", " + text3);
					}
					foreach (MonoBehaviour item2 in item.GetComponentsInChildren<MonoBehaviour>().Where(IsCloth))
					{
						num3++;
						if (((Behaviour)item2).isActiveAndEnabled && ClothIsValid(item2))
						{
							num4++;
						}
					}
				}
				Material val2 = (Object.op_Implicit((Object)(object)component.m_bodyModel) ? ((Renderer)component.m_bodyModel).sharedMaterial : null);
				string arg = (Object.op_Implicit((Object)(object)val2) ? TextureName(val2, "_ChestTex") : "no body material");
				Say("Chest slot: " + text + ". " + ((list.Count == 0) ? "No skinned mesh attached" : string.Join("; ", list)) + ". " + $"Painted on the body: {arg}. Cloth: {num3} component(s), {num4} running");
			}
		}

		private static string DescribeLegs(VisEquipment visual, int legHash)
		{
			if (legHash == 0)
			{
				return "Leg slot: empty";
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(legHash);
			string text = (Object.op_Implicit((Object)(object)itemPrefab) ? ((Object)itemPrefab).name : ("unknown item " + legHash));
			int num = 0;
			int num2 = 0;
			if (LegInstancesField?.GetValue(visual) is List<GameObject> list)
			{
				foreach (GameObject item in list)
				{
					if (!Object.op_Implicit((Object)(object)item))
					{
						continue;
					}
					Renderer[] componentsInChildren = item.GetComponentsInChildren<Renderer>(true);
					foreach (Renderer obj in componentsInChildren)
					{
						num++;
						if (!obj.enabled)
						{
							num2++;
						}
					}
				}
			}
			if (num == 0)
			{
				return "Leg slot: " + text + ". It has no 3D parts, only trousers painted on the legs";
			}
			return $"Leg slot: {text}. {num} 3D part(s), {num2} hidden" + ((num2 == num) ? " under the gown" : ((num2 == 0) ? "" : " (some still showing)"));
		}

		private static string TextureName(Material material, string property)
		{
			if (!material.HasProperty(property))
			{
				return "(no such slot)";
			}
			Texture texture = material.GetTexture(property);
			if (!Object.op_Implicit((Object)(object)texture))
			{
				return "none";
			}
			return $"{((Object)texture).name} {texture.width}x{texture.height}";
		}

		private static bool ClothIsValid(MonoBehaviour cloth)
		{
			try
			{
				MethodInfo method = ((object)cloth).GetType().GetMethod("IsValid", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
				bool flag = default(bool);
				int num;
				if (method != null)
				{
					object obj = method.Invoke(cloth, null);
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch
			{
				return false;
			}
		}

		private static IEnumerable<ItemData> Owned(Inventory inventory, string id)
		{
			return from item in inventory.GetAllItems()
				where Object.op_Implicit((Object)(object)item.m_dropPrefab) && ((Object)item.m_dropPrefab).name == id
				select item;
		}

		private static void Say(string message)
		{
			DressesPlugin.Log.LogInfo((object)("[test] " + message));
		}
	}
	internal static class GownFactory
	{
		private static readonly int MainTex = Shader.PropertyToID("_MainTex");

		private static readonly int BumpMap = Shader.PropertyToID("_BumpMap");

		private static readonly int EmissionMap = Shader.PropertyToID("_EmissionMap");

		private static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor");

		private static readonly int ChestTex = Shader.PropertyToID("_ChestTex");

		private static readonly Quaternion IconRotation = Quaternion.Euler(50f, 0f, 0f) * Quaternion.Euler(0f, 25f, 0f);

		private static readonly Dictionary<Mesh, Mesh> WideMeshes = new Dictionary<Mesh, Mesh>();

		public static void Add(GownDef def, float glowScale, bool keepVanillaFoldMap, bool saveIcon)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bf: Expected O, but got Unknown
			ItemConfig val = new ItemConfig
			{
				Name = "$" + def.NameToken,
				Description = "$" + def.DescriptionToken,
				CraftingStation = def.CraftingStation
			};
			foreach (var (text, num, num2) in def.Recipe)
			{
				val.AddRequirement(text, num, num2);
			}
			CustomItem val2 = new CustomItem(def.Id, def.BasePrefab, val);
			if (!Object.op_Implicit((Object)(object)val2.ItemPrefab))
			{
				throw new InvalidOperationException("Could not clone " + def.BasePrefab + ".");
			}
			GameObject itemPrefab = val2.ItemPrefab;
			Transform val3 = itemPrefab.transform.Find("attach_skin");
			if (!Object.op_Implicit((Object)(object)val3))
			{
				throw new InvalidOperationException(def.BasePrefab + " has no 'attach_skin' child.");
			}
			SkinnedMeshRenderer componentInChildren = ((Component)val3).GetComponentInChildren<SkinnedMeshRenderer>(true);
			if (!Object.op_Implicit((Object)(object)componentInChildren) || !Object.op_Implicit((Object)(object)((Renderer)componentInChildren).sharedMaterial))
			{
				throw new InvalidOperationException(def.BasePrefab + " has no skirt mesh with a material.");
			}
			Material sharedMaterial = ((Renderer)componentInChildren).sharedMaterial;
			Texture2D val4 = GownTextures.Load(def.TextureId + "_skirt.png");
			Material val5 = new Material(sharedMaterial)
			{
				name = def.Id + "_skirt"
			};
			val5.SetTexture(MainTex, (Texture)(def.Wide ? ((object)GownTextures.FirstCopy(val4)) : ((object)val4)));
			string text2 = "none";
			Texture2D val6 = null;
			float num3 = def.GlowStrength * glowScale;
			if (num3 > 0f && GownTextures.Has(def.TextureId + "_glow.png"))
			{
				if (val5.HasProperty(EmissionMap) && val5.HasProperty(EmissionColor))
				{
					val6 = GownTextures.Load(def.TextureId + "_glow.png");
					val5.SetTexture(EmissionMap, (Texture)(def.Wide ? ((object)GownTextures.FirstCopy(val6)) : ((object)val6)));
					val5.SetColor(EmissionColor, new Color(num3, num3, num3, 1f));
					text2 = "x" + num3.ToString("0.##");
				}
				else
				{
					text2 = "not possible, shader '" + ((Object)val5.shader).name + "' has no emission map";
				}
			}
			string text3 = "vanilla";
			if (!keepVanillaFoldMap && val5.HasProperty(BumpMap))
			{
				Texture2D val7 = GownTextures.FoldMapWithoutHemBand(sharedMaterial.GetTexture(BumpMap));
				if ((Object)(object)val7 != (Object)null)
				{
					val5.SetTexture(BumpMap, (Texture)(object)val7);
					text3 = "vanilla with the hem band smoothed away";
				}
			}
			int num4 = 0;
			Renderer[] componentsInChildren = itemPrefab.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val8 in componentsInChildren)
			{
				Material[] sharedMaterials = val8.sharedMaterials;
				bool flag = false;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					if (!((Object)(object)sharedMaterials[j] != (Object)(object)sharedMaterial))
					{
						sharedMaterials[j] = val5;
						flag = true;
					}
				}
				if (flag)
				{
					val8.sharedMaterials = sharedMaterials;
					num4++;
				}
			}
			string text4 = (def.Wide ? WideLayout(def, val3, componentInChildren, val5, val4, val6) : "vanilla");
			SharedData shared = val2.ItemDrop.m_itemData.m_shared;
			if (!Object.op_Implicit((Object)(object)shared.m_armorMaterial))
			{
				throw new InvalidOperationException(def.BasePrefab + " has no armour material to paint the body with.");
			}
			Texture2D val9 = GownTextures.Load(def.TextureId + "_body.png");
			Material val10 = new Material(shared.m_armorMaterial)
			{
				name = def.Id + "_body"
			};
			val10.SetTexture(ChestTex, (Texture)(object)val9);
			shared.m_armorMaterial = val10;
			int num5 = ((Component)val3).GetComponentsInChildren<MonoBehaviour>(true).Count(GownDiagnostics.IsCloth);
			Sprite val11 = RenderIcon(itemPrefab, def.Id);
			if (Object.op_Implicit((Object)(object)val11))
			{
				shared.m_icons = (Sprite[])(object)new Sprite[1] { val11 };
			}
			else
			{
				DressesPlugin.Log.LogWarning((object)(def.Id + ": the icon could not be rendered; it keeps the " + def.BasePrefab + " icon."));
			}
			if (Object.op_Implicit((Object)(object)val11) && saveIcon)
			{
				SaveIcon(val11, def.Id);
			}
			if (!ItemManager.Instance.AddItem(val2))
			{
				throw new InvalidOperationException("Jotunn refused to add " + def.Id + ".");
			}
			DressesPlugin.Log.LogInfo((object)("Added " + def.Id + ": cloned from " + def.BasePrefab + ", skirt mesh " + (Object.op_Implicit((Object)(object)componentInChildren.sharedMesh) ? ((Object)componentInChildren.sharedMesh).name : "?") + " " + $"on shader {((Object)val5.shader).name}, skirt texture {((Texture)val4).width}x{((Texture)val4).height}, " + $"layout {text4}, body texture {((Texture)val9).width}x{((Texture)val9).height}, glow {text2}, fold map {text3}, " + string.Format("{0} renderer(s) re-skinned, {1} cloth component(s) kept, icon {2}", num4, num5, Object.op_Implicit((Object)(object)val11) ? "rendered" : "vanilla")));
		}

		private static string WideLayout(GownDef def, Transform attach, SkinnedMeshRenderer skirt, Material narrow, Texture2D skirtTexture, Texture2D? glowTexture)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Invalid comparison between Unknown and I4
			try
			{
				Mesh sharedMesh = skirt.sharedMesh;
				if (!Object.op_Implicit((Object)(object)sharedMesh) || !sharedMesh.isReadable)
				{
					return "vanilla, so the pattern is mirrored (the skirt mesh cannot be read)";
				}
				if (!WideMeshes.TryGetValue(sharedMesh, out Mesh value) || !Object.op_Implicit((Object)(object)value))
				{
					value = WideSkirt.Build(sharedMesh, out var moved);
					WideMeshes[sharedMesh] = value;
					DressesPlugin.Log.LogInfo((object)$"Wide skirt mesh {((Object)value).name} made from {((Object)sharedMesh).name}: {moved} of {value.vertexCount} vertices on the second copy of the layout");
				}
				Material val = new Material(narrow)
				{
					name = def.Id + "_skirt_wide"
				};
				val.SetTexture(MainTex, (Texture)(object)skirtTexture);
				if ((Object)(object)glowTexture != (Object)null && val.HasProperty(EmissionMap) && Object.op_Implicit((Object)(object)val.GetTexture(EmissionMap)))
				{
					val.SetTexture(EmissionMap, (Texture)(object)glowTexture);
				}
				int num = 0;
				string[] texturePropertyNames = val.GetTexturePropertyNames();
				for (int i = 0; i < texturePropertyNames.Length; i++)
				{
					int num2 = Shader.PropertyToID(texturePropertyNames[i]);
					if (num2 != MainTex && num2 != EmissionMap)
					{
						Texture texture = val.GetTexture(num2);
						if (Object.op_Implicit((Object)(object)texture) && (int)texture.dimension == 2)
						{
							val.SetTexture(num2, (Texture)(object)GownTextures.Doubled(texture));
							num++;
						}
					}
				}
				int num3 = 0;
				int num4 = 0;
				foreach (MonoBehaviour item in ((Component)attach).GetComponentsInChildren<MonoBehaviour>(true).Where(GownDiagnostics.IsCloth))
				{
					num3++;
					object obj = ((object)item).GetType().GetMethod("GetSerializeData2")?.Invoke(item, null);
					object obj2 = obj?.GetType().GetField("initData")?.GetValue(obj);
					if (!(obj2?.GetType().GetField("clothSetupDataList")?.GetValue(obj2) is IEnumerable enumerable))
					{
						continue;
					}
					foreach (object item2 in enumerable)
					{
						FieldInfo fieldInfo = item2?.GetType().GetField("originalMesh");
						if (!(fieldInfo == null) && !((Object)/*isinst with value type is only supported in some contexts*/ != (Object)(object)sharedMesh))
						{
							fieldInfo.SetValue(item2, value);
							num4++;
						}
					}
				}
				if (num3 > 0 && num4 == 0)
				{
					return "vanilla, so the pattern is mirrored (the cloth's saved mesh was not found; has the cloth library changed?)";
				}
				skirt.sharedMesh = value;
				Material[] sharedMaterials = ((Renderer)skirt).sharedMaterials;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					if ((Object)(object)sharedMaterials[j] == (Object)(object)narrow)
					{
						sharedMaterials[j] = val;
					}
				}
				((Renderer)skirt).sharedMaterials = sharedMaterials;
				return $"wide ({((Texture)skirtTexture).width}x{((Texture)skirtTexture).height}) on mesh {((Object)value).name}, {num} vanilla map(s) doubled, {num4} cloth mesh note(s) pointed at it";
			}
			catch (Exception ex)
			{
				DressesPlugin.Log.LogWarning((object)(def.Id + ": the wide layout could not be set up, so its pattern is mirrored: " + ex.Message));
				return "vanilla, so the pattern is mirrored";
			}
		}

		private static Sprite? RenderIcon(GameObject prefab, string name)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			MeshRenderer val = prefab.GetComponentsInChildren<MeshRenderer>(true).FirstOrDefault();
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject);
			try
			{
				((Object)val2).name = name;
				val2.SetActive(true);
				RenderRequest val3 = new RenderRequest(val2)
				{
					Rotation = IconRotation,
					DistanceMultiplier = 0.9f
				};
				return RenderManager.Instance.Render(val3);
			}
			catch (Exception ex)
			{
				DressesPlugin.Log.LogWarning((object)("Icon render for " + name + " failed: " + ex.Message));
				return null;
			}
			finally
			{
				Object.DestroyImmediate((Object)(object)val2);
			}
		}

		private static void SaveIcon(Sprite icon, string id)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Texture2D texture = icon.texture;
				Color32[] pixels = texture.GetPixels32();
				int num = 0;
				long num2 = 0L;
				Color32[] array = pixels;
				foreach (Color32 val in array)
				{
					if (val.a != 0)
					{
						num++;
						num2 += (val.r + val.g + val.b) / 3;
					}
				}
				string text = Path.Combine(Paths.BepInExRootPath, "Dresses");
				Directory.CreateDirectory(text);
				string text2 = Path.Combine(text, id + "_icon.png");
				File.WriteAllBytes(text2, ImageConversion.EncodeToPNG(texture));
				DressesPlugin.Log.LogInfo((object)($"[test] {id} icon: {((Texture)texture).width}x{((Texture)texture).height}, {100f * (float)num / (float)pixels.Length:0}% of it drawn, " + $"average brightness {((num == 0) ? 0 : (num2 / num))} of 255, saved to {text2}"));
			}
			catch (Exception ex)
			{
				DressesPlugin.Log.LogWarning((object)("The icon for " + id + " could not be saved: " + ex.Message));
			}
		}
	}
	internal static class GownTextures
	{
		private static readonly Assembly Self = typeof(GownTextures).Assembly;

		private static readonly Dictionary<Texture, Texture2D> FoldMaps = new Dictionary<Texture, Texture2D>();

		private static readonly Dictionary<string, Texture2D> Loaded = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase);

		private static readonly MethodInfo? LoadImage = typeof(ImageConversion).GetMethod("LoadImage", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
		{
			typeof(Texture2D),
			typeof(byte[])
		}, null);

		private static readonly Dictionary<Texture, Texture2D> FirstCopies = new Dictionary<Texture, Texture2D>();

		private static readonly Dictionary<Texture, Texture2D> Doubles = new Dictionary<Texture, Texture2D>();

		private const int LayoutSize = 128;

		private const int BandLeft = 47;

		private const int BandRight = 62;

		private const int BandTop = 58;

		private const int PlainOffset = 15;

		private const int TunicBandLeft = 100;

		private const int TunicBandRight = 113;

		private const int TunicBandTop = 50;

		private const int TunicPlainOffset = 13;

		public static bool Has(string file)
		{
			return ResourceName(file) != null;
		}

		public static Texture2D Load(string file)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			if (Loaded.TryGetValue(file, out Texture2D value) && Object.op_Implicit((Object)(object)value))
			{
				return value;
			}
			string text = ResourceName(file);
			if (text == null)
			{
				throw new FileNotFoundException("The texture " + file + " is not embedded in the plugin.");
			}
			byte[] array;
			using (Stream stream = Self.GetManifestResourceStream(text))
			{
				using MemoryStream memoryStream = new MemoryStream();
				stream.CopyTo(memoryStream);
				array = memoryStream.ToArray();
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
			if (LoadImage == null)
			{
				throw new MissingMethodException("ImageConversion.LoadImage(Texture2D, byte[]) was not found in this version of the game.");
			}
			if (!(bool)LoadImage.Invoke(null, new object[2] { val, array }))
			{
				throw new InvalidDataException("The texture " + file + " could not be read as a PNG.");
			}
			((Object)val).name = Path.GetFileNameWithoutExtension(file);
			((Texture)val).filterMode = (FilterMode)0;
			((Texture)val).wrapMode = (TextureWrapMode)0;
			Loaded[file] = val;
			return val;
		}

		public static Texture2D FirstCopy(Texture2D wide)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (FirstCopies.TryGetValue((Texture)(object)wide, out Texture2D value) && Object.op_Implicit((Object)(object)value))
			{
				return value;
			}
			int num = ((Texture)wide).width / 2;
			Texture2D val = new Texture2D(num, ((Texture)wide).height, (TextureFormat)4, true);
			val.SetPixels(wide.GetPixels(0, 0, num, ((Texture)wide).height));
			val.Apply(true, false);
			((Object)val).name = ((Object)wide).name + "_first";
			((Texture)val).filterMode = ((Texture)wide).filterMode;
			((Texture)val).wrapMode = ((Texture)wide).wrapMode;
			FirstCopies[(Texture)(object)wide] = val;
			return val;
		}

		public static Texture2D Doubled(Texture source)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_008a: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if (Doubles.TryGetValue(source, out Texture2D value) && Object.op_Implicit((Object)(object)value))
			{
				return value;
			}
			bool isDataSRGB = source.isDataSRGB;
			RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)((!isDataSRGB) ? 1 : 2));
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit(source, temporary);
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(source.width * 2, source.height, (TextureFormat)4, true, !isDataSRGB);
				Rect val2 = default(Rect);
				((Rect)(ref val2))..ctor(0f, 0f, (float)source.width, (float)source.height);
				val.ReadPixels(val2, 0, 0, false);
				val.ReadPixels(val2, source.width, 0, false);
				val.Apply(true, false);
				((Object)val).name = ((Object)source).name + "_twice";
				((Texture)val).filterMode = source.filterMode;
				((Texture)val).wrapMode = source.wrapMode;
				Doubles[source] = val;
				return val;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}

		private static string? ResourceName(string file)
		{
			return Self.GetManifestResourceNames().FirstOrDefault((string name) => name.EndsWith("." + file, StringComparison.OrdinalIgnoreCase));
		}

		public static Texture2D? FoldMapWithoutHemBand(Texture? source)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00e7: 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_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			if (FoldMaps.TryGetValue(source, out Texture2D value))
			{
				return value;
			}
			if (source.width != 128 || source.height != 128)
			{
				DressesPlugin.Log.LogWarning((object)$"The skirt fold map {((Object)source).name} is {source.width} x {source.height}, not {128} x {128}; it is used as it is.");
				return null;
			}
			RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)1);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit(source, temporary);
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(source.width, source.height, (TextureFormat)4, true, true);
				val.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0, false);
				Color32[] pixels = val.GetPixels32();
				for (int i = 0; i < 58; i++)
				{
					for (int j = 47; j < 62; j++)
					{
						pixels[i * source.width + j] = pixels[i * source.width + j - 15];
					}
				}
				for (int k = 0; k < 50; k++)
				{
					for (int l = 100; l < 113; l++)
					{
						pixels[k * source.width + l] = pixels[k * source.width + l - 13];
					}
				}
				val.SetPixels32(pixels);
				val.Apply(true, false);
				((Object)val).name = ((Object)source).name + "_nohemband";
				((Texture)val).filterMode = source.filterMode;
				((Texture)val).wrapMode = source.wrapMode;
				FoldMaps[source] = val;
				return val;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
	internal static class LegArmourUnderGown
	{
		private sealed class State
		{
			public List<GameObject>? Legs;

			public bool Hidden;

			public List<GameObject>? BootParts;

			public Mesh? BootBody;
		}

		private static readonly ConditionalWeakTable<VisEquipment, State> States = new ConditionalWeakTable<VisEquipment, State>();

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

		public static bool Enabled { get; set; } = true;

		public static bool Install(Harmony harmony)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			GownDef[] all = GownDefs.All;
			foreach (GownDef gownDef in all)
			{
				if (!gownDef.Short)
				{
					GownHashes.Add(StringExtensionMethods.GetStableHashCode(gownDef.Id));
				}
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(VisEquipment), "UpdateEquipmentVisuals", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				DressesPlugin.Log.LogWarning((object)"VisEquipment.UpdateEquipmentVisuals was not found in this version of the game, so leg armour is not hidden under gowns.");
				return false;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(LegArmourUnderGown), "AfterEquipmentUpdate", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				return true;
			}
			catch (Exception ex)
			{
				DressesPlugin.Log.LogWarning((object)("Leg armour is not hidden under gowns: the game's equipment code could not be hooked (" + ex.Message + ")."));
				return false;
			}
		}

		private static void FitBoots(VisEquipment visual, List<GameObject> legs, int legHash, SkinnedMeshRenderer body)
		{
			if (legs != null && Object.op_Implicit((Object)(object)body) && BootFactory.IsBoots(legHash))
			{
				State orCreateValue = States.GetOrCreateValue(visual);
				if (orCreateValue.BootParts != legs || !((Object)(object)orCreateValue.BootBody == (Object)(object)body.sharedMesh))
				{
					orCreateValue.BootParts = legs;
					orCreateValue.BootBody = body.sharedMesh;
					BootFactory.Fit(legs, body);
				}
			}
		}

		private static void AfterEquipmentUpdate(VisEquipment __instance, int ___m_currentChestItemHash, List<GameObject> ___m_legItemInstances, int ___m_currentLegItemHash, SkinnedMeshRenderer ___m_bodyModel)
		{
			FitBoots(__instance, ___m_legItemInstances, ___m_currentLegItemHash, ___m_bodyModel);
			bool flag = Enabled && ___m_legItemInstances != null && GownHashes.Contains(___m_currentChestItemHash);
			if (!States.TryGetValue(__instance, out State value))
			{
				if (!flag)
				{
					return;
				}
				value = States.GetOrCreateValue(__instance);
			}
			if (value.Hidden == flag && value.Legs == ___m_legItemInstances)
			{
				return;
			}
			value.Hidden = flag;
			value.Legs = ___m_legItemInstances;
			if (___m_legItemInstances == null)
			{
				return;
			}
			foreach (GameObject ___m_legItemInstance in ___m_legItemInstances)
			{
				if (Object.op_Implicit((Object)(object)___m_legItemInstance))
				{
					Renderer[] componentsInChildren = ___m_legItemInstance.GetComponentsInChildren<Renderer>(true);
					for (int i = 0; i < componentsInChildren.Length; i++)
					{
						componentsInChildren[i].enabled = !flag;
					}
				}
			}
		}
	}
	public static class WideSkirt
	{
		public static Mesh Build(Mesh source, out int moved)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] vertices = source.vertices;
			Vector2[] uv = source.uv;
			int[] triangles = source.triangles;
			int num = vertices.Length;
			int[] parent = new int[num];
			for (int i = 0; i < num; i++)
			{
				parent[i] = i;
			}
			for (int j = 0; j + 2 < triangles.Length; j += 3)
			{
				int num2 = Find(triangles[j]);
				int num3 = Find(triangles[j + 1]);
				int num4 = Find(triangles[j + 2]);
				parent[num3] = num2;
				parent[num4] = num2;
			}
			Dictionary<int, float> dictionary = new Dictionary<int, float>();
			for (int k = 0; k < num; k++)
			{
				int key = Find(k);
				dictionary.TryGetValue(key, out var value);
				dictionary[key] = value + vertices[k].x;
			}
			moved = 0;
			Vector2[] array = (Vector2[])(object)new Vector2[num];
			for (int l = 0; l < num; l++)
			{
				bool flag = dictionary[Find(l)] < 0f;
				array[l] = new Vector2(uv[l].x * 0.5f + (flag ? 0.5f : 0f), uv[l].y);
				if (flag)
				{
					moved++;
				}
			}
			Mesh obj = Object.Instantiate<Mesh>(source);
			((Object)obj).name = ((Object)source).name + "Wide";
			obj.uv = array;
			obj.UploadMeshData(false);
			return obj;
			int Find(int v)
			{
				while (parent[v] != v)
				{
					parent[v] = parent[parent[v]];
					v = parent[v];
				}
				return v;
			}
		}
	}
}