Decompiled source of ITT REPO v1.1.5

BepInEx/plugins/DPC.Pinozen/Pinozen.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("0.5.7.0")]
[assembly: AssemblyInformationalVersion("0.5.7")]
[assembly: AssemblyVersion("0.5.7.0")]
namespace DPC.Pinozen;

internal static class ImportedNames
{
	private static readonly Regex Suffix = new Regex("(?:\\s*\\((?:Clone|Instance|\\d+)\\)|[. _-]\\d+)\\s*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

	internal static string Normalize(string name)
	{
		string text = (name ?? "").Trim();
		for (int i = 0; i < 8; i++)
		{
			string text2 = Suffix.Replace(text, "").TrimEnd();
			if (text2 == text)
			{
				break;
			}
			text = text2;
		}
		return SkinMatcher.Normalize(text);
	}

	internal static bool IsHand(string name, bool left)
	{
		string text = Normalize(name);
		if (!left)
		{
			switch (text)
			{
			default:
				return text == "handright";
			case "meshhandr":
			case "handr":
			case "righthand":
				return true;
			}
		}
		switch (text)
		{
		default:
			return text == "handleft";
		case "meshhandl":
		case "handl":
		case "lefthand":
			return true;
		}
	}

	internal static bool IsBody(string name)
	{
		return Normalize(name) == "meshbody";
	}
}
internal static class OriginalMeshes
{
	private static readonly HashSet<string> Known = Build();

	private static HashSet<string> Build()
	{
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		string[] array = new string[5] { "mesh head", "mesh body", "Face Idle", "Face Attack", "Face Stun" };
		foreach (string value in array)
		{
			hashSet.Add(SkinMatcher.Normalize(value));
		}
		string[] array2 = new string[2] { "L", "R" };
		foreach (string text in array2)
		{
			string[] array3 = new string[2] { "hand", "foot" };
			foreach (string text2 in array3)
			{
				hashSet.Add(SkinMatcher.Normalize("mesh " + text2 + "_" + text));
			}
			string[] array4 = new string[3] { "arm", "leg", "thumb" };
			foreach (string text3 in array4)
			{
				for (int m = 1; m <= 2; m++)
				{
					hashSet.Add(SkinMatcher.Normalize("mesh " + text3 + "_" + text + "_0" + m));
				}
			}
			for (int n = 1; n <= 4; n++)
			{
				hashSet.Add(SkinMatcher.Normalize("mesh toe_" + text + "_0" + n));
				for (int num = 1; num <= 3; num++)
				{
					hashSet.Add(SkinMatcher.Normalize("mesh finger_" + text + "_0" + n + "_0" + num));
				}
			}
		}
		return hashSet;
	}

	internal static bool IsKnown(string name)
	{
		string text = (name ?? "").Trim();
		for (int i = 0; i < 8; i++)
		{
			if (Known.Contains(SkinMatcher.Normalize(text)))
			{
				return true;
			}
			string text2 = Regex.Replace(text, "(?:\\s*\\((?:Clone|Instance|\\d+)\\)|[. _-]\\d+)\\s*$", "", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).TrimEnd();
			if (text2 == text)
			{
				break;
			}
			text = text2;
		}
		return false;
	}
}
internal sealed class AlbedoCandidate
{
	internal string Property;

	internal string TextureName;

	internal bool HasTexture;

	internal bool MainTexture;

	internal AlbedoCandidate(string property, string textureName, bool hasTexture, bool mainTexture = false)
	{
		Property = property;
		TextureName = textureName;
		HasTexture = hasTexture;
		MainTexture = mainTexture;
	}
}
internal static class AlbedoSelector
{
	private static readonly string[] Common = new string[7] { "_MainTex", "_BaseMap", "_BaseColorMap", "_BaseColorTexture", "_Albedo", "_AlbedoMap", "_AlbedoTexture" };

	internal static bool Protected(string name)
	{
		string text = SkinMatcher.Normalize(name);
		string[] array = new string[16]
		{
			"normal", "bump", "metallic", "metalness", "specular", "roughness", "smoothness", "gloss", "mask", "occlusion",
			"emission", "emissive", "height", "displacement", "detail", "lightmap"
		};
		foreach (string value in array)
		{
			if (text.Contains(value))
			{
				return true;
			}
		}
		return false;
	}

	internal static bool Semantic(string name)
	{
		if (Protected(name))
		{
			return false;
		}
		string text = SkinMatcher.Normalize(name);
		if (!text.Contains("basecolor") && !text.Contains("albedo"))
		{
			return text.Contains("diffuse");
		}
		return true;
	}

	internal static bool Safe(AlbedoCandidate item)
	{
		if (item != null && !string.IsNullOrEmpty(item.Property) && !Protected(item.Property))
		{
			return !Protected(item.TextureName);
		}
		return false;
	}

	internal static bool Recognized(AlbedoCandidate item)
	{
		if (!Safe(item))
		{
			return false;
		}
		string[] common = Common;
		foreach (string text in common)
		{
			if (item.Property == text)
			{
				return true;
			}
		}
		if (!Semantic(item.Property))
		{
			if (SkinMatcher.Normalize(item.TextureName).Contains("floater"))
			{
				return Semantic(item.TextureName);
			}
			return false;
		}
		return true;
	}

	internal static string Select(IList<AlbedoCandidate> items, string requested)
	{
		if (!string.IsNullOrWhiteSpace(requested))
		{
			foreach (AlbedoCandidate item in items)
			{
				if (item.Property == requested.Trim() && Safe(item))
				{
					return item.Property;
				}
			}
			return null;
		}
		foreach (AlbedoCandidate item2 in items)
		{
			if (item2.HasTexture && Safe(item2) && SkinMatcher.Normalize(item2.TextureName).Contains("floater") && Semantic(item2.TextureName))
			{
				return item2.Property;
			}
		}
		string[] common = Common;
		foreach (string text in common)
		{
			foreach (AlbedoCandidate item3 in items)
			{
				if (item3.Property == text && item3.HasTexture && Safe(item3))
				{
					return item3.Property;
				}
			}
		}
		foreach (AlbedoCandidate item4 in items)
		{
			if (item4.HasTexture && Recognized(item4))
			{
				return item4.Property;
			}
		}
		foreach (AlbedoCandidate item5 in items)
		{
			if (item5.MainTexture && item5.HasTexture && Safe(item5))
			{
				return item5.Property;
			}
		}
		string[] common2 = Common;
		foreach (string text2 in common2)
		{
			foreach (AlbedoCandidate item6 in items)
			{
				if (item6.Property == text2 && Safe(item6))
				{
					return item6.Property;
				}
			}
		}
		foreach (AlbedoCandidate item7 in items)
		{
			if (Recognized(item7))
			{
				return item7.Property;
			}
		}
		return null;
	}
}
internal struct RuntimeWorkPlan
{
	internal bool Scan;

	internal bool LoadTexture;

	internal bool LoadPsp;

	internal bool ApplySkin;

	internal bool AttachPsp;

	internal static RuntimeWorkPlan Create(bool enabled, bool textureReady, bool pspEnabled, bool pspReady)
	{
		return new RuntimeWorkPlan
		{
			Scan = enabled,
			LoadTexture = (enabled && !textureReady),
			LoadPsp = (enabled && pspEnabled && !pspReady),
			ApplySkin = (enabled && textureReady),
			AttachPsp = (enabled && pspEnabled && pspReady)
		};
	}
}
internal static class ScopedTraversal
{
	internal static bool HasBlockedAncestor<T>(T node, Func<T, T> parent, Func<T, bool> foreignActor, Func<T, bool> accessory) where T : class
	{
		HashSet<T> hashSet = new HashSet<T>();
		for (T val = node; val != null; val = parent(val))
		{
			if (!hashSet.Add(val) || foreignActor(val) || accessory(val))
			{
				return true;
			}
		}
		return false;
	}

	internal static List<T> Collect<T>(IEnumerable<T> roots, Func<T, IEnumerable<T>> children, Func<T, bool> foreignActor, Func<T, bool> accessory, int limit = 4096) where T : class
	{
		List<T> list = new List<T>();
		HashSet<T> hashSet = new HashSet<T>();
		Stack<T> stack = new Stack<T>();
		foreach (T root in roots)
		{
			if (root != null)
			{
				stack.Push(root);
			}
		}
		while (stack.Count != 0)
		{
			T val = stack.Pop();
			if (val == null || !hashSet.Add(val) || foreignActor(val) || accessory(val))
			{
				continue;
			}
			if (list.Count >= limit)
			{
				throw new InvalidOperationException("Verified enemy scope exceeded the node safety limit.");
			}
			list.Add(val);
			foreach (T item in children(val))
			{
				if (item != null)
				{
					stack.Push(item);
				}
			}
		}
		return list;
	}
}
internal sealed class DamageFlashBridge
{
	private static readonly int OverlayColor = Shader.PropertyToID("_ColorOverlay");

	private static readonly int OverlayAmount = Shader.PropertyToID("_ColorOverlayAmount");

	private static readonly int BaseColor = Shader.PropertyToID("_Color");

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

	private readonly Material source;

	private readonly Material target;

	private readonly bool nativeOverlay;

	private readonly bool supported;

	private readonly Color baseColor;

	private readonly Color baseEmission;

	private readonly Action<string> log;

	private bool observedFlash;

	private bool observedReset;

	private float previousAmount = -1f;

	private Color previousColor;

	internal DamageFlashBridge(Material nativeSource, Material ownedTarget, Action<string> logger)
	{
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		source = nativeSource;
		target = ownedTarget;
		log = logger;
		if ((Object)(object)source == (Object)null || (Object)(object)target == (Object)null || (Object)(object)source == (Object)(object)target || !source.HasProperty(OverlayColor) || !source.HasProperty(OverlayAmount))
		{
			return;
		}
		nativeOverlay = target.HasProperty(OverlayColor) && target.HasProperty(OverlayAmount);
		supported = nativeOverlay || (target.HasProperty(BaseColor) && target.HasProperty(EmissionColor));
		if (supported)
		{
			if (!nativeOverlay)
			{
				baseColor = target.GetColor(BaseColor);
				baseEmission = (target.IsKeywordEnabled("_EMISSION") ? target.GetColor(EmissionColor) : Color.black);
				target.EnableKeyword("_EMISSION");
			}
			if (log != null)
			{
				log("Damage flash linked to the original enemy material; per-instance visual bridge active.");
			}
			Update();
		}
	}

	internal void Update()
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: 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_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: 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_01bd: Unknown result type (might be due to invalid IL or missing references)
		if (!supported || (Object)(object)source == (Object)null || (Object)(object)target == (Object)null)
		{
			return;
		}
		float num = DamageFlashMath.ClampAmount(source.GetFloat(OverlayAmount));
		Color val = source.GetColor(OverlayColor);
		if (!DamageFlashMath.Finite(val.r) || !DamageFlashMath.Finite(val.g) || !DamageFlashMath.Finite(val.b))
		{
			num = 0f;
			val = Color.black;
		}
		if (num == previousAmount && val == previousColor)
		{
			return;
		}
		if (nativeOverlay)
		{
			target.SetColor(OverlayColor, val);
			target.SetFloat(OverlayAmount, num);
		}
		else
		{
			Color val2 = baseColor * (1f - num);
			val2.a = baseColor.a;
			Color val3 = baseEmission * (1f - num) + val * num;
			val3.a = baseEmission.a;
			target.SetColor(BaseColor, val2);
			target.SetColor(EmissionColor, val3);
		}
		if (num > 0.01f && !observedFlash)
		{
			observedFlash = true;
			if (log != null)
			{
				log("Damage flash observed on the modeled head; native intensity=" + num + ".");
			}
		}
		if (observedFlash && num <= 0.001f && !observedReset)
		{
			observedReset = true;
			if (log != null)
			{
				log("Damage flash returned to the original head appearance.");
			}
		}
		previousAmount = num;
		previousColor = val;
	}
}
internal static class DamageFlashMath
{
	internal static bool Finite(float value)
	{
		if (!float.IsNaN(value))
		{
			return !float.IsInfinity(value);
		}
		return false;
	}

	internal static float ClampAmount(float value)
	{
		if (Finite(value))
		{
			return Math.Max(0f, Math.Min(1f, value));
		}
		return 0f;
	}
}
internal sealed class DiagnosticReport
{
	private const int Limit = 1048576;

	private readonly string path;

	private readonly string gamePath;

	private readonly string pluginPath;

	private readonly HashSet<string> written = new HashSet<string>();

	private int bytes;

	private bool available;

	internal bool Available => available;

	internal DiagnosticReport(string output, string game, string plugin)
	{
		path = output;
		gamePath = game;
		pluginPath = plugin;
		try
		{
			File.WriteAllText(path, "", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			available = true;
		}
		catch
		{
			available = false;
		}
	}

	internal string Sanitize(string value)
	{
		string text = value ?? "";
		if (!string.IsNullOrEmpty(pluginPath))
		{
			text = text.Replace(pluginPath, "<plugin>");
		}
		if (!string.IsNullOrEmpty(gamePath))
		{
			text = text.Replace(gamePath, "<game>");
		}
		return text.Replace('\r', ' ').Replace('\n', ' ');
	}

	internal void Write(string stage, string message, string onceKey = null)
	{
		if (!available || (onceKey != null && !written.Add(stage + ":" + onceKey)))
		{
			return;
		}
		string text = "[" + stage + "] " + Sanitize(message) + Environment.NewLine;
		byte[] array = Encoding.UTF8.GetBytes(text);
		if (bytes + array.Length > 1048448)
		{
			text = "[LIMIT] Diagnostic report reached 1 MiB; further output suppressed." + Environment.NewLine;
			available = false;
		}
		try
		{
			File.AppendAllText(path, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			bytes += Encoding.UTF8.GetByteCount(text);
		}
		catch
		{
			available = false;
		}
	}
}
internal static class EnemyScopeDiscovery
{
	private static readonly string[] SpringFields = new string[5] { "springHeadSource", "springArmLSource", "springArmRSource", "springLegLSource", "springLegRSource" };

	internal static FieldInfo Field(Type type, string name)
	{
		Type type2 = type;
		while (type2 != null)
		{
			FieldInfo field = type2.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				return field;
			}
			type2 = type2.BaseType;
		}
		return null;
	}

	private static bool HasTypeName(Type type, string name)
	{
		Type type2 = type;
		while (type2 != null)
		{
			if (type2.Name == name)
			{
				return true;
			}
			type2 = type2.BaseType;
		}
		return false;
	}

	private static Component EnemyComponent(Transform transform)
	{
		if ((Object)(object)transform == (Object)null)
		{
			return null;
		}
		Component[] components = ((Component)transform).GetComponents<Component>();
		foreach (Component val in components)
		{
			if ((Object)(object)val != (Object)null && HasTypeName(((object)val).GetType(), "Enemy"))
			{
				return val;
			}
		}
		return null;
	}

	private static Component NearestEnemy(Transform transform)
	{
		Transform val = transform;
		while ((Object)(object)val != (Object)null)
		{
			Component val2 = EnemyComponent(val);
			if ((Object)(object)val2 != (Object)null)
			{
				return val2;
			}
			val = val.parent;
		}
		return null;
	}

	private static Transform Reference(object value, string label, Action<string> diagnostic)
	{
		Component val = (Component)((value is Component) ? value : null);
		if ((Object)(object)val != (Object)null)
		{
			return val.transform;
		}
		GameObject val2 = (GameObject)((value is GameObject) ? value : null);
		if ((Object)(object)val2 != (Object)null)
		{
			return val2.transform;
		}
		if (value != null)
		{
			diagnostic(label + " has unsupported type " + value.GetType().Name + "; skipped.");
		}
		return null;
	}

	private static object Read(object source, string fieldName, Action<string> diagnostic)
	{
		if (source == null)
		{
			return null;
		}
		FieldInfo fieldInfo = Field(source.GetType(), fieldName);
		if (fieldInfo == null)
		{
			diagnostic(source.GetType().Name + "." + fieldName + " field absent.");
			return null;
		}
		try
		{
			return fieldInfo.GetValue(source);
		}
		catch (Exception ex)
		{
			diagnostic(fieldName + " unreadable: " + ex.GetType().Name);
			return null;
		}
	}

	private static bool Foreign(Transform node, Component floater, Component owner)
	{
		Component[] components = ((Component)node).GetComponents<Component>();
		foreach (Component val in components)
		{
			if (!((Object)(object)val == (Object)null))
			{
				if (HasTypeName(((object)val).GetType(), "EnemyFloater") && (Object)(object)val != (Object)(object)floater)
				{
					return true;
				}
				if (HasTypeName(((object)val).GetType(), "Enemy") && (Object)(object)val != (Object)(object)owner)
				{
					return true;
				}
			}
		}
		return false;
	}

	private static IEnumerable<Transform> Children(Transform node)
	{
		for (int i = 0; i < node.childCount; i++)
		{
			yield return node.GetChild(i);
		}
	}

	internal static Renderer[] Collect(Component floater, Action<string> diagnostic)
	{
		if ((Object)(object)floater == (Object)null || !HasTypeName(((object)floater).GetType(), "EnemyFloater"))
		{
			throw new ArgumentException("Only a verified EnemyFloater component can define an accessory/skin scope.");
		}
		List<Transform> roots = new List<Transform>();
		HashSet<int> rootIds = new HashSet<int>();
		Component owner = NearestEnemy(floater.transform);
		Func<Transform, string, bool> func = delegate(Transform node, string reason)
		{
			if ((Object)(object)node == (Object)null)
			{
				return false;
			}
			Component val7 = NearestEnemy(node);
			if ((Object)(object)val7 != (Object)null && (Object)(object)val7 != (Object)(object)owner)
			{
				diagnostic("Rejected foreign actor reference " + reason + ": " + Path(node));
				return false;
			}
			if (ScopedTraversal.HasBlockedAncestor(node, (Transform val8) => val8.parent, (Transform node2) => Foreign(node2, floater, owner), (Transform val8) => (Object)(object)((Component)val8).GetComponent<PinozenPspMarker>() != (Object)null))
			{
				diagnostic("Rejected actor/accessory ancestor boundary " + reason + ": " + Path(node));
				return false;
			}
			if (rootIds.Add(((Object)node).GetInstanceID()))
			{
				roots.Add(node);
				diagnostic("scope " + reason + "=" + Path(node));
			}
			return true;
		};
		func(floater.transform, "EnemyFloater.transform");
		object value = Read(floater, "enemy", diagnostic);
		Transform val = Reference(value, "EnemyFloater.enemy", diagnostic);
		if ((Object)(object)owner == (Object)null && (Object)(object)val != (Object)null)
		{
			Component val2 = EnemyComponent(val);
			if ((Object)(object)val2 != (Object)null)
			{
				bool flag = false;
				Component[] components = ((Component)val).GetComponents<Component>();
				foreach (Component val3 in components)
				{
					if ((Object)(object)val3 != (Object)null && HasTypeName(((object)val3).GetType(), "EnemyFloater") && (Object)(object)val3 != (Object)(object)floater)
					{
						flag = true;
					}
				}
				if (!flag)
				{
					owner = val2;
				}
			}
		}
		func(val, "EnemyFloater.enemy");
		if ((Object)(object)owner != (Object)null)
		{
			func(owner.transform, "nearest Enemy component");
		}
		object obj = Read(floater, "animator", diagnostic);
		if (func(Reference(obj, "EnemyFloater.animator", diagnostic), "animator") && (obj is Component || obj is GameObject))
		{
			Transform val4 = Reference(obj, "animator", diagnostic);
			if ((Object)(object)val4 != (Object)null)
			{
				Component[] components2 = ((Component)val4).GetComponents<Component>();
				foreach (Component val5 in components2)
				{
					if ((Object)(object)val5 == (Object)null)
					{
						continue;
					}
					string[] springFields = SpringFields;
					foreach (string text in springFields)
					{
						if (Field(((object)val5).GetType(), text) != null)
						{
							func(Reference(Read(val5, text, diagnostic), text, diagnostic), "animator." + text);
						}
					}
				}
			}
		}
		List<Transform> list = ScopedTraversal.Collect(roots, Children, (Transform node) => Foreign(node, floater, owner), (Transform node) => (Object)(object)((Component)node).GetComponent<PinozenPspMarker>() != (Object)null);
		List<Renderer> list2 = new List<Renderer>();
		HashSet<int> hashSet = new HashSet<int>();
		foreach (Transform item in list)
		{
			Renderer[] components3 = ((Component)item).GetComponents<Renderer>();
			foreach (Renderer val6 in components3)
			{
				if ((Object)(object)val6 != (Object)null && (val6 is MeshRenderer || val6 is SkinnedMeshRenderer) && hashSet.Add(((Object)val6).GetInstanceID()))
				{
					list2.Add(val6);
				}
			}
		}
		return list2.ToArray();
	}

	internal static string Path(Transform transform)
	{
		List<string> list = new List<string>();
		Transform val = transform;
		while ((Object)(object)val != (Object)null && list.Count < 32)
		{
			list.Add(((Object)val).name);
			val = val.parent;
		}
		list.Reverse();
		return string.Join("/", list.ToArray());
	}
}
internal sealed class HalloweenAccessories
{
	private sealed class HiddenRoot
	{
		internal GameObject Object;

		internal bool WasActive;
	}

	private readonly Dictionary<int, HiddenRoot> roots = new Dictionary<int, HiddenRoot>();

	internal void Hide(Renderer[] verifiedFloaterRenderers, Action<string> diagnostic)
	{
		foreach (Renderer val in verifiedFloaterRenderers)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Transform val2 = ((Component)val).transform;
			while ((Object)(object)val2 != (Object)null)
			{
				if (!(((Object)val2).name != "Halloween Mask") || !(((Object)val2).name != "Halloween Bucket"))
				{
					int instanceID = ((Object)((Component)val2).gameObject).GetInstanceID();
					if (!roots.ContainsKey(instanceID))
					{
						roots.Add(instanceID, new HiddenRoot
						{
							Object = ((Component)val2).gameObject,
							WasActive = ((Component)val2).gameObject.activeSelf
						});
						((Component)val2).gameObject.SetActive(false);
						diagnostic(EnemyScopeDiscovery.Path(val2) + "; activeSelf=" + ((Component)val2).gameObject.activeSelf);
					}
					break;
				}
				val2 = val2.parent;
			}
		}
		Enforce();
	}

	internal void Enforce()
	{
		List<int> list = null;
		foreach (KeyValuePair<int, HiddenRoot> root in roots)
		{
			if ((Object)(object)root.Value.Object == (Object)null)
			{
				if (list == null)
				{
					list = new List<int>();
				}
				list.Add(root.Key);
			}
			else if (root.Value.Object.activeSelf)
			{
				root.Value.Object.SetActive(false);
			}
		}
		if (list == null)
		{
			return;
		}
		foreach (int item in list)
		{
			roots.Remove(item);
		}
	}

	internal void Restore()
	{
		foreach (HiddenRoot value in roots.Values)
		{
			if ((Object)(object)value.Object != (Object)null)
			{
				value.Object.SetActive(value.WasActive);
			}
		}
		roots.Clear();
	}
}
[Serializable]
public sealed class HeadModelData
{
	public int schema;

	public PspBounds referenceBounds;

	public PspMeshData mesh;
}
internal static class HeadValidation
{
	private static void Require(bool ok, string message)
	{
		if (!ok)
		{
			throw new InvalidDataException("Head: " + message);
		}
	}

	private static void Numbers(float[] a, int size)
	{
		Require(a != null && a.Length == size, "invalid array length.");
		foreach (float n in a)
		{
			Require(PspValidation.Finite(n), "non-finite coordinate.");
		}
	}

	internal static void Validate(HeadModelData data)
	{
		Require(data != null && data.schema == 3, "unsupported schema; use the outward-facing head export from 0.5.1 or newer.");
		Require(data.referenceBounds != null, "missing calibration.");
		Numbers(data.referenceBounds.min, 3);
		Numbers(data.referenceBounds.max, 3);
		for (int i = 0; i < 3; i++)
		{
			float num = data.referenceBounds.max[i] - data.referenceBounds.min[i];
			Require(num > 0.0001f && num < 100f, "invalid reference bounds.");
		}
		PspMeshData mesh = data.mesh;
		Require(mesh != null && mesh.vertices != null && mesh.vertices.Length % 3 == 0, "invalid vertices.");
		int num2 = mesh.vertices.Length / 3;
		Require(num2 >= 3 && num2 <= 60000, "vertex budget exceeded.");
		Numbers(mesh.vertices, num2 * 3);
		Numbers(mesh.normals, num2 * 3);
		Numbers(mesh.uv, num2 * 2);
		Require(mesh.triangles != null && mesh.triangles.Length > 0 && mesh.triangles.Length <= 300000 && mesh.triangles.Length % 3 == 0, "invalid indices.");
		int[] triangles = mesh.triangles;
		foreach (int num3 in triangles)
		{
			Require(num3 >= 0 && num3 < num2, "index outside vertices.");
		}
		for (int k = 0; k < num2; k++)
		{
			double num4 = 0.0;
			for (int l = 0; l < 3; l++)
			{
				float num5 = data.referenceBounds.min[l];
				float num6 = data.referenceBounds.max[l];
				Require(mesh.vertices[k * 3 + l] > num5 - (num6 - num5) && mesh.vertices[k * 3 + l] < num6 + (num6 - num5), "vertex outside safe calibrated extent.");
				num4 += (double)mesh.normals[k * 3 + l] * (double)mesh.normals[k * 3 + l];
			}
			Require(num4 > 0.9 && num4 < 1.1, "normal is not unit length.");
			Require(mesh.uv[k * 2] >= 0f && mesh.uv[k * 2] <= 1f && mesh.uv[k * 2 + 1] >= 0f && mesh.uv[k * 2 + 1] <= 1f, "UV outside baked atlas.");
		}
		for (int m = 0; m < mesh.triangles.Length; m += 3)
		{
			int num7 = mesh.triangles[m] * 3;
			int num8 = mesh.triangles[m + 1] * 3;
			int num9 = mesh.triangles[m + 2] * 3;
			double num10 = (double)mesh.vertices[num8] - (double)mesh.vertices[num7];
			double num11 = (double)mesh.vertices[num8 + 1] - (double)mesh.vertices[num7 + 1];
			double num12 = (double)mesh.vertices[num8 + 2] - (double)mesh.vertices[num7 + 2];
			double num13 = (double)mesh.vertices[num9] - (double)mesh.vertices[num7];
			double num14 = (double)mesh.vertices[num9 + 1] - (double)mesh.vertices[num7 + 1];
			double num15 = (double)mesh.vertices[num9 + 2] - (double)mesh.vertices[num7 + 2];
			double num16 = (double)mesh.normals[num7] + (double)mesh.normals[num8] + (double)mesh.normals[num9];
			double num17 = (double)mesh.normals[num7 + 1] + (double)mesh.normals[num8 + 1] + (double)mesh.normals[num9 + 1];
			double num18 = (double)mesh.normals[num7 + 2] + (double)mesh.normals[num8 + 2] + (double)mesh.normals[num9 + 2];
			double num19 = (num11 * num15 - num12 * num14) * num16 + (num12 * num13 - num10 * num15) * num17 + (num10 * num14 - num11 * num13) * num18;
			Require(num19 > 1E-12, "inward-facing or degenerate triangle.");
		}
	}
}
internal sealed class ModeledHead : IDisposable
{
	private sealed class Binding
	{
		internal Renderer Renderer;

		internal MeshFilter Filter;

		internal Mesh OriginalMesh;

		internal Mesh ReplacementMesh;

		internal Material OriginalMaterial;

		internal Material ReplacementMaterial;

		internal DamageFlashBridge DamageFlash;

		internal int LastMaterialId;
	}

	private readonly Dictionary<int, Binding> bindings = new Dictionary<int, Binding>();

	private HeadModelData data;

	private Texture2D texture;

	internal bool Ready
	{
		get
		{
			if (data != null)
			{
				return (Object)(object)texture != (Object)null;
			}
			return false;
		}
	}

	internal void Load(string folder)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Expected O, but got Unknown
		HeadModelData headModelData = PspJson.Read<HeadModelData>(Encoding.UTF8.GetString(Read(folder, "pinozen_head.mesh.json", 25165824)));
		HeadValidation.Validate(headModelData);
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true, false);
		try
		{
			if (!ImageConversion.LoadImage(val, Read(folder, "Pinozen_Head_BaseColor.png", 25165824), true))
			{
				throw new InvalidDataException("Head PNG could not be decoded.");
			}
			if (((Texture)val).width != 2048 || ((Texture)val).height != 2048)
			{
				throw new InvalidDataException("Head atlas must be 2048 x 2048.");
			}
			((Object)val).name = "Pinozen Head BaseColor";
			((Texture)val).wrapMode = (TextureWrapMode)0;
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).anisoLevel = 2;
			texture = val;
			data = headModelData;
			val = null;
		}
		finally
		{
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
		}
	}

	private static byte[] Read(string folder, string name, int max)
	{
		FileInfo fileInfo = new FileInfo(Path.Combine(folder, name));
		if (!fileInfo.Exists || fileInfo.Length == 0 || fileInfo.Length > max)
		{
			throw new InvalidDataException("Missing or oversized " + name);
		}
		return File.ReadAllBytes(fileInfo.FullName);
	}

	private static Vector3 V(float[] a)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(a[0], a[1], a[2]);
	}

	internal Bounds OriginalBounds(Renderer renderer)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		if (bindings.TryGetValue(((Object)renderer).GetInstanceID(), out var value) && (Object)(object)value.OriginalMesh != (Object)null)
		{
			return value.OriginalMesh.bounds;
		}
		Mesh val = PspAssets.HandMesh(renderer);
		if ((Object)(object)val == (Object)null || ((Object)val).name != "Floater Head")
		{
			throw new InvalidDataException("Original head calibration mesh unavailable.");
		}
		return val.bounds;
	}

	internal bool Apply(Renderer renderer, Action<string> log)
	{
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0230: Unknown result type (might be due to invalid IL or missing references)
		//IL_0235: Unknown result type (might be due to invalid IL or missing references)
		//IL_0295: Unknown result type (might be due to invalid IL or missing references)
		//IL_029c: Expected O, but got Unknown
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0318: Unknown result type (might be due to invalid IL or missing references)
		//IL_031d: Unknown result type (might be due to invalid IL or missing references)
		//IL_031f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0326: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0330: Unknown result type (might be due to invalid IL or missing references)
		//IL_0366: Unknown result type (might be due to invalid IL or missing references)
		//IL_036b: 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_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f4: Expected O, but got Unknown
		//IL_0419: Unknown result type (might be due to invalid IL or missing references)
		//IL_042a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0449: Unknown result type (might be due to invalid IL or missing references)
		Prune();
		int instanceID = ((Object)renderer).GetInstanceID();
		if (bindings.TryGetValue(instanceID, out var value))
		{
			if ((Object)(object)value.Filter == (Object)null || (Object)(object)value.Filter.sharedMesh != (Object)(object)value.ReplacementMesh)
			{
				return false;
			}
			Material sharedMaterial = renderer.sharedMaterial;
			int num = ((!((Object)(object)sharedMaterial == (Object)null)) ? ((Object)sharedMaterial).GetInstanceID() : 0);
			if (num != value.LastMaterialId)
			{
				log("MATERIAL_CHANGED; " + Describe(sharedMaterial) + "; propertyBlock=" + renderer.HasPropertyBlock());
				value.LastMaterialId = num;
			}
			if ((Object)(object)sharedMaterial == (Object)(object)value.OriginalMaterial)
			{
				renderer.sharedMaterial = value.ReplacementMaterial;
			}
			return true;
		}
		if (!Ready || ((Object)renderer).name != "mesh head" || !(renderer is MeshRenderer))
		{
			return false;
		}
		MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>();
		if ((Object)(object)component == (Object)null || (Object)(object)component.sharedMesh == (Object)null || ((Object)component.sharedMesh).name != "Floater Head")
		{
			return false;
		}
		Material[] sharedMaterials = renderer.sharedMaterials;
		if (sharedMaterials.Length != 1 || (Object)(object)sharedMaterials[0] == (Object)null)
		{
			throw new InvalidDataException("Unexpected head material layout.");
		}
		Material val = sharedMaterials[0];
		Shader val2 = Shader.Find("Standard");
		if ((Object)(object)val2 == (Object)null || !val2.isSupported)
		{
			val2 = Shader.Find("Unlit/Texture");
		}
		if ((Object)(object)val2 == (Object)null || !val2.isSupported)
		{
			throw new InvalidDataException("No supported textured face shader is available.");
		}
		Bounds bounds = component.sharedMesh.bounds;
		Vector3 val3 = V(data.referenceBounds.min);
		Vector3 val4 = V(data.referenceBounds.max);
		Vector3 val5 = val4 - val3;
		Vector3 size = ((Bounds)(ref bounds)).size;
		float num2 = ((Vector3)(ref size)).magnitude / ((Vector3)(ref val5)).magnitude;
		if (!PspValidation.Finite(num2) || num2 < 1E-05f || num2 > 100000f)
		{
			throw new InvalidDataException("Invalid head scale calibration.");
		}
		for (int i = 0; i < 3; i++)
		{
			Vector3 size2 = ((Bounds)(ref bounds)).size;
			if (Mathf.Abs(((Vector3)(ref size2))[i] / (((Vector3)(ref val5))[i] * num2) - 1f) > 0.05f)
			{
				throw new InvalidDataException("Head axes/bounds differ from the Blender reference; replacement skipped.");
			}
		}
		Mesh val6 = null;
		Material val7 = null;
		try
		{
			PspMeshData mesh = data.mesh;
			int num3 = mesh.vertices.Length / 3;
			val6 = new Mesh();
			((Object)val6).name = "Pinozen Modeled Head";
			Vector3[] array = (Vector3[])(object)new Vector3[num3];
			Vector3[] array2 = (Vector3[])(object)new Vector3[num3];
			Vector2[] array3 = (Vector2[])(object)new Vector2[num3];
			Vector3 val8 = (val3 + val4) * 0.5f;
			for (int j = 0; j < num3; j++)
			{
				ref Vector3 reference = ref array[j];
				reference = ((Bounds)(ref bounds)).center + (new Vector3(mesh.vertices[j * 3], mesh.vertices[j * 3 + 1], mesh.vertices[j * 3 + 2]) - val8) * num2;
				ref Vector3 reference2 = ref array2[j];
				reference2 = new Vector3(mesh.normals[j * 3], mesh.normals[j * 3 + 1], mesh.normals[j * 3 + 2]);
				ref Vector2 reference3 = ref array3[j];
				reference3 = new Vector2(mesh.uv[j * 2], mesh.uv[j * 2 + 1]);
			}
			val6.vertices = array;
			val6.normals = array2;
			val6.uv = array3;
			val6.triangles = mesh.triangles;
			val6.RecalculateBounds();
			val6.RecalculateTangents();
			val6.UploadMeshData(true);
			val7 = new Material(val2);
			((Object)val7).name = "Pinozen modeled face";
			val7.SetTexture("_MainTex", (Texture)(object)texture);
			val7.SetTextureScale("_MainTex", Vector2.one);
			val7.SetTextureOffset("_MainTex", Vector2.zero);
			if (val7.HasProperty("_Color"))
			{
				val7.SetColor("_Color", Color.white);
			}
			if (val7.HasProperty("_Metallic"))
			{
				val7.SetFloat("_Metallic", 0f);
			}
			if (val7.HasProperty("_Glossiness"))
			{
				val7.SetFloat("_Glossiness", 0.15f);
			}
			Binding binding = new Binding();
			binding.Renderer = renderer;
			binding.Filter = component;
			binding.OriginalMesh = component.sharedMesh;
			binding.ReplacementMesh = val6;
			binding.OriginalMaterial = val;
			binding.ReplacementMaterial = val7;
			binding.LastMaterialId = ((Object)val7).GetInstanceID();
			Binding binding2 = binding;
			binding2.DamageFlash = new DamageFlashBridge(val, val7, log);
			bindings.Add(instanceID, binding2);
			try
			{
				component.sharedMesh = val6;
				renderer.sharedMaterial = val7;
			}
			catch
			{
				bindings.Remove(instanceID);
				Restore(binding2);
				val6 = null;
				val7 = null;
				throw;
			}
			val6 = null;
			val7 = null;
			log("path=" + EnemyScopeDiscovery.Path(((Component)renderer).transform) + "; vertices=" + num3 + "; triangles=" + mesh.triangles.Length / 3 + "; scale=" + num2 + "; " + Describe(binding2.ReplacementMaterial) + "; previousShader=" + ((Object)val.shader).name + "; propertyBlock=" + renderer.HasPropertyBlock());
			return true;
		}
		finally
		{
			if ((Object)(object)val6 != (Object)null)
			{
				Object.Destroy((Object)(object)val6);
			}
			if ((Object)(object)val7 != (Object)null)
			{
				Object.Destroy((Object)(object)val7);
			}
		}
	}

	private static string Describe(Material material)
	{
		if ((Object)(object)material == (Object)null)
		{
			return "material=<null>";
		}
		Texture val = (material.HasProperty("_MainTex") ? material.GetTexture("_MainTex") : null);
		return "material=" + ((Object)material).name + "; shader=" + ((Object)material.shader).name + "; supported=" + material.shader.isSupported + "; texture=" + (((Object)(object)val == (Object)null) ? "<null>" : (((Object)val).name + " " + val.width + "x" + val.height));
	}

	private void Prune()
	{
		List<int> list = null;
		foreach (KeyValuePair<int, Binding> binding in bindings)
		{
			if ((Object)(object)binding.Value.Renderer == (Object)null || (Object)(object)binding.Value.Filter == (Object)null)
			{
				if (list == null)
				{
					list = new List<int>();
				}
				list.Add(binding.Key);
			}
		}
		if (list == null)
		{
			return;
		}
		foreach (int item in list)
		{
			Restore(bindings[item]);
			bindings.Remove(item);
		}
	}

	private static void Restore(Binding b)
	{
		if ((Object)(object)b.Filter != (Object)null && (Object)(object)b.Filter.sharedMesh == (Object)(object)b.ReplacementMesh)
		{
			b.Filter.sharedMesh = b.OriginalMesh;
		}
		if ((Object)(object)b.Renderer != (Object)null)
		{
			Material[] sharedMaterials = b.Renderer.sharedMaterials;
			if (sharedMaterials.Length == 1 && (Object)(object)sharedMaterials[0] == (Object)(object)b.ReplacementMaterial)
			{
				b.Renderer.sharedMaterial = b.OriginalMaterial;
			}
		}
		if ((Object)(object)b.ReplacementMesh != (Object)null)
		{
			Object.Destroy((Object)(object)b.ReplacementMesh);
		}
		if ((Object)(object)b.ReplacementMaterial != (Object)null)
		{
			Object.Destroy((Object)(object)b.ReplacementMaterial);
		}
	}

	internal void RestoreAll()
	{
		foreach (Binding value in bindings.Values)
		{
			Restore(value);
		}
		bindings.Clear();
	}

	internal void UpdateDamageFlash()
	{
		foreach (Binding value in bindings.Values)
		{
			if ((Object)(object)value.Renderer != (Object)null && value.DamageFlash != null)
			{
				value.DamageFlash.Update();
			}
		}
	}

	public void Dispose()
	{
		RestoreAll();
		data = null;
		if ((Object)(object)texture != (Object)null)
		{
			Object.Destroy((Object)(object)texture);
		}
		texture = null;
	}
}
internal sealed class OrbitAssets : IDisposable
{
	private readonly List<PspAssets> models = new List<PspAssets>();

	private OrbitLayoutData layout;

	internal PspBounds ReferenceBounds;

	internal static readonly string[] Filenames = new string[3] { "pinozen_psp.mesh.json", "pinozen_monkey.mesh.json", "pinozen_tung.mesh.json" };

	private static string Read(string folder, string filename, long max)
	{
		FileInfo fileInfo = new FileInfo(Path.Combine(folder, filename));
		if (!fileInfo.Exists || fileInfo.Length == 0 || fileInfo.Length > max)
		{
			throw new InvalidDataException("Missing or oversized " + filename);
		}
		return File.ReadAllText(fileInfo.FullName);
	}

	internal static OrbitAssets Load(string folder)
	{
		OrbitAssets orbitAssets = new OrbitAssets();
		try
		{
			HeadModelData headModelData = PspJson.Read<HeadModelData>(Read(folder, "pinozen_head.mesh.json", 25165824L));
			HeadValidation.Validate(headModelData);
			orbitAssets.ReferenceBounds = headModelData.referenceBounds;
			orbitAssets.layout = PspJson.Read<OrbitLayoutData>(Read(folder, "pinozen_orbit.layout.json", 131072L));
			OrbitLayoutValidation.Validate(orbitAssets.layout);
			string[] filenames = Filenames;
			foreach (string filename in filenames)
			{
				orbitAssets.models.Add(PspAssets.Load(folder, filename));
			}
			return orbitAssets;
		}
		catch
		{
			orbitAssets.Dispose();
			throw;
		}
	}

	internal PinozenOrbitVisual Create(Component enemy, Renderer body, Renderer head, Bounds originalHeadBounds, float radiusMultiplier, float sizeMultiplier, float speedMultiplier, float extraHeight)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Expected O, but got Unknown
		OrbitGeometry.ValidateSettings(radiusMultiplier, sizeMultiplier, speedMultiplier, extraHeight);
		Vector3 val = V(ReferenceBounds.max) - V(ReferenceBounds.min);
		Vector3 size = ((Bounds)(ref originalHeadBounds)).size;
		float num = ((Vector3)(ref size)).magnitude / ((Vector3)(ref val)).magnitude;
		if (!PspValidation.Finite(num) || num < 1E-05f || num > 100000f)
		{
			throw new InvalidDataException("Invalid orbit head calibration scale.");
		}
		for (int i = 0; i < 3; i++)
		{
			Vector3 size2 = ((Bounds)(ref originalHeadBounds)).size;
			if (Mathf.Abs(((Vector3)(ref size2))[i] / (((Vector3)(ref val))[i] * num) - 1f) > 0.05f)
			{
				throw new InvalidDataException("Original head axes do not match orbit calibration.");
			}
		}
		GameObject val2 = new GameObject("Pinozen orbit trio");
		val2.SetActive(false);
		val2.AddComponent<PinozenPspMarker>();
		PinozenOrbitVisual pinozenOrbitVisual = null;
		try
		{
			Transform[] array = (Transform[])(object)new Transform[layout.props.Length];
			for (int j = 0; j < array.Length; j++)
			{
				OrbitPropLayout orbitPropLayout = layout.props[j];
				GameObject val3 = models[OrbitLayoutValidation.ModelIndex(orbitPropLayout.id)].Create(val2.transform, ((Component)body).gameObject.layer);
				((Object)val3).name = "Pinozen orbit " + orbitPropLayout.id;
				array[j] = val3.transform;
			}
			pinozenOrbitVisual = enemy.gameObject.AddComponent<PinozenOrbitVisual>();
			pinozenOrbitVisual.Initialize(val2, array, body, head, num, layout, radiusMultiplier, sizeMultiplier, speedMultiplier, extraHeight);
			return pinozenOrbitVisual;
		}
		catch
		{
			if ((Object)(object)pinozenOrbitVisual != (Object)null)
			{
				Object.Destroy((Object)(object)pinozenOrbitVisual);
			}
			Object.Destroy((Object)(object)val2);
			throw;
		}
	}

	private static Vector3 V(float[] p)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(p[0], p[1], p[2]);
	}

	public void Dispose()
	{
		foreach (PspAssets model in models)
		{
			model.Dispose();
		}
		models.Clear();
	}
}
[DefaultExecutionOrder(20000)]
public sealed class PinozenOrbitVisual : MonoBehaviour
{
	private GameObject root;

	private Transform[] props;

	private Renderer body;

	private Renderer head;

	private OrbitLayoutData layout;

	private float calibration;

	private float radiusMultiplier;

	private float sizeMultiplier;

	private float speedMultiplier;

	private float extraHeight;

	private double started;

	private Vector3 forwardInBody;

	private Quaternion heading = Quaternion.identity;

	internal bool IsValid
	{
		get
		{
			if ((Object)(object)root != (Object)null && (Object)(object)body != (Object)null)
			{
				return (Object)(object)head != (Object)null;
			}
			return false;
		}
	}

	internal void Initialize(GameObject owner, Transform[] items, Renderer torso, Renderer headRenderer, float ratio, OrbitLayoutData sceneLayout, float radius, float size, float speed, float height)
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		root = owner;
		props = items;
		body = torso;
		head = headRenderer;
		calibration = ratio;
		layout = sceneLayout;
		radiusMultiplier = radius;
		sizeMultiplier = size;
		speedMultiplier = speed;
		extraHeight = height;
		Vector3 val = ((Component)head).transform.TransformVector(V(layout.canonicalForwardInHead));
		Vector3 val2 = ((Component)head).transform.TransformVector(V(layout.canonicalUpInHead));
		if (((Vector3)(ref val)).sqrMagnitude < 1E-10f || ((Vector3)(ref val2)).sqrMagnitude < 1E-10f)
		{
			throw new InvalidDataException("Invalid calibrated orbit orientation.");
		}
		forwardInBody = ((Component)body).transform.InverseTransformVector(((Vector3)(ref val)).normalized);
		started = Time.time;
		LateUpdate();
	}

	private static Vector3 V(float[] p)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(p[0], p[1], p[2]);
	}

	private static Quaternion Q(float[] p)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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)
		Quaternion val = new Quaternion(p[0], p[1], p[2], p[3]);
		return ((Quaternion)(ref val)).normalized;
	}

	private static bool Visible(Renderer r)
	{
		if ((Object)(object)r != (Object)null && r.enabled && !r.forceRenderingOff)
		{
			return ((Component)r).gameObject.activeInHierarchy;
		}
		return false;
	}

	private void LateUpdate()
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: 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_0106: 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_011b: 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_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0184: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0221: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)root == (Object)null)
		{
			return;
		}
		if (!IsValid)
		{
			Remove();
			return;
		}
		bool flag = Visible(body) && Visible(head);
		if (root.activeSelf != flag)
		{
			root.SetActive(flag);
		}
		if (flag)
		{
			Vector3 lossyScale = ((Component)head).transform.lossyScale;
			float num;
			try
			{
				num = OrbitGeometry.CalibratedScale(calibration, lossyScale.x, lossyScale.y, lossyScale.z);
			}
			catch (InvalidDataException)
			{
				root.SetActive(false);
				return;
			}
			Vector3 val = ((Component)body).transform.TransformVector(forwardInBody);
			val.y = 0f;
			if (((Vector3)(ref val)).sqrMagnitude > 1E-08f)
			{
				heading = Quaternion.LookRotation(((Vector3)(ref val)).normalized, Vector3.up);
			}
			Transform transform = root.transform;
			Bounds bounds = body.bounds;
			transform.position = ((Bounds)(ref bounds)).center + heading * ((V(layout.centerOffset) + Vector3.up * extraHeight) * num);
			root.transform.rotation = heading;
			double num2 = OrbitGeometry.Angle((double)Time.time - started, layout.degreesPerSecond * speedMultiplier);
			Quaternion val2 = Quaternion.AngleAxis((float)num2, Vector3.up);
			for (int i = 0; i < props.Length; i++)
			{
				OrbitPropLayout orbitPropLayout = layout.props[i];
				Vector3 val3 = V(orbitPropLayout.offset);
				val3.x *= radiusMultiplier;
				val3.z *= radiusMultiplier;
				val3 = val2 * val3;
				val3.y += OrbitGeometry.Bob(num2, layout.bobAmplitude, OrbitLayoutValidation.ModelIndex(orbitPropLayout.id));
				props[i].localPosition = val3 * num;
				props[i].localRotation = val2 * Q(orbitPropLayout.rotation);
				props[i].localScale = V(orbitPropLayout.scale) * (num * sizeMultiplier);
			}
		}
	}

	private void OnDisable()
	{
		if ((Object)(object)root != (Object)null)
		{
			root.SetActive(false);
		}
	}

	internal void Remove()
	{
		if ((Object)(object)root != (Object)null)
		{
			root.SetActive(false);
			Object.Destroy((Object)(object)root);
			root = null;
		}
		Object.Destroy((Object)(object)this);
	}

	private void OnDestroy()
	{
		if ((Object)(object)root != (Object)null)
		{
			Object.Destroy((Object)(object)root);
		}
	}
}
internal static class OrbitGeometry
{
	internal const int PropCount = 3;

	internal const float ReferenceObjectScale = 0.8f;

	internal static void ValidateModel(PspModelData data)
	{
		PspValidation.Model(data);
		int num = 0;
		PspMeshData[] meshes = data.meshes;
		foreach (PspMeshData pspMeshData in meshes)
		{
			num += pspMeshData.triangles.Length / 3;
			for (int j = 0; j < pspMeshData.triangles.Length; j += 3)
			{
				if (TriangleDot(pspMeshData, j) <= 0.0)
				{
					throw new InvalidDataException("Orbit model has inward or degenerate triangles.");
				}
			}
		}
		if (num > 15000)
		{
			throw new InvalidDataException("Orbit accessory exceeds 15000 triangles.");
		}
		for (int k = 0; k < 3; k++)
		{
			if ((double)Math.Abs(data.bounds.max[k] + data.bounds.min[k]) > Math.Max(1E-05, (double)(data.bounds.max[k] - data.bounds.min[k]) * 0.0001))
			{
				throw new InvalidDataException("Orbit payload geometry must be centered by the scene exporter.");
			}
		}
	}

	internal static double TriangleDot(PspMeshData mesh, int offset)
	{
		int num = mesh.triangles[offset] * 3;
		int num2 = mesh.triangles[offset + 1] * 3;
		int num3 = mesh.triangles[offset + 2] * 3;
		float[] vertices = mesh.vertices;
		float[] normals = mesh.normals;
		double num4 = vertices[num2] - vertices[num];
		double num5 = vertices[num2 + 1] - vertices[num + 1];
		double num6 = vertices[num2 + 2] - vertices[num + 2];
		double num7 = vertices[num3] - vertices[num];
		double num8 = vertices[num3 + 1] - vertices[num + 1];
		double num9 = vertices[num3 + 2] - vertices[num + 2];
		return (num5 * num9 - num6 * num8) * (double)(normals[num] + normals[num2] + normals[num3]) + (num6 * num7 - num4 * num9) * (double)(normals[num + 1] + normals[num2 + 1] + normals[num3 + 1]) + (num4 * num8 - num5 * num7) * (double)(normals[num + 2] + normals[num2 + 2] + normals[num3 + 2]);
	}

	internal static void ValidateSettings(float radius, float size, float speed, float height)
	{
		float[] array = new float[4] { radius, size, speed, height };
		foreach (float n in array)
		{
			if (!PspValidation.Finite(n))
			{
				throw new InvalidDataException("Orbit settings must be finite.");
			}
		}
		if (radius < 0.25f || radius > 4f || size < 0.25f || size > 4f || Math.Abs(speed) > 4f || Math.Abs(height) > 2f)
		{
			throw new InvalidDataException("Orbit settings outside supported range.");
		}
	}

	internal static double Angle(double seconds, float speedDegrees)
	{
		return seconds * (double)speedDegrees % 360.0;
	}

	internal static float CalibratedScale(float ratio, float sx, float sy, float sz)
	{
		float num = ratio * (Math.Abs(sx) + Math.Abs(sy) + Math.Abs(sz)) / 2.4f;
		if (!PspValidation.Finite(num) || num < 1E-05f || num > 100000f)
		{
			throw new InvalidDataException("Invalid world scale for orbit accessories.");
		}
		return num;
	}

	internal static float Bob(double angleDegrees, float amplitude, int index)
	{
		double num = (double)index * 2.0 * Math.PI / 3.0;
		return (float)((double)amplitude * (Math.Sin(angleDegrees * Math.PI / 90.0 + num) - Math.Sin(num)));
	}
}
[Serializable]
public sealed class OrbitPropLayout
{
	public string id;

	public float[] offset;

	public float[] rotation;

	public float[] scale;
}
[Serializable]
public sealed class OrbitLayoutData
{
	public int schema;

	public float[] centerOffset;

	public float[] canonicalForwardInHead;

	public float[] canonicalUpInHead;

	public float degreesPerSecond;

	public float bobAmplitude;

	public OrbitPropLayout[] props;
}
internal static class OrbitLayoutValidation
{
	internal static int ModelIndex(string id)
	{
		return id switch
		{
			"psp" => 0, 
			"monkey" => 1, 
			"tung" => 2, 
			_ => throw new InvalidDataException("Unknown orbit accessory id: " + id), 
		};
	}

	private static void Require(bool value, string name)
	{
		if (!value)
		{
			throw new InvalidDataException("Orbit layout: " + name);
		}
	}

	private static void Numbers(float[] values, int count, float limit, string name)
	{
		Require(values != null && values.Length == count, "invalid " + name + " dimensions");
		foreach (float num in values)
		{
			Require(PspValidation.Finite(num) && Math.Abs(num) <= limit, "invalid " + name);
		}
	}

	internal static void Validate(OrbitLayoutData data)
	{
		Require(data != null && data.schema == 1, "unsupported schema");
		Numbers(data.centerOffset, 3, 20f, "center offset");
		Numbers(data.canonicalForwardInHead, 3, 100f, "reference forward");
		Numbers(data.canonicalUpInHead, 3, 100f, "reference up");
		double num = 0.0;
		double num2 = 0.0;
		double num3 = 0.0;
		for (int i = 0; i < 3; i++)
		{
			num += (double)(data.canonicalForwardInHead[i] * data.canonicalForwardInHead[i]);
			num2 += (double)(data.canonicalUpInHead[i] * data.canonicalUpInHead[i]);
			num3 += (double)(data.canonicalForwardInHead[i] * data.canonicalUpInHead[i]);
		}
		Require(num > 1E-08 && num2 > 1E-08 && Math.Abs(num3) < 0.01 * Math.Sqrt(num * num2), "invalid reference frame");
		Require(PspValidation.Finite(data.degreesPerSecond) && Math.Abs(data.degreesPerSecond) <= 360f, "invalid orbit speed");
		Require(PspValidation.Finite(data.bobAmplitude) && data.bobAmplitude >= 0f && data.bobAmplitude <= 1f, "invalid bob amplitude");
		Require(data.props != null && data.props.Length == 3, "expected exactly three props");
		HashSet<string> hashSet = new HashSet<string>();
		OrbitPropLayout[] props = data.props;
		foreach (OrbitPropLayout orbitPropLayout in props)
		{
			Require(orbitPropLayout != null, "missing prop");
			ModelIndex(orbitPropLayout.id);
			Require(hashSet.Add(orbitPropLayout.id), "duplicate prop id");
			Numbers(orbitPropLayout.offset, 3, 20f, "prop offset");
			Numbers(orbitPropLayout.rotation, 4, 1.01f, "prop rotation");
			Numbers(orbitPropLayout.scale, 3, 100f, "prop scale");
			double num4 = 0.0;
			float[] rotation = orbitPropLayout.rotation;
			foreach (float num5 in rotation)
			{
				num4 += (double)(num5 * num5);
			}
			Require(Math.Abs(num4 - 1.0) < 0.01, "rotation must be a unit quaternion");
			float[] scale = orbitPropLayout.scale;
			foreach (float num6 in scale)
			{
				Require((double)num6 > 1E-05, "prop scale must be positive; mirrored geometry must be baked by exporter");
			}
		}
	}
}
internal sealed class OriginalEyeOverlays
{
	private sealed class HiddenRenderer
	{
		internal Renderer Renderer;

		internal bool WasForcedOff;
	}

	private readonly Dictionary<int, HiddenRenderer> hidden = new Dictionary<int, HiddenRenderer>();

	internal void Hide(Renderer[] verifiedFloaterRenderers, Action<string> diagnostic)
	{
		foreach (Renderer val in verifiedFloaterRenderers)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			string text;
			switch (((Object)val).name)
			{
			case "Face Idle":
				text = "Floater Face Idle";
				break;
			case "Face Attack":
				text = "Floater Face Attack";
				break;
			case "Face Stun":
				text = "Floater Face Stun";
				break;
			default:
				continue;
			}
			Mesh val2 = PspAssets.HandMesh(val);
			if (!((Object)(object)val2 == (Object)null) && !(((Object)val2).name != text))
			{
				int instanceID = ((Object)val).GetInstanceID();
				if (!hidden.ContainsKey(instanceID))
				{
					hidden.Add(instanceID, new HiddenRenderer
					{
						Renderer = val,
						WasForcedOff = val.forceRenderingOff
					});
					val.forceRenderingOff = true;
					diagnostic(EnemyScopeDiscovery.Path(((Component)val).transform) + "; mesh=" + ((Object)val2).name + "; forceRenderingOff=" + val.forceRenderingOff);
				}
			}
		}
		Enforce();
	}

	internal void Enforce()
	{
		List<int> list = null;
		foreach (KeyValuePair<int, HiddenRenderer> item in hidden)
		{
			if ((Object)(object)item.Value.Renderer == (Object)null)
			{
				if (list == null)
				{
					list = new List<int>();
				}
				list.Add(item.Key);
			}
			else
			{
				item.Value.Renderer.forceRenderingOff = true;
			}
		}
		if (list == null)
		{
			return;
		}
		foreach (int item2 in list)
		{
			hidden.Remove(item2);
		}
	}

	internal void Restore()
	{
		foreach (HiddenRenderer value in hidden.Values)
		{
			if ((Object)(object)value.Renderer != (Object)null)
			{
				value.Renderer.forceRenderingOff = value.WasForcedOff;
			}
		}
		hidden.Clear();
	}
}
[BepInPlugin("dpc.pinozen.visual", "Pinozen", "0.5.7")]
[BepInProcess("REPO.exe")]
public sealed class PinozenPlugin : BaseUnityPlugin
{
	private sealed class SlotBinding
	{
		internal int Slot;

		internal Material Original;

		internal Material Replacement;

		internal DamageFlashBridge DamageFlash;
	}

	private sealed class RendererBinding
	{
		internal Renderer Renderer;

		internal readonly List<SlotBinding> Slots = new List<SlotBinding>();
	}

	private const string TextureFilename = "Pinozen_Mentalist_BaseColor.png";

	private const float ScanInterval = 2f;

	private ConfigEntry<bool> enabledConfig;

	private ConfigEntry<string> includeNames;

	private ConfigEntry<string> excludeNames;

	private ConfigEntry<string> textureProperty;

	private ConfigEntry<bool> diagnosticLogging;

	private ConfigEntry<bool> hideHalloweenAccessories;

	private readonly HalloweenAccessories halloweenAccessories = new HalloweenAccessories();

	private ConfigEntry<bool> hideOriginalEyes;

	private readonly OriginalEyeOverlays originalEyeOverlays = new OriginalEyeOverlays();

	private ConfigEntry<bool> useModeledHead;

	private readonly ModeledHead modeledHead = new ModeledHead();

	private bool? previousHeadEnabled;

	private float nextHeadLoad;

	private string previousHeadError;

	private readonly Dictionary<int, RendererBinding> bindings = new Dictionary<int, RendererBinding>();

	private readonly HashSet<int> warnedEnemies = new HashSet<int>();

	private readonly HashSet<string> warnedMaterials = new HashSet<string>();

	private Texture2D replacementTexture;

	private Type enemyType;

	private ConfigEntry<bool> useOriginalMeshNames;

	private DiagnosticReport diagnosis;

	private bool? lastEnabled;

	private string folder;

	private string previousSettings;

	private string previousLoadError;

	private float nextScan;

	private float nextLoadAttempt;

	private bool warnedType;

	private bool initialized;

	private ConfigEntry<bool> orbitEnabled;

	private ConfigEntry<float> orbitRadius;

	private ConfigEntry<float> orbitSize;

	private ConfigEntry<float> orbitSpeed;

	private ConfigEntry<float> orbitHeight;

	private OrbitAssets orbitAssets;

	private readonly Dictionary<int, PinozenOrbitVisual> props = new Dictionary<int, PinozenOrbitVisual>();

	private readonly HashSet<int> warnedProps = new HashSet<int>();

	private string previousOrbitSettings;

	private string previousOrbitError;

	private float nextOrbitLoad;

	private void Awake()
	{
		folder = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		diagnosis = new DiagnosticReport(Path.Combine(Paths.BepInExRootPath, "Pinozen-diagnosi.txt"), Paths.GameRootPath, folder);
		if (!diagnosis.Available)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Could not create BepInEx/Pinozen-diagnosi.txt; standard BepInEx logging remains available.");
		}
		diagnosis.Write("BOOT", "Pinozen 0.5.7 giant cranium and orbit accessories; native Mentalist names preserved; Unity=" + Application.unityVersion + "; plugin=<plugin>/Pinozen.dll");
		enabledConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Use Pinozen's custom outfit, modeled head and orbiting props. Original animation transforms, AI, sounds and colliders remain in place.");
		includeNames = ((BaseUnityPlugin)this).Config.Bind<string>("Matching", "IncludeNames", "enemy floater", "Semicolon-separated fragments matched against material, base-color texture, renderer or mesh names, only within verified EnemyFloater actor scopes. Matching ignores punctuation and case.");
		excludeNames = ((BaseUnityPlugin)this).Config.Bind<string>("Matching", "ExcludeNames", "liquid;particle;aura;effect;beam;trail;halo;vfx;glow", "Excluded name fragments take priority over IncludeNames. Keep the Mentalist's liquid/psychic effects excluded.");
		useOriginalMeshNames = ((BaseUnityPlugin)this).Config.Bind<bool>("AdditionalMatching", "UseOriginalMeshNames", true, "Also match the known original Mentalist body, face, limb, hand and digit meshes inside verified EnemyFloater scopes. Effect exclusions still win.");
		textureProperty = ((BaseUnityPlugin)this).Config.Bind<string>("Matching", "TextureProperty", "", "Optional exact shader texture property. Leave empty for common base-color/albedo property detection. Normal, metallic and other maps are preserved.");
		diagnosticLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogMaterialCandidates", true, "If no material matches a Mentalist, log candidate renderer, mesh, material, and texture names once for that enemy.");
		hideHalloweenAccessories = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "HideHalloweenAccessories", true, "Hide the Mentalist Halloween alien mask and candy bucket, including their children, to expose Pinozen's face.");
		hideOriginalEyes = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "HideOriginalEyes", true, "Hide the original Idle, Attack and Stun face overlays that duplicate the eyes. Pinozen's face on the head remains visible.");
		useModeledHead = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "UseModeledHead", true, "Use the Blender-sculpted head and its dedicated face atlas. False restores the original head geometry with the old skin.");
		if (File.Exists(Path.Combine(folder, "pinozen.mesh.json")))
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Old Pinozen 0.1 full-character model data is ignored. This version replaces the head render mesh and adds three orbiting props.");
		}
		orbitEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Orbit", "Enabled", true, "Show the PSP, low-poly monkey and Tung Tung Sahur orbiting the torso. No hand attachment or gameplay collider is added.");
		orbitRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Orbit", "RadiusMultiplier", 1f, "Multiply the orbit offsets exported from the user's Blender scene. Range 0.25 to 4; 1 preserves the scene.");
		orbitSize = ((BaseUnityPlugin)this).Config.Bind<float>("Orbit", "SizeMultiplier", 1f, "Multiply the actual accessory dimensions exported from Blender. Range 0.25 to 4; 1 preserves the scene.");
		orbitSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Orbit", "SpeedMultiplier", 1f, "Multiply the scene orbit speed. Range -4 to 4; zero pauses the orbit and its bob.");
		orbitHeight = ((BaseUnityPlugin)this).Config.Bind<float>("Orbit", "ExtraHeightMeters", 0f, "Additional height relative to the scene orbit center. Range -2 to 2 metres; zero preserves the scene.");
		initialized = true;
		LogEnabled();
		if (enabledConfig.Value)
		{
			TryLoadTexture();
			if (orbitEnabled.Value)
			{
				TryLoadOrbit();
			}
			if (useModeledHead.Value)
			{
				TryLoadHead();
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Pinozen 0.5.7 giant cranium and orbit accessories loaded. Spawn/catalog name remains Mentalist. Diagnostic report: BepInEx/Pinozen-diagnosi.txt.");
	}

	private void LogEnabled()
	{
		if (lastEnabled != enabledConfig.Value)
		{
			lastEnabled = enabledConfig.Value;
			string text = (enabledConfig.Value ? "enabled" : "disabled by General.Enabled=false");
			diagnosis.Write("STATE", text + "; Orbit.Enabled=" + orbitEnabled.Value);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Pinozen " + text + "."));
		}
	}

	private void Update()
	{
		if (!initialized)
		{
			return;
		}
		LogEnabled();
		if ((!enabledConfig.Value || !orbitEnabled.Value) && props.Count != 0)
		{
			DestroyProps();
		}
		bool flag = enabledConfig.Value && useModeledHead.Value;
		if (previousHeadEnabled != flag)
		{
			modeledHead.RestoreAll();
			RestoreAll();
			previousHeadEnabled = flag;
			nextScan = 0f;
		}
		if (flag && !modeledHead.Ready && Time.unscaledTime >= nextHeadLoad)
		{
			TryLoadHead();
		}
		if (!enabledConfig.Value || !hideHalloweenAccessories.Value)
		{
			halloweenAccessories.Restore();
		}
		if (!enabledConfig.Value || !hideOriginalEyes.Value || (Object)(object)replacementTexture == (Object)null)
		{
			originalEyeOverlays.Restore();
		}
		RuntimeWorkPlan runtimeWorkPlan = RuntimeWorkPlan.Create(enabledConfig.Value, (Object)(object)replacementTexture != (Object)null, orbitEnabled.Value, orbitAssets != null);
		if (!runtimeWorkPlan.Scan)
		{
			if (bindings.Count != 0)
			{
				RestoreAll();
			}
			if (props.Count != 0)
			{
				DestroyProps();
			}
			return;
		}
		if (runtimeWorkPlan.LoadTexture && Time.unscaledTime >= nextLoadAttempt)
		{
			TryLoadTexture();
		}
		if (runtimeWorkPlan.LoadPsp && Time.unscaledTime >= nextOrbitLoad)
		{
			TryLoadOrbit();
		}
		if (!(Time.unscaledTime < nextScan))
		{
			nextScan = Time.unscaledTime + 2f;
			string text = includeNames.Value + "\n" + excludeNames.Value + "\n" + textureProperty.Value + "\n" + useOriginalMeshNames.Value;
			if (previousSettings != text)
			{
				modeledHead.RestoreAll();
				RestoreAll();
				warnedEnemies.Clear();
				warnedMaterials.Clear();
				previousSettings = text;
				diagnosis.Write("MATCHING", "originalMeshes=" + useOriginalMeshNames.Value + "; include=" + includeNames.Value + "; exclude=" + excludeNames.Value + "; requestedProperty=" + textureProperty.Value);
			}
			string text2 = orbitEnabled.Value + "|" + orbitRadius.Value + "|" + orbitSize.Value + "|" + orbitSpeed.Value + "|" + orbitHeight.Value;
			if (previousOrbitSettings != text2)
			{
				DestroyProps();
				warnedProps.Clear();
				previousOrbitSettings = text2;
				diagnosis.Write("ORBIT_STATE", "enabled=" + orbitEnabled.Value + "; radius=" + orbitRadius.Value + "; dataReady=" + (orbitAssets != null));
			}
			Scan();
		}
	}

	private void LateUpdate()
	{
		if (initialized && enabledConfig.Value)
		{
			modeledHead.UpdateDamageFlash();
			foreach (RendererBinding value in bindings.Values)
			{
				if (!((Object)(object)value.Renderer != (Object)null))
				{
					continue;
				}
				foreach (SlotBinding slot in value.Slots)
				{
					if (slot.DamageFlash != null)
					{
						slot.DamageFlash.Update();
					}
				}
			}
		}
		if (initialized && enabledConfig.Value && hideHalloweenAccessories.Value)
		{
			halloweenAccessories.Enforce();
		}
		if (initialized && enabledConfig.Value && hideOriginalEyes.Value && (Object)(object)replacementTexture != (Object)null)
		{
			originalEyeOverlays.Enforce();
		}
	}

	private void TryLoadTexture()
	{
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Expected O, but got Unknown
		nextLoadAttempt = Time.unscaledTime + 10f;
		Texture2D val = null;
		try
		{
			string text = Path.Combine(folder, "Pinozen_Mentalist_BaseColor.png");
			FileInfo fileInfo = new FileInfo(text);
			if (!fileInfo.Exists)
			{
				throw new FileNotFoundException("Place Pinozen_Mentalist_BaseColor.png next to Pinozen.dll.");
			}
			if (fileInfo.Length == 0 || fileInfo.Length > 33554432)
			{
				throw new InvalidDataException("Base-color PNG must be between 1 byte and 32 MiB.");
			}
			val = new Texture2D(2, 2, (TextureFormat)4, true, false);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text), true))
			{
				throw new InvalidDataException("The base-color PNG could not be decoded.");
			}
			((Object)val).name = "Pinozen_Mentalist_BaseColor";
			((Texture)val).wrapMode = (TextureWrapMode)0;
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).anisoLevel = 1;
			replacementTexture = val;
			val = null;
			previousLoadError = null;
			nextScan = 0f;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded Pinozen_Mentalist_BaseColor.png (" + ((Texture)replacementTexture).width + " x " + ((Texture)replacementTexture).height + ")."));
			diagnosis.Write("TEXTURE_LOADED", "Pinozen_Mentalist_BaseColor.png; " + ((Texture)replacementTexture).width + "x" + ((Texture)replacementTexture).height);
		}
		catch (Exception ex)
		{
			string text2 = ex.GetType().Name + ": " + ex.Message;
			if (previousLoadError != text2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Texture not loaded; original Mentalists remain untouched. " + text2));
			}
			diagnosis.Write("TEXTURE_FAILED", text2 + "; Orbit accessories remain independent.", text2);
			previousLoadError = text2;
		}
		finally
		{
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
		}
	}

	private void Scan()
	{
		if (enemyType == null)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				Type type = assembly.GetType("EnemyFloater", throwOnError: false);
				if (type != null && typeof(Component).IsAssignableFrom(type))
				{
					enemyType = type;
					break;
				}
			}
			if (enemyType == null)
			{
				if (!warnedType)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"EnemyFloater is not loaded yet; waiting. No other enemy type is modified.");
				}
				diagnosis.Write("ENEMY_TYPE", "EnemyFloater not found; waiting.", "missing");
				warnedType = true;
				return;
			}
			diagnosis.Write("ENEMY_TYPE", "EnemyFloater found; assembly=" + enemyType.Assembly.GetName().Name, "found");
		}
		RemoveDestroyedBindings();
		Object[] array = Object.FindObjectsOfType(enemyType);
		diagnosis.Write("ENEMY_COUNT", "active EnemyFloater count=" + array.Length, array.Length.ToString());
		RuntimeWorkPlan runtimeWorkPlan = RuntimeWorkPlan.Create(enabledConfig.Value, (Object)(object)replacementTexture != (Object)null, orbitEnabled.Value, orbitAssets != null);
		Object[] array2 = array;
		foreach (Object val in array2)
		{
			Component val2 = (Component)(object)((val is Component) ? val : null);
			if ((Object)(object)val2 == (Object)null || !enemyType.IsInstanceOfType(val2))
			{
				continue;
			}
			int enemyId = ((Object)val2).GetInstanceID();
			Renderer[] array3;
			try
			{
				array3 = EnemyScopeDiscovery.Collect(val2, delegate(string message)
				{
					diagnosis.Write("SCOPE", message, enemyId + ":" + message);
				});
				diagnosis.Write("RENDERERS", EnemyScopeDiscovery.Path(val2.transform) + "; count=" + array3.Length, enemyId + ":" + array3.Length);
				if (hideHalloweenAccessories.Value)
				{
					halloweenAccessories.Hide(array3, delegate(string message)
					{
						diagnosis.Write("HALLOWEEN_HIDDEN", message, enemyId + ":" + message);
					});
				}
			}
			catch (Exception ex)
			{
				diagnosis.Write("SCOPE_FAILED", "enemy=" + enemyId + "; " + ex.GetType().Name + ": " + ex.Message, enemyId + ":" + ex.Message);
				continue;
			}
			int num = 0;
			Renderer[] array4 = array3;
			foreach (Renderer val3 in array4)
			{
				if ((Object)(object)val3 == (Object)null)
				{
					continue;
				}
				try
				{
					if (runtimeWorkPlan.ApplySkin && useModeledHead.Value && modeledHead.Ready)
					{
						try
						{
							if (modeledHead.Apply(val3, delegate(string message)
							{
								diagnosis.Write("HEAD_APPLIED", message);
								if (message.StartsWith("Damage flash ", StringComparison.Ordinal))
								{
									((BaseUnityPlugin)this).Logger.LogInfo((object)message);
								}
							}))
							{
								num++;
								continue;
							}
						}
						catch (Exception ex2)
						{
							string text = ex2.GetType().Name + ": " + ex2.Message;
							diagnosis.Write("HEAD_FAILED", text, ((Object)val3).GetInstanceID() + ":" + text);
							if (warnedMaterials.Add("head:" + text))
							{
								((BaseUnityPlugin)this).Logger.LogWarning((object)("Modeled head skipped; original skin remains available. " + text));
							}
						}
					}
					if (runtimeWorkPlan.ApplySkin)
					{
						num += ApplyRenderer(val3, null);
					}
					else
					{
						DescribeRenderer(val3);
					}
				}
				catch (Exception ex3)
				{
					string text2 = EnemyScopeDiscovery.Path(((Component)val3).transform) + "; " + ex3.GetType().Name + ": " + ex3.Message;
					diagnosis.Write("SKIN_FAILED", text2, text2);
					if (warnedMaterials.Add(text2))
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Skin renderer failed; other renderers and orbit accessories will still be processed. " + diagnosis.Sanitize(text2)));
					}
				}
			}
			if (runtimeWorkPlan.ApplySkin && hideOriginalEyes.Value)
			{
				originalEyeOverlays.Hide(array3, delegate(string message)
				{
					diagnosis.Write("EYES_HIDDEN", message, enemyId + ":" + message);
				});
			}
			if (runtimeWorkPlan.AttachPsp)
			{
				try
				{
					TryAttachOrbit(val2, array3);
				}
				catch (Exception ex4)
				{
					diagnosis.Write("ORBIT_FAILED", ex4.GetType().Name + ": " + ex4.Message, enemyId + ":" + ex4.Message);
				}
			}
			if (runtimeWorkPlan.ApplySkin && num == 0 && warnedEnemies.Add(enemyId))
			{
				diagnosis.Write("SKIN_FAILED", "No eligible base-color material for enemy=" + enemyId + "; inspect MATERIAL entries.");
				((BaseUnityPlugin)this).Logger.LogWarning((object)"No Mentalist base-color material matched. See BepInEx/Pinozen-diagnosi.txt; Orbit processing remains independent.");
			}
		}
	}

	private void DescribeRenderer(Renderer renderer)
	{
		Material[] sharedMaterials = renderer.sharedMaterials;
		for (int i = 0; i < sharedMaterials.Length; i++)
		{
			if ((Object)(object)sharedMaterials[i] != (Object)null)
			{
				DescribeMaterial(renderer, sharedMaterials[i], i, TextureCandidates(sharedMaterials[i]));
			}
		}
	}

	private void DescribeMaterial(Renderer renderer, Material material, int slot, List<AlbedoCandidate> properties)
	{
		List<string> list = new List<string>();
		foreach (AlbedoCandidate property in properties)
		{
			list.Add(property.Property + ":" + (property.HasTexture ? property.TextureName : "<null>") + (property.MainTexture ? "[MainTexture]" : ""));
		}
		string text = "path=" + EnemyScopeDiscovery.Path(((Component)renderer).transform) + "; mesh=" + MeshName(renderer) + "; slot=" + slot + "; material=" + ((Object)material).name + "; shader=" + (((Object)(object)material.shader == (Object)null) ? "<null>" : ((Object)material.shader).name) + "; propertyBlock=" + renderer.HasPropertyBlock() + "; textures=[" + string.Join(", ", list.ToArray()) + "]";
		diagnosis.Write("MATERIAL", text, ((Object)renderer).GetInstanceID() + ":" + slot + ":" + ((Object)material).GetInstanceID());
		if (diagnosticLogging.Value && warnedMaterials.Add("describe:" + text))
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Candidate: " + text));
		}
	}

	private static List<AlbedoCandidate> TextureCandidates(Material material)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		List<AlbedoCandidate> list = new List<AlbedoCandidate>();
		HashSet<string> hashSet = new HashSet<string>();
		Shader shader = material.shader;
		if ((Object)(object)shader != (Object)null)
		{
			for (int i = 0; i < shader.GetPropertyCount(); i++)
			{
				if ((shader.GetPropertyFlags(i) & 0x80) != 0)
				{
					hashSet.Add(shader.GetPropertyName(i));
				}
			}
		}
		string[] texturePropertyNames = material.GetTexturePropertyNames();
		foreach (string text in texturePropertyNames)
		{
			Texture texture = material.GetTexture(text);
			list.Add(new AlbedoCandidate(text, ((Object)(object)texture == (Object)null) ? "" : ((Object)texture).name, (Object)(object)texture != (Object)null, hashSet.Contains(text)));
		}
		return list;
	}

	private int ApplyRenderer(Renderer renderer, List<string> candidates)
	{
		//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ef: Expected O, but got Unknown
		int instanceID = ((Object)renderer).GetInstanceID();
		bindings.TryGetValue(instanceID, out var value);
		Material[] sharedMaterials = renderer.sharedMaterials;
		if (value != null)
		{
			for (int num = value.Slots.Count - 1; num >= 0; num--)
			{
				SlotBinding slotBinding = value.Slots[num];
				if (slotBinding.Slot >= sharedMaterials.Length || (Object)(object)sharedMaterials[slotBinding.Slot] != (Object)(object)slotBinding.Replacement)
				{
					if ((Object)(object)slotBinding.Replacement != (Object)null)
					{
						Object.Destroy((Object)(object)slotBinding.Replacement);
					}
					value.Slots.RemoveAt(num);
				}
			}
		}
		string text = MeshName(renderer);
		int num2 = value?.Slots.Count ?? 0;
		for (int i = 0; i < sharedMaterials.Length; i++)
		{
			Material val = sharedMaterials[i];
			if ((Object)(object)val == (Object)null || IsOwned(value, val))
			{
				continue;
			}
			List<AlbedoCandidate> list = TextureCandidates(val);
			DescribeMaterial(renderer, val, i, list);
			string text2 = AlbedoSelector.Select(list, textureProperty.Value);
			Texture val2 = ((text2 == null) ? null : val.GetTexture(text2));
			string text3 = (((Object)(object)val2 == (Object)null) ? "" : ((Object)val2).name);
			string text4 = "renderer=" + ((Object)renderer).name + ", mesh=" + text + ", material=" + ((Object)val).name + ", colorProperty=" + (text2 ?? "<none>") + ", colorTexture=" + text3;
			candidates?.Add(text4);
			List<string> list2 = new List<string>();
			list2.Add(((Object)val).name);
			list2.Add(text3);
			list2.Add(((Object)renderer).name);
			list2.Add(text);
			List<string> list3 = list2;
			foreach (AlbedoCandidate item in list)
			{
				list3.Add(item.TextureName);
			}
			bool flag = SkinMatcher.AnyTokenMatches(excludeNames.Value, list3.ToArray()) || SkinMatcher.AnyTokenMatches("liquid;particle;aura;effect;beam;trail;halo;vfx;glow", list3.ToArray());
			bool flag2 = SkinMatcher.AnyTokenMatches(includeNames.Value, list3.ToArray()) || (useOriginalMeshNames.Value && (OriginalMeshes.IsKnown(((Object)renderer).name) || OriginalMeshes.IsKnown(text)));
			if (flag || !flag2)
			{
				continue;
			}
			if (text2 == null)
			{
				if (warnedMaterials.Add(text4))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Matched a material but no safe base-color texture property was found; leaving it untouched. " + text4));
				}
				diagnosis.Write("SKIN_FAILED", "No safe texture property; " + text4, text4);
				continue;
			}
			Material val3 = new Material(val);
			try
			{
				((Object)val3).name = ((Object)val).name + " [Pinozen texture]";
				val3.SetTexture(text2, (Texture)(object)replacementTexture);
				if ((Object)(object)val2 != (Object)null)
				{
					string[] texturePropertyNames = val.GetTexturePropertyNames();
					foreach (string text5 in texturePropertyNames)
					{
						if (text5 != text2 && AlbedoSelector.Recognized(new AlbedoCandidate(text5, text3, hasTexture: true)) && (Object)(object)val.GetTexture(text5) == (Object)(object)val2)
						{
							val3.SetTexture(text5, (Texture)(object)replacementTexture);
						}
					}
				}
				sharedMaterials[i] = val3;
				renderer.sharedMaterials = sharedMaterials;
				if (value == null)
				{
					RendererBinding rendererBinding = new RendererBinding();
					rendererBinding.Renderer = renderer;
					value = rendererBinding;
					bindings.Add(instanceID, value);
				}
				value.Slots.Add(new SlotBinding
				{
					Slot = i,
					Original = val,
					Replacement = val3,
					DamageFlash = new DamageFlashBridge(val, val3, null)
				});
				num2++;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Applied Pinozen texture: " + text4));
				diagnosis.Write("SKIN_APPLIED", EnemyScopeDiscovery.Path(((Component)renderer).transform) + "; " + text4);
				val3 = null;
			}
			finally
			{
				if ((Object)(object)val3 != (Object)null)
				{
					Object.Destroy((Object)(object)val3);
				}
			}
		}
		return num2;
	}

	private static bool IsOwned(RendererBinding binding, Material material)
	{
		if (binding == null)
		{
			return false;
		}
		foreach (SlotBinding slot in binding.Slots)
		{
			if ((Object)(object)slot.Replacement == (Object)(object)material)
			{
				return true;
			}
		}
		return false;
	}

	private static string MeshName(Renderer renderer)
	{
		SkinnedMeshRenderer val = (SkinnedMeshRenderer)(object)((renderer is SkinnedMeshRenderer) ? renderer : null);
		if ((Object)(object)val != (Object)null)
		{
			if (!((Object)(object)val.sharedMesh == (Object)null))
			{
				return ((Object)val.sharedMesh).name;
			}
			return "";
		}
		MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>();
		if (!((Object)(object)component == (Object)null) && !((Object)(object)component.sharedMesh == (Object)null))
		{
			return ((Object)component.sharedMesh).name;
		}
		return "";
	}

	private void RemoveDestroyedBindings()
	{
		List<int> list = null;
		foreach (KeyValuePair<int, RendererBinding> binding in bindings)
		{
			if ((Object)(object)binding.Value.Renderer != (Object)null)
			{
				continue;
			}
			foreach (SlotBinding slot in binding.Value.Slots)
			{
				if ((Object)(object)slot.Replacement != (Object)null)
				{
					Object.Destroy((Object)(object)slot.Replacement);
				}
			}
			if (list == null)
			{
				list = new List<int>();
			}
			list.Add(binding.Key);
		}
		if (list == null)
		{
			return;
		}
		foreach (int item in list)
		{
			bindings.Remove(item);
		}
	}

	private void RestoreAll()
	{
		foreach (RendererBinding value in bindings.Values)
		{
			if ((Object)(object)value.Renderer != (Object)null)
			{
				Material[] sharedMaterials = value.Renderer.sharedMaterials;
				bool flag = false;
				foreach (SlotBinding slot in value.Slots)
				{
					if (slot.Slot < sharedMaterials.Length && (Object)(object)sharedMaterials[slot.Slot] == (Object)(object)slot.Replacement)
					{
						sharedMaterials[slot.Slot] = slot.Original;
						flag = true;
					}
				}
				if (flag)
				{
					value.Renderer.sharedMaterials = sharedMaterials;
				}
			}
			foreach (SlotBinding slot2 in value.Slots)
			{
				if ((Object)(object)slot2.Replacement != (Object)null)
				{
					Object.Destroy((Object)(object)slot2.Replacement);
				}
			}
		}
		bindings.Clear();
	}

	private void TryLoadHead()
	{
		nextHeadLoad = Time.unscaledTime + 10f;
		try
		{
			modeledHead.Load(folder);
			previousHeadError = null;
			diagnosis.Write("HEAD_DATA_LOADED", "Blender mesh and 2048px head atlas validated.");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded Blender-modeled Pinozen head and face atlas.");
		}
		catch (Exception ex)
		{
			string text = ex.GetType().Name + ": " + ex.Message;
			if (previousHeadError != text)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Modeled head unavailable; original skin remains active. " + text));
			}
			diagnosis.Write("HEAD_DATA_FAILED", text, text);
			previousHeadError = text;
		}
	}

	private void TryLoadOrbit()
	{
		nextOrbitLoad = Time.unscaledTime + 10f;
		try
		{
			orbitAssets = OrbitAssets.Load(folder);
			previousOrbitError = null;
			nextScan = 0f;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded three orbit accessories: PSP, monkey and Tung Tung Sahur. No hand attachment, collision or gameplay component is added.");
			diagnosis.Write("ORBIT_DATA_LOADED", "three schema1 models, user Blender layout and original head calibration validated");
		}
		catch (Exception ex)
		{
			string text = ex.GetType().Name + ": " + ex.Message;
			if (previousOrbitError != text)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Orbit accessories unavailable; the custom Mentalist appearance remains active. " + text));
			}
			diagnosis.Write("ORBIT_DATA_FAILED", text, text);
			previousOrbitError = text;
		}
	}

	private void TryAttachOrbit(Component enemy, Renderer[] renderers)
	{
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		int instanceID = ((Object)enemy).GetInstanceID();
		if (props.TryGetValue(instanceID, out var value))
		{
			if ((Object)(object)value != (Object)null && value.IsValid)
			{
				return;
			}
			if ((Object)(object)value != (Object)null)
			{
				value.Remove();
			}
			props.Remove(instanceID);
		}
		List<int> list = new List<int>();
		foreach (KeyValuePair<int, PinozenOrbitVisual> prop in props)
		{
			if ((Object)(object)prop.Value == (Object)null)
			{
				list.Add(prop.Key);
			}
		}
		foreach (int item in list)
		{
			props.Remove(item);
		}
		Renderer val = null;
		Renderer val2 = null;
		int num = 0;
		int num2 = 0;
		foreach (Renderer val3 in renderers)
		{
			if (!((Object)(object)val3 == (Object)null) && !((Object)(object)((Component)val3).GetComponentInParent<PinozenPspMarker>() != (Object)null))
			{
				if (ImportedNames.IsBody(((Object)val3).name) || ImportedNames.IsBody(MeshName(val3)))
				{
					val = val3;
					num++;
				}
				if (((Object)val3).name == "mesh head" && val3 is MeshRenderer)
				{
					val2 = val3;
					num2++;
				}
			}
		}
		if (num != 1 || num2 != 1)
		{
			diagnosis.Write("ORBIT_ANCHOR_MISSING", "enemy=" + instanceID + "; verified torso/head matches=" + num + "/" + num2, instanceID + ":" + num + ":" + num2);
			if (warnedProps.Add(instanceID))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Orbit accessories await one verified torso and head renderer.");
			}
			return;
		}
		try
		{
			props[instanceID] = orbitAssets.Create(enemy, val, val2, modeledHead.OriginalBounds(val2), orbitRadius.Value, orbitSize.Value, orbitSpeed.Value, orbitHeight.Value);
			diagnosis.Write("ORBIT_ATTACHED", "enemy=" + instanceID + "; count=3; torso=" + EnemyScopeDiscovery.Path(((Component)val).transform) + "; radius=" + orbitRadius.Value + "; headCalibration=original");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Three orbiting accessories attached to Mentalist torso; original hands remain free.");
		}
		catch (Exception ex)
		{
			string text = ex.GetType().Name + ": " + ex.Message;
			if (warnedProps.Add(instanceID))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not create orbit accessories; appearance remains active. " + text));
			}
			diagnosis.Write("ORBIT_FAILED", text, instanceID + ":" + text);
		}
	}

	private static bool Finite(Vector3 v)
	{
		if (PspValidation.Finite(v.x) && PspValidation.Finite(v.y))
		{
			return PspValidation.Finite(v.z);
		}
		return false;
	}

	private void DestroyProps()
	{
		foreach (PinozenOrbitVisual value in props.Values)
		{
			if ((Object)(object)value != (Object)null)
			{
				value.Remove();
			}
		}
		props.Clear();
	}

	private void OnDisable()
	{
		if (diagnosis != null)
		{
			diagnosis.Write("STATE", "plugin component disabled; restoring originals and removing orbit accessories.");
		}
		DestroyProps();
		modeledHead.RestoreAll();
		halloweenAccessories.Restore();
		originalEyeOverlays.Restore();
		RestoreAll();
		nextScan = 0f;
	}

	private void OnDestroy()
	{
		if (diagnosis != null)
		{
			diagnosis.Write("STATE", "plugin destroyed; releasing assets.");
		}
		DestroyProps();
		modeledHead.Dispose();
		halloweenAccessories.Restore();
		originalEyeOverlays.Restore();
		if (orbitAssets != null)
		{
			orbitAssets.Dispose();
		}
		orbitAssets = null;
		RestoreAll();
		if ((Object)(object)replacementTexture != (Object)null)
		{
			Object.Destroy((Object)(object)replacementTexture);
		}
		replacementTexture = null;
	}
}
internal sealed class PspAssets : IDisposable
{
	private readonly List<Mesh> meshes = new List<Mesh>();

	private readonly List<Material> materials = new List<Material>();

	private readonly List<Texture2D> solidTextures = new List<Texture2D>();

	private PspModelData data;

	internal string ShaderName;

	internal static PspAssets Load(string directory, string filename)
	{
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Expected O, but got Unknown
		//IL_0142: 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_030b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0312: Expected O, but got Unknown
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Expected O, but got Unknown
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0411: Unknown result type (might be due to invalid IL or missing references)
		//IL_0416: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
		PspAssets pspAssets = new PspAssets();
		try
		{
			pspAssets.data = PspJson.Read<PspModelData>(Read(directory, filename, 33554432L));
			OrbitGeometry.ValidateModel(pspAssets.data);
			Shader val = null;
			string[] array = new string[5] { "Standard", "Universal Render Pipeline/Lit", "Unlit/Color", "Unlit/Texture", "Sprites/Default" };
			foreach (string text in array)
			{
				Shader val2 = Shader.Find(text);
				if ((Object)(object)val2 != (Object)null && val2.isSupported)
				{
					val = val2;
					break;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				throw new InvalidDataException("PSP has no available supported shader: Standard, URP/Lit, Unlit/Color, Unlit/Texture and Sprites/Default were unavailable. Accessory skipped.");
			}
			pspAssets.ShaderName = ((Object)val).name;
			PspMaterialData[] array2 = pspAssets.data.materials;
			Color val4 = default(Color);
			foreach (PspMaterialData pspMaterialData in array2)
			{
				Material val3 = new Material(val);
				pspAssets.materials.Add(val3);
				((Object)val3).name = "Pinozen PSP " + pspMaterialData.name;
				((Color)(ref val4))..ctor(pspMaterialData.color[0], pspMaterialData.color[1], pspMaterialData.color[2], pspMaterialData.color[3]);
				if (val3.HasProperty("_Color"))
				{
					val3.SetColor("_Color", val4);
				}
				if (val3.HasProperty("_BaseColor"))
				{
					val3.SetColor("_BaseColor", val4);
				}
				if (!val3.HasProperty("_Color") && !val3.HasProperty("_BaseColor") && val3.HasProperty("_MainTex"))
				{
					Texture2D val5 = new Texture2D(1, 1, (TextureFormat)4, false, false);
					pspAssets.solidTextures.Add(val5);
					((Object)val5).name = "Pinozen PSP solid " + pspMaterialData.name;
					val5.SetPixels((Color[])(object)new Color[1] { val4 });
					val5.Apply(false, true);
					val3.SetTexture("_MainTex", (Texture)(object)val5);
				}
				if (val3.HasProperty("_Metallic"))
				{
					val3.SetFloat("_Metallic", pspMaterialData.metallic);
				}
				if (val3.HasProperty("_Glossiness"))
				{
					val3.SetFloat("_Glossiness", 1f - pspMaterialData.roughness);
				}
				if (val3.HasProperty("_Smoothness"))
				{
					val3.SetFloat("_Smoothness", 1f - pspMaterialData.roughness);
				}
				if (pspMaterialData.emission != null && pspMaterialData.emission.Length == 3 && pspMaterialData.emissionStrength > 0f && val3.HasProperty("_EmissionColor"))
				{
					val3.EnableKeyword("_EMISSION");
					val3.SetColor("_EmissionColor", new Color(pspMaterialData.emission[0], pspMaterialData.emission[1], pspMaterialData.emission[2]) * pspMaterialData.emissionStrength);
				}
			}
			PspMeshData[] array3 = pspAssets.data.meshes;
			foreach (PspMeshData pspMeshData in array3)
			{
				Mesh val6 = new Mesh();
				pspAssets.meshes.Add(val6);
				((Object)val6).name = "Pinozen PSP " + pspMeshData.name;
				int num = pspMeshData.vertices.Length / 3;
				if (num > 65535)
				{
					val6.indexFormat = (IndexFormat)1;
				}
				Vector3[] array4 = (Vector3[])(object)new Vector3[num];
				Vector3[] array5 = (Vector3[])(object)new Vector3[num];
				Vector2[] array6 = (Vector2[])(object)new Vector2[num];
				for (int l = 0; l < num; l++)
				{
					ref Vector3 reference = ref array4[l];
					reference = new Vector3(pspMeshData.vertices[l * 3], pspMeshData.vertices[l * 3 + 1], pspMeshData.vertices[l * 3 + 2]);
					ref Vector3 reference2 = ref array5[l];
					reference2 = new Vector3(pspMeshData.normals[l * 3], pspMeshData.normals[l * 3 + 1], pspMeshData.normals[l * 3 + 2]);
					ref Vector2 reference3 = ref array6[l];
					reference3 = new Vector2(pspMeshData.uv[l * 2], pspMeshData.uv[l * 2 + 1]);
				}
				val6.vertices = array4;
				val6.normals = array5;
				val6.uv = array6;
				val6.triangles = pspMeshData.triangles;
				val6.RecalculateBounds();
				val6.UploadMeshData(true);
			}
			return pspAssets;
		}
		catch
		{
			pspAssets.Dispose();
			throw;
		}
	}

	private static string Read(string directory, string filename, long limit)
	{
		string text = Path.Combine(directory, filename);
		FileInfo fileInfo = new FileInfo(text);
		if (!fileInfo.Exists)
		{
			throw new FileNotFoundException("Missing " + filename + " next to Pinozen.dll.");
		}
		if (fileInfo.Length <= 0 || fileInfo.Length > limit)
		{
			throw new InvalidDataException("Invalid size for " + filename + ".");
		}
		return File.ReadAllText(text);
	}

	internal GameObject Create(Transform owner, int layer)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Expected O, but got Unknown
		GameObject val = new GameObject("Pinozen orbit accessory");
		try
		{
			val.AddComponent<PinozenPspMarker>();
			val.layer = layer;
			val.transform.SetParent(owner, false);
			for (int i = 0; i < meshes.Count; i++)
			{
				GameObject val2 = new GameObject(data.meshes[i].name);
				val2.layer = layer;
				val2.transform.SetParent(val.transform, false);
				val2.AddComponent<MeshFilter>().sharedMesh = meshes[i];
				MeshRenderer val3 = val2.AddComponent<MeshRenderer>();
				((Renderer)val3).sharedMaterial = materials[data.meshes[i].material];
				((Renderer)val3).shadowCastingMode = (ShadowCastingMode)1;
				((Renderer)val3).receiveShadows = true;
			}
			return val;
		}
		catch
		{
			Object.Destroy((Object)(object)val);
			throw;
		}
	}

	internal static Mesh HandMesh(Renderer renderer)
	{
		SkinnedMeshRenderer val = (SkinnedMeshRenderer)(object)((renderer is SkinnedMeshRenderer) ? renderer : null);
		if ((Object)(object)val != (Object)null)
		{
			return val.sharedMesh;
		}
		MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>();
		if (!((Object)(object)component == (Object)null))
		{
			return component.sharedMesh;
		}
		return null;
	}

	internal static string Normalize(string name)
	{
		if (name == null)
		{
			return "";
		}
		StringBuilder stringBuilder = new StringBuilder();
		foreach (char c in name)
		{
			if (char.IsLetterOrDigit(c))
			{
				stringBuilder.Append(char.ToLowerInvariant(c));
			}
		}
		return stringBuilder.ToString();
	}

	private static Vector3 V(float[] a)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(a[0], a[1], a[2]);
	}

	public void Dispose()
	{
		foreach (Mesh mesh in meshes)
		{
			if ((Object)(object)mesh != (Object)null)
			{
				Object.Destroy((Object)(object)mesh);
			}
		}
		foreach (Material material in materials)
		{
			if ((Object)(object)material != (Object)null)
			{
				Object.Destroy((Object)(object)material);
			}
		}
		foreach (Texture2D solidTexture in solidTextures)
		{
			if ((Object)(object)solidTexture != (Object)null)
			{
				Object.Destroy((Object)(object)solidTexture);
			}
		}
		meshes.Clear();
		materials.Clear();
		solidTextures.Clear()

BepInEx/plugins/Migna/Migna.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Migna;

internal sealed class BodyMeshOverrides : IDisposable
{
	private sealed class Entry
	{
		internal MeshFilter Filter;

		internal Mesh Original;

		internal Mesh Replacement;
	}

	private readonly List<Entry> entries = new List<Entry>();

	internal void Add(MeshFilter filter, Mesh replacement)
	{
		if ((Object)(object)filter == (Object)null || (Object)(object)filter.sharedMesh == (Object)null || (Object)(object)replacement == (Object)null)
		{
			throw new InvalidOperationException("Missing body mesh replacement.");
		}
		foreach (Entry entry2 in entries)
		{
			if ((Object)(object)entry2.Filter == (Object)(object)filter)
			{
				throw new InvalidOperationException("Duplicate body mesh assignment.");
			}
		}
		Entry entry = new Entry();
		entry.Filter = filter;
		entry.Original = filter.sharedMesh;
		entry.Replacement = replacement;
		Entry item = entry;
		entries.Add(item);
		filter.sharedMesh = replacement;
	}

	public void Dispose()
	{
		foreach (Entry entry in entries)
		{
			if ((Object)(object)entry.Filter != (Object)null && (Object)(object)entry.Filter.sharedMesh == (Object)(object)entry.Replacement)
			{
				entry.Filter.sharedMesh = entry.Original;
			}
		}
		entries.Clear();
	}
}
internal sealed class HitFlash : IDisposable
{
	private sealed class Surface
	{
		internal Material Material;

		internal Color Color;

		internal Color Emission;

		internal bool Native;
	}

	private sealed class Target
	{
		internal Renderer Renderer;

		internal Material[] Original;

		internal Material[] Replacement;
	}

	private static readonly FieldInfo NativeMaterials = typeof(EnemyHealth).GetField("instancedMaterials", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly int OverlayColor = Shader.PropertyToID("_ColorOverlay");

	private static readonly int OverlayAmount = Shader.PropertyToID("_ColorOverlayAmount");

	private static readonly int BaseColor = Shader.PropertyToID("_Color");

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

	private static readonly int BodyAlbedo = Shader.PropertyToID("_AlbedoTexture");

	private readonly List<Surface> surfaces = new List<Surface>();

	private readonly List<Target> targets = new List<Target>();

	private readonly Dictionary<Material, Material> copies = new Dictionary<Material, Material>();

	private readonly Action<string> log;

	private Material source;

	private float lastAmount = -1f;

	private Color lastColor;

	private bool hitObserved;

	private bool resetObserved;

	internal HitFlash(EnemyHealth health, Renderer original, Action<string> logger)
	{
		log = logger;
		if ((Object)(object)original != (Object)null && Compatible(original.sharedMaterial))
		{
			source = original.sharedMaterial;
		}
		if ((Object)(object)source == (Object)null && (Object)(object)health != (Object)null && NativeMaterials != null && NativeMaterials.GetValue(health) is List<Material> list)
		{
			foreach (Material item in list)
			{
				if (Compatible(item))
				{
					source = item;
					break;
				}
			}
		}
		if ((Object)(object)source == (Object)null)
		{
			throw new InvalidOperationException("Rugrat native damage material is unavailable.");
		}
	}

	private static bool Compatible(Material material)
	{
		if ((Object)(object)material != (Object)null && material.HasProperty(OverlayColor))
		{
			return material.HasProperty(OverlayAmount);
		}
		return false;
	}

	internal void Add(Renderer renderer, Texture2D bodyTexture)
	{
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Expected O, but got Unknown
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		bool flag = (Object)(object)bodyTexture != (Object)null;
		Material[] sharedMaterials = renderer.sharedMaterials;
		Material[] array = (Material[])sharedMaterials.Clone();
		if (sharedMaterials.Length == 0)
		{
			throw new InvalidOperationException("Missing Rugrat surface material.");
		}
		int num = 0;
		while (num < sharedMaterials.Length)
		{
			Material val = sharedMaterials[num];
			bool num2;
			if (!((Object)(object)val == (Object)null))
			{
				if (!flag)
				{
					if (val.HasProperty(BaseColor))
					{
						num2 = !val.HasProperty(EmissionColor);
						goto IL_0081;
					}
				}
				else if (Compatible(val))
				{
					num2 = !val.HasProperty(BodyAlbedo);
					goto IL_0081;
				}
			}
			goto IL_0083;
			IL_0083:
			throw new InvalidOperationException("Unexpected Rugrat surface shader.");
			IL_0081:
			if (!num2)
			{
				if (!copies.TryGetValue(val, out var value))
				{
					value = new Material(val);
					((Object)value).name = "Migna " + (flag ? "body" : "portrait") + " instance";
					Surface surface = new Surface();
					surface.Material = value;
					surface.Native = flag;
					Surface surface2 = surface;
					surfaces.Add(surface2);
					copies.Add(val, value);
					if (flag)
					{
						value.SetTexture(BodyAlbedo, (Texture)(object)bodyTexture);
					}
					else
					{
						surface2.Color = value.GetColor(BaseColor);
						surface2.Emission = (value.IsKeywordEnabled("_EMISSION") ? value.GetColor(EmissionColor) : Color.black);
						value.EnableKeyword("_EMISSION");
					}
				}
				array[num] = value;
				num++;
				continue;
			}
			goto IL_0083;
		}
		targets.Add(new Target
		{
			Renderer = renderer,
			Original = sharedMaterials,
			Replacement = array
		});
		renderer.sharedMaterials = array;
	}

	internal void Update()
	{
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0222: Unknown result type (might be due to invalid IL or missing references)
		//IL_0223: Unknown result type (might be due to invalid IL or missing references)
		float num = (((Object)(object)source == (Object)null) ? 0f : source.GetFloat(OverlayAmount));
		if (!ModelValidation.Finite(num))
		{
			num = 0f;
		}
		num = Mathf.Clamp01(num);
		Color val = (((Object)(object)source == (Object)null) ? Color.black : source.GetColor(OverlayColor));
		if (!ModelValidation.Finite(val.r) || !ModelValidation.Finite(val.g) || !ModelValidation.Finite(val.b))
		{
			num = 0f;
			val = Color.black;
		}
		if (num == lastAmount && (num == 0f || val == lastColor))
		{
			return;
		}
		foreach (Surface surface in surfaces)
		{
			if (!((Object)(object)surface.Material == (Object)null))
			{
				if (surface.Native)
				{
					surface.Material.SetColor(OverlayColor, val);
					surface.Material.SetFloat(OverlayAmount, num);
					continue;
				}
				Color val2 = surface.Color * (1f - num);
				val2.a = surface.Color.a;
				Color val3 = surface.Emission * (1f - num) + val * num;
				val3.a = surface.Emission.a;
				surface.Material.SetColor(BaseColor, val2);
				surface.Material.SetColor(EmissionColor, val3);
			}
		}
		if (!hitObserved && num > 0.05f && val.r > val.g && val.r > val.b)
		{
			hitObserved = true;
			log("Native red damage flash observed on Migna head and body; per-enemy materials.");
		}
		if (hitObserved && !resetObserved && num == 0f)
		{
			resetObserved = true;
			log("Migna native damage flash completed; original colors restored.");
		}
		lastAmount = num;
		lastColor = val;
	}

	public void Dispose()
	{
		foreach (Target target in targets)
		{
			if ((Object)(object)target.Renderer == (Object)null)
			{
				continue;
			}
			Material[] sharedMaterials = target.Renderer.sharedMaterials;
			bool flag = false;
			for (int i = 0; i < sharedMaterials.Length && i < target.Replacement.Length; i++)
			{
				if ((Object)(object)sharedMaterials[i] == (Object)(object)target.Replacement[i] && (Object)(object)sharedMaterials[i] != (Object)(object)target.Original[i])
				{
					sharedMaterials[i] = target.Original[i];
					flag = true;
				}
			}
			if (flag)
			{
				target.Renderer.sharedMaterials = sharedMaterials;
			}
		}
		foreach (Surface surface in surfaces)
		{
			if ((Object)(object)surface.Material != (Object)null)
			{
				Object.Destroy((Object)(object)surface.Material);
			}
		}
		surfaces.Clear();
		targets.Clear();
		copies.Clear();
		source = null;
	}
}
[BepInPlugin("ittrepo.migna", "MIGNÀ", "0.1.5")]
public sealed class MignaPlugin : BaseUnityPlugin
{
	private ConfigEntry<bool> enabledSetting;

	private readonly PortraitAssets assets = new PortraitAssets();

	private readonly PortraitBindings bindings = new PortraitBindings();

	private readonly VisibleEnemyNames visibleNames = new VisibleEnemyNames();

	private readonly HashSet<int> warned = new HashSet<int>();

	private float nextScan;

	private float nextLoad;

	private bool settingsChanged;

	private string folder;

	private void Awake()
	{
		enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Replace Rugrat's appearance with Migna. Native AI, attacks and colliders remain unchanged.");
		enabledSetting.SettingChanged += SettingsChanged;
		folder = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		InstallVisibleNames();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Migna 0.1.5 loaded; Rugrat visual replacement with native head animation and per-enemy damage flash.");
	}

	private void InstallVisibleNames()
	{
		try
		{
			visibleNames.Install(delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)message);
			});
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Visible enemy labels unchanged: " + ex.Message));
		}
	}

	private void OnEnable()
	{
		if (folder != null)
		{
			InstallVisibleNames();
		}
	}

	private void SettingsChanged(object sender, EventArgs args)
	{
		settingsChanged = true;
	}

	private void Update()
	{
		if (settingsChanged)
		{
			settingsChanged = false;
			bindings.RestoreAll();
			warned.Clear();
			nextScan = 0f;
		}
		if (!enabledSetting.Value)
		{
			return;
		}
		if (!assets.Ready)
		{
			if (Time.unscaledTime < nextLoad)
			{
				return;
			}
			nextLoad = Time.unscaledTime + 15f;
			try
			{
				assets.Load(folder);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Validated Migna portrait and body geometry, face atlas and body atlas loaded.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Migna assets unavailable; original Rugrat remains visible. " + ex.Message));
				return;
			}
		}
		if (Time.unscaledTime < nextScan)
		{
			return;
		}
		nextScan = Time.unscaledTime + 1f;
		EnemyValuableThrower[] array = Object.FindObjectsByType<EnemyValuableThrower>((FindObjectsSortMode)0);
		foreach (EnemyValuableThrower val in array)
		{
			try
			{
				bindings.Apply(val, assets, delegate(string message)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)message);
				});
			}
			catch (Exception ex2)
			{
				if ((Object)(object)val != (Object)null && warned.Add(((Object)val).GetInstanceID()))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Migna replacement skipped: " + ex2.Message));
				}
			}
		}
	}

	private void LateUpdate()
	{
		if (enabledSetting != null && enabledSetting.Value)
		{
			bindings.Maintain();
		}
	}

	private void OnDisable()
	{
		visibleNames.Dispose();
		bindings.RestoreAll();
		nextScan = 0f;
	}

	private void OnDestroy()
	{
		if (enabledSetting != null)
		{
			enabledSetting.SettingChanged -= SettingsChanged;
		}
		visibleNames.Dispose();
		bindings.RestoreAll();
		assets.Dispose();
	}
}
internal sealed class ModelData
{
	public int version;

	public MeshData[] meshes;

	public ReferenceBounds referenceBounds;
}
internal sealed class ReferenceBounds
{
	public float[] min;

	public float[] max;
}
internal sealed class MeshData
{
	public string name;

	public float[] vertices;

	public float[] normals;

	public float[] uv;

	public int[] triangles;

	public int material;
}
internal static class ModelValidation
{
	internal static readonly Dictionary<string, int> NativeBodyVertices = new Dictionary<string, int>(StringComparer.Ordinal)
	{
		{ "body", 334 },
		{ "arm_straight_R", 115 },
		{ "arm_bent_R", 115 },
		{ "arm_straight_L", 115 },
		{ "arm_bent_L", 115 },
		{ "leg_straight_R", 44 },
		{ "leg_bent_R", 49 },
		{ "leg_straight_L", 46 },
		{ "leg_bent_L", 55 }
	};

	internal static bool Finite(float value)
	{
		if (!float.IsNaN(value))
		{
			return !float.IsInfinity(value);
		}
		return false;
	}

	private static void Require(bool value, string message)
	{
		if (!value)
		{
			throw new InvalidDataException(message);
		}
	}

	internal static ModelData Read(string json)
	{
		return Read(json, body: false);
	}

	internal static ModelData ReadBody(string json)
	{
		return Read(json, body: true);
	}

	private static ModelData Read(string json, bool body)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		JsonSerializerSettings val = new JsonSerializerSettings();
		val.TypeNameHandling = (TypeNameHandling)0;
		val.MetadataPropertyHandling = (MetadataPropertyHandling)2;
		val.MaxDepth = 24;
		val.Culture = CultureInfo.InvariantCulture;
		ModelData modelData = JsonConvert.DeserializeObject<ModelData>(json, val);
		Validate(modelData);
		if (body)
		{
			ValidateBody(modelData);
		}
		return modelData;
	}

	internal static void ValidateBody(ModelData data)
	{
		Validate(data);
		Require(data.meshes.Length == NativeBodyVertices.Count, "Missing body animation variants.");
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		MeshData[] meshes = data.meshes;
		foreach (MeshData meshData in meshes)
		{
			Require(NativeBodyVertices.ContainsKey(meshData.name) && hashSet.Add(meshData.name), "Unknown or duplicate body animation variant.");
			Require(meshData.material == 0, "Unsupported body material.");
		}
	}

	internal static void Validate(ModelData data)
	{
		Require(data != null && data.version == 1, "Unsupported portrait format.");
		Require(data.meshes != null && data.meshes.Length > 0 && data.meshes.Length <= 12, "Invalid portrait pieces.");
		Require(data.referenceBounds != null && data.referenceBounds.min != null && data.referenceBounds.max != null && data.referenceBounds.min.Length == 3 && data.referenceBounds.max.Length == 3, "Missing reference bounds.");
		for (int i = 0; i < 3; i++)
		{
			Require(Finite(data.referenceBounds.min[i]) && Finite(data.referenceBounds.max[i]) && data.referenceBounds.max[i] > data.referenceBounds.min[i] && data.referenceBounds.max[i] - data.referenceBounds.min[i] < 2f, "Invalid reference bounds.");
		}
		int num = 0;
		MeshData[] meshes = data.meshes;
		foreach (MeshData meshData in meshes)
		{
			Require(meshData != null && !string.IsNullOrEmpty(meshData.name) && meshData.name.Length <= 64 && meshData.name.IndexOfAny(new char[3] { '/', '\\', ':' }) < 0, "Invalid mesh name.");
			Require(meshData.material == 0 || meshData.material == 1, "Invalid material index.");
			Require(meshData.vertices != null && meshData.vertices.Length >= 9 && meshData.vertices.Length % 3 == 0 && meshData.vertices.Length <= 90000, "Invalid vertices.");
			int num2 = meshData.vertices.Length / 3;
			Require(meshData.normals != null && meshData.normals.Length == meshData.vertices.Length && meshData.uv != null && meshData.uv.Length == num2 * 2, "Invalid vertex attributes.");
			Require(meshData.triangles != null && meshData.triangles.Length > 0 && meshData.triangles.Length % 3 == 0 && meshData.triangles.Length <= 30000, "Invalid triangle list.");
			num += meshData.triangles.Length / 3;
			for (int k = 0; k < num2; k++)
			{
				double num3 = 0.0;
				for (int l = 0; l < 3; l++)
				{
					float value = meshData.vertices[k * 3 + l];
					float num4 = meshData.normals[k * 3 + l];
					Require(Finite(value) && Math.Abs(value) < 2f && Finite(num4), "Non-finite or oversized vertex.");
					num3 += (double)(num4 * num4);
				}
				Require(num3 > 0.25 && num3 < 2.25, "Invalid normal.");
				Require(Finite(meshData.uv[k * 2]) && Finite(meshData.uv[k * 2 + 1]) && Math.Abs(meshData.uv[k * 2]) <= 8f && Math.Abs(meshData.uv[k * 2 + 1]) <= 8f, "Invalid UV.");
			}
			for (int m = 0; m < meshData.triangles.Length; m++)
			{
				Require(meshData.triangles[m] >= 0 && meshData.triangles[m] < num2, "Triangle index outside mesh.");
			}
			for (int n = 0; n < meshData.triangles.Length; n += 3)
			{
				int num5 = meshData.triangles[n];
				int num6 = meshData.triangles[n + 1];
				int num7 = meshData.triangles[n + 2];
				Require(num5 != num6 && num5 != num7 && num6 != num7, "Repeated triangle index.");
				double num8 = meshData.vertices[num6 * 3] - meshData.vertices[num5 * 3];
				double num9 = meshData.vertices[num6 * 3 + 1] - meshData.vertices[num5 * 3 + 1];
				double num10 = meshData.vertices[num6 * 3 + 2] - meshData.vertices[num5 * 3 + 2];
				double num11 = meshData.vertices[num7 * 3] - meshData.vertices[num5 * 3];
				double num12 = meshData.vertices[num7 * 3 + 1] - meshData.vertices[num5 * 3 + 1];
				double num13 = meshData.vertices[num7 * 3 + 2] - meshData.vertices[num5 * 3 + 2];
				double num14 = num9 * num13 - num10 * num12;
				double num15 = num10 * num11 - num8 * num13;
				double num16 = num8 * num12 - num9 * num11;
				Require(num14 * num14 + num15 * num15 + num16 * num16 > 1E-20, "Degenerate triangle.");
				double num17 = num14 * (double)(meshData.normals[num5 * 3] + meshData.normals[num6 * 3] + meshData.normals[num7 * 3]) + num15 * (double)(meshData.normals[num5 * 3 + 1] + meshData.normals[num6 * 3 + 1] + meshData.normals[num7 * 3 + 1]) + num16 * (double)(meshData.normals[num5 * 3 + 2] + meshData.normals[num6 * 3 + 2] + meshData.normals[num7 * 3 + 2]);
				Require(num17 > 0.0, "Triangle winding disagrees with outward normals.");
			}
		}
		Require(num <= 10000, "Portrait exceeds triangle safety limit.");
	}
}
internal sealed class PortraitAssets : IDisposable
{
	internal sealed class Piece
	{
		internal string Name;

		internal Mesh Mesh;

		internal int Material;
	}

	internal Piece[] Pieces;

	internal readonly Dictionary<string, Mesh> BodyPieces = new Dictionary<string, Mesh>(StringComparer.Ordinal);

	internal Material Skin;

	internal Material Accessory;

	internal Texture2D BodyTexture;

	private Texture2D headTexture;

	internal bool Ready
	{
		get
		{
			if (Pieces != null && BodyPieces.Count == 9 && (Object)(object)Skin != (Object)null && (Object)(object)Accessory != (Object)null)
			{
				return (Object)(object)BodyTexture != (Object)null;
			}
			return false;
		}
	}

	private static byte[] Read(string folder, string name)
	{
		FileInfo fileInfo = new FileInfo(Path.Combine(folder, name));
		if (!fileInfo.Exists || fileInfo.Length <= 0 || fileInfo.Length > 25165824)
		{
			throw new InvalidDataException("Missing or oversized " + name);
		}
		return File.ReadAllBytes(fileInfo.FullName);
	}

	private static Texture2D Texture(string folder, string name, int requiredSize)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true, false);
		try
		{
			if (!ImageConversion.LoadImage(val, Read(folder, name), true))
			{
				throw new InvalidDataException("Invalid texture " + name);
			}
			if (((Texture)val).width != ((Texture)val).height || ((Texture)val).width < 256 || ((Texture)val).width > 2048 || (((Texture)val).width & (((Texture)val).width - 1)) != 0 || (requiredSize > 0 && ((Texture)val).width != requiredSize))
			{
				throw new InvalidDataException("Unsupported texture dimensions: " + name);
			}
			((Object)val).name = name;
			((Texture)val).wrapMode = (TextureWrapMode)0;
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).anisoLevel = 2;
			return val;
		}
		catch
		{
			Object.Destroy((Object)(object)val);
			throw;
		}
	}

	internal void Load(string folder)
	{
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Expected O, but got Unknown
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Expected O, but got Unknown
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Expected O, but got Unknown
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_022e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0256: Unknown result type (might be due to invalid IL or missing references)
		//IL_025b: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f5: Expected O, but got Unknown
		//IL_036a: Unknown result type (might be due to invalid IL or missing references)
		//IL_036f: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d7: Unknown result type (might be due to invalid IL or missing references)
		if (Ready)
		{
			return;
		}
		ModelData modelData = ModelValidation.Read(Encoding.UTF8.GetString(Read(folder, "migna_head.mesh.json")));
		ModelData modelData2 = ModelValidation.ReadBody(Encoding.UTF8.GetString(Read(folder, "migna_body.mesh.json")));
		List<Piece> list = new List<Piece>();
		try
		{
			headTexture = Texture(folder, "Migna_BaseColor.png", 2048);
			BodyTexture = Texture(folder, "Migna_Body_BaseColor.png", 0);
			Shader val = Shader.Find("Standard");
			if ((Object)(object)val == (Object)null || !val.isSupported)
			{
				throw new InvalidDataException("Supported Standard shader is required for portrait and damage flash.");
			}
			Skin = new Material(val);
			((Object)Skin).name = "Migna portrait";
			Skin.SetTexture("_MainTex", (Texture)(object)headTexture);
			Skin.SetColor("_Color", Color.white);
			Skin.SetFloat("_Metallic", 0f);
			Skin.SetFloat("_Glossiness", 0.12f);
			Accessory = new Material(Skin);
			((Object)Accessory).name = "Migna glasses";
			Accessory.SetFloat("_Glossiness", 0.35f);
			MeshData[] meshes = modelData.meshes;
			foreach (MeshData meshData in meshes)
			{
				Mesh val2 = new Mesh();
				list.Add(new Piece
				{
					Name = meshData.name,
					Mesh = val2,
					Material = meshData.material
				});
				int num = meshData.vertices.Length / 3;
				Vector3[] array = (Vector3[])(object)new Vector3[num];
				Vector3[] array2 = (Vector3[])(object)new Vector3[num];
				Vector2[] array3 = (Vector2[])(object)new Vector2[num];
				for (int j = 0; j < num; j++)
				{
					ref Vector3 reference = ref array[j];
					reference = new Vector3(meshData.vertices[j * 3], meshData.vertices[j * 3 + 1], meshData.vertices[j * 3 + 2]);
					ref Vector3 reference2 = ref array2[j];
					reference2 = new Vector3(meshData.normals[j * 3], meshData.normals[j * 3 + 1], meshData.normals[j * 3 + 2]);
					ref Vector2 reference3 = ref array3[j];
					reference3 = new Vector2(meshData.uv[j * 2], meshData.uv[j * 2 + 1]);
				}
				((Object)val2).name = "Migna " + meshData.name;
				val2.vertices = array;
				val2.normals = array2;
				val2.uv = array3;
				val2.triangles = meshData.triangles;
				val2.RecalculateBounds();
				val2.RecalculateTangents();
				val2.UploadMeshData(true);
			}
			MeshData[] meshes2 = modelData2.meshes;
			foreach (MeshData meshData2 in meshes2)
			{
				Mesh val3 = new Mesh();
				BodyPieces.Add(meshData2.name, val3);
				int num2 = meshData2.vertices.Length / 3;
				Vector3[] array4 = (Vector3[])(object)new Vector3[num2];
				Vector3[] array5 = (Vector3[])(object)new Vector3[num2];
				Vector2[] array6 = (Vector2[])(object)new Vector2[num2];
				for (int l = 0; l < num2; l++)
				{
					ref Vector3 reference4 = ref array4[l];
					reference4 = new Vector3(meshData2.vertices[l * 3], meshData2.vertices[l * 3 + 1], meshData2.vertices[l * 3 + 2]);
					ref Vector3 reference5 = ref array5[l];
					reference5 = new Vector3(meshData2.normals[l * 3], meshData2.normals[l * 3 + 1], meshData2.normals[l * 3 + 2]);
					ref Vector2 reference6 = ref array6[l];
					reference6 = new Vector2(meshData2.uv[l * 2], meshData2.uv[l * 2 + 1]);
				}
				((Object)val3).name = "Migna " + meshData2.name;
				val3.vertices = array4;
				val3.normals = array5;
				val3.uv = array6;
				val3.triangles = meshData2.triangles;
				val3.RecalculateBounds();
				val3.RecalculateTangents();
				val3.UploadMeshData(true);
			}
			Pieces = list.ToArray();
		}
		catch
		{
			foreach (Piece item in list)
			{
				if ((Object)(object)item.Mesh != (Object)null)
				{
					Object.Destroy((Object)(object)item.Mesh);
				}
			}
			Dispose();
			throw;
		}
	}

	public void Dispose()
	{
		if (Pieces != null)
		{
			Piece[] pieces = Pieces;
			foreach (Piece piece in pieces)
			{
				if ((Object)(object)piece.Mesh != (Object)null)
				{
					Object.Destroy((Object)(object)piece.Mesh);
				}
			}
		}
		Pieces = null;
		foreach (Mesh value in BodyPieces.Values)
		{
			if ((Object)(object)value != (Object)null)
			{
				Object.Destroy((Object)(object)value);
			}
		}
		BodyPieces.Clear();
		if ((Object)(object)Skin != (Object)null)
		{
			Object.Destroy((Object)(object)Skin);
		}
		if ((Object)(object)Accessory != (Object)null)
		{
			Object.Destroy((Object)(object)Accessory);
		}
		if ((Object)(object)headTexture != (Object)null)
		{
			Object.Destroy((Object)(object)headTexture);
		}
		if ((Object)(object)BodyTexture != (Object)null)
		{
			Object.Destroy((Object)(object)BodyTexture);
		}
		Skin = null;
		Accessory = null;
		headTexture = null;
		BodyTexture = null;
	}
}
internal sealed class PortraitBindings
{
	private sealed class Hidden
	{
		internal Renderer Renderer;

		internal bool ForceOff;
	}

	private sealed class Binding
	{
		internal EnemyValuableThrower Controller;

		internal EnemyParent Owner;

		internal MeshRenderer OriginalHead;

		internal GameObject Root;

		internal HitFlash Flash;

		internal readonly BodyMeshOverrides Body = new BodyMeshOverrides();

		internal readonly List<Hidden> Hidden = new List<Hidden>();
	}

	private readonly Dictionary<int, Binding> bindings = new Dictionary<int, Binding>();

	private readonly List<int> expired = new List<int>();

	private static readonly HashSet<string> BodyMeshes = new HashSet<string>(StringComparer.Ordinal) { "body", "arm_straight_R", "arm_bent_R", "arm_straight_L", "arm_bent_L", "leg_straight_R", "leg_bent_R", "leg_straight_L", "leg_bent_L" };

	internal bool Apply(EnemyValuableThrower controller, PortraitAssets assets, Action<string> log)
	{
		//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_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0220: Unknown result type (might be due to invalid IL or missing references)
		//IL_0225: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0244: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Unknown result type (might be due to invalid IL or missing references)
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Unknown result type (might be due to invalid IL or missing references)
		//IL_029a: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c1: 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_03ae: Expected O, but got Unknown
		//IL_0408: Unknown result type (might be due to invalid IL or missing references)
		//IL_040f: Expected O, but got Unknown
		//IL_0470: Unknown result type (might be due to invalid IL or missing references)
		//IL_048c: Unknown result type (might be due to invalid IL or missing references)
		//IL_049a: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)controller == (Object)null))
		{
			Scene scene = ((Component)controller).gameObject.scene;
			if (((Scene)(ref scene)).IsValid() && assets.Ready)
			{
				int instanceID = ((Object)controller).GetInstanceID();
				if (bindings.ContainsKey(instanceID))
				{
					return true;
				}
				EnemyParent componentInParent = ((Component)controller).GetComponentInParent<EnemyParent>();
				EnemyValuableThrowerAnim anim = controller.anim;
				if ((Object)(object)componentInParent == (Object)null || (Object)(object)anim == (Object)null || (Object)(object)((Component)anim).GetComponentInParent<EnemyParent>() != (Object)(object)componentInParent || (Object)(object)anim.controller != (Object)(object)controller)
				{
					throw new InvalidOperationException("Verified Rugrat animation owner is unavailable.");
				}
				Transform val = null;
				Transform[] componentsInChildren = ((Component)anim).GetComponentsInChildren<Transform>(true);
				foreach (Transform val2 in componentsInChildren)
				{
					if (((Object)val2).name == "ANIM HEAD")
					{
						if ((Object)(object)val != (Object)null)
						{
							throw new InvalidOperationException("Ambiguous Rugrat head anchors.");
						}
						val = val2;
					}
				}
				if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).GetComponentInParent<EnemyParent>() != (Object)(object)componentInParent) && !((Object)(object)val.parent == (Object)null) && !((Object)(object)val.parent.parent == (Object)null) && !(((Object)val.parent.parent).name != "ANIM BODY"))
				{
					Vector3 val3 = val.parent.localPosition - new Vector3(0f, 0.27126074f, -0.01176444f);
					if (!(((Vector3)(ref val3)).sqrMagnitude > 1E-06f))
					{
						Transform val4 = val.Find("mesh head");
						MeshFilter val5 = (((Object)(object)val4 == (Object)null) ? null : ((Component)val4).GetComponent<MeshFilter>());
						MeshRenderer val6 = (((Object)(object)val4 == (Object)null) ? null : ((Component)val4).GetComponent<MeshRenderer>());
						if (!((Object)(object)val5 == (Object)null) && !((Object)(object)val6 == (Object)null) && !((Object)(object)val5.sharedMesh == (Object)null) && !(((Object)val5.sharedMesh).name != "head") && val5.sharedMesh.vertexCount == 322)
						{
							Vector3 localPosition = val4.localPosition;
							if (!(((Vector3)(ref localPosition)).sqrMagnitude > 1E-06f))
							{
								Vector3 val7 = val4.localScale - Vector3.one;
								if (!(((Vector3)(ref val7)).sqrMagnitude > 1E-06f) && !(Quaternion.Angle(val4.localRotation, Quaternion.identity) > 0.1f))
								{
									Bounds bounds = val5.sharedMesh.bounds;
									Vector3 val8 = ((Bounds)(ref bounds)).center - new Vector3(0f, 0.15112521f, 0.13254835f);
									if (!(((Vector3)(ref val8)).sqrMagnitude > 1E-06f))
									{
										Bounds bounds2 = val5.sharedMesh.bounds;
										Vector3 val9 = ((Bounds)(ref bounds2)).extents - new Vector3(0.27643389f, 0.24636467f, 0.23048638f);
										if (!(((Vector3)(ref val9)).sqrMagnitude > 1E-06f))
										{
											Binding binding = new Binding();
											binding.Controller = controller;
											binding.Owner = componentInParent;
											binding.OriginalHead = val6;
											Binding binding2 = binding;
											try
											{
												Renderer[] componentsInChildren2 = ((Component)val4).GetComponentsInChildren<Renderer>(true);
												foreach (Renderer val10 in componentsInChildren2)
												{
													if (!(val10 is MeshRenderer) || (Object)(object)((Component)val10).GetComponentInParent<EnemyParent>() != (Object)(object)componentInParent)
													{
														throw new InvalidOperationException("Unexpected renderer in Rugrat head hierarchy.");
													}
													binding2.Hidden.Add(new Hidden
													{
														Renderer = val10,
														ForceOff = val10.forceRenderingOff
													});
												}
												if (binding2.Hidden.Count != 4)
												{
													throw new InvalidOperationException("Rugrat head/eye variant layout changed.");
												}
												binding2.Flash = new HitFlash(((Component)controller).GetComponent<EnemyHealth>(), (Renderer)(object)val6, log);
												GameObject val11 = (binding2.Root = new GameObject("Migna portrait"));
												val11.layer = ((Component)val4).gameObject.layer;
												val11.SetActive(false);
												val11.transform.SetParent(val, false);
												PortraitAssets.Piece[] pieces = assets.Pieces;
												foreach (PortraitAssets.Piece piece in pieces)
												{
													GameObject val12 = new GameObject("Migna " + piece.Name);
													val12.layer = val11.layer;
													val12.transform.SetParent(val11.transform, false);
													val12.AddComponent<MeshFilter>().sharedMesh = piece.Mesh;
													MeshRenderer val13 = val12.AddComponent<MeshRenderer>();
													((Renderer)val13).sharedMaterial = ((piece.Material == 1) ? assets.Accessory : assets.Skin);
													((Renderer)val13).shadowCastingMode = ((Renderer)val6).shadowCastingMode;
													((Renderer)val13).receiveShadows = ((Renderer)val6).receiveShadows;
													((Renderer)val13).lightProbeUsage = ((Renderer)val6).lightProbeUsage;
													((Renderer)val13).reflectionProbeUsage = ((Renderer)val6).reflectionProbeUsage;
													binding2.Flash.Add((Renderer)(object)val13, null);
												}
												HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
												MeshFilter[] componentsInChildren3 = ((Component)anim).GetComponentsInChildren<MeshFilter>(true);
												foreach (MeshFilter val14 in componentsInChildren3)
												{
													if (!((Object)(object)val14.sharedMesh == (Object)null) && BodyMeshes.Contains(((Object)val14.sharedMesh).name) && !((Component)val14).transform.IsChildOf(val4))
													{
														MeshRenderer component = ((Component)val14).GetComponent<MeshRenderer>();
														if ((Object)(object)component == (Object)null || (Object)(object)((Component)component).GetComponentInParent<EnemyParent>() != (Object)(object)componentInParent)
														{
															throw new InvalidOperationException("Unexpected Rugrat body owner.");
														}
														string name = ((Object)val14.sharedMesh).name;
														if (!hashSet.Add(name) || val14.sharedMesh.vertexCount != ModelValidation.NativeBodyVertices[name])
														{
															throw new InvalidOperationException("Rugrat body geometry calibration changed.");
														}
														binding2.Flash.Add((Renderer)(object)component, assets.BodyTexture);
														binding2.Body.Add(val14, assets.BodyPieces[name]);
													}
												}
												if (hashSet.Count != 9)
												{
													throw new InvalidOperationException("Rugrat body variant layout changed.");
												}
												bindings.Add(instanceID, binding2);
												Maintain(binding2);
												log("Migna attached to native Rugrat ANIM HEAD; 4 original head surfaces hidden, 9 body variants use the custom shape; native animation transforms, AI, attacks, collisions and spawn identifiers preserved.");
												return true;
											}
											catch
											{
												bindings.Remove(instanceID);
												Restore(binding2);
												throw;
											}
										}
									}
								}
							}
						}
						throw new InvalidOperationException("Rugrat head calibration changed; keeping the original model.");
					}
				}
				throw new InvalidOperationException("Verified Rugrat head anchor is missing.");
			}
		}
		return false;
	}

	private static void Maintain(Binding binding)
	{
		foreach (Hidden item in binding.Hidden)
		{
			if ((Object)(object)item.Renderer != (Object)null)
			{
				item.Renderer.forceRenderingOff = true;
			}
		}
		if ((Object)(object)binding.Root != (Object)null && (Object)(object)binding.OriginalHead != (Object)null)
		{
			bool flag = ((Renderer)binding.OriginalHead).enabled && ((Component)binding.OriginalHead).gameObject.activeInHierarchy && !binding.Hidden[0].ForceOff;
			if (binding.Root.activeSelf != flag)
			{
				binding.Root.SetActive(flag);
			}
		}
		if (binding.Flash != null)
		{
			binding.Flash.Update();
		}
	}

	internal void Maintain()
	{
		expired.Clear();
		foreach (KeyValuePair<int, Binding> binding in bindings)
		{
			if ((Object)(object)binding.Value.Controller == (Object)null || (Object)(object)binding.Value.Owner == (Object)null || (Object)(object)binding.Value.Root == (Object)null)
			{
				Restore(binding.Value);
				expired.Add(binding.Key);
			}
			else
			{
				Maintain(binding.Value);
			}
		}
		foreach (int item in expired)
		{
			bindings.Remove(item);
		}
	}

	private static void Restore(Binding binding)
	{
		binding.Body.Dispose();
		if (binding.Flash != null)
		{
			binding.Flash.Dispose();
			binding.Flash = null;
		}
		foreach (Hidden item in binding.Hidden)
		{
			if ((Object)(object)item.Renderer != (Object)null)
			{
				item.Renderer.forceRenderingOff = item.ForceOff;
			}
		}
		if ((Object)(object)binding.Root != (Object)null)
		{
			binding.Root.SetActive(false);
			Object.Destroy((Object)(object)binding.Root);
		}
		binding.Hidden.Clear();
		binding.Root = null;
	}

	internal void RestoreAll()
	{
		foreach (Binding value in bindings.Values)
		{
			Restore(value);
		}
		bindings.Clear();
	}
}
internal sealed class VisibleEnemyNames : IDisposable
{
	private const string PatchId = "ittrepo.migna.visible_names";

	private static readonly FieldInfo Parent = AccessTools.Field(typeof(EnemyRigidbody), "enemyParent");

	private static readonly MethodInfo Tooltip = AccessTools.Method(typeof(ItemInfoUI), "ItemInfoText", new Type[3]
	{
		typeof(ItemAttributes),
		typeof(string),
		typeof(bool)
	}, (Type[])null);

	private Harmony harmony;

	internal void Install(Action<string> log)
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Expected O, but got Unknown
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Expected O, but got Unknown
		if (harmony != null)
		{
			return;
		}
		MethodInfo methodInfo = AccessTools.Method(typeof(EnemyRigidbody), "Update", (Type[])null, (Type[])null);
		if (Parent == null || Parent.FieldType != typeof(EnemyParent) || Tooltip == null || methodInfo == null)
		{
			throw new InvalidOperationException("Native tooltip contract changed; original labels retained.");
		}
		Harmony val = new Harmony("ittrepo.migna.visible_names");
		try
		{
			val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(VisibleEnemyNames), "TooltipTextOnly", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony = val;
			log("Visible grab labels: PINOZEN, PENNISI, MIGNÀ. Canonical spawn names and localization assets unchanged.");
		}
		catch
		{
			val.UnpatchSelf();
			throw;
		}
	}

	private static IEnumerable<CodeInstruction> TooltipTextOnly(IEnumerable<CodeInstruction> input)
	{
		List<CodeInstruction> code = new List<CodeInstruction>(input);
		MethodInfo resolve = AccessTools.Method(typeof(VisibleEnemyNames), "Resolve", (Type[])null, (Type[])null);
		int matches = 0;
		for (int i = 0; i < code.Count; i++)
		{
			CodeInstruction instruction = code[i];
			if (instruction.opcode == OpCodes.Ldc_I4_1 && i > 0 && i + 1 < code.Count && code[i - 1].opcode == OpCodes.Ldloc_0 && CodeInstructionExtensions.Calls(code[i + 1], Tooltip))
			{
				CodeInstruction actor = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
				actor.labels.AddRange(instruction.labels);
				instruction.labels.Clear();
				actor.blocks.AddRange(instruction.blocks);
				instruction.blocks.Clear();
				yield return actor;
				yield return new CodeInstruction(OpCodes.Call, (object)resolve);
				matches++;
			}
			yield return instruction;
		}
		if (matches != 1)
		{
			throw new InvalidOperationException("Expected one native grab-tooltip call; presentation patch cancelled.");
		}
	}

	private static string Resolve(string original, EnemyRigidbody body)
	{
		if ((Object)(object)body == (Object)null || Parent == null)
		{
			return original;
		}
		object? value = Parent.GetValue(body);
		EnemyParent val = (EnemyParent)((value is EnemyParent) ? value : null);
		if ((Object)(object)val == (Object)null)
		{
			return original;
		}
		string text = null;
		MeshFilter[] componentsInChildren = ((Component)val).GetComponentsInChildren<MeshFilter>(false);
		foreach (MeshFilter val2 in componentsInChildren)
		{
			if ((Object)(object)val2.sharedMesh == (Object)null || (Object)(object)((Component)val2).GetComponentInParent<EnemyParent>() != (Object)(object)val)
			{
				continue;
			}
			string text2 = null;
			switch (((Object)val2.sharedMesh).name)
			{
			case "Migna head":
				text2 = "MIGNÀ";
				break;
			case "Pinozen Modeled Head":
				text2 = "PINOZEN";
				break;
			case "HeadmanPortrait skinned head":
				text2 = "PENNISI";
				break;
			}
			if (text2 != null)
			{
				if (text != null && text != text2)
				{
					return original;
				}
				text = text2;
			}
		}
		return text ?? original;
	}

	public void Dispose()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
			harmony = null;
		}
	}
}

BepInEx/plugins/Pennisi/Pennisi.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: AssemblyTitle("Pennisi")]
[assembly: AssemblyDescription("Pennisi: an animated visual replacement for the R.E.P.O. Headman enemy")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyVersion("1.0.4.0")]
namespace HeadmanPortrait;

internal static class DisplayNamePolicy
{
	internal const string Target = "Pennisi";

	internal static bool Original(string value)
	{
		return string.Equals(value, "Headman", StringComparison.Ordinal);
	}

	internal static bool SamePrefab(string instanceName, string prefabName)
	{
		if (!(instanceName == prefabName) && !(instanceName == prefabName + "(Clone)"))
		{
			return instanceName == prefabName + " (Clone)";
		}
		return true;
	}

	internal static bool Owns(string currentName, object currentLocalized, bool actor)
	{
		if (currentName == "Pennisi")
		{
			if (actor)
			{
				return currentLocalized == null;
			}
			return true;
		}
		return false;
	}
}
internal sealed class EnemyDisplayName
{
	private sealed class Binding
	{
		internal Component Parent;

		internal string OriginalName;

		internal string TechnicalName;

		internal object OriginalLocalized;

		internal bool Actor;
	}

	private readonly Dictionary<int, Binding> bindings = new Dictionary<int, Binding>();

	private Type parentType;

	private FieldInfo nameField;

	private FieldInfo localizedField;

	private static FieldInfo Field(Type type, string name)
	{
		Type type2 = type;
		while (type2 != null)
		{
			FieldInfo field = type2.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				return field;
			}
			type2 = type2.BaseType;
		}
		return null;
	}

	private bool Resolve()
	{
		if (parentType != null)
		{
			return true;
		}
		Type typeFromHandle = typeof(EnemyParent);
		if (typeFromHandle == null || !typeof(Component).IsAssignableFrom(typeFromHandle))
		{
			return false;
		}
		FieldInfo fieldInfo = Field(typeFromHandle, "enemyName");
		FieldInfo fieldInfo2 = Field(typeFromHandle, "enemyNameLocalized");
		if (fieldInfo == null || fieldInfo.FieldType != typeof(string) || fieldInfo2 == null || fieldInfo2.FieldType.IsValueType)
		{
			return false;
		}
		parentType = typeFromHandle;
		nameField = fieldInfo;
		localizedField = fieldInfo2;
		return true;
	}

	private bool Verified(Component parent)
	{
		EnemyHeadController[] componentsInChildren = parent.GetComponentsInChildren<EnemyHeadController>(true);
		foreach (EnemyHeadController val in componentsInChildren)
		{
			Component componentInParent = (Component)(object)((Component)val).GetComponentInParent<EnemyParent>();
			if ((Object)(object)componentInParent != (Object)(object)parent)
			{
				continue;
			}
			Component componentInParent2 = (Component)(object)((Component)val).GetComponentInParent<Enemy>();
			if ((Object)(object)componentInParent2 == (Object)null || !componentInParent2.transform.IsChildOf(parent.transform) || (Object)(object)componentInParent2.GetComponentInParent<EnemyParent>() != (Object)(object)parent)
			{
				continue;
			}
			FieldInfo fieldInfo = Field(typeof(EnemyHeadController), "Enemy");
			Component val2 = (Component)((fieldInfo == null) ? null : /*isinst with value type is only supported in some contexts*/);
			if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)componentInParent2)
			{
				continue;
			}
			FieldInfo fieldInfo2 = Field(((object)componentInParent2).GetType(), "EnemyParent");
			Component val3 = (Component)((fieldInfo2 == null) ? null : /*isinst with value type is only supported in some contexts*/);
			if (!((Object)(object)val3 != (Object)null) || !((Object)(object)val3 != (Object)(object)parent))
			{
				FieldInfo fieldInfo3 = Field(parentType, "Enemy");
				Component val4 = (Component)((fieldInfo3 == null) ? null : /*isinst with value type is only supported in some contexts*/);
				if (!((Object)(object)val4 != (Object)null) || !((Object)(object)val4 != (Object)(object)componentInParent2))
				{
					return true;
				}
			}
		}
		return false;
	}

	private Binding SourceFor(Component actor)
	{
		foreach (Binding value in bindings.Values)
		{
			if (!value.Actor && (Object)(object)value.Parent != (Object)null && DisplayNamePolicy.SamePrefab(((Object)actor).name, value.TechnicalName))
			{
				return value;
			}
		}
		return null;
	}

	private void Bind(Component parent, bool actor, Action<string> log)
	{
		int instanceID = ((Object)parent).GetInstanceID();
		if (bindings.ContainsKey(instanceID) || !Verified(parent))
		{
			return;
		}
		string text = nameField.GetValue(parent) as string;
		if (!DisplayNamePolicy.Original(text))
		{
			Binding binding = ((actor && text == "Pennisi") ? SourceFor(parent) : null);
			if (binding == null)
			{
				return;
			}
			text = binding.OriginalName;
		}
		Binding binding2 = new Binding();
		binding2.Parent = parent;
		binding2.Actor = actor;
		binding2.OriginalName = text;
		binding2.OriginalLocalized = localizedField.GetValue(parent);
		binding2.TechnicalName = ((Object)parent).name;
		Binding binding3 = binding2;
		bindings.Add(instanceID, binding3);
		try
		{
			nameField.SetValue(parent, "Pennisi");
			if (actor)
			{
				localizedField.SetValue(parent, null);
			}
		}
		catch
		{
			nameField.SetValue(parent, binding3.OriginalName);
			if (actor)
			{
				localizedField.SetValue(parent, binding3.OriginalLocalized);
			}
			bindings.Remove(instanceID);
			throw;
		}
		log((actor ? "ACTOR" : "PREFAB") + "; technicalName=" + binding3.TechnicalName + "; displayName=Pennisi; localizedFallback=" + (actor ? "disabled" : "preserved"));
	}

	internal void Apply(Action<string> log)
	{
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: 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)
		if (!Resolve())
		{
			throw new InvalidOperationException("Native enemy display fields are unavailable; presentation names were not changed.");
		}
		List<int> list = new List<int>();
		foreach (KeyValuePair<int, Binding> binding in bindings)
		{
			if ((Object)(object)binding.Value.Parent == (Object)null)
			{
				list.Add(binding.Key);
			}
		}
		foreach (int item in list)
		{
			bindings.Remove(item);
		}
		Object[] array = Resources.FindObjectsOfTypeAll(parentType);
		Object[] array2 = array;
		foreach (Object val in array2)
		{
			Component val2 = (Component)(object)((val is Component) ? val : null);
			if ((Object)(object)val2 != (Object)null)
			{
				Scene scene = val2.gameObject.scene;
				if (!((Scene)(ref scene)).IsValid())
				{
					Bind(val2, actor: false, log);
				}
			}
		}
		Object[] array3 = array;
		foreach (Object val3 in array3)
		{
			Component val4 = (Component)(object)((val3 is Component) ? val3 : null);
			if ((Object)(object)val4 != (Object)null)
			{
				Scene scene2 = val4.gameObject.scene;
				if (((Scene)(ref scene2)).IsValid())
				{
					Bind(val4, actor: true, log);
				}
			}
		}
	}

	internal void RestoreAll()
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		if (bindings.Count == 0)
		{
			return;
		}
		Object[] array = Resources.FindObjectsOfTypeAll(parentType);
		foreach (Object val in array)
		{
			Component val2 = (Component)(object)((val is Component) ? val : null);
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			Scene scene = val2.gameObject.scene;
			if (((Scene)(ref scene)).IsValid() && !bindings.ContainsKey(((Object)val2).GetInstanceID()))
			{
				Binding binding = SourceFor(val2);
				if (binding != null && nameField.GetValue(val2) as string == "Pennisi" && Verified(val2))
				{
					nameField.SetValue(val2, binding.OriginalName);
				}
			}
		}
		foreach (Binding value in bindings.Values)
		{
			if ((Object)(object)value.Parent != (Object)null && DisplayNamePolicy.Owns(nameField.GetValue(value.Parent) as string, localizedField.GetValue(value.Parent), value.Actor))
			{
				nameField.SetValue(value.Parent, value.OriginalName);
				if (value.Actor)
				{
					localizedField.SetValue(value.Parent, value.OriginalLocalized);
				}
			}
		}
		bindings.Clear();
	}
}
internal static class FacialMotion
{
	internal static float Clamp01(float value)
	{
		return Math.Max(0f, Math.Min(1f, value));
	}

	internal static float SignedDegrees(float angle)
	{
		if (!HeadValidation.Finite(angle))
		{
			return 0f;
		}
		float num = angle % 360f;
		if (num > 180f)
		{
			num -= 360f;
		}
		if (num < -180f)
		{
			num += 360f;
		}
		return num;
	}

	internal static float JawOpening(bool bite, float bottomGumPitch, float topGumPitch, bool closed, bool halfOpen, bool chase)
	{
		if (bite)
		{
			return Clamp01((SignedDegrees(bottomGumPitch) - SignedDegrees(topGumPitch)) / 60f);
		}
		if (closed)
		{
			return 0f;
		}
		if (chase)
		{
			return 0.72f;
		}
		if (!halfOpen)
		{
			return 0f;
		}
		return 0.5f;
	}

	internal static float Blink(float elapsed)
	{
		if (elapsed < 0f || elapsed >= 0.2f || !HeadValidation.Finite(elapsed))
		{
			return 0f;
		}
		if (elapsed < 0.065f)
		{
			return Smooth(elapsed / 0.065f);
		}
		if (elapsed <= 0.105f)
		{
			return 1f;
		}
		return 1f - Smooth((elapsed - 0.105f) / 0.095f);
	}

	internal static float TongueOpening(bool nativeBite, float jawOpening, bool chase, bool closed)
	{
		if (!HeadValidation.Finite(jawOpening))
		{
			return 0f;
		}
		if (nativeBite)
		{
			return Clamp01(jawOpening);
		}
		if (closed || !chase)
		{
			return 0f;
		}
		return 0.92f * Clamp01(jawOpening / 0.72f);
	}

	private static float Smooth(float value)
	{
		float num = Clamp01(value);
		return num * num * (3f - 2f * num);
	}

	internal static float Follow(float deltaTime, float speed)
	{
		if (HeadValidation.Finite(deltaTime) && !(deltaTime <= 0f))
		{
			return 1f - (float)Math.Exp((0f - Math.Max(0f, speed)) * deltaTime);
		}
		return 0f;
	}
}
internal sealed class HeadFit
{
	internal float[] Center;

	internal float Height;

	internal float UniformScale(float referenceHeight, float multiplier)
	{
		if (!HeadValidation.Finite(referenceHeight) || referenceHeight < 0.001f || !HeadValidation.Finite(multiplier) || multiplier < 0.25f || multiplier > 3f)
		{
			throw new InvalidDataException("Invalid uniform head calibration.");
		}
		return Height / referenceHeight * multiplier;
	}
}
internal static class HeadCalibration
{
	internal static HeadFit FromIdle(float[] topCenter, float[] topExtent, float[] topPosition, float[] bottomCenter, float[] bottomExtent, float[] bottomPosition, float nativeScale)
	{
		float[][] array = new float[6][] { topCenter, topExtent, topPosition, bottomCenter, bottomExtent, bottomPosition };
		float[][] array2 = array;
		foreach (float[] array3 in array2)
		{
			if (array3 == null || array3.Length != 3)
			{
				throw new InvalidDataException("Invalid stock bounds.");
			}
			float[] array4 = array3;
			foreach (float value in array4)
			{
				if (!HeadValidation.Finite(value))
				{
					throw new InvalidDataException("Invalid stock coordinate.");
				}
			}
		}
		if (!HeadValidation.Finite(nativeScale) || nativeScale <= 0f || nativeScale > 10f)
		{
			throw new InvalidDataException("Invalid stock scale.");
		}
		HeadFit headFit = new HeadFit();
		headFit.Center = new float[3];
		HeadFit headFit2 = headFit;
		for (int k = 0; k < 3; k++)
		{
			if (topExtent[k] <= 0f || bottomExtent[k] <= 0f)
			{
				throw new InvalidDataException("Empty stock bounds.");
			}
			float num = Math.Min(topCenter[k] + topPosition[k] - topExtent[k], bottomCenter[k] + bottomPosition[k] - bottomExtent[k]) * nativeScale;
			float num2 = Math.Max(topCenter[k] + topPosition[k] + topExtent[k], bottomCenter[k] + bottomPosition[k] + bottomExtent[k]) * nativeScale;
			headFit2.Center[k] = (num + num2) * 0.5f;
			if (k == 1)
			{
				headFit2.Height = num2 - num;
			}
		}
		if (headFit2.Height < 0.05f || headFit2.Height > 10f)
		{
			throw new InvalidDataException("Unexpected stock head size.");
		}
		return headFit2;
	}
}
[Serializable]
public sealed class MeshBoundsData
{
	public float[] min;

	public float[] max;
}
[Serializable]
public sealed class HeadMeshData
{
	public string name;

	public int material;

	public float[] vertices;

	public float[] normals;

	public float[] uv;

	public int[] triangles;

	public int[] triangleMaterials;
}
[Serializable]
public sealed class JawRigData
{
	public float[] weights;

	public float[] pivot;

	public float[] axis;

	public float maxOpenAngle;
}
[Serializable]
public sealed class EyeMeshData
{
	public string name;

	public float[] pivot;

	public HeadMeshData mesh;
}
[Serializable]
public sealed class FacialBlendShapeData
{
	public string name;

	public float[] deltaVertices;

	public float[] deltaNormals;
}
[Serializable]
public sealed class TonguePhysicsData
{
	public float[] restTip;

	public float[] extendedTip;

	public float maxOffset;
}
[Serializable]
public sealed class HeadModelData
{
	public int schema;

	public MeshBoundsData referenceBounds;

	public HeadMeshData mesh;

	public JawRigData jaw;

	public EyeMeshData[] eyes;

	public FacialBlendShapeData[] blendShapes;

	public TonguePhysicsData tonguePhysics;
}
internal static class HeadValidation
{
	internal static bool Finite(float value)
	{
		if (!float.IsNaN(value))
		{
			return !float.IsInfinity(value);
		}
		return false;
	}

	private static void Require(bool ok, string message)
	{
		if (!ok)
		{
			throw new InvalidDataException("Head: " + message);
		}
	}

	private static void Numbers(float[] a, int size)
	{
		Require(a != null && a.Length == size, "invalid array length.");
		foreach (float value in a)
		{
			Require(Finite(value), "non-finite coordinate.");
		}
	}

	internal static void Validate(HeadModelData data)
	{
		Require(data != null && data.schema == 3, "unsupported mesh schema.");
		Require(data.referenceBounds != null, "missing calibration.");
		Numbers(data.referenceBounds.min, 3);
		Numbers(data.referenceBounds.max, 3);
		for (int i = 0; i < 3; i++)
		{
			float num = data.referenceBounds.max[i] - data.referenceBounds.min[i];
			Require(num > 0.0001f && num < 100f, "invalid reference bounds.");
		}
		Surface(data.mesh, data.referenceBounds, 60000);
		int num2 = data.mesh.vertices.Length / 3;
		JawRigData jaw = data.jaw;
		Require(jaw != null, "animated jaw data missing.");
		Numbers(jaw.weights, num2);
		Numbers(jaw.pivot, 3);
		Numbers(jaw.axis, 3);
		bool flag = false;
		bool flag2 = false;
		double num3 = 0.0;
		float[] weights = jaw.weights;
		foreach (float num4 in weights)
		{
			Require(num4 >= 0f && num4 <= 1f, "jaw weight outside 0..1.");
			flag = flag || num4 > 0.01f;
			flag2 = flag2 || num4 < 0.01f;
		}
		Require(flag && flag2, "jaw must contain moving and fixed vertices.");
		for (int k = 0; k < 3; k++)
		{
			num3 += (double)jaw.axis[k] * (double)jaw.axis[k];
			Require(jaw.pivot[k] >= data.referenceBounds.min[k] && jaw.pivot[k] <= data.referenceBounds.max[k], "jaw pivot outside head bounds.");
		}
		Require(num3 > 0.99 && num3 < 1.01, "jaw axis is not unit length.");
		Require(Finite(jaw.maxOpenAngle) && jaw.maxOpenAngle >= 1f && jaw.maxOpenAngle <= 65f, "invalid maximum jaw angle.");
		Require(data.eyes != null && data.eyes.Length == 2, "exactly two animated eyes are required.");
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		EyeMeshData[] eyes = data.eyes;
		foreach (EyeMeshData eyeMeshData in eyes)
		{
			Require(eyeMeshData != null && !string.IsNullOrEmpty(eyeMeshData.name) && eyeMeshData.name.Length <= 32 && hashSet.Add(eyeMeshData.name), "invalid or duplicate eye name.");
			Numbers(eyeMeshData.pivot, 3);
			for (int m = 0; m < 3; m++)
			{
				Require(eyeMeshData.pivot[m] >= data.referenceBounds.min[m] && eyeMeshData.pivot[m] <= data.referenceBounds.max[m], "eye pivot outside head bounds.");
			}
			Surface(eyeMeshData.mesh, data.referenceBounds, 4000);
			Require(eyeMeshData.mesh.triangleMaterials == null, "eyes use their separate eye material.");
		}
		Require(data.blendShapes != null && (data.blendShapes.Length == 3 || data.blendShapes.Length == 4 || data.blendShapes.Length == 10), "Invalid expression/physics shape count.");
		HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
		float num5 = data.referenceBounds.max[1] - data.referenceBounds.min[1];
		if (data.tonguePhysics != null)
		{
			Numbers(data.tonguePhysics.restTip, 3);
			Numbers(data.tonguePhysics.extendedTip, 3);
			Require(Finite(data.tonguePhysics.maxOffset) && data.tonguePhysics.maxOffset > 0f && data.tonguePhysics.maxOffset <= num5 * 0.12f, "Unsafe tongue physics radius.");
			for (int n = 0; n < 3; n++)
			{
				Require(data.tonguePhysics.restTip[n] >= data.referenceBounds.min[n] - num5 * 0.8f && data.tonguePhysics.restTip[n] <= data.referenceBounds.max[n] + num5 * 0.8f, "Invalid rest tongue tip.");
				Require(Math.Abs(data.tonguePhysics.extendedTip[n] - data.tonguePhysics.restTip[n]) <= num5 * 0.75f, "Invalid extended tongue tip.");
			}
		}
		FacialBlendShapeData[] blendShapes = data.blendShapes;
		foreach (FacialBlendShapeData facialBlendShapeData in blendShapes)
		{
			int num7 = ((facialBlendShapeData == null) ? (-1) : Array.IndexOf(TonguePhysicsMath.ShapeNames, facialBlendShapeData.name));
			Require(facialBlendShapeData != null && (facialBlendShapeData.name == "BlinkLeft" || facialBlendShapeData.name == "BlinkRight" || facialBlendShapeData.name == "Alert" || facialBlendShapeData.name == "TongueOut" || num7 >= 0) && hashSet2.Add(facialBlendShapeData.name), "invalid or duplicate facial shape.");
			if (num7 >= 0)
			{
				Require(data.tonguePhysics != null, "Tongue flex requires physics calibration.");
			}
			Numbers(facialBlendShapeData.deltaVertices, num2 * 3);
			if (facialBlendShapeData.deltaNormals != null)
			{
				Numbers(facialBlendShapeData.deltaNormals, num2 * 3);
			}
			bool flag3 = false;
			for (int num8 = 0; num8 < facialBlendShapeData.deltaVertices.Length; num8++)
			{
				float num9 = ((facialBlendShapeData.name == "TongueOut") ? 0.75f : 0.35f);
				Require(Math.Abs(facialBlendShapeData.deltaVertices[num8]) <= num5 * num9, "facial shape deformation too large.");
				if (num7 >= 0)
				{
					Require(Math.Abs(facialBlendShapeData.deltaVertices[num8]) <= data.tonguePhysics.maxOffset + 1E-06f, "Tongue flex exceeds calibrated radius.");
					if (num8 % 3 != num7 / 2)
					{
						Require(Math.Abs(facialBlendShapeData.deltaVertices[num8]) < 1E-06f, "Tongue flex must follow its canonical axis.");
					}
					else
					{
						Require(facialBlendShapeData.deltaVertices[num8] * (float)((num7 % 2 == 0) ? 1 : (-1)) >= -1E-06f, "Tongue flex direction is reversed.");
					}
					if (Math.Abs(facialBlendShapeData.deltaVertices[num8]) > 1E-06f)
					{
						Require(jaw.weights[num8 / 3] >= 0.999f, "Tongue physics must be fully attached to the jaw.");
					}
				}
				flag3 |= Math.Abs(facialBlendShapeData.deltaVertices[num8]) > 1E-06f;
				if (facialBlendShapeData.name == "TongueOut" && Math.Abs(facialBlendShapeData.deltaVertices[num8]) > 1E-06f)
				{
					Require(jaw.weights[num8 / 3] >= 0.95f, "tongue extension must remain attached to the jaw.");
				}
				if (facialBlendShapeData.deltaNormals != null)
				{
					Require(Math.Abs(facialBlendShapeData.deltaNormals[num8]) <= 2.01f, "facial normal delta too large.");
				}
			}
			Require(flag3, "facial shape is empty.");
		}
		Require(hashSet2.Contains("BlinkLeft") && hashSet2.Contains("BlinkRight") && hashSet2.Contains("Alert"), "required expression is missing.");
		if (data.tonguePhysics == null)
		{
			return;
		}
		Require(hashSet2.Contains("TongueOut"), "Tongue physics requires extension shape.");
		string[] shapeNames = TonguePhysicsMath.ShapeNames;
		foreach (string item in shapeNames)
		{
			Require(hashSet2.Contains(item), "Incomplete tongue physics shapes.");
		}
		FacialBlendShapeData[] array = new FacialBlendShapeData[6];
		FacialBlendShapeData[] blendShapes2 = data.blendShapes;
		foreach (FacialBlendShapeData facialBlendShapeData2 in blendShapes2)
		{
			int num12 = Array.IndexOf(TonguePhysicsMath.ShapeNames, facialBlendShapeData2.name);
			if (num12 >= 0)
			{
				array[num12] = facialBlendShapeData2;
			}
		}
		for (int num13 = 0; num13 < num2; num13++)
		{
			float num14 = array[0].deltaVertices[num13 * 3];
			for (int num15 = 0; num15 < 6; num15++)
			{
				float num16 = array[num15].deltaVertices[num13 * 3 + num15 / 2] * (float)((num15 % 2 == 0) ? 1 : (-1));
				Require(Math.Abs(num16 - num14) < 2E-06f, "Tongue flex axes must use the same distal influence.");
			}
		}
	}

	private static void Surface(HeadMeshData m, MeshBoundsData bounds, int budget)
	{
		Require(m != null && m.vertices != null && m.vertices.Length % 3 == 0, "invalid vertices.");
		int num = m.vertices.Length / 3;
		Require(num >= 3 && num <= budget, "vertex budget exceeded.");
		Numbers(m.vertices, num * 3);
		Numbers(m.normals, num * 3);
		Numbers(m.uv, num * 2);
		Require(m.triangles != null && m.triangles.Length > 0 && m.triangles.Length <= 300000 && m.triangles.Length % 3 == 0, "invalid indices.");
		int[] triangles = m.triangles;
		foreach (int num2 in triangles)
		{
			Require(num2 >= 0 && num2 < num, "index outside vertices.");
		}
		if (m.triangleMaterials != null)
		{
			Require(m.triangleMaterials.Length == m.triangles.Length / 3, "triangle material count mismatch.");
			int[] triangleMaterials = m.triangleMaterials;
			foreach (int num3 in triangleMaterials)
			{
				Require(num3 >= 0 && num3 <= 2, "unknown triangle material.");
			}
		}
		for (int k = 0; k < num; k++)
		{
			double num4 = 0.0;
			for (int l = 0; l < 3; l++)
			{
				float num5 = bounds.min[l];
				float num6 = bounds.max[l];
				Require(m.vertices[k * 3 + l] > num5 - (num6 - num5) && m.vertices[k * 3 + l] < num6 + (num6 - num5), "vertex outside safe calibrated extent.");
				num4 += (double)m.normals[k * 3 + l] * (double)m.normals[k * 3 + l];
			}
			Require(num4 > 0.9 && num4 < 1.1, "normal is not unit length.");
			Require(m.uv[k * 2] >= 0f && m.uv[k * 2] <= 1f && m.uv[k * 2 + 1] >= 0f && m.uv[k * 2 + 1] <= 1f, "UV outside baked atlas.");
		}
		for (int n = 0; n < m.triangles.Length; n += 3)
		{
			int num7 = m.triangles[n] * 3;
			int num8 = m.triangles[n + 1] * 3;
			int num9 = m.triangles[n + 2] * 3;
			double num10 = (double)m.vertices[num8] - (double)m.vertices[num7];
			double num11 = (double)m.vertices[num8 + 1] - (double)m.vertices[num7 + 1];
			double num12 = (double)m.vertices[num8 + 2] - (double)m.vertices[num7 + 2];
			double num13 = (double)m.vertices[num9] - (double)m.vertices[num7];
			double num14 = (double)m.vertices[num9 + 1] - (double)m.vertices[num7 + 1];
			double num15 = (double)m.vertices[num9 + 2] - (double)m.vertices[num7 + 2];
			double num16 = (double)m.normals[num7] + (double)m.normals[num8] + (double)m.normals[num9];
			double num17 = (double)m.normals[num7 + 1] + (double)m.normals[num8 + 1] + (double)m.normals[num9 + 1];
			double num18 = (double)m.normals[num7 + 2] + (double)m.normals[num8 + 2] + (double)m.normals[num9 + 2];
			Require((num11 * num15 - num12 * num14) * num16 + (num12 * num13 - num10 * num15) * num17 + (num10 * num14 - num11 * num13) * num18 > 1E-12, "inward-facing or degenerate triangle.");
		}
	}
}
[BepInPlugin("ittrepo.pennisi", "Pennisi", "1.0.4")]
public sealed class HeadmanPortraitPlugin : BaseUnityPlugin
{
	private ConfigEntry<bool> enabledSetting;

	private ConfigEntry<float> scaleSetting;

	private ConfigEntry<float> offsetSetting;

	private readonly PortraitAssets assets = new PortraitAssets();

	private readonly PortraitBindings bindings = new PortraitBindings();

	private readonly EnemyDisplayName displayNames = new EnemyDisplayName();

	private readonly HashSet<int> warned = new HashSet<int>();

	private float nextScan;

	private float nextLoad;

	private bool settingsChanged;

	private bool nameWarning;

	private string folder;

	private void Awake()
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Expected O, but got Unknown
		enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Replace Headman's visible head. AI, attacks and colliders remain native.");
		scaleSetting = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "Scale", 1f, new ConfigDescription("Uniform size relative to Headman's original head.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 3f), new object[0]));
		offsetSetting = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "VerticalOffset", 0f, new ConfigDescription("Additional vertical offset in the native head animation space.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 1f), new object[0]));
		enabledSetting.SettingChanged += SettingsChanged;
		scaleSetting.SettingChanged += SettingsChanged;
		offsetSetting.SettingChanged += SettingsChanged;
		folder = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Pennisi 1.0.4 loaded. Replacement and presentation name target EnemyHeadController only; native damage flash linked to each portrait.");
	}

	private void SettingsChanged(object sender, EventArgs args)
	{
		settingsChanged = true;
	}

	private void Update()
	{
		if (settingsChanged)
		{
			settingsChanged = false;
			displayNames.RestoreAll();
			bindings.RestoreAll();
			warned.Clear();
			nextScan = 0f;
		}
		if (!enabledSetting.Value)
		{
			return;
		}
		if (!assets.Ready)
		{
			if (Time.unscaledTime < nextLoad)
			{
				return;
			}
			nextLoad = Time.unscaledTime + 15f;
			try
			{
				assets.Load(folder);
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Validated animated portrait, jaw, two eyes, facial shapes and 2048x2048 atlas loaded; attack tongue=" + (assets.TongueOutIndex >= 0)));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Portrait assets unavailable; original Headman remains visible. " + ex.Message));
				return;
			}
		}
		if (Time.unscaledTime < nextScan)
		{
			return;
		}
		nextScan = Time.unscaledTime + 1f;
		try
		{
			displayNames.Apply(delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)message);
			});
		}
		catch (Exception ex2)
		{
			if (!nameWarning)
			{
				nameWarning = true;
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Pennisi presentation rename skipped: " + ex2.Message));
			}
		}
		EnemyHeadController[] array = Object.FindObjectsOfType<EnemyHeadController>();
		foreach (EnemyHeadController val in array)
		{
			try
			{
				bindings.Apply(val, assets, scaleSetting.Value, offsetSetting.Value, delegate(string message)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)message);
				});
			}
			catch (Exception ex3)
			{
				if ((Object)(object)val != (Object)null && warned.Add(((Object)val).GetInstanceID()))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Headman replacement skipped: " + ex3.Message));
				}
			}
		}
	}

	private void LateUpdate()
	{
		if (enabledSetting != null && enabledSetting.Value)
		{
			bindings.Maintain();
		}
	}

	private void OnDisable()
	{
		displayNames.RestoreAll();
		bindings.RestoreAll();
		nextScan = 0f;
	}

	private void OnDestroy()
	{
		if (enabledSetting != null)
		{
			enabledSetting.SettingChanged -= SettingsChanged;
		}
		if (scaleSetting != null)
		{
			scaleSetting.SettingChanged -= SettingsChanged;
		}
		if (offsetSetting != null)
		{
			offsetSetting.SettingChanged -= SettingsChanged;
		}
		displayNames.RestoreAll();
		bindings.RestoreAll();
		assets.Dispose();
	}
}
internal static class ModelJson
{
	internal static T Read<T>(string json)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		JsonSerializerSettings val = new JsonSerializerSettings();
		val.TypeNameHandling = (TypeNameHandling)0;
		val.MetadataPropertyHandling = (MetadataPropertyHandling)2;
		val.MaxDepth = 32;
		val.Culture = CultureInfo.InvariantCulture;
		return JsonConvert.DeserializeObject<T>(json, val);
	}
}
internal sealed class PortraitEyeAsset
{
	internal string Name;

	internal Vector3 Pivot;

	internal Mesh Mesh;
}
internal sealed class PortraitAssets : IDisposable
{
	internal Mesh Mesh;

	internal Material Material;

	internal Material EyeMaterial;

	internal Material[] HeadMaterials;

	private Material teethMaterial;

	private Material mouthMaterial;

	internal PortraitEyeAsset[] Eyes;

	internal JawRigData Jaw;

	internal Bounds AnimatedBounds;

	internal int BlinkLeftIndex;

	internal int BlinkRightIndex;

	internal int AlertIndex;

	internal int TongueOutIndex;

	internal TonguePhysicsData TonguePhysics;

	internal int[] TongueFlexIndices;

	private Texture2D texture;

	internal Vector3 ReferenceCenter;

	internal float ReferenceHeight;

	internal bool Ready
	{
		get
		{
			if ((Object)(object)Mesh != (Object)null && (Object)(object)Material != (Object)null && (Object)(object)EyeMaterial != (Object)null)
			{
				return Eyes != null;
			}
			return false;
		}
	}

	internal void Load(string folder)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Expected O, but got Unknown
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Expected O, but got Unknown
		//IL_0109: 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_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Expected O, but got Unknown
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Expected O, but got Unknown
		//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Expected O, but got Unknown
		//IL_026c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0303: Unknown result type (might be due to invalid IL or missing references)
		//IL_0308: Unknown result type (might be due to invalid IL or missing references)
		//IL_036e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0373: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0402: Unknown result type (might be due to invalid IL or missing references)
		//IL_0469: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_0582: Unknown result type (might be due to invalid IL or missing references)
		//IL_0592: Unknown result type (might be due to invalid IL or missing references)
		//IL_0597: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_05fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_05fe: Unknown result type (might be due to invalid IL or missing references)
		HeadModelData headModelData = ModelJson.Read<HeadModelData>(Encoding.UTF8.GetString(Read(folder, "headman_portrait.mesh.json")));
		HeadValidation.Validate(headModelData);
		Texture2D val = null;
		Mesh val2 = null;
		Material val3 = null;
		Material val4 = null;
		Material val5 = null;
		Material val6 = null;
		List<PortraitEyeAsset> list = new List<PortraitEyeAsset>();
		try
		{
			val = new Texture2D(2, 2, (TextureFormat)4, true, false);
			if (!ImageConversion.LoadImage(val, Read(folder, "HeadmanPortrait_BaseColor.png"), true) || ((Texture)val).width != 2048 || ((Texture)val).height != 2048)
			{
				throw new InvalidDataException("The face atlas must be a valid 2048 x 2048 PNG.");
			}
			((Object)val).name = "HeadmanPortrait BaseColor";
			((Texture)val).wrapMode = (TextureWrapMode)0;
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).anisoLevel = 2;
			Shader val7 = Shader.Find("Standard");
			if ((Object)(object)val7 == (Object)null || !val7.isSupported)
			{
				val7 = Shader.Find("Unlit/Texture");
			}
			if ((Object)(object)val7 == (Object)null || !val7.isSupported)
			{
				throw new InvalidDataException("No supported textured shader is available.");
			}
			val3 = new Material(val7);
			((Object)val3).name = "HeadmanPortrait face";
			val3.SetTexture("_MainTex", (Texture)(object)val);
			val3.SetTextureScale("_MainTex", Vector2.one);
			val3.SetTextureOffset("_MainTex", Vector2.zero);
			if (val3.HasProperty("_Color"))
			{
				val3.SetColor("_Color", Color.white);
			}
			if (val3.HasProperty("_Metallic"))
			{
				val3.SetFloat("_Metallic", 0f);
			}
			if (val3.HasProperty("_Glossiness"))
			{
				val3.SetFloat("_Glossiness", 0.15f);
			}
			val4 = new Material(val3);
			((Object)val4).name = "HeadmanPortrait eyes";
			if (val4.HasProperty("_Glossiness"))
			{
				val4.SetFloat("_Glossiness", 0.65f);
			}
			if (headModelData.mesh.triangleMaterials != null)
			{
				val5 = new Material(val3);
				((Object)val5).name = "HeadmanPortrait teeth";
				val6 = new Material(val3);
				((Object)val6).name = "HeadmanPortrait wet mouth";
				if (val5.HasProperty("_Glossiness"))
				{
					val5.SetFloat("_Glossiness", 0.45f);
				}
				if (val6.HasProperty("_Glossiness"))
				{
					val6.SetFloat("_Glossiness", 0.5f);
				}
			}
			val2 = MakeMesh(headModelData.mesh, Vector3.zero, "HeadmanPortrait skinned head");
			BoneWeight[] array = (BoneWeight[])(object)new BoneWeight[headModelData.jaw.weights.Length];
			Vector3 val8 = V(headModelData.jaw.pivot);
			for (int i = 0; i < array.Length; i++)
			{
				ref BoneWeight reference = ref array[i];
				BoneWeight val9 = default(BoneWeight);
				((BoneWeight)(ref val9)).boneIndex0 = 0;
				((BoneWeight)(ref val9)).weight0 = 1f - headModelData.jaw.weights[i];
				((BoneWeight)(ref val9)).boneIndex1 = 1;
				((BoneWeight)(ref val9)).weight1 = headModelData.jaw.weights[i];
				reference = val9;
			}
			val2.boneWeights = array;
			val2.bindposes = (Matrix4x4[])(object)new Matrix4x4[2]
			{
				Matrix4x4.identity,
				Matrix4x4.TRS(-val8, Quaternion.identity, Vector3.one)
			};
			FacialBlendShapeData[] blendShapes = headModelData.blendShapes;
			foreach (FacialBlendShapeData facialBlendShapeData in blendShapes)
			{
				val2.AddBlendShapeFrame(facialBlendShapeData.name, 100f, Vectors(facialBlendShapeData.deltaVertices), (facialBlendShapeData.deltaNormals == null) ? null : Vectors(facialBlendShapeData.deltaNormals), (Vector3[])null);
			}
			Bounds bounds = val2.bounds;
			float num = 0f;
			float num2 = 2f * Mathf.Sin(headModelData.jaw.maxOpenAngle * ((float)Math.PI / 180f) * 0.5f);
			for (int k = 0; k < array.Length; k++)
			{
				Vector3 val10 = At(headModelData.mesh.vertices, k) - val8;
				float num3 = ((Vector3)(ref val10)).magnitude * headModelData.jaw.weights[k] * num2;
				FacialBlendShapeData[] blendShapes2 = headModelData.blendShapes;
				foreach (FacialBlendShapeData facialBlendShapeData2 in blendShapes2)
				{
					float num4 = num3;
					Vector3 val11 = At(facialBlendShapeData2.deltaVertices, k);
					num3 = num4 + ((Vector3)(ref val11)).magnitude;
				}
				num = Mathf.Max(num, num3);
			}
			((Bounds)(ref bounds)).Expand(num * 2f);
			EyeMeshData[] eyes = headModelData.eyes;
			foreach (EyeMeshData eyeMeshData in eyes)
			{
				Mesh val12 = MakeMesh(eyeMeshData.mesh, V(eyeMeshData.pivot), "HeadmanPortrait " + eyeMeshData.name);
				list.Add(new PortraitEyeAsset
				{
					Name = eyeMeshData.name,
					Pivot = V(eyeMeshData.pivot),
					Mesh = val12
				});
				val12.UploadMeshData(true);
			}
			BlinkLeftIndex = val2.GetBlendShapeIndex("BlinkLeft");
			BlinkRightIndex = val2.GetBlendShapeIndex("BlinkRight");
			AlertIndex = val2.GetBlendShapeIndex("Alert");
			TongueOutIndex = val2.GetBlendShapeIndex("TongueOut");
			TonguePhysics = headModelData.tonguePhysics;
			TongueFlexIndices = ((headModelData.tonguePhysics == null) ? null : new int[6]);
			if (TongueFlexIndices != null)
			{
				for (int n = 0; n < 6; n++)
				{
					TongueFlexIndices[n] = val2.GetBlendShapeIndex(TonguePhysicsMath.ShapeNames[n]);
				}
			}
			val2.UploadMeshData(true);
			ReferenceCenter = (V(headModelData.referenceBounds.min) + V(headModelData.referenceBounds.max)) * 0.5f;
			ReferenceHeight = headModelData.referenceBounds.max[1] - headModelData.referenceBounds.min[1];
			Mesh = val2;
			Material = val3;
			EyeMaterial = val4;
			Eyes = list.ToArray();
			Jaw = headModelData.jaw;
			AnimatedBounds = bounds;
			texture = val;
			teethMaterial = val5;
			mouthMaterial = val6;
			HeadMaterials = (Material[])(object)(((Object)(object)val5 == (Object)null) ? new Material[1] { val3 } : new Material[3] { val3, val5, val6 });
			val2 = null;
			val3 = null;
			val4 = null;
			val5 = null;
			val6 = null;
			val = null;
			list.Clear();
		}
		finally
		{
			if ((Object)(object)val2 != (Object)null)
			{
				Object.Destroy((Object)(object)val2);
			}
			if ((Object)(object)val3 != (Object)null)
			{
				Object.Destroy((Object)(object)val3);
			}
			if ((Object)(object)val4 != (Object)null)
			{
				Object.Destroy((Object)(object)val4);
			}
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			if ((Object)(object)val5 != (Object)null)
			{
				Object.Destroy((Object)(object)val5);
			}
			if ((Object)(object)val6 != (Object)null)
			{
				Object.Destroy((Object)(object)val6);
			}
			foreach (PortraitEyeAsset item in list)
			{
				if ((Object)(object)item.Mesh != (Object)null)
				{
					Object.Destroy((Object)(object)item.Mesh);
				}
			}
		}
	}

	private static Mesh MakeMesh(HeadMeshData data, Vector3 offset, string name)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//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_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		Mesh val = new Mesh();
		try
		{
			((Object)val).name = name;
			Vector3[] array = Vectors(data.vertices);
			for (int i = 0; i < array.Length; i++)
			{
				ref Vector3 reference = ref array[i];
				reference -= offset;
			}
			Vector2[] array2 = (Vector2[])(object)new Vector2[data.uv.Length / 2];
			for (int j = 0; j < array2.Length; j++)
			{
				ref Vector2 reference2 = ref array2[j];
				reference2 = new Vector2(data.uv[j * 2], data.uv[j * 2 + 1]);
			}
			val.vertices = array;
			val.normals = Vectors(data.normals);
			val.uv = array2;
			if (data.triangleMaterials == null)
			{
				val.triangles = data.triangles;
			}
			else
			{
				List<int>[] array3 = new List<int>[3]
				{
					new List<int>(),
					new List<int>(),
					new List<int>()
				};
				for (int k = 0; k < data.triangleMaterials.Length; k++)
				{
					for (int l = 0; l < 3; l++)
					{
						array3[data.triangleMaterials[k]].Add(data.triangles[k * 3 + l]);
					}
				}
				val.subMeshCount = array3.Length;
				for (int m = 0; m < array3.Length; m++)
				{
					val.SetTriangles(array3[m].ToArray(), m);
				}
			}
			val.RecalculateBounds();
			val.RecalculateTangents();
			return val;
		}
		catch
		{
			Object.Destroy((Object)(object)val);
			throw;
		}
	}

	private static Vector3 V(float[] a)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(a[0], a[1], a[2]);
	}

	private static Vector3 At(float[] a, int i)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(a[i * 3], a[i * 3 + 1], a[i * 3 + 2]);
	}

	private static Vector3[] Vectors(float[] a)
	{
		//IL_0018: 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)
		Vector3[] array = (Vector3[])(object)new Vector3[a.Length / 3];
		for (int i = 0; i < array.Length; i++)
		{
			ref Vector3 reference = ref array[i];
			reference = At(a, i);
		}
		return array;
	}

	private static byte[] Read(string folder, string name)
	{
		FileInfo fileInfo = new FileInfo(Path.Combine(folder, name));
		if (!fileInfo.Exists || fileInfo.Length == 0 || fileInfo.Length > 25165824)
		{
			throw new InvalidDataException("Missing or oversized " + name);
		}
		return File.ReadAllBytes(fileInfo.FullName);
	}

	public void Dispose()
	{
		if ((Object)(object)Material != (Object)null)
		{
			Object.Destroy((Object)(object)Material);
		}
		if ((Object)(object)EyeMaterial != (Object)null)
		{
			Object.Destroy((Object)(object)EyeMaterial);
		}
		if ((Object)(object)Mesh != (Object)null)
		{
			Object.Destroy((Object)(object)Mesh);
		}
		if ((Object)(object)texture != (Object)null)
		{
			Object.Destroy((Object)(object)texture);
		}
		if ((Object)(object)teethMaterial != (Object)null)
		{
			Object.Destroy((Object)(object)teethMaterial);
		}
		if ((Object)(object)mouthMaterial != (Object)null)
		{
			Object.Destroy((Object)(object)mouthMaterial);
		}
		if (Eyes != null)
		{
			PortraitEyeAsset[] eyes = Eyes;
			foreach (PortraitEyeAsset portraitEyeAsset in eyes)
			{
				if ((Object)(object)portraitEyeAsset.Mesh != (Object)null)
				{
					Object.Destroy((Object)(object)portraitEyeAsset.Mesh);
				}
			}
		}
		Material = null;
		EyeMaterial = null;
		teethMaterial = null;
		mouthMaterial = null;
		HeadMaterials = null;
		Mesh = null;
		texture = null;
		Eyes = null;
		Jaw = null;
	}
}
public sealed class HeadmanPortraitMarker : MonoBehaviour
{
}
internal sealed class PortraitBindings
{
	private sealed class Hidden
	{
		internal Renderer Renderer;

		internal bool OriginalForceOff;
	}

	private sealed class Binding
	{
		internal EnemyHeadController Controller;

		internal Transform Anchor;

		internal GameObject Portrait;

		internal PortraitFaceRig Face;

		internal readonly List<Hidden> Hidden = new List<Hidden>();
	}

	private const string TopPath = "Top Mesh/Offset/Top Animation/Mesh";

	private const string BottomPath = "Bot Mesh/Offset/Bot Animation/Mesh";

	private readonly Dictionary<int, Binding> bindings = new Dictionary<int, Binding>();

	internal bool Apply(EnemyHeadController controller, PortraitAssets assets, float size, float verticalOffset, Action<string> log)
	{
		//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_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_020c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0218: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_0235: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b9: Expected O, but got Unknown
		//IL_0318: Unknown result type (might be due to invalid IL or missing references)
		//IL_031e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0325: Unknown result type (might be due to invalid IL or missing references)
		//IL_032a: Unknown result type (might be due to invalid IL or missing references)
		//IL_033b: Unknown result type (might be due to invalid IL or missing references)
		//IL_034c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0353: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)controller == (Object)null))
		{
			Scene scene = ((Component)controller).gameObject.scene;
			if (((Scene)(ref scene)).IsValid() && assets.Ready)
			{
				if (!HeadValidation.Finite(verticalOffset) || Mathf.Abs(verticalOffset) > 1f)
				{
					throw new InvalidDataException("Invalid vertical offset.");
				}
				int instanceID = ((Object)controller).GetInstanceID();
				if (bindings.ContainsKey(instanceID))
				{
					return true;
				}
				EnemyParent componentInParent = ((Component)controller).GetComponentInParent<EnemyParent>();
				if ((Object)(object)componentInParent == (Object)null || (Object)(object)controller.AnimationSystem == (Object)null || (Object)(object)controller.HairParent == (Object)null)
				{
					return false;
				}
				Transform transform = ((Component)controller.AnimationSystem).transform;
				if ((Object)(object)((Component)transform).GetComponentInParent<EnemyParent>() != (Object)(object)componentInParent || (Object)(object)((Component)controller.HairParent).GetComponentInParent<EnemyParent>() != (Object)(object)componentInParent)
				{
					throw new InvalidDataException("Headman visual references do not belong to this enemy.");
				}
				Transform val = transform.Find("Main Animation");
				if ((Object)(object)val == (Object)null)
				{
					throw new InvalidDataException("Headman animation anchor is missing.");
				}
				Transform val2 = val.Find("Top Mesh/Offset/Top Animation/Mesh");
				Transform val3 = val.Find("Bot Mesh/Offset/Bot Animation/Mesh");
				if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
				{
					throw new InvalidDataException("Headman visual variant roots are missing.");
				}
				MeshFilter val4 = Stock(val2, "Enemy Head Top - Idle/Head Top", "Head Top_Idle optimized");
				MeshFilter val5 = Stock(val3, "Enemy Head Bot - Idle/Head Bot", "Head Bot_Idle optimized");
				RequireUniform(val2.localScale);
				RequireUniform(val3.localScale);
				if (!(Mathf.Abs(val2.localScale.x - val3.localScale.x) > 0.001f))
				{
					Vector3 localPosition = ((Component)val4).transform.parent.localPosition;
					if (!(((Vector3)(ref localPosition)).sqrMagnitude > 1E-05f))
					{
						Vector3 localPosition2 = ((Component)val5).transform.parent.localPosition;
						if (!(((Vector3)(ref localPosition2)).sqrMagnitude > 1E-05f))
						{
							Bounds bounds = val4.sharedMesh.bounds;
							Bounds bounds2 = val5.sharedMesh.bounds;
							HeadFit headFit = HeadCalibration.FromIdle(A(((Bounds)(ref bounds)).center), A(((Bounds)(ref bounds)).extents), A(((Component)val4).transform.localPosition), A(((Bounds)(ref bounds2)).center), A(((Bounds)(ref bounds2)).extents), A(((Component)val5).transform.localPosition), val2.localScale.x);
							float num = headFit.UniformScale(assets.ReferenceHeight, size);
							Binding binding = new Binding();
							binding.Controller = controller;
							binding.Anchor = val;
							Binding binding2 = binding;
							try
							{
								Collect(binding2, transform, componentInParent);
								Collect(binding2, controller.HairParent, componentInParent);
								if (binding2.Hidden.Count == 0)
								{
									throw new InvalidDataException("No original Headman renderers were found.");
								}
								GameObject val6 = (binding2.Portrait = new GameObject("HeadmanPortrait modeled head"));
								val6.layer = ((Component)val4).gameObject.layer;
								val6.SetActive(false);
								val6.AddComponent<HeadmanPortraitMarker>();
								val6.transform.SetParent(val, false);
								val6.transform.localPosition = new Vector3(headFit.Center[0], headFit.Center[1] + verticalOffset, headFit.Center[2]) - assets.ReferenceCenter * num;
								val6.transform.localRotation = Quaternion.identity;
								val6.transform.localScale = Vector3.one * num;
								MeshRenderer component = ((Component)val4).GetComponent<MeshRenderer>();
								binding2.Face = new PortraitFaceRig(val6, val3, transform, assets, component, instanceID, log);
								bindings.Add(instanceID, binding2);
								Update(binding2);
								val6.SetActive(true);
								log("Portrait attached to Headman; anchor=" + ((Object)val).name + "; hiddenRenderers=" + binding2.Hidden.Count + "; uniformScale=" + num + "; nativeHeight=" + headFit.Height + "; shader=" + ((Object)assets.Material.shader).name + "; native bite jaw + tracked eyes + blink/alert rig active; AI, Animator, colliders and native GameObjects preserved.");
								return true;
							}
							catch
							{
								bindings.Remove(instanceID);
								Restore(binding2);
								throw;
							}
						}
					}
				}
				throw new InvalidDataException("Headman idle variants have unexpected calibration.");
			}
		}
		return false;
	}

	private static float[] A(Vector3 v)
	{
		return new float[3] { v.x, v.y, v.z };
	}

	private static void RequireUniform(Vector3 scale)
	{
		if (!HeadValidation.Finite(scale.x) || scale.x <= 0f || Mathf.Abs(scale.x - scale.y) > 0.001f || Mathf.Abs(scale.x - scale.z) > 0.001f)
		{
			throw new InvalidDataException("Headman base scale is not uniform.");
		}
	}

	private static MeshFilter Stock(Transform root, string path, string meshName)
	{
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: 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)
		Transform val = root.Find(path);
		MeshFilter val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<MeshFilter>());
		if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.sharedMesh == (Object)null) && !(((Object)val2.sharedMesh).name != meshName) && !((Object)(object)((Component)val).GetComponent<MeshRenderer>() == (Object)null))
		{
			Vector3 val3 = val.localScale - Vector3.one;
			if (!(((Vector3)(ref val3)).sqrMagnitude > 1E-05f) && !(Quaternion.Angle(val.localRotation, Quaternion.identity) > 0.1f))
			{
				return val2;
			}
		}
		throw new InvalidDataException("Verified stock mesh is unavailable: " + meshName);
	}

	private static void Collect(Binding binding, Transform scope, EnemyParent owner)
	{
		Renderer[] componentsInChildren = ((Component)scope).GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val in componentsInChildren)
		{
			if ((val is MeshRenderer || val is SkinnedMeshRenderer) && !((Object)(object)((Component)val).GetComponentInParent<HeadmanPortraitMarker>() != (Object)null) && !((Object)(object)((Component)val).GetComponentInParent<EnemyParent>() != (Object)(object)owner))
			{
				binding.Hidden.Add(new Hidden
				{
					Renderer = val,
					OriginalForceOff = val.forceRenderingOff
				});
			}
		}
	}

	private static void Update(Binding binding)
	{
		bool visible = false;
		foreach (Hidden item in binding.Hidden)
		{
			Renderer renderer = item.Renderer;
			if (!((Object)(object)renderer == (Object)null))
			{
				if (!item.OriginalForceOff && renderer.enabled && ((Component)renderer).gameObject.activeInHierarchy)
				{
					visible = true;
				}
				renderer.forceRenderingOff = true;
			}
		}
		if (binding.Face != null)
		{
			binding.Face.SetVisible(visible);
			binding.Face.Update();
		}
	}

	internal void Maintain()
	{
		List<int> list = null;
		foreach (KeyValuePair<int, Binding> binding in bindings)
		{
			Binding value = binding.Value;
			if ((Object)(object)value.Controller == (Object)null || (Object)(object)value.Anchor == (Object)null || (Object)(object)value.Portrait == (Object)null)
			{
				if (list == null)
				{
					list = new List<int>();
				}
				list.Add(binding.Key);
			}
			else
			{
				Update(value);
			}
		}
		if (list == null)
		{
			return;
		}
		foreach (int item in list)
		{
			Restore(bindings[item]);
			bindings.Remove(item);
		}
	}

	private static void Restore(Binding binding)
	{
		if (binding.Face != null)
		{
			binding.Face.Dispose();
		}
		foreach (Hidden item in binding.Hidden)
		{
			if ((Object)(object)item.Renderer != (Object)null && item.Renderer.forceRenderingOff)
			{
				item.Renderer.forceRenderingOff = item.OriginalForceOff;
			}
		}
		if ((Object)(object)binding.Portrait != (Object)null)
		{
			binding.Portrait.SetActive(false);
			Object.Destroy((Object)(object)binding.Portrait);
		}
	}

	internal void RestoreAll()
	{
		foreach (Binding value in bindings.Values)
		{
			Restore(value);
		}
		bindings.Clear();
	}
}
internal sealed class PortraitFaceRig
{
	private sealed class Eye
	{
		internal Transform Transform;

		internal Renderer Renderer;

		internal EnemyHeadEye Native;
	}

	internal SkinnedMeshRenderer Renderer;

	private readonly Transform root;

	private readonly Transform jawBone;

	private readonly Transform bite;

	private readonly Transform gumBottom;

	private readonly Transform gumTop;

	private readonly Transform closed;

	private readonly Transform halfOpen;

	private readonly Transform chase;

	private readonly Eye[] eyes;

	private readonly PortraitAssets assets;

	private readonly Random random;

	private readonly Action<string> log;

	private float currentJaw;

	private float currentAlert;

	private float nextBlink;

	private float blinkStart = -10f;

	private bool blinkVisibleStart;

	private bool blinkObserved;

	private bool jawOpenedObserved;

	private bool jawClosedObserved;

	private bool tongueOutObserved;

	private bool tongueRetractedObserved;

	private bool chaseExpressionObserved;

	private readonly TonguePhysics tonguePhysics;

	private readonly PortraitHitFlash hitFlash;

	internal PortraitFaceRig(GameObject portrait, Transform nativeBottom, Transform system, PortraitAssets portraitAssets, MeshRenderer stock, int seed, Action<string> logger)
	{
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		root = portrait.transform;
		assets = portraitAssets;
		random = new Random(seed);
		log = logger;
		bite = Required(nativeBottom, "Enemy Head Bot - Bite");
		gumBottom = Required(bite, "Gum Bot/Gum Bot Anim");
		gumTop = Required(bite, "Gum Top/Gum Top Anim");
		closed = Required(nativeBottom, "Enemy Head Bot - Closed");
		halfOpen = Required(nativeBottom, "Enemy Head Bot - Half Open");
		chase = Required(nativeBottom, "Enemy Head Bot - Chase");
		Transform val = Child(root, "Skull", Vector3.zero);
		jawBone = Child(root, "Jaw", V(assets.Jaw.pivot));
		Renderer = portrait.AddComponent<SkinnedMeshRenderer>();
		Renderer.sharedMesh = assets.Mesh;
		((Renderer)Renderer).sharedMaterials = assets.HeadMaterials;
		Renderer.bones = (Transform[])(object)new Transform[2] { val, jawBone };
		Renderer.rootBone = val;
		Renderer.quality = (SkinQuality)2;
		Renderer.updateWhenOffscreen = true;
		((Renderer)Renderer).localBounds = assets.AnimatedBounds;
		((Renderer)Renderer).shadowCastingMode = ((Renderer)stock).shadowCastingMode;
		((Renderer)Renderer).receiveShadows = ((Renderer)stock).receiveShadows;
		EnemyHeadEye[] componentsInChildren = ((Component)system).GetComponentsInChildren<EnemyHeadEye>(true);
		if (componentsInChildren.Length < 2)
		{
			throw new InvalidDataException("Native eye tracking references are missing.");
		}
		eyes = new Eye[assets.Eyes.Length];
		for (int i = 0; i < eyes.Length; i++)
		{
			PortraitEyeAsset portraitEyeAsset = assets.Eyes[i];
			Transform val2 = Child(root, portraitEyeAsset.Name, portraitEyeAsset.Pivot);
			((Component)val2).gameObject.AddComponent<MeshFilter>().sharedMesh = portraitEyeAsset.Mesh;
			MeshRenderer val3 = ((Component)val2).gameObject.AddComponent<MeshRenderer>();
			((Renderer)val3).sharedMaterial = assets.EyeMaterial;
			((Renderer)val3).shadowCastingMode = ((Renderer)stock).shadowCastingMode;
			((Renderer)val3).receiveShadows = ((Renderer)stock).receiveShadows;
			EnemyHeadEye val4 = null;
			float num = float.MaxValue;
			EnemyHeadEye[] array = componentsInChildren;
			foreach (EnemyHeadEye val5 in array)
			{
				if (!((Object)(object)val5 == (Object)null) && !((Object)(object)val5.Target == (Object)null) && !((Object)(object)val5.EyeTarget == (Object)null))
				{
					float x = ((Component)val5).transform.localPosition.x;
					float num2 = Mathf.Abs(x - portraitEyeAsset.Pivot.x);
					if (Mathf.Sign(x) != Mathf.Sign(portraitEyeAsset.Pivot.x))
					{
						num2 += 100f;
					}
					if (num2 < num)
					{
						val4 = val5;
						num = num2;
					}
				}
			}
			if ((Object)(object)val4 == (Object)null)
			{
				throw new InvalidDataException("Native eye target is missing.");
			}
			eyes[i] = new Eye
			{
				Transform = val2,
				Renderer = (Renderer)(object)val3,
				Native = val4
			};
		}
		if ((Object)(object)eyes[0].Native.Target == (Object)(object)eyes[1].Native.Target)
		{
			throw new InvalidDataException("Distinct native eye targets were not found.");
		}
		if (assets.TonguePhysics != null)
		{
			tonguePhysics = portrait.AddComponent<TonguePhysics>();
			tonguePhysics.Initialize(root, jawBone, Renderer, assets, log);
		}
		nextBlink = Time.time + 1.5f + (float)random.NextDouble() * 2f;
		log("Facial gaze linked to two distinct native eye targets.");
		hitFlash = new PortraitHitFlash(((Component)stock).GetComponentInParent<EnemyHealth>(), (Renderer)(object)stock, log);
		try
		{
			hitFlash.Add((Renderer)(object)Renderer);
			Eye[] array2 = eyes;
			foreach (Eye eye in array2)
			{
				hitFlash.Add(eye.Renderer);
			}
			hitFlash.Update();
		}
		catch
		{
			hitFlash.Dispose();
			throw;
		}
	}

	private static Transform Required(Transform parent, string path)
	{
		Transform val = parent.Find(path);
		if ((Object)(object)val == (Object)null)
		{
			throw new InvalidDataException("Native facial animation channel missing: " + path);
		}
		return val;
	}

	private static Vector3 V(float[] values)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(values[0], values[1], values[2]);
	}

	private static Transform Child(Transform parent, string name, Vector3 position)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("HeadmanPortrait " + name);
		val.layer = ((Component)parent).gameObject.layer;
		val.transform.SetParent(parent, false);
		val.transform.localPosition = position;
		val.transform.localRotation = Quaternion.identity;
		val.transform.localScale = Vector3.one;
		return val.transform;
	}

	internal void SetVisible(bool visible)
	{
		if ((Object)(object)Renderer != (Object)null)
		{
			((Renderer)Renderer).enabled = visible;
		}
		Eye[] array = eyes;
		foreach (Eye eye in array)
		{
			if ((Object)(object)eye.Renderer != (Object)null)
			{
				eye.Renderer.enabled = visible;
			}
		}
	}

	internal void Update()
	{
		//IL_0095: 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_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0370: Unknown result type (might be due to invalid IL or missing references)
		//IL_037c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0381: Unknown result type (might be due to invalid IL or missing references)
		//IL_0386: Unknown result type (might be due to invalid IL or missing references)
		//IL_038b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0449: Unknown result type (might be due to invalid IL or missing references)
		//IL_044e: Unknown result type (might be due to invalid IL or missing references)
		//IL_045e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0463: Unknown result type (might be due to invalid IL or missing references)
		//IL_0481: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)root == (Object)null || (Object)(object)jawBone == (Object)null || (Object)(object)Renderer == (Object)null)
		{
			return;
		}
		hitFlash.Update();
		float deltaTime = Mathf.Min(Time.deltaTime, 0.1f);
		bool flag = (Object)(object)bite != (Object)null && ((Component)bite).gameObject.activeInHierarchy;
		bool flag2 = Active(chase);
		bool flag3 = Active(closed);
		float num = FacialMotion.JawOpening(flag, ((Object)(object)gumBottom == (Object)null) ? 0f : gumBottom.localEulerAngles.x, ((Object)(object)gumTop == (Object)null) ? 0f : gumTop.localEulerAngles.x, flag3, Active(halfOpen), flag2);
		currentJaw = ((flag && num <= currentJaw) ? num : Mathf.Lerp(currentJaw, num, FacialMotion.Follow(deltaTime, flag ? 45f : 14f)));
		jawBone.localRotation = Quaternion.AngleAxis(currentJaw * assets.Jaw.maxOpenAngle, V(assets.Jaw.axis));
		bool flag4 = ((Component)root).gameObject.activeInHierarchy && ((Renderer)Renderer).enabled;
		if (flag4 && flag && currentJaw > 0.2f && !jawOpenedObserved)
		{
			jawOpenedObserved = true;
			log("Facial jaw opening observed above 0.2 from the native bite animation.");
		}
		if (flag4 && flag && currentJaw < 0.05f && jawOpenedObserved && !jawClosedObserved)
		{
			jawClosedObserved = true;
			log("Facial jaw closure observed at the native bite impact.");
		}
		float num2 = 0f;
		if (assets.TongueOutIndex >= 0)
		{
			num2 = FacialMotion.TongueOpening(flag, currentJaw, flag2, flag3);
			Renderer.SetBlendShapeWeight(assets.TongueOutIndex, num2 * 100f);
			if (flag4 && flag && num2 > 0.2f && !tongueOutObserved)
			{
				tongueOutObserved = true;
				log("Facial tongue extension observed during the native bite.");
			}
			if (flag4 && num2 == 0f && tongueOutObserved && !tongueRetractedObserved)
			{
				tongueRetractedObserved = true;
				log("Facial tongue retraction observed on bite impact or idle/closed transition.");
			}
			if (flag4 && flag2 && !flag && !flag3 && currentJaw > 0.65f && num2 > 0.85f && !chaseExpressionObserved)
			{
				chaseExpressionObserved = true;
				log("Facial chase pose observed: wide-open jaw and very long extended tongue.");
			}
		}
		bool flag5 = flag2 || flag;
		Eye[] array = eyes;
		foreach (Eye eye in array)
		{
			if (!((Object)(object)eye.Transform == (Object)null) && !((Object)(object)eye.Native == (Object)null) && !((Object)(object)eye.Native.Target == (Object)null) && !((Object)(object)eye.Native.EyeTarget == (Object)null))
			{
				EnemyHeadEyeTarget eyeTarget = eye.Native.EyeTarget;
				flag5 |= !eyeTarget.Idle;
				Vector3 val = root.InverseTransformDirection(eye.Native.Target.position - eye.Transform.position);
				if (!(((Vector3)(ref val)).sqrMagnitude < 1E-06f))
				{
					float num3 = Mathf.Atan2(val.x, val.z) * 57.29578f;
					float num4 = (0f - Mathf.Atan2(val.y, Mathf.Sqrt(val.x * val.x + val.z * val.z))) * 57.29578f;
					float num5 = Mathf.Min(20f, Mathf.Abs(eyeTarget.Limit.y));
					float num6 = Mathf.Min(15f, Mathf.Abs(eyeTarget.Limit.x));
					Quaternion val2 = Quaternion.Euler(Mathf.Clamp(num4, 0f - num6, num6), Mathf.Clamp(num3, 0f - num5, num5), 0f);
					eye.Transform.localRotation = Quaternion.Slerp(eye.Transform.localRotation, val2, FacialMotion.Follow(deltaTime, Mathf.Clamp(eyeTarget.Speed, 2f, 20f)));
				}
			}
		}
		currentAlert = Mathf.Lerp(currentAlert, Mathf.Max(flag5 ? 1f : 0f, currentJaw * 0.5f), FacialMotion.Follow(deltaTime, 8f));
		float time = Time.time;
		if (time >= nextBlink)
		{
			blinkStart = time;
			blinkVisibleStart = flag4;
			nextBlink = time + (flag5 ? 1.8f : 2.5f) + (float)random.NextDouble() * (flag5 ? 1.8f : 3f);
		}
		if (!flag4 && time - blinkStart < 0.212f)
		{
			blinkVisibleStart = false;
		}
		float num7 = FacialMotion.Blink(time - blinkStart);
		float num8 = FacialMotion.Blink(time - blinkStart - 0.012f);
		Renderer.SetBlendShapeWeight(assets.BlinkLeftIndex, num7 * 100f);
		Renderer.SetBlendShapeWeight(assets.BlinkRightIndex, num8 * 100f);
		Renderer.SetBlendShapeWeight(assets.AlertIndex, currentAlert * (1f - Mathf.Max(num7, num8)) * 100f);
		if (!blinkObserved && blinkVisibleStart && flag4 && time - blinkStart >= 0.212f)
		{
			blinkObserved = true;
			log("Facial blink completed on both eyelids while the portrait was visible.");
		}
		if ((Object)(object)tonguePhysics != (Object)null)
		{
			tonguePhysics.SetPoseAndApply(num2, flag4);
		}
	}

	private static bool Active(Transform value)
	{
		if ((Object)(object)value != (Object)null)
		{
			return ((Component)value).gameObject.activeInHierarchy;
		}
		return false;
	}

	internal void Dispose()
	{
		if (hitFlash != null)
		{
			hitFlash.Dispose();
		}
	}
}
internal sealed class PortraitHitFlash : IDisposable
{
	private sealed class Surface
	{
		internal Material Material;

		internal Color Color;

		internal Color Emission;
	}

	private sealed class Target
	{
		internal Renderer Renderer;

		internal Material[] Original;

		internal Material[] Replacement;
	}

	private static readonly FieldInfo NativeMaterials = typeof(EnemyHealth).GetField("instancedMaterials", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly int OverlayColor = Shader.PropertyToID("_ColorOverlay");

	private static readonly int OverlayAmount = Shader.PropertyToID("_ColorOverlayAmount");

	private static readonly int BaseColor = Shader.PropertyToID("_Color");

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

	private readonly List<Surface> surfaces = new List<Surface>();

	private readonly List<Target> targets = new List<Target>();

	private readonly Dictionary<Material, Material> copies = new Dictionary<Material, Material>();

	private readonly Action<string> log;

	private Material source;

	private float lastAmount = -1f;

	private Color lastColor;

	private bool hitObserved;

	private bool resetObserved;

	internal PortraitHitFlash(EnemyHealth health, Renderer original, Action<string> logger)
	{
		log = logger;
		if ((Object)(object)health != (Object)null && NativeMaterials != null && NativeMaterials.GetValue(health) is List<Material> list)
		{
			foreach (Material item in list)
			{
				if (CompatibleSource(item))
				{
					source = item;
					break;
				}
			}
		}
		if ((Object)(object)source == (Object)null && (Object)(object)original != (Object)null && CompatibleSource(original.sharedMaterial))
		{
			source = original.sharedMaterial;
		}
		if ((Object)(object)source == (Object)null)
		{
			log("Native portrait flash source unavailable; portrait appearance remains unchanged.");
		}
	}

	private static bool CompatibleSource(Material value)
	{
		if ((Object)(object)value != (Object)null && value.HasProperty(OverlayColor))
		{
			return value.HasProperty(OverlayAmount);
		}
		return false;
	}

	internal void Add(Renderer renderer)
	{
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Expected O, but got Unknown
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: 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)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)source == (Object)null || (Object)(object)renderer == (Object)null)
		{
			return;
		}
		Material[] sharedMaterials = renderer.sharedMaterials;
		Material[] array = (Material[])sharedMaterials.Clone();
		for (int i = 0; i < sharedMaterials.Length; i++)
		{
			Material val = sharedMaterials[i];
			if (!((Object)(object)val == (Object)null) && val.HasProperty(BaseColor) && val.HasProperty(EmissionColor))
			{
				if (!copies.TryGetValue(val, out var value))
				{
					value = new Material(val);
					((Object)value).name = ((Object)val).name + " [native flash]";
					Surface surface = new Surface();
					surface.Material = value;
					surface.Color = value.GetColor(BaseColor);
					surface.Emission = (value.IsKeywordEnabled("_EMISSION") ? value.GetColor(EmissionColor) : Color.black);
					Surface item = surface;
					value.EnableKeyword("_EMISSION");
					surfaces.Add(item);
					copies.Add(val, value);
				}
				array[i] = value;
			}
		}
		targets.Add(new Target
		{
			Renderer = renderer,
			Original = sharedMaterials,
			Replacement = array
		});
		renderer.sharedMaterials = array;
	}

	internal void Update()
	{
		//IL_0063: 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_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: 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_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: 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_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		//IL_0184: Unknown result type (might be due to invalid IL or missing references)
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: Unknown result type (might be due to invalid IL or missing references)
		float num = (((Object)(object)source == (Object)null) ? 0f : source.GetFloat(OverlayAmount));
		if (float.IsNaN(num) || float.IsInfinity(num))
		{
			num = 0f;
		}
		num = Mathf.Clamp01(num);
		Color val = (((Object)(object)source == (Object)null) ? Color.black : source.GetColor(OverlayColor));
		if (float.IsNaN(val.r) || float.IsInfinity(val.r) || float.IsNaN(val.g) || float.IsInfinity(val.g) || float.IsNaN(val.b) || float.IsInfinity(val.b))
		{
			num = 0f;
			val = Color.black;
		}
		if (num == lastAmount && (num == 0f || val == lastColor))
		{
			return;
		}
		foreach (Surface surface in surfaces)
		{
			if (!((Object)(object)surface.Material == (Object)null))
			{
				Color val2 = surface.Color * (1f - num);
				val2.a = surface.Color.a;
				Color val3 = surface.Emission * (1f - num) + val * num;
				val3.a = surface.Emission.a;
				surface.Material.SetColor(BaseColor, val2);
				surface.Material.SetColor(EmissionColor, val3);
			}
		}
		if (!hitObserved && num > 0.05f && val.r > val.g && val.r > val.b && surfaces.Count > 0)
		{
			hitObserved = true;
			log("Native red damage flash observed on Pennisi skin, mouth, tongue and eyes; per-enemy materials active.");
		}
		if (hitObserved && !resetObserved && num == 0f)
		{
			resetObserved = true;
			log("Native red damage flash completed on Pennisi; original portrait colors restored.");
		}
		lastAmount = num;
		lastColor = val;
	}

	public void Dispose()
	{
		foreach (Target target in targets)
		{
			if ((Object)(object)target.Renderer == (Object)null)
			{
				continue;
			}
			Material[] sharedMaterials = target.Renderer.sharedMaterials;
			bool flag = false;
			for (int i = 0; i < sharedMaterials.Length && i < target.Replacement.Length; i++)
			{
				if ((Object)(object)sharedMaterials[i] == (Object)(object)target.Replacement[i] && (Object)(object)sharedMaterials[i] != (Object)(object)target.Original[i])
				{
					sharedMaterials[i] = target.Original[i];
					flag = true;
				}
			}
			if (flag)
			{
				target.Renderer.sharedMaterials = sharedMaterials;
			}
		}
		foreach (Surface surface in surfaces)
		{
			if ((Object)(object)surface.Material != (Object)null)
			{
				Object.Destroy((Object)(object)surface.Material);
			}
		}
		surfaces.Clear();
		copies.Clear();
		targets.Clear();
		source = null;
	}
}
public sealed class TonguePhysics : MonoBehaviour
{
	private Transform head;

	private Transform jaw;

	private SkinnedMeshRenderer renderer;

	private TonguePhysicsData data;

	private Vector3 pivot;

	private int[] indices;

	private Action<string> log;

	private GameObject worldRoot;

	private Rigidbody anchor;

	private Rigidbody tip;

	private ConfigurableJoint joint;

	private readonly float[] weights = new float[6];

	private readonly TongueFlutterState flutter = new TongueFlutterState();

	private float tongue;

	private float previousScale;

	private Vector3 previousTarget;

	private Vector3 previousOrigin;

	private Quaternion previousRotation;

	private bool requested;

	private bool simulating;

	private bool observed;

	private bool retractionObserved;

	private bool initialized;

	private bool observedLeft;

	private bool observedRight;

	private bool flutterObserved;

	internal void Initialize(Transform headTransform, Transform jawTransform, SkinnedMeshRenderer target, PortraitAssets assets, Action<string> logger)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		head = headTransform;
		jaw = jawTransform;
		renderer = target;
		data = assets.TonguePhysics;
		pivot = V(assets.Jaw.pivot);
		indices = assets.TongueFlexIndices;
		log = logger;
		initialized = data != null;
	}

	private static Vector3 V(float[] a)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(a[0], a[1], a[2]);
	}

	private static bool Finite(Vector3 v)
	{
		if (HeadValidation.Finite(v.x) && HeadValidation.Finite(v.y))
		{
			return HeadValidation.Finite(v.z);
		}
		return false;
	}

	private bool Pose(out Vector3 target, out float scale)
	{
		//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_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		target = Vector3.zero;
		scale = 0f;
		if (!initialized || (Object)(object)head == (Object)null || (Object)(object)jaw == (Object)null || (Object)(object)renderer == (Object)null || !((Component)head).gameObject.activeInHierarchy || !((Renderer)renderer).enabled)
		{
			return false;
		}
		Vector3 lossyScale = head.lossyScale;
		if (!TonguePhysicsMath.ScaleValid(lossyScale.x, lossyScale.y, lossyScale.z))
		{
			return false;
		}
		scale = (lossyScale.x + lossyScale.y + lossyScale.z) / 3f;
		Vector3 val = Vector3.Lerp(V(data.restTip), V(data.extendedTip), tongue);
		target = head.TransformPoint(pivot + jaw.localRotation * (val - pivot));
		if (HeadValidation.Finite(target.x) && HeadValidation.Finite(target.y))
		{
			return HeadValidation.Finite(target.z);
		}
		return false;
	}

	private void CreateBodies(Vector3 target, float scale)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		//IL_001b: 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_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Expected O, but got Unknown
		//IL_0089: 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_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_0213: Unknown result type (might be due to invalid IL or missing references)
		//IL_0223: 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_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		worldRoot = new GameObject("HeadmanPortrait tongue physics");
		Scene scene = ((Component)head).gameObject.scene;
		if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded)
		{
			SceneManager.MoveGameObjectToScene(worldRoot, scene);
		}
		GameObject val = new GameObject("Tongue anchor");
		GameObject val2 = new GameObject("Tongue tip");
		val.transform.SetParent(worldRoot.transform, false);
		val2.transform.SetParent(worldRoot.transform, false);
		val.transform.position = target;
		val2.transform.position = target;
		anchor = val.AddComponent<Rigidbody>();
		anchor.isKinematic = true;
		anchor.useGravity = false;
		anchor.detectCollisions = false;
		tip = val2.AddComponent<Rigidbody>();
		tip.isKinematic = true;
		tip.mass = 0.06f;
		tip.useGravity = true;
		tip.detectCollisions = false;
		tip.constraints = (RigidbodyConstraints)112;
		tip.linearDamping = 0.15f;
		tip.interpolation = (RigidbodyInterpolation)0;
		tip.solverIterations = 8;
		tip.solverVelocityIterations = 4;
		joint = val2.AddComponent<ConfigurableJoint>();
		((Joint)joint).connectedBody = anchor;
		((Joint)joint).autoConfigureConnectedAnchor = false;
		((Joint)joint).anchor = Vector3.zero;
		((Joint)joint).connectedAnchor = Vector3.zero;
		((Joint)joint).axis = Vector3.right;
		joint.secondaryAxis = Vector3.up;
		ConfigurableJoint obj = joint;
		ConfigurableJoint obj2 = joint;
		ConfigurableJoint obj3 = joint;
		ConfigurableJointMotion val3 = (ConfigurableJointMotion)1;
		obj3.zMotion = (ConfigurableJointMotion)1;
		ConfigurableJointMotion xMotion = (obj2.yMotion = val3);
		obj.xMotion = xMotion;
		ConfigurableJoint obj4 = joint;
		ConfigurableJoint obj5 = joint;
		ConfigurableJoint obj6 = joint;
		ConfigurableJointMotion val5 = (ConfigurableJointMotion)0;
		obj6.angularZMotion = (ConfigurableJointMotion)0;
		ConfigurableJointMotion angularXMotion = (obj5.angularYMotion = val5);
		obj4.angularXMotion = angularXMotion;
		joint.targetPosition = Vector3.zero;
		joint.targetVelocity = Vector3.zero;
		joint.projectionMode = (JointProjectionMode)0;
		((Joint)joint).enableCollision = false;
		ConfigurableJoint obj7 = joint;
		SoftJointLimitSpring linearLimitSpring = default(SoftJointLimitSpring);
		((SoftJointLimitSpring)(ref linearLimitSpring)).spring = 0f;
		((SoftJointLimitSpring)(ref linearLimitSpring)).damper = 0f;
		obj7.linearLimitSpring = linearLimitSpring;
		Configure(scale);
	}

	private void Configure(float scale)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		float num = tip.mass * 180f / scale;
		JointDrive val = default(JointDrive);
		((JointDrive)(ref val)).positionSpring = num;
		((JointDrive)(ref val)).positionDamper = 0.9f * Mathf.Sqrt(num * tip.mass);
		((JointDrive)(ref val)).maximumForce = tip.mass * 200f;
		JointDrive val2 = val;
		ConfigurableJoint obj = joint;
		ConfigurableJoint obj2 = joint;
		JointDrive val3 = (joint.zDrive = val2);
		JointDrive xDrive = (obj2.yDrive = val3);
		obj.xDrive = xDrive;
		ConfigurableJoint obj3 = joint;
		SoftJointLimit linearLimit = default(SoftJointLimit);
		((SoftJointLimit)(ref linearLimit)).limit = data.maxOffset * scale;
		((SoftJointLimit)(ref linearLimit)).bounciness = 0f;
		((SoftJointLimit)(ref linearLimit)).contactDistance = 0.002f * scale;
		obj3.linearLimit = linearLimit;
		tip.maxLinearVelocity = Mathf.Max(2f, scale * 5f);
	}

	private void ResetAt(Vector3 target, float scale)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: 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_0097: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)worldRoot == (Object)null)
		{
			CreateBodies(target, scale);
		}
		if (!tip.isKinematic)
		{
			tip.linearVelocity = Vector3.zero;
			tip.angularVelocity = Vector3.zero;
		}
		tip.isKinematic = true;
		anchor.position = target;
		tip.position = target;
		anchor.rotation = Quaternion.identity;
		tip.rotation = Quaternion.identity;
		Configure(scale);
		previousScale = scale;
		previousTarget = target;
		previousRotation = head.rotation;
		previousOrigin = head.position;
		flutter.Reset();
		simulating = false;
		ClearShapes();
	}

	private void FixedUpdate()
	{
		//IL_006c: 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_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: 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_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_00f8: 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_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		if (!requested || TonguePhysicsMath.Envelope(tongue) == 0f || !Pose(out var target, out var scale))
		{
			Suspend();
			return;
		}
		if ((Object)(object)worldRoot == (Object)null || TonguePhysicsMath.ResetRequired(Vector3.Distance(target, previousTarget), Quaternion.Angle(head.rotation, previousRotation), scale, previousScale))
		{
			ResetAt(target, scale);
		}
		if (!Finite(tip.position) || !Finite(tip.linearVelocity) || Vector3.Distance(tip.position, target) > data.maxOffset * scale * 4f)
		{
			ResetAt(target, scale);
		}
		if (!simulating)
		{
			tip.isKinematic = false;
			tip.WakeUp();
			simulating = true;
		}
		Configure(scale);
		anchor.MovePosition(target);
		float num = flutter.Step(Vector3.Distance(head.position, previousOrigin), scale, Time.fixedDeltaTime, data.maxOffset);
		tip.AddForce(head.right * num, (ForceMode)5);
		previousOrigin = head.position;
		previousTarget = target;
		previousScale = scale;
		previousRotation = head.rotation;
	}

	internal void SetPoseAndApply(float extension, bool visible)
	{
		//IL_0094: 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_00a6: 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_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_00e9: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		tongue = extension;
		requested = visible && TonguePhysicsMath.Envelope(tongue) > 0f;
		if (observed && !retractionObserved && visible && tongue <= 0.5f)
		{
			retractionObserved = true;
			log("Tongue PhysX retraction observed: physical motion stopped and all flex cleared as the tongue retracts.");
		}
		if (!requested || !Pose(out var target, out var scale))
		{
			Suspend();
			return;
		}
		if (!simulating || (Object)(object)tip == (Object)null)
		{
			ClearShapes();
			return;
		}
		if (TonguePhysicsMath.ResetRequired(Vector3.Distance(target, previousTarget), Quaternion.Angle(head.rotation, previousRotation), scale, previousScale))
		{
			ResetAt(target, scale);
			return;
		}
		Vector3 val = Quaternion.Inverse(jaw.localRotation) * head.InverseTransformVector(tip.position - target);
		TonguePhysicsMath.Weights(val.x, val.y, val.z, data.maxOffset, TonguePhysicsMath.Envelope(tongue), weights);
		float num = 0f;
		for (int i = 0; i < weights.Length; i++)
		{
			renderer.SetBlendShapeWeight(indices[i], weights[i] * 100f);
			num = Mathf.Max(num, weights[i]);
		}
		if (!observed && num > 0.08f)
		{
			observed = true;
			log("Tongue PhysX motion observed: dynamic tip, gravity and spring joint; bounded visual flex active.");
		}
		observedRight |= weights[0] > 0.15f;
		observedLeft |= weights[1] > 0.15f;
		if (!flutterObserved && observedRight && observedLeft)
		{
			flutterObserved = true;
			log("Tongue air flutter observed in both directions: real PhysX motion, speed-scaled wind and fixed mouth attachment.");
		}
	}

	private void ClearShapes()
	{
		if (!((Object)(object)renderer == (Object)null) && indices != null)
		{
			for (int i = 0; i < indices.Length; i++)
			{
				renderer.SetBlendShapeWeight(indices[i], 0f);
			}
		}
	}

	private void Suspend()
	{
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		requested = false;
		simulating = false;
		ClearShapes();
		if ((Object)(object)tip != (Object)null && !tip.isKinematic)
		{
			tip.linearVelocity = Vector3.zero;
			tip.angularVelocity = Vector3.zero;
			tip.isKinematic = true;
		}
		previousScale = 0f;
		flutter.Reset();
		previousOrigin = Vector3.zero;
	}

	private void OnDisable()
	{
		Cleanup();
	}

	private void OnDestroy()
	{
		Cleanup();
	}

	private void Cleanup()
	{
		Suspend();
		if ((Object)(object)worldRoot != (Object)null)
		{
			worldRoot.SetActive(false);
			Object.Destroy((Object)(object)worldRoot);
		}
		worldRoot = null;
		anchor = null;
		tip = null;
		joint = null;
	}
}
internal sealed class TongueFlutterState
{
	internal float FilteredSpeed;

	internal float Phase;

	internal float SecondaryPhase;

	internal float ActiveTime;

	internal void Reset()
	{
		FilteredSpeed = (Phase = (SecondaryPhase = (ActiveTime = 0f)));
	}

	internal float Step(float originDistance, float scale, float dt, float maxOffset)
	{
		if (!HeadValidation.Finite(originDistance) || originDistance < 0f || !HeadValidation.Finite(scale) || scale <= 0.001f || !HeadValidation.Finite(dt) || dt <= 0f || dt > 0.1f || !HeadValidation.Finite(maxOffset) || maxOffset <= 0f)
		{
			Reset();
			return 0f;
		}
		float num = Math.Min(6f, originDistance / (scale * dt));
		FilteredSpeed += (num - FilteredSpeed) * (1f - (float)Math.Exp((0f - dt) / 0.18f));
		float num2 = TonguePhysicsMath.FlutterFrequency(FilteredSpeed);
		Phase = TonguePhysicsMath.AdvancePhase(Phase, num2, dt);
		SecondaryPhase = TonguePhysicsMath.AdvancePhase(SecondaryPhase, num2 * 1.73f, dt);
		ActiveTime = Math.Min(0.35f, ActiveTime + dt);
		return TonguePhysicsMath.WindAcceleration(Phase, SecondaryPhase, num2, TonguePhysicsMath.FlutterAmplitude(FilteredSpeed) * maxOffset * scale, scale) * TonguePhysicsMath.Smooth01(ActiveTime / 0.35f);
	}
}
internal static class TonguePhysicsMath
{
	internal const float SpringPerMassAtUnitScale = 180f;

	internal const float DampingRatio = 0.45f;

	internal const float BodyDamping = 0.15f;

	internal static readonly string[] ShapeNames = new string[6] { "TongueFlexRight", "TongueFlexLeft", "TongueFlexUp", "TongueFlexDown", "TongueFlexForward", "TongueFlexBack" };

	internal static float Smooth01(float value)
	{
		if (!HeadValidation.Finite(value))
		{
			return 0f;
		}
		float num = Math.Max(0f, Math.Min(1f, value));
		return num * num * (3f - 2f * num);
	}

	internal static float FlutterFrequency(float speed)
	{
		return 1.35f + 1.5f * Smooth01(speed / 2.4f);
	}

	internal static float FlutterAmplitude(float speed)
	{
		return 0.42f + 0.46f * Smooth01(speed / 2.4f);
	}

	internal static float AdvancePhase(float phase, float frequency, float dt)
	{
		if (!HeadValidation.Finite(phase) || !HeadValidation.Finite(frequency) || !HeadValidation.Finite(dt))
		{
			return 0f;
		}
		double num = Math.PI * 2.0;
		return (float)(((double)phase + (double)(Math.Max(0f, frequency) * Math.Max(0f, dt)) * num) % num);
	}

	private static double HarmonicForce(float phase, double angularFrequency, double amplitude, double springPerMass, double dampingPerMass)
	{
		return amplitude * ((springPerMass - angularFrequency * angularFrequency) * Math.Sin(phase) + dampingPerMass * angularFrequency * Math.Cos(phase));
	}

	internal static float WindAcceleration(float phase, float secondaryPhase, float frequency, float amplitude, float scale)
	{
		if (!HeadValidation.Finite(phase) || !HeadValidation.Finite(secondaryPhase) || !HeadValidation.Finite(frequency) || !HeadValidation.Finite(amplitude) || !HeadValidation.Finite(scale) || frequency < 0f || amplitude < 0f || scale <= 0.001f)
		{
			return 0f;
		}
		double num = 180f / scale;
		double dampingPerMass = 0.8999999761581421 * Math.Sqrt(num) + 0.15000000596046448;
		double num2 = Math.PI * 2.0 * (double)Math.Min(3.5f, frequency);
		double val = HarmonicForce(phase, num2, (double)amplitude * 0.88, num, dampingPerMass) + HarmonicForce(secondaryPhase, num2 * 1.73, (double)amplitude * 0.12, num, dampingPerMass);
		return (float)Math.Max(-80f * scale, Math.Min(80f * scale, val));
	}

	internal static float Envelope(float tongue)
	{
		if (!HeadValidation.Finite(tongue))
		{
			return 0f;
		}
		float num = Math.Max(0f, Math.Min(1f, (tongue - 0.5f) / 0.5f));
		return num * num * (3f - 2f * num);
	}

	internal static bool ScaleValid(float x, float y, float z)
	{
		if (!HeadValidation.Finite(x) || !HeadValidation.Finite(y) || !HeadValidation.Finite(z))
		{
			return false;
		}
		float num = Math.Min(x, Math.Min(y, z));
		float num2 = Math.Max(x, Math.Max(y, z));
		if (num > 0.001f && num2 < 100f)
		{
			return num2 / num < 1.15f;
		}
		return false;
	}

	internal static bool ResetRequired(float distance, float angle, float scale, float previousScale)
	{
		if (HeadValidation.Finite(distance) && HeadValidation.Finite(angle) && HeadValidation.Finite(scale) && HeadValidation.Finite(previousScale) && !(previousScale <= 0.001f) && !(scale <= 0.001f) && !(distance > Math.Max(0.5f, scale * 0.5f)) && !(angle > 75f) && !(scale / previousScale < 0.85f))
		{
			return scale / previousScale > 1.15f;
		}
		return true;
	}

	internal static void Weights(float x, float y, float z, float maximum, float envelope, float[] output)
	{
		Array.Clear(output, 0, output.Length);
		if (output.Length == 6 && HeadValidation.Finite(x) && HeadValidation.Finite(y) && HeadValidation.Finite(z) && HeadValidation.Finite(maximum) && !(maximum <= 0f) && HeadValidation.Finite(envelope) && !(envelope <= 0f))
		{
			double val = Math.Sqrt((double)x * (double)x + (double)y * (double)y + (double)z * (double)z);
			float num = (float)(Math.Min(1.0, (double)maximum / Math.Max(val, 1E-20)) / (double)maximum) * Math.Min(1f, envelope);
			output[0] = Math.Max(x, 0f) * num;
			output[1] = Math.Max(0f - x, 0f) * num;
			output[2] = Math.Max(y, 0f) * num;
			output[3] = Math.Max(0f - y, 0f) * num;
			output[4] = Math.Max(z, 0f) * num;
			output[5] = Math.Max(0f - z, 0f) * num;
		}
	}
}