Decompiled source of NahidaFrieren v0.1.2

NahidaFrieren.dll

Decompiled 4 hours ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using Dissonance;
using GameNetcodeStuff;
using Microsoft.CodeAnalysis;
using ModelReplacement;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("NahidaFrieren")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("NahidaFrieren")]
[assembly: AssemblyTitle("NahidaFrieren")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NahidaFrierenMod
{
	internal sealed class NahidaExpressions
	{
		private GameObject root;

		private SkinnedMeshRenderer face;

		private int mouthDefault = -1;

		private int a = -1;

		private int o = -1;

		private int eyeDefault = -1;

		private int l = -1;

		private int r = -1;

		internal bool Ready => Object.op_Implicit((Object)(object)face);

		internal void Bind(GameObject model)
		{
			if ((Object)(object)root == (Object)(object)model)
			{
				return;
			}
			root = model;
			face = null;
			if (!Object.op_Implicit((Object)(object)model))
			{
				return;
			}
			SkinnedMeshRenderer[] componentsInChildren = model.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val in componentsInChildren)
			{
				Mesh sharedMesh = val.sharedMesh;
				if (Object.op_Implicit((Object)(object)sharedMesh))
				{
					int blendShapeIndex = sharedMesh.GetBlendShapeIndex("Mouth_A01");
					int blendShapeIndex2 = sharedMesh.GetBlendShapeIndex("Eye_WinkA_L");
					int blendShapeIndex3 = sharedMesh.GetBlendShapeIndex("Eye_WinkA_R");
					if (blendShapeIndex >= 0 && blendShapeIndex2 >= 0 && blendShapeIndex3 >= 0)
					{
						face = val;
						a = blendShapeIndex;
						l = blendShapeIndex2;
						r = blendShapeIndex3;
						mouthDefault = sharedMesh.GetBlendShapeIndex("Mouth_Default");
						o = sharedMesh.GetBlendShapeIndex("Mouth_Open01");
						eyeDefault = sharedMesh.GetBlendShapeIndex("Eye_Default");
						break;
					}
				}
			}
		}

		internal void Apply(float open, float round, float blink)
		{
			if (Object.op_Implicit((Object)(object)face))
			{
				float num = Mathf.Clamp01(open);
				float num2 = Mathf.Clamp(round, 0f, 1f - num);
				float num3 = Mathf.Clamp01(blink);
				if (mouthDefault >= 0)
				{
					face.SetBlendShapeWeight(mouthDefault, (1f - num - num2) * 100f);
				}
				face.SetBlendShapeWeight(a, num * 100f);
				if (o >= 0)
				{
					face.SetBlendShapeWeight(o, num2 * 100f);
				}
				if (eyeDefault >= 0)
				{
					face.SetBlendShapeWeight(eyeDefault, (1f - num3) * 100f);
				}
				face.SetBlendShapeWeight(l, num3 * 100f);
				face.SetBlendShapeWeight(r, num3 * 100f);
			}
		}
	}
	[BepInPlugin("dtopaz.nahidafrieren", "Nahida Frieren", "0.1.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static GameObject Prefab;

		internal static GameObject Capeless;

		internal static Texture2D[] Atlases;

		private AssetBundle bundle;

		private void Awake()
		{
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "nahidafrieren");
			bundle = AssetBundle.LoadFromFile(text);
			if (!Object.op_Implicit((Object)(object)bundle))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Nahida Frieren asset bundle could not be opened");
				return;
			}
			Prefab = bundle.LoadAsset<GameObject>("assets/nahidafrieren/nahidafrieren.prefab");
			if (!Object.op_Implicit((Object)(object)Prefab))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Nahida Frieren outfit prefab not found");
				return;
			}
			Atlases = (Texture2D[])(object)new Texture2D[4];
			for (int i = 0; i < RuntimeMaterials.Names.Length; i++)
			{
				string text2 = RuntimeMaterials.Names[i];
				using Stream stream = typeof(Plugin).Assembly.GetManifestResourceStream("NahidaFrieren." + text2 + ".png");
				using MemoryStream memoryStream = new MemoryStream();
				if (stream == null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Missing embedded atlas " + text2));
					return;
				}
				stream.CopyTo(memoryStream);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)3, true, false);
				if (!ImageConversion.LoadImage(val, memoryStream.ToArray(), true))
				{
					Object.Destroy((Object)(object)val);
					((BaseUnityPlugin)this).Logger.LogError((object)("Could not decode " + text2));
					return;
				}
				((Object)val).name = text2;
				((Texture)val).anisoLevel = 4;
				Atlases[i] = val;
			}
			ModelReplacementAPI.RegisterSuitModelReplacement("Nahida Frieren", typeof(Body));
			Capeless = bundle.LoadAsset<GameObject>("assets/nahidafrieren/nahidafrierencapeless.prefab");
			if (Object.op_Implicit((Object)(object)Capeless))
			{
				ModelReplacementAPI.RegisterSuitModelReplacement("Nahida Frieren Capeless", typeof(CapelessBody));
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Optional capeless outfit prefab not found.");
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Registered separate suit Nahida Frieren: four embedded diffuse atlases decoded.");
		}
	}
	public class Body : BodyReplacementBase
	{
		private readonly VoiceFace voice = new VoiceFace();

		private Material[] materials;

		private GameObject main;

		private GameObject hands;

		private GameObject dead;

		private GameObject shadow;

		private bool logged;

		private bool reportedMissing;

		protected override GameObject LoadAssetsAndReturnModel()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Prefab.transform.localScale = Vector3.one;
			return Plugin.Prefab;
		}

		public override void LateUpdate()
		{
			((BodyReplacementBase)this).LateUpdate();
			voice.Frame(base.replacementModel, base.replacementModelShadow, base.replacementViewModel, ((BodyReplacementBase)this).controller);
			if (materials == null && Object.op_Implicit((Object)(object)base.replacementModel) && Object.op_Implicit((Object)(object)((BodyReplacementBase)this).controller) && Plugin.Atlases != null)
			{
				SkinnedMeshRenderer val = (Object.op_Implicit((Object)(object)((BodyReplacementBase)this).controller.thisPlayerModel) ? ((Component)((BodyReplacementBase)this).controller.thisPlayerModel).GetComponent<SkinnedMeshRenderer>() : null);
				materials = RuntimeMaterials.Create(Object.op_Implicit((Object)(object)val) ? ((Renderer)val).sharedMaterial : null, Plugin.Atlases);
				if (materials == null && !reportedMissing)
				{
					reportedMissing = true;
					Debug.LogWarning((object)"[Nahida Frieren] Native HDRP/Lit not available.");
				}
			}
			if (materials != null)
			{
				Bind(ref main, base.replacementModel, body: true);
				Bind(ref hands, base.replacementViewModel, body: false);
				Bind(ref dead, base.replacementDeadBody, body: false);
				Bind(ref shadow, base.replacementModelShadow, body: false);
			}
		}

		private void Bind(ref GameObject prior, GameObject next, bool body)
		{
			if (Object.op_Implicit((Object)(object)next) && !((Object)(object)prior == (Object)(object)next))
			{
				prior = next;
				int num = RuntimeMaterials.Apply(next, materials);
				if (body && !logged)
				{
					logged = true;
					Debug.Log((object)$"[Nahida Frieren] Assigned native opaque {((Object)materials[0].shader).name} to {num} renderers: skin, hair, face and dress.");
				}
			}
		}

		protected override void OnDestroy()
		{
			if (materials != null)
			{
				Material[] array = materials;
				foreach (Material val in array)
				{
					if (Object.op_Implicit((Object)(object)val))
					{
						Object.Destroy((Object)(object)val);
					}
				}
			}
			((BodyReplacementBase)this).OnDestroy();
		}
	}
	public sealed class CapelessBody : Body
	{
		protected override GameObject LoadAssetsAndReturnModel()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Capeless.transform.localScale = Vector3.one;
			return Plugin.Capeless;
		}
	}
	internal static class RuntimeMaterials
	{
		internal static readonly string[] Names = new string[4] { "NahidaSkin", "NahidaHair", "NahidaFace", "FrierenCloth" };

		internal static Material[] Create(Material native, Texture2D[] atlases)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			Shader val = ((Object.op_Implicit((Object)(object)native) && Object.op_Implicit((Object)(object)native.shader) && native.shader.isSupported && ((Object)native.shader).name == "HDRP/Lit") ? native.shader : Shader.Find("HDRP/Lit"));
			if (!Object.op_Implicit((Object)(object)val) || !val.isSupported)
			{
				return null;
			}
			Material[] array = (Material[])(object)new Material[4];
			for (int i = 0; i < array.Length; i++)
			{
				Material val2 = (array[i] = ((Object.op_Implicit((Object)(object)native) && native.shader == val) ? new Material(native) : new Material(val)));
				((Object)val2).name = Names[i] + " Runtime";
				string[] array2 = new string[2] { "_BaseColorMap", "_MainTex" };
				foreach (string text in array2)
				{
					if (val2.HasProperty(text))
					{
						val2.SetTexture(text, (Texture)(object)atlases[i]);
						val2.SetTextureScale(text, Vector2.one);
						val2.SetTextureOffset(text, Vector2.zero);
					}
				}
				array2 = new string[3] { "_BaseColor", "_Color", "_UnlitColor" };
				foreach (string text2 in array2)
				{
					if (val2.HasProperty(text2))
					{
						val2.SetColor(text2, Color.white);
					}
				}
				array2 = new string[11]
				{
					"_MaskMap", "_NormalMap", "_NormalMapOS", "_DetailMap", "_BentNormalMap", "_BentNormalMapOS", "_EmissiveColorMap", "_AnisotropyMap", "_CoatMaskMap", "_HeightMap",
					"_DistortionVectorMap"
				};
				foreach (string text3 in array2)
				{
					if (val2.HasProperty(text3))
					{
						val2.SetTexture(text3, (Texture)null);
					}
				}
				array2 = new string[17]
				{
					"_SURFACE_TYPE_TRANSPARENT", "_ALPHATEST_ON", "_BLENDMODE_ALPHA", "_BLENDMODE_ADD", "_BLENDMODE_PRE_MULTIPLY", "_ENABLE_FOG_ON_TRANSPARENT", "_TRANSPARENT_WRITES_MOTION_VEC", "_MASKMAP", "_NORMALMAP", "_NORMALMAP_TANGENT_SPACE",
					"_DETAIL_MAP", "_EMISSIVE_COLOR_MAP", "_BENTNORMALMAP", "_HEIGHTMAP", "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", "_MATERIAL_FEATURE_TRANSMISSION", "_ENABLE_GEOMETRIC_SPECULAR_AA"
				};
				foreach (string text4 in array2)
				{
					val2.DisableKeyword(text4);
				}
				array2 = new string[17]
				{
					"_SurfaceType", "_AlphaCutoffEnable", "_TransparentZWrite", "_TransparentDepthPrepassEnable", "_TransparentDepthPostpassEnable", "_BlendMode", "_CullMode", "_CullModeForward", "_CullModeForDepth", "_OpaqueCullMode",
					"_Metallic", "_EnableBlendModePreserveSpecularLighting", "_EnableFogOnTransparent", "_UseEmissiveIntensity", "_EmissiveIntensity", "_EnableSpecularOcclusion", "_CoatMask"
				};
				foreach (string text5 in array2)
				{
					if (val2.HasProperty(text5))
					{
						val2.SetFloat(text5, 0f);
					}
				}
				array2 = new string[5] { "_ZWrite", "_AlphaDstBlendIgnored", "_SrcBlend", "_AlphaSrcBlend", "_DoubleSidedEnable" };
				foreach (string text6 in array2)
				{
					if (val2.HasProperty(text6))
					{
						val2.SetFloat(text6, 1f);
					}
				}
				array2 = new string[2] { "_DstBlend", "_AlphaDstBlend" };
				foreach (string text7 in array2)
				{
					if (val2.HasProperty(text7))
					{
						val2.SetFloat(text7, 0f);
					}
				}
				array2 = new string[3] { "_ZTestDepthEqualForOpaque", "_ZTestGBuffer", "_ZTestTransparent" };
				foreach (string text8 in array2)
				{
					if (val2.HasProperty(text8))
					{
						val2.SetFloat(text8, 4f);
					}
				}
				if (val2.HasProperty("_Smoothness"))
				{
					val2.SetFloat("_Smoothness", 0.27f);
				}
				val2.EnableKeyword("_DOUBLESIDED_ON");
				val2.SetOverrideTag("RenderType", "Opaque");
				val2.renderQueue = 2000;
				array2 = new string[6] { "Forward", "ForwardOnly", "GBuffer", "DepthOnly", "DepthForwardOnly", "ShadowCaster" };
				foreach (string text9 in array2)
				{
					val2.SetShaderPassEnabled(text9, true);
				}
				array2 = new string[4] { "TransparentDepthPrepass", "TransparentDepthPostpass", "TransparentBackface", "DistortionVectors" };
				foreach (string text10 in array2)
				{
					val2.SetShaderPassEnabled(text10, false);
				}
			}
			return array;
		}

		internal static int Apply(GameObject o, Material[] m)
		{
			if (!Object.op_Implicit((Object)(object)o) || m == null)
			{
				return 0;
			}
			int num = 0;
			SkinnedMeshRenderer[] componentsInChildren = o.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val in componentsInChildren)
			{
				if (Object.op_Implicit((Object)(object)val.sharedMesh))
				{
					if (val.sharedMesh.subMeshCount == 5 && val.sharedMesh.blendShapeCount >= 40)
					{
						((Renderer)val).sharedMaterials = (Material[])(object)new Material[5]
						{
							m[0],
							m[1],
							m[1],
							m[0],
							m[2]
						};
						num++;
					}
					else if (val.sharedMesh.subMeshCount == 1 && ((Object)val.sharedMesh).name.StartsWith("FrierenOutfit", StringComparison.Ordinal))
					{
						((Renderer)val).sharedMaterial = m[3];
						num++;
					}
					else if (val.sharedMesh.subMeshCount == 1 && ((Object)val.sharedMesh).name.StartsWith("EyeStar", StringComparison.Ordinal))
					{
						((Renderer)val).sharedMaterial = m[2];
						num++;
					}
				}
			}
			return num;
		}
	}
	internal sealed class VoiceEnvelope
	{
		public float Open { get; private set; }

		public float Round { get; private set; }

		public void Step(bool active, float amplitude, float dt)
		{
			if (float.IsNaN(amplitude) || float.IsInfinity(amplitude))
			{
				amplitude = 0f;
			}
			float num = (active ? Mathf.Clamp01((amplitude - 0.006f) / 0.105f) : 0f);
			Open = Smooth(Open, Mathf.Pow(num, 1.35f) * 0.68f, dt, 0.025f, 0.085f);
			Round = Smooth(Round, Mathf.Sqrt(num) * (1f - num) * 0.15f, dt, 0.035f, 0.09f);
		}

		private static float Smooth(float a, float b, float dt, float attack, float release)
		{
			float num = Mathf.Lerp(a, b, 1f - Mathf.Exp((0f - Mathf.Clamp(dt, 0f, 0.1f)) / ((b > a) ? attack : release)));
			if (!(num < 0.001f))
			{
				return num;
			}
			return 0f;
		}
	}
	internal sealed class VoiceFace
	{
		private static readonly FieldInfo CaptureField = typeof(DissonanceComms).GetField("_capture", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly PropertyInfo CaptureAmp = CaptureField?.FieldType.GetProperty("Amplitude", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private readonly NahidaExpressions[] faces = new NahidaExpressions[3]
		{
			new NahidaExpressions(),
			new NahidaExpressions(),
			new NahidaExpressions()
		};

		private readonly VoiceEnvelope envelope = new VoiceEnvelope();

		private bool logged;

		private float nextBlink;

		private float started = -100f;

		internal void Frame(GameObject body, GameObject shadow, GameObject view, PlayerControllerB p)
		{
			faces[0].Bind(body);
			faces[1].Bind(shadow);
			faces[2].Bind(view);
			bool num = Object.op_Implicit((Object)(object)p) && !p.isPlayerDead;
			(bool, float, bool) tuple = Read(p);
			envelope.Step(tuple.Item1, tuple.Item2, Time.unscaledDeltaTime);
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= nextBlink)
			{
				started = unscaledTime;
				nextBlink = unscaledTime + Random.Range(2.4f, 6.3f);
			}
			float num2 = unscaledTime - started;
			float blink = ((!num) ? 0f : ((num2 < 0.065f) ? Mathf.SmoothStep(0f, 1f, num2 / 0.065f) : Mathf.SmoothStep(1f, 0f, (num2 - 0.078f) / 0.115f)));
			NahidaExpressions[] array = faces;
			for (int i = 0; i < array.Length; i++)
			{
				array[i].Apply(envelope.Open, envelope.Round, blink);
			}
			if (!logged && envelope.Open > 0.003f)
			{
				logged = true;
				Debug.Log((object)("[Nahida Frieren] Voice enabled: active " + (tuple.Item3 ? "local microphone" : "remote player") + " envelope."));
			}
		}

		private static (bool active, float amplitude, bool local) Read(PlayerControllerB p)
		{
			if (!Object.op_Implicit((Object)(object)p) || p.isPlayerDead)
			{
				return (active: false, amplitude: 0f, local: false);
			}
			GameNetworkManager instance = GameNetworkManager.Instance;
			if (!Object.op_Implicit((Object)(object)instance) || (Object)(object)instance.localPlayerController != (Object)(object)p)
			{
				VoicePlayerState voicePlayerState = p.voicePlayerState;
				if (voicePlayerState != null && !voicePlayerState.IsLocallyMuted)
				{
					return (active: voicePlayerState.IsSpeaking || voicePlayerState.Amplitude > 0.001f, amplitude: voicePlayerState.Amplitude, local: false);
				}
				return (active: false, amplitude: 0f, local: false);
			}
			StartOfRound instance2 = StartOfRound.Instance;
			DissonanceComms val = (Object.op_Implicit((Object)(object)instance2) ? instance2.voiceChatModule : null);
			if (!Object.op_Implicit((Object)(object)val) || !((Behaviour)val).enabled || val.IsMuted)
			{
				return (active: false, amplitude: 0f, local: true);
			}
			IngamePlayerSettings instance3 = IngamePlayerSettings.Instance;
			if (Object.op_Implicit((Object)(object)instance3) && !instance3.settings.micEnabled)
			{
				return (active: false, amplitude: 0f, local: true);
			}
			bool num = Object.op_Implicit((Object)(object)instance3) && instance3.settings.pushToTalk;
			string localPlayerName = val.LocalPlayerName;
			VoicePlayerState val2 = (string.IsNullOrEmpty(localPlayerName) ? null : val.FindPlayer(localPlayerName));
			if (num && (val2 == null || !val2.IsSpeaking))
			{
				return (active: false, amplitude: 0f, local: true);
			}
			float num2 = ((val2 != null) ? val2.Amplitude : 0f);
			if (num2 < 0.012f)
			{
				object obj = CaptureField?.GetValue(val);
				if (obj != null && CaptureAmp?.GetValue(obj) is float num3)
				{
					num2 = Mathf.Max(num2, num3);
				}
			}
			return (active: num2 > 0.0006f, amplitude: num2, local: true);
		}
	}
}