Decompiled source of Bjurd v0.2.0

Bjurd.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn;
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("Bjurd")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ea20827758cbe69bd729832e5679cf541bd9e49e")]
[assembly: AssemblyProduct("Bjurd")]
[assembly: AssemblyTitle("Bjurd")]
[assembly: AssemblyVersion("1.0.0.0")]
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;
		}
	}
}
namespace Bjurd
{
	[BepInPlugin("talismon.bjurd", "Bjurd", "0.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private static class ArmoireCompatibility
		{
			private static readonly Type? SlotType = AccessTools.TypeByName("Advize_Armoire.AppearanceSlotType");

			private static readonly FieldInfo? OverridesField = FindField("Advize_Armoire.StaticMembers", "ActiveOverrides");

			private static readonly FieldInfo? ItemNameField = FindField("Advize_Armoire.AppearanceSlot", "ItemName");

			private static readonly FieldInfo? ItemVariantField = FindField("Advize_Armoire.AppearanceSlot", "ItemVariant");

			private static readonly MethodInfo? IsPanelActiveMethod = FindMethod("Advize_Armoire.ArmoireUIController", "IsArmoirePanelActive");

			private static readonly object? ChestSlot = ((SlotType == null) ? null : Enum.ToObject(SlotType, 1));

			internal static bool IsOpen()
			{
				try
				{
					object obj = IsPanelActiveMethod?.Invoke(null, null);
					return obj is bool && (bool)obj;
				}
				catch
				{
					return false;
				}
			}

			internal static bool TryGetVariant(out int variant)
			{
				variant = 0;
				if (OverridesField == null || ItemNameField == null || ItemVariantField == null || ChestSlot == null)
				{
					return false;
				}
				object obj = (OverridesField.GetValue(null) as IDictionary)?[ChestSlot];
				if (obj == null || ItemNameField.GetValue(obj) as string != BjurdItemPrefabName || !(ItemVariantField.GetValue(obj) is int num) || num < 0 || num >= EyeColors.Length)
				{
					return false;
				}
				variant = num;
				return true;
			}

			private static FieldInfo? FindField(string typeName, string fieldName)
			{
				Type type = AccessTools.TypeByName(typeName);
				if (!(type == null))
				{
					return AccessTools.Field(type, fieldName);
				}
				return null;
			}

			private static MethodInfo? FindMethod(string typeName, string methodName)
			{
				Type type = AccessTools.TypeByName(typeName);
				if (!(type == null))
				{
					return AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(ItemStyle), "Setup")]
		private static class ItemStylePatch
		{
			private static void Postfix(ItemStyle __instance, int style)
			{
				Transform val = ((Component)__instance).transform;
				while ((Object)(object)val != (Object)null && ((Object)val).name != "Bjurd001")
				{
					val = val.parent;
				}
				if (!((Object)(object)val == (Object)null))
				{
					ApplyStyleAtlases(((Component)val).gameObject);
					ApplyStyle(((Component)val).gameObject, style);
				}
			}
		}

		[HarmonyPatch(typeof(VisEquipment), "SetChestEquipped")]
		[HarmonyPriority(0)]
		private static class EquipmentPatch
		{
			private static void Postfix(VisEquipment __instance, int hash, bool __result)
			{
				if (hash != BjurdItemHash)
				{
					return;
				}
				List<GameObject> list = ChestItemInstancesField.GetValue(__instance) as List<GameObject>;
				if ((Object)(object)BjurdSkinSource == (Object)null || list == null)
				{
					WarnAboutWings("attachment missing");
					return;
				}
				int chestVariant = GetChestVariant(__instance);
				ApplyEquippedStyle(__instance, chestVariant);
				if (!__result)
				{
					return;
				}
				foreach (GameObject item in list)
				{
					if (!PrepareWingInstance(__instance, BjurdSkinSource, item, out string problem))
					{
						WarnAboutWings(problem);
						break;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "SetupVisEquipment")]
		[HarmonyPriority(0)]
		private static class EquipmentRefreshPatch
		{
			private static void Postfix(VisEquipment __0)
			{
				RefreshEquippedStyle(__0);
			}
		}

		[HarmonyPatch(typeof(Player), "OnDeath")]
		private static class PlayerOnDeathPatch
		{
			private static void Prefix(Player __instance)
			{
				Inventory inventory = ((Humanoid)__instance).GetInventory();
				List<ItemData> list = new List<ItemData>();
				foreach (ItemData item in new List<ItemData>(inventory.GetAllItems()))
				{
					if (item.m_equipped && !((Object)(object)item.m_dropPrefab == (Object)null) && !(((Object)item.m_dropPrefab).name != BjurdItemPrefabName))
					{
						item.m_equipped = false;
						list.Add(item);
						inventory.RemoveOneItem(item);
					}
				}
				if (list.Count > 0)
				{
					DeathHeldItems[__instance.GetPlayerID()] = list;
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class PlayerOnSpawnedPatch
		{
			private static void Postfix(Player __instance)
			{
				long playerID = __instance.GetPlayerID();
				if (!DeathHeldItems.TryGetValue(playerID, out List<ItemData> value))
				{
					return;
				}
				DeathHeldItems.Remove(playerID);
				Inventory inventory = ((Humanoid)__instance).GetInventory();
				foreach (ItemData item in value)
				{
					if (!inventory.AddItem(item) || !((Humanoid)__instance).EquipItem(item, true))
					{
						Logger.LogWarning((object)"Bjurd could not be restored after death.");
					}
				}
			}
		}

		[HarmonyPatch(typeof(VisEquipment), "SetChestEquipped")]
		private static class BodyVisibilityPatch
		{
			private static void Prefix(VisEquipment __instance, out int __state)
			{
				__state = (int)CurrentChestHashField.GetValue(__instance);
			}

			private static void Postfix(VisEquipment __instance, int hash, bool __result, int __state)
			{
				if (!__result || (Object)(object)__instance.m_bodyModel == (Object)null || (Object)(object)TransparentBodyMaterial == (Object)null)
				{
					return;
				}
				Renderer bodyModel = (Renderer)(object)__instance.m_bodyModel;
				if (hash == BjurdItemHash)
				{
					bodyModel.sharedMaterials = (Material[])(object)new Material[2] { TransparentBodyMaterial, TransparentBodyMaterial };
				}
				else if (__state == BjurdItemHash && UsesBjurdTransparency(bodyModel))
				{
					int modelIndex = __instance.GetModelIndex();
					if (modelIndex >= 0 && modelIndex < __instance.m_models.Length)
					{
						Material baseMaterial = __instance.m_models[modelIndex].m_baseMaterial;
						bodyModel.sharedMaterials = (Material[])(object)new Material[2] { baseMaterial, baseMaterial };
					}
				}
			}

			private static bool UsesBjurdTransparency(Renderer renderer)
			{
				Material[] sharedMaterials = renderer.sharedMaterials;
				foreach (Material val in sharedMaterials)
				{
					if ((Object)(object)val != (Object)null && ((Object)val).name.StartsWith("Bjurd Body Transparency", StringComparison.Ordinal))
					{
						return true;
					}
				}
				return false;
			}
		}

		public const string PluginGuid = "talismon.bjurd";

		public const string PluginName = "Bjurd";

		public const string PluginVersion = "0.2.0";

		private const string WingClipName = "Bjurd_WingIdle";

		private const string TransparentBodyMaterialName = "Bjurd Body Transparency";

		private static readonly FieldInfo CurrentChestHashField = AccessTools.Field(typeof(VisEquipment), "m_currentChestItemHash");

		private static readonly FieldInfo ChestItemHashField = AccessTools.Field(typeof(VisEquipment), "m_chestItem");

		private static readonly FieldInfo ChestItemInstancesField = AccessTools.Field(typeof(VisEquipment), "m_chestItemInstances");

		private static readonly FieldInfo HumanoidChestItemField = AccessTools.Field(typeof(Humanoid), "m_chestItem");

		private static readonly int ChestVariantHash = StringExtensionMethods.GetStableHashCode("ChestItemVariant");

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

		private static readonly int StyleProperty = Shader.PropertyToID("_Style");

		private static readonly Color[] EyeColors;

		private static readonly Dictionary<long, List<ItemData>> DeathHeldItems;

		private static Material? TransparentBodyMaterial;

		private static AnimationClip? WingClip;

		private static Transform? BjurdSkinSource;

		private static GameObject? BjurdPrefab;

		private static Texture2D? BaseStyleAtlas;

		private static Texture2D? TailStyleAtlas;

		private static Texture2D? WingsStyleAtlas;

		private static ConfigEntry<bool>? HoldJumpOpen;

		private static int BjurdItemHash;

		private static string BjurdItemPrefabName;

		private static bool WingWarningShown;

		internal static bool HoldJumpOpensWings => HoldJumpOpen?.Value ?? true;

		internal static bool IsArmoireOpen => ArmoireCompatibility.IsOpen();

		private void Awake()
		{
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Expected O, but got Unknown
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Expected O, but got Unknown
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: 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_0277: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Expected O, but got Unknown
			HoldJumpOpen = ((BaseUnityPlugin)this).Config.Bind<bool>("Wings", "Holding jump keeps wings open", true, "Holding the jump button keeps Bjurd's wings open.");
			try
			{
				AssetBundle val = AssetUtils.LoadAssetBundleFromResources("bjurd", Assembly.GetExecutingAssembly());
				GameObject val2 = val.LoadAsset<GameObject>("Assets/Bjurd/Prefabs/Bjurd.prefab");
				if ((Object)(object)val2 == (Object)null)
				{
					throw new InvalidOperationException("prefab missing");
				}
				AnimationClip[] array = val.LoadAllAssets<AnimationClip>();
				foreach (AnimationClip val3 in array)
				{
					if (((Object)val3).name == "Bjurd_WingIdle")
					{
						WingClip = val3;
						break;
					}
				}
				if ((Object)(object)WingClip == (Object)null)
				{
					WarnAboutWings("clip missing");
				}
				RememberStyleAtlases(val2);
				if ((Object)(object)BaseStyleAtlas == (Object)null || (Object)(object)TailStyleAtlas == (Object)null || (Object)(object)WingsStyleAtlas == (Object)null)
				{
					throw new InvalidOperationException("style atlas missing");
				}
				BjurdPrefab = val2;
				BjurdItemPrefabName = ((Object)val2).name;
				BjurdItemHash = StringExtensionMethods.GetStableHashCode(((Object)val2).name);
				BjurdSkinSource = val2.transform.Find("attach_skin");
				TransparentBodyMaterial = new Material(Shader.Find("Standard"))
				{
					name = "Bjurd Body Transparency",
					renderQueue = 2450
				};
				TransparentBodyMaterial.SetColor("_Color", Color.clear);
				TransparentBodyMaterial.SetFloat("_Mode", 1f);
				TransparentBodyMaterial.SetInt("_SrcBlend", 1);
				TransparentBodyMaterial.SetInt("_DstBlend", 0);
				TransparentBodyMaterial.EnableKeyword("_ALPHATEST_ON");
				ItemDrop component = val2.GetComponent<ItemDrop>();
				if ((Object)(object)component == (Object)null)
				{
					throw new InvalidOperationException("ItemDrop missing");
				}
				component.m_itemData.m_quality = 1;
				component.m_itemData.m_shared.m_maxQuality = 4;
				new Harmony("talismon.bjurd").PatchAll(typeof(Plugin).Assembly);
				ItemConfig val4 = new ItemConfig();
				val4.Name = "Bjurd";
				val4.Description = "Forged in Feathers. -For Lari ♥";
				val4.Icons = component.m_itemData.m_shared.m_icons;
				val4.StyleTex = BaseStyleAtlas;
				val4.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
				{
					new RequirementConfig
					{
						Item = "Wood",
						Amount = 0,
						AmountPerLevel = 10
					},
					new RequirementConfig
					{
						Item = "Feathers",
						Amount = 1,
						AmountPerLevel = 5
					}
				};
				ItemConfig val5 = val4;
				ItemManager.OnItemsRegistered += ApplyStyleAtlases;
				ItemManager.Instance.AddItem(new CustomItem(val2, true, val5));
				val.Unload(false);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[ Bjurd is alive! v0.2.0 ]");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Bjurd failed: " + ex.Message));
			}
		}

		private static void RememberStyleAtlases(GameObject prefab)
		{
			Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] sharedMaterials = componentsInChildren[i].sharedMaterials;
				foreach (Material val in sharedMaterials)
				{
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					Texture texture = val.GetTexture("_StyleTex");
					Texture2D val2 = (Texture2D)(object)((texture is Texture2D) ? texture : null);
					if (!((Object)(object)val2 == (Object)null))
					{
						if (((Object)val).name.StartsWith("Bjurd_Base", StringComparison.Ordinal))
						{
							BaseStyleAtlas = val2;
						}
						else if (((Object)val).name.StartsWith("Bjurd_Tail", StringComparison.Ordinal))
						{
							TailStyleAtlas = val2;
						}
						else if (((Object)val).name.StartsWith("Bjurd_Wings", StringComparison.Ordinal))
						{
							WingsStyleAtlas = val2;
						}
					}
				}
			}
		}

		private static void ApplyStyleAtlases()
		{
			if (!((Object)(object)BjurdPrefab == (Object)null))
			{
				ApplyStyleAtlases(BjurdPrefab);
			}
		}

		private static void ApplyStyleAtlases(GameObject root)
		{
			Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] sharedMaterials = componentsInChildren[i].sharedMaterials;
				foreach (Material val in sharedMaterials)
				{
					if (!((Object)(object)val == (Object)null) && val.HasProperty("_StyleTex"))
					{
						if (((Object)val).name.StartsWith("Bjurd_Base", StringComparison.Ordinal))
						{
							val.SetTexture("_StyleTex", (Texture)(object)BaseStyleAtlas);
						}
						else if (((Object)val).name.StartsWith("Bjurd_Tail", StringComparison.Ordinal))
						{
							val.SetTexture("_StyleTex", (Texture)(object)TailStyleAtlas);
						}
						else if (((Object)val).name.StartsWith("Bjurd_Wings", StringComparison.Ordinal))
						{
							val.SetTexture("_StyleTex", (Texture)(object)WingsStyleAtlas);
						}
					}
				}
			}
		}

		private static void WarnAboutWings(string reason)
		{
			if (!WingWarningShown)
			{
				WingWarningShown = true;
				Logger.LogWarning((object)("Bjurd wings unavailable: " + reason + "."));
			}
		}

		private static Transform? FindChildNamed(Transform root, string name)
		{
			if (((Object)root).name == name)
			{
				return root;
			}
			for (int i = 0; i < root.childCount; i++)
			{
				Transform val = FindChildNamed(root.GetChild(i), name);
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}

		private static Dictionary<string, Transform> IndexBones(Transform root)
		{
			Dictionary<string, Transform> dictionary = new Dictionary<string, Transform>(StringComparer.Ordinal);
			Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (!dictionary.ContainsKey(((Object)val).name))
				{
					dictionary.Add(((Object)val).name, val);
				}
			}
			return dictionary;
		}

		private static Dictionary<string, SkinnedMeshRenderer> IndexRenderers(Transform root)
		{
			Dictionary<string, SkinnedMeshRenderer> dictionary = new Dictionary<string, SkinnedMeshRenderer>(StringComparer.Ordinal);
			SkinnedMeshRenderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val in componentsInChildren)
			{
				if (!dictionary.ContainsKey(((Object)val).name))
				{
					dictionary.Add(((Object)val).name, val);
				}
			}
			return dictionary;
		}

		private static bool UsesWingBones(SkinnedMeshRenderer renderer)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)renderer.sharedMesh == (Object)null)
			{
				return false;
			}
			Transform[] bones = renderer.bones;
			BoneWeight[] boneWeights = renderer.sharedMesh.boneWeights;
			for (int i = 0; i < boneWeights.Length; i++)
			{
				BoneWeight val = boneWeights[i];
				if (IsWingWeight(bones, ((BoneWeight)(ref val)).boneIndex0, ((BoneWeight)(ref val)).weight0) || IsWingWeight(bones, ((BoneWeight)(ref val)).boneIndex1, ((BoneWeight)(ref val)).weight1) || IsWingWeight(bones, ((BoneWeight)(ref val)).boneIndex2, ((BoneWeight)(ref val)).weight2) || IsWingWeight(bones, ((BoneWeight)(ref val)).boneIndex3, ((BoneWeight)(ref val)).weight3))
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsWingWeight(Transform[] bones, int boneIndex, float weight)
		{
			if (weight > 0f && boneIndex >= 0 && boneIndex < bones.Length && (Object)(object)bones[boneIndex] != (Object)null)
			{
				return ((Object)bones[boneIndex]).name.StartsWith("Wing", StringComparison.Ordinal);
			}
			return false;
		}

		private static bool PrepareWingInstance(VisEquipment equipment, Transform sourceAttach, GameObject instance, out string problem)
		{
			WingPoseController component = instance.GetComponent<WingPoseController>();
			if ((Object)(object)component != (Object)null && component.IsConfigured)
			{
				problem = string.Empty;
				return true;
			}
			SkinnedMeshRenderer bodyModel = equipment.m_bodyModel;
			Transform val = ((bodyModel != null) ? bodyModel.rootBone : null);
			Transform val2 = FindChildNamed(instance.transform, "Bjurd001");
			Transform val3 = (((Object)(object)val2 == (Object)null) ? null : FindChildNamed(val2, "Visual"));
			Player componentInParent = ((Component)equipment).GetComponentInParent<Player>();
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
			{
				problem = "rig incomplete";
				return false;
			}
			Dictionary<string, Transform> dictionary = IndexBones(val);
			Dictionary<string, Transform> dictionary2 = IndexBones(val3);
			if (!dictionary.TryGetValue("Spine2", out var value) || !dictionary2.TryGetValue("Spine2", out var value2))
			{
				problem = "Spine2 missing";
				return false;
			}
			Dictionary<string, SkinnedMeshRenderer> dictionary3 = IndexRenderers(sourceAttach);
			SkinnedMeshRenderer[] componentsInChildren = instance.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val4 in componentsInChildren)
			{
				if (!dictionary3.TryGetValue(((Object)val4).name, out var value3))
				{
					problem = "renderer " + ((Object)val4).name + " missing";
					return false;
				}
				Transform[] bones = value3.bones;
				Transform[] array = (Transform[])(object)new Transform[bones.Length];
				bool flag = UsesWingBones(value3);
				for (int j = 0; j < bones.Length; j++)
				{
					Transform val5 = bones[j];
					if ((Object)(object)val5 == (Object)null)
					{
						problem = $"bone {j} missing";
						return false;
					}
					if (!(((Object)val5).name.StartsWith("Wing", StringComparison.Ordinal) ? dictionary2 : dictionary).TryGetValue(((Object)val5).name, out var value4))
					{
						problem = "bone " + ((Object)val5).name + " missing";
						return false;
					}
					array[j] = value4;
				}
				val4.bones = array;
				val4.rootBone = (flag ? value2 : val);
			}
			if ((Object)(object)WingClip == (Object)null)
			{
				problem = "clip missing";
				return false;
			}
			(component ?? instance.AddComponent<WingPoseController>()).Configure(componentInParent, WingClip, val2, val3, value2, value);
			problem = string.Empty;
			return true;
		}

		private static int GetChestVariant(VisEquipment equipment)
		{
			Player componentInParent = ((Component)equipment).GetComponentInParent<Player>();
			ZNetView componentInParent2 = ((Component)equipment).GetComponentInParent<ZNetView>();
			ZDO val = ((componentInParent2 != null) ? componentInParent2.GetZDO() : null);
			ArmorStand componentInParent3 = ((Component)equipment).GetComponentInParent<ArmorStand>();
			if ((Object)(object)componentInParent3 != (Object)null)
			{
				foreach (ArmorStandSlot slot in componentInParent3.m_slots)
				{
					if (slot.m_visualHash == BjurdItemHash)
					{
						return slot.m_visualVariant;
					}
				}
			}
			if ((Object)(object)componentInParent == (Object)(object)Player.m_localPlayer && ArmoireCompatibility.TryGetVariant(out var variant))
			{
				if ((Object)(object)componentInParent2 != (Object)null && componentInParent2.IsOwner() && val != null)
				{
					val.Set(ChestVariantHash, variant, false);
				}
				return variant;
			}
			if ((Object)(object)componentInParent != (Object)null && (Object)(object)componentInParent != (Object)(object)Player.m_localPlayer && val != null)
			{
				return val.GetInt(ChestVariantHash, 0);
			}
			Humanoid componentInParent4 = ((Component)equipment).GetComponentInParent<Humanoid>();
			ItemData val2 = (ItemData)(((Object)(object)componentInParent4 == (Object)null) ? null : /*isinst with value type is only supported in some contexts*/);
			if ((Object)(object)val2?.m_dropPrefab != (Object)null && ((Object)val2.m_dropPrefab).name == BjurdItemPrefabName)
			{
				return val2.m_variant;
			}
			if (val == null)
			{
				return 0;
			}
			return val.GetInt(ChestVariantHash, 0);
		}

		private static void ApplyEquippedStyle(VisEquipment equipment, int variant)
		{
			if (!(ChestItemInstancesField.GetValue(equipment) is List<GameObject> list))
			{
				return;
			}
			foreach (GameObject item in list)
			{
				ApplyStyleAtlases(item);
				ApplyStyle(item, variant);
			}
		}

		private static void RefreshEquippedStyle(VisEquipment equipment)
		{
			if ((int)ChestItemHashField.GetValue(equipment) != BjurdItemHash)
			{
				return;
			}
			int chestVariant = GetChestVariant(equipment);
			ZNetView componentInParent = ((Component)equipment).GetComponentInParent<ZNetView>();
			if (componentInParent != null && componentInParent.IsOwner())
			{
				ZDO zDO = componentInParent.GetZDO();
				if (zDO != null)
				{
					zDO.Set(ChestVariantHash, chestVariant, false);
				}
			}
			ApplyEquippedStyle(equipment, chestVariant);
		}

		private static void ApplyStyle(GameObject instance, int variant)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			Color val = ((variant >= 0 && variant < EyeColors.Length) ? EyeColors[variant] : Color.white);
			ItemStyle[] componentsInChildren = instance.GetComponentsInChildren<ItemStyle>(true);
			foreach (ItemStyle val2 in componentsInChildren)
			{
				MaterialMan.instance.SetValue<int>(((Component)val2).gameObject, StyleProperty, variant, false);
				Renderer component = ((Component)val2).GetComponent<Renderer>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				Material[] sharedMaterials = component.sharedMaterials;
				foreach (Material val3 in sharedMaterials)
				{
					if ((Object)(object)val3 != (Object)null && ((Object)val3).name.StartsWith("Bjurd_Base", StringComparison.Ordinal))
					{
						MaterialMan.instance.SetValue<Color>(((Component)val2).gameObject, EmissionColorProperty, val, false);
						break;
					}
				}
			}
		}

		static Plugin()
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: 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_00f6: 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_0111: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: 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_0141: Unknown result type (might be due to invalid IL or missing references)
			Color[] array = new Color[5];
			Color val = new Color(0f, 83f / 85f, 11f / 15f);
			array[0] = ((Color)(ref val)).linear;
			val = new Color(0f, 0.9372549f, 1f);
			array[1] = ((Color)(ref val)).linear;
			val = new Color(1f, 0f, 1f / 85f);
			array[2] = ((Color)(ref val)).linear;
			val = new Color(0.6313726f, 0f, 0.8235294f);
			array[3] = ((Color)(ref val)).linear;
			val = new Color(84f / 85f, 0.5294118f, 0f);
			array[4] = ((Color)(ref val)).linear;
			EyeColors = (Color[])(object)array;
			DeathHeldItems = new Dictionary<long, List<ItemData>>();
			BjurdItemPrefabName = "Bjurd";
		}
	}
	internal sealed class WingPoseController : MonoBehaviour
	{
		private struct BonePose
		{
			internal Vector3 Position;

			internal Quaternion Rotation;

			internal Vector3 Scale;
		}

		private const float IdleFrame = 1f;

		private const float RunFrame = 12f;

		private const float AirFrame = 40f;

		private const float TransitionSpeed = 80f;

		private static readonly int ForwardSpeed = Animator.StringToHash("forward_speed");

		private static readonly int SidewaySpeed = Animator.StringToHash("sideway_speed");

		private static readonly int OnGround = Animator.StringToHash("onGround");

		private static readonly int InWater = Animator.StringToHash("inWater");

		private static readonly int ForcedOpenHash = StringExtensionMethods.GetStableHashCode("BjurdWingHold");

		private static readonly FieldInfo CharacterAnimatorField = AccessTools.Field(typeof(Character), "m_animator");

		private static readonly Func<Player, bool> PlayerTakesInput = AccessTools.MethodDelegate<Func<Player, bool>>(AccessTools.Method(typeof(Player), "TakeInput", (Type[])null, (Type[])null), (object)null, true);

		private Player? player;

		private Animator? playerAnimator;

		private ZNetView? playerView;

		private Transform? wingSpine;

		private Transform? liveSpine;

		private Transform[] wingBones = Array.Empty<Transform>();

		private BonePose[] idlePose = Array.Empty<BonePose>();

		private BonePose[] runPose = Array.Empty<BonePose>();

		private BonePose[] airPose = Array.Empty<BonePose>();

		private float currentFrame = 1f;

		private bool? lastForcedOpen;

		internal bool IsConfigured { get; private set; }

		internal void Configure(Player? owner, AnimationClip wingClip, Transform importedModel, Transform importedRig, Transform importedSpine, Transform liveSpine)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			if (IsConfigured)
			{
				return;
			}
			player = owner;
			playerAnimator = (Animator?)(((Object)(object)owner == (Object)null) ? null : /*isinst with value type is only supported in some contexts*/);
			playerView = ((owner != null) ? ((Component)owner).GetComponent<ZNetView>() : null);
			wingSpine = importedSpine;
			this.liveSpine = liveSpine;
			List<Transform> list = new List<Transform>();
			Transform[] componentsInChildren = ((Component)importedRig).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (((Object)val).name.StartsWith("Wing", StringComparison.Ordinal))
				{
					list.Add(val);
				}
			}
			wingBones = list.ToArray();
			Animator val2 = ((Component)importedModel).GetComponent<Animator>();
			bool flag = (Object)(object)val2 == (Object)null;
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = ((Component)importedModel).gameObject.AddComponent<Animator>();
			}
			AnimatorCullingMode cullingMode = val2.cullingMode;
			val2.cullingMode = (AnimatorCullingMode)0;
			idlePose = CapturePose(wingClip, importedModel, importedRig, wingBones, 1f);
			runPose = CapturePose(wingClip, importedModel, importedRig, wingBones, 12f);
			airPose = CapturePose(wingClip, importedModel, importedRig, wingBones, 40f);
			if (flag)
			{
				((Behaviour)val2).enabled = false;
				Object.Destroy((Object)(object)val2);
			}
			else
			{
				val2.cullingMode = cullingMode;
			}
			currentFrame = 1f;
			ApplyFrame(currentFrame);
			FollowSpine();
			IsConfigured = true;
		}

		private void LateUpdate()
		{
			if ((Object)(object)wingSpine == (Object)null || (Object)(object)liveSpine == (Object)null)
			{
				return;
			}
			if ((Object)(object)player == (Object)null || (Object)(object)playerAnimator == (Object)null)
			{
				FollowSpine();
				return;
			}
			bool flag = playerAnimator.GetBool(InWater);
			bool flag2 = playerAnimator.GetBool(OnGround);
			bool flag3 = ((Character)player).IsSitting();
			float num = playerAnimator.GetFloat(ForwardSpeed);
			float num2 = playerAnimator.GetFloat(SidewaySpeed);
			bool flag4 = Mathf.Sqrt(num * num + num2 * num2) > (((Character)player).m_speed + ((Character)player).m_runSpeed) * 0.5f;
			float num3 = ((IsCharacterPreview() || WingsForcedOpen(flag3)) ? 40f : (flag3 ? 1f : ((!flag && !flag2) ? 40f : ((!flag4) ? 1f : 12f))));
			float num4 = currentFrame;
			currentFrame = Mathf.MoveTowards(currentFrame, num3, 80f * Time.deltaTime);
			if (!Mathf.Approximately(currentFrame, num4))
			{
				ApplyFrame(currentFrame);
			}
			FollowSpine();
		}

		private bool IsCharacterPreview()
		{
			FejdStartup instance = FejdStartup.instance;
			if ((Object)(object)instance != (Object)null)
			{
				return (Object)(object)instance.GetPreviewPlayer() == (Object)(object)player;
			}
			return false;
		}

		private bool WingsForcedOpen(bool sitting)
		{
			Player val = player;
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			ZNetView? obj = playerView;
			ZDO val2 = ((obj != null) ? obj.GetZDO() : null);
			if ((Object)(object)val != (Object)(object)Player.m_localPlayer)
			{
				if (val2 == null)
				{
					return false;
				}
				return val2.GetBool(ForcedOpenHash, false);
			}
			bool flag = Plugin.IsArmoireOpen || (!sitting && Plugin.HoldJumpOpensWings && PlayerTakesInput(val) && ZInput.GetButton("Jump"));
			if (lastForcedOpen != flag)
			{
				if (val2 != null)
				{
					val2.Set(ForcedOpenHash, flag);
				}
				lastForcedOpen = flag;
			}
			return flag;
		}

		private void OnDestroy()
		{
			if (!((Object)(object)player == (Object)(object)Player.m_localPlayer))
			{
				return;
			}
			ZNetView? obj = playerView;
			if (obj != null && obj.IsOwner())
			{
				ZDO zDO = playerView.GetZDO();
				if (zDO != null)
				{
					zDO.Set(ForcedOpenHash, false);
				}
			}
		}

		private static BonePose[] CapturePose(AnimationClip clip, Transform modelRoot, Transform rigRoot, Transform[] bones, float frame)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			Vector3 localPosition = modelRoot.localPosition;
			Quaternion localRotation = modelRoot.localRotation;
			Vector3 localScale = modelRoot.localScale;
			Vector3 localPosition2 = rigRoot.localPosition;
			Quaternion localRotation2 = rigRoot.localRotation;
			Vector3 localScale2 = rigRoot.localScale;
			float num = Mathf.Clamp((frame - 1f) / clip.frameRate, 0f, clip.length);
			clip.SampleAnimation(((Component)modelRoot).gameObject, num);
			modelRoot.localPosition = localPosition;
			modelRoot.localRotation = localRotation;
			modelRoot.localScale = localScale;
			rigRoot.localPosition = localPosition2;
			rigRoot.localRotation = localRotation2;
			rigRoot.localScale = localScale2;
			BonePose[] array = new BonePose[bones.Length];
			for (int i = 0; i < bones.Length; i++)
			{
				Transform val = bones[i];
				array[i] = new BonePose
				{
					Position = val.localPosition,
					Rotation = val.localRotation,
					Scale = val.localScale
				};
			}
			return array;
		}

		private void ApplyFrame(float frame)
		{
			//IL_005c: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			BonePose[] array;
			BonePose[] array2;
			float num;
			if (frame <= 12f)
			{
				array = idlePose;
				array2 = runPose;
				num = Mathf.InverseLerp(1f, 12f, frame);
			}
			else
			{
				array = runPose;
				array2 = airPose;
				num = Mathf.InverseLerp(12f, 40f, frame);
			}
			for (int i = 0; i < wingBones.Length; i++)
			{
				Transform obj = wingBones[i];
				obj.localPosition = Vector3.Lerp(array[i].Position, array2[i].Position, num);
				obj.localRotation = Quaternion.Slerp(array[i].Rotation, array2[i].Rotation, num);
				obj.localScale = Vector3.Lerp(array[i].Scale, array2[i].Scale, num);
			}
		}

		private void FollowSpine()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)wingSpine == (Object)null) && !((Object)(object)liveSpine == (Object)null))
			{
				wingSpine.position = liveSpine.position;
				wingSpine.rotation = liveSpine.rotation;
			}
		}
	}
}