Decompiled source of Toastie NurseAcrid v1.0.0

Toast_NurseAcrid.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using MonoMod.RuntimeDetour.HookGen;
using RoR2;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Toast_NurseAcrid;

public class MeshActivator : MonoBehaviour
{
	[Serializable]
	public struct CustomRendererInfo
	{
		public Material material;

		public string addressableMaterialPath;

		public bool ignoreOverlays;

		public ShadowCastingMode shadowCastingMode;
	}

	[Header("Reference Settings")]
	[Tooltip("Name of the in-game original mesh object.")]
	public string referenceObjectName;

	[Tooltip("Copy Bone Data From Reference Object.")]
	public bool CopyBoneData = true;

	[Tooltip("Active state applied once registered.")]
	public bool initialActiveState = true;

	[Tooltip("Custom configuration for the renderer info applied to the CharacterModel.")]
	public CustomRendererInfo customRendererInfo = new CustomRendererInfo
	{
		shadowCastingMode = (ShadowCastingMode)1,
		ignoreOverlays = false
	};

	private CharacterModel characterModel;

	private bool registered;

	private IEnumerator Start()
	{
		for (int i = 0; i < 5; i++)
		{
			yield return null;
		}
		Register();
	}

	private void Register()
	{
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: 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_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_0293: Unknown result type (might be due to invalid IL or missing references)
		//IL_0294: 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_025c: Unknown result type (might be due to invalid IL or missing references)
		if (registered)
		{
			return;
		}
		Renderer component = ((Component)this).GetComponent<Renderer>();
		if (!Object.op_Implicit((Object)(object)component))
		{
			Debug.LogWarning((object)("[MeshActivator] '" + ((Object)this).name + "' has no SkinnedMeshRenderer."), (Object)(object)this);
			return;
		}
		Transform val = FindReference();
		if (!Object.op_Implicit((Object)(object)val))
		{
			Debug.LogWarning((object)("[MeshActivator] '" + ((Object)this).name + "': '" + referenceObjectName + "'not found in its hierarchy."), (Object)(object)this);
			return;
		}
		characterModel = ((Component)val).GetComponentInParent<CharacterModel>();
		if (!Object.op_Implicit((Object)(object)characterModel))
		{
			characterModel = ((Component)this).GetComponentInParent<CharacterModel>();
		}
		if (!Object.op_Implicit((Object)(object)characterModel))
		{
			Debug.LogWarning((object)("[MeshActivator] '" + ((Object)this).name + "': no CharacterModel found above '" + ((Object)val).name + "'"), (Object)(object)this);
			return;
		}
		if (CopyBoneData)
		{
			SkinnedMeshRenderer val2 = ((Component)val).GetComponent<SkinnedMeshRenderer>();
			if (!Object.op_Implicit((Object)(object)val2))
			{
				val2 = ((Component)val).GetComponentInChildren<SkinnedMeshRenderer>(true);
			}
			if (Object.op_Implicit((Object)(object)val2))
			{
				SkinnedMeshRenderer val3 = (SkinnedMeshRenderer)(object)((component is SkinnedMeshRenderer) ? component : null);
				if (val3 != null)
				{
					val3.rootBone = val2.rootBone;
					val3.bones = val2.bones;
					goto IL_015d;
				}
			}
			Debug.LogWarning((object)("[MeshActivator] '" + ((Object)val).name + "' has no SkinnedMeshRenderer to copy bones from."), (Object)(object)this);
		}
		goto IL_015d;
		IL_015d:
		Material val4 = customRendererInfo.material;
		if (!Object.op_Implicit((Object)(object)val4) && !string.IsNullOrEmpty(customRendererInfo.addressableMaterialPath))
		{
			val4 = Addressables.LoadAssetAsync<Material>((object)customRendererInfo.addressableMaterialPath).WaitForCompletion();
			if (!Object.op_Implicit((Object)(object)val4))
			{
				Debug.LogWarning((object)("[MeshActivator] Failed to load material via Addressables path: '" + customRendererInfo.addressableMaterialPath + "'. Falling back to sharedMaterial."), (Object)(object)this);
			}
		}
		if (!Object.op_Implicit((Object)(object)val4))
		{
			val4 = component.sharedMaterial;
		}
		RendererInfo val5 = new RendererInfo
		{
			renderer = component,
			defaultMaterial = val4,
			defaultShadowCastingMode = customRendererInfo.shadowCastingMode,
			ignoreOverlays = customRendererInfo.ignoreOverlays
		};
		RendererInfo[] baseRendererInfos = characterModel.baseRendererInfos;
		int num = -1;
		for (int i = 0; i < baseRendererInfos.Length; i++)
		{
			if ((Object)(object)baseRendererInfos[i].renderer == (Object)(object)component)
			{
				num = i;
				break;
			}
		}
		if (num >= 0)
		{
			baseRendererInfos[num] = val5;
		}
		else
		{
			Array.Resize(ref characterModel.baseRendererInfos, baseRendererInfos.Length + 1);
			characterModel.baseRendererInfos[characterModel.baseRendererInfos.Length - 1] = val5;
		}
		registered = true;
		characterModel.UpdateMaterials();
		((Component)this).gameObject.SetActive(initialActiveState);
	}

	private Transform FindReference()
	{
		if (string.IsNullOrEmpty(referenceObjectName))
		{
			return null;
		}
		Transform parent = ((Component)this).transform.parent;
		while (Object.op_Implicit((Object)(object)parent))
		{
			if (((Object)parent).name == referenceObjectName)
			{
				return parent;
			}
			Transform[] componentsInChildren = ((Component)parent).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)(object)((Component)this).transform) && !val.IsChildOf(((Component)this).transform) && ((Object)val).name == referenceObjectName)
				{
					return val;
				}
			}
			parent = parent.parent;
		}
		return null;
	}
}
[BepInPlugin("com.KrononConpsirator.Toast_NurseAcrid", "Toast_NurseAcrid", "1.0.0")]
public class Toast_NurseAcridPlugin : BaseUnityPlugin
{
	private class FieldException : Exception
	{
		public FieldException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}

	private class ElementException : Exception
	{
		public int Index { get; }

		public ElementException(int index, string message)
			: base(message)
		{
			Index = index;
		}
	}

	private static AssetBundle assetBundle;

	private static readonly List<Material> materialsWithRoRShader = new List<Material>();

	internal static Toast_NurseAcridPlugin Instance { get; private set; }

	internal static ManualLogSource InstanceLogger
	{
		get
		{
			Toast_NurseAcridPlugin instance = Instance;
			if (instance == null)
			{
				return null;
			}
			return ((BaseUnityPlugin)instance).Logger;
		}
	}

	private void Start()
	{
		Instance = this;
		using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Toast_NurseAcrid.krononconpsiratortoast_nurseacrid"))
		{
			assetBundle = AssetBundle.LoadFromStream(stream);
		}
		((ResourceAvailability)(ref BodyCatalog.availability)).CallWhenAvailable((Action)BodyCatalogInit);
		HookEndpointManager.Add((MethodBase)typeof(Language).GetMethod("LoadStrings"), (Delegate)new Action<Action<Language>, Language>(LanguageLoadStrings));
		ReplaceShaders();
	}

	private static void ReplaceShaders()
	{
		LoadMaterialsWithReplacedShader("RoR2/Base/Shaders/HGStandard.shader", "Assets/Skins/SkinAsset/Vanilla/Acrid/ToastNurseAcrid/NurseAcridAddonMat.mat", "Assets/Skins/SkinAsset/Vanilla/Acrid/ToastNurseAcrid/AcridNurseScrubsMat.mat");
	}

	private static void LoadMaterialsWithReplacedShader(string shaderPath, params string[] materialPaths)
	{
		//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)
		Shader shader = Addressables.LoadAssetAsync<Shader>((object)shaderPath).WaitForCompletion();
		foreach (string text in materialPaths)
		{
			Material val = assetBundle.LoadAsset<Material>(text);
			val.shader = shader;
			materialsWithRoRShader.Add(val);
		}
	}

	private static void LanguageLoadStrings(Action<Language> orig, Language self)
	{
		orig(self);
		self.SetStringByToken("KRONONCONPSIRATOR_SKIN_TOASTNUSEACRIDSKINDEF_NAME", "Vile Resident");
	}

	private static void BodyCatalogInit()
	{
		AddCrocoBodyToastNuseAcridSkinDefSkin();
	}

	private static void AddCrocoBodyToastNuseAcridSkinDefSkin()
	{
		string text = "CrocoBody";
		string text2 = "ToastNuseAcridSkinDef";
		try
		{
			GameObject val = BodyCatalog.FindBodyPrefab(text);
			if (!Object.op_Implicit((Object)(object)val))
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin because \"" + text + "\" doesn't exist"));
				return;
			}
			ModelLocator component = val.GetComponent<ModelLocator>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\" because it doesn't have \"ModelLocator\" component"));
				return;
			}
			GameObject mdl = ((Component)component.modelTransform).gameObject;
			ModelSkinController skinController = (Object.op_Implicit((Object)(object)mdl) ? mdl.GetComponent<ModelSkinController>() : null);
			if (!Object.op_Implicit((Object)(object)skinController))
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\" because it doesn't have \"ModelSkinController\" component"));
				return;
			}
			Renderer[] renderers = mdl.GetComponentsInChildren<Renderer>(true);
			mdl.GetComponentsInChildren<Light>(true);
			SkinDef skin = ScriptableObject.CreateInstance<SkinDef>();
			SkinDefParams skinParams = ScriptableObject.CreateInstance<SkinDefParams>();
			skin.skinDefParams = skinParams;
			TryCatchThrow("Icon", delegate
			{
				skin.icon = assetBundle.LoadAsset<Sprite>("Assets\\SkinMods\\Toast_NurseAcrid\\Icons\\ToastNuseAcridSkinDefIcon.png");
			});
			((Object)skin).name = text2;
			skin.nameToken = "KRONONCONPSIRATOR_SKIN_TOASTNUSEACRIDSKINDEF_NAME";
			skin.rootObject = mdl;
			TryCatchThrow("Base Skins", delegate
			{
				skin.baseSkins = (SkinDef[])(object)new SkinDef[1] { ThrowIfOutOfBounds(0, "Index 0 is out of bounds of skins array", skinController.skins, 0) };
			});
			TryCatchThrow("Unlockable Name", delegate
			{
				skin.unlockableDef = null;
			});
			TryCatchThrow("Game Object Activations", delegate
			{
				//IL_0010: 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_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0094: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
				skinParams.gameObjectActivations = (GameObjectActivation[])(object)new GameObjectActivation[1]
				{
					new GameObjectActivation
					{
						gameObject = ThrowIfNull<GameObject>(0, "There is no renderer at path \"CrocoArmature\"", GetChildGameObject(mdl, "CrocoArmature")).gameObject,
						shouldActivate = false,
						spawnPrefabOnModelObject = true,
						localPosition = new Vector3(0f, 0f, 0f),
						localRotation = new Vector3(0f, 0f, 0f),
						localScale = new Vector3(0f, 0f, 0f),
						prefab = assetBundle.LoadAsset<GameObject>("Assets/Skins/SkinAsset/Vanilla/Acrid/ToastNurseAcrid/AcridAddonMesh.prefab")
					}
				};
			});
			TryCatchThrow("Renderer Infos", delegate
			{
				skinParams.rendererInfos = Array.Empty<RendererInfo>();
			});
			TryCatchThrow("Mesh Replacements", delegate
			{
				//IL_0010: 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_0069: Unknown result type (might be due to invalid IL or missing references)
				skinParams.meshReplacements = (MeshReplacement[])(object)new MeshReplacement[1]
				{
					new MeshReplacement
					{
						mesh = assetBundle.LoadAsset<Mesh>("Assets\\SkinMods\\Toast_NurseAcrid\\Meshes\\CrocoMesh.mesh"),
						renderer = ThrowIfNull<Renderer>(0, "There is no renderer with the name \"CrocoMesh\"", ((IEnumerable<Renderer>)renderers).FirstOrDefault((Func<Renderer, bool>)((Renderer r) => ((Object)r).name == "CrocoMesh")))
					}
				};
			});
			TryCatchThrow("Light Infos", delegate
			{
				skinParams.lightReplacements = (LightInfo[])(object)new LightInfo[0];
			});
			TryCatchThrow("Minion Skin Replacements", delegate
			{
				skinParams.minionSkinReplacements = Array.Empty<MinionSkinReplacement>();
			});
			TryCatchThrow("Projectile Ghost Replacements", delegate
			{
				skinParams.projectileGhostReplacements = Array.Empty<ProjectileGhostReplacement>();
			});
			Array.Resize(ref skinController.skins, skinController.skins.Length + 1);
			skinController.skins[skinController.skins.Length - 1] = skin;
		}
		catch (FieldException ex)
		{
			if (ex.InnerException is ElementException ex2)
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\""));
				InstanceLogger.LogWarning((object)$"Field causing issue: {ex.Message}, element: {ex2.Index}");
				InstanceLogger.LogWarning((object)ex2.Message);
				InstanceLogger.LogError((object)ex.InnerException);
			}
			else
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\""));
				InstanceLogger.LogWarning((object)("Field causing issue: " + ex.Message));
				InstanceLogger.LogError((object)ex.InnerException);
			}
		}
		catch (Exception ex3)
		{
			InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\""));
			InstanceLogger.LogError((object)ex3);
		}
	}

	private static T ThrowIfEquals<T>(int index, string message, T value, T expected) where T : Enum
	{
		if (value.Equals(expected))
		{
			throw new ElementException(index, message);
		}
		return value;
	}

	private static T ThrowIfOutOfBounds<T>(int index, string message, T[] array, int elementIndex) where T : class
	{
		if (array == null || array.Length <= elementIndex)
		{
			throw new ElementException(index, message);
		}
		return array[elementIndex];
	}

	private static T ThrowIfNull<T>(int index, string message, T value) where T : class
	{
		if (value == null)
		{
			throw new ElementException(index, message);
		}
		return value;
	}

	private static void TryCatchThrow(string message, Action action)
	{
		try
		{
			action?.Invoke();
		}
		catch (Exception innerException)
		{
			throw new FieldException(message, innerException);
		}
	}

	private static void TryAddComponent<T>(GameObject obj) where T : Component
	{
		if (Object.op_Implicit((Object)(object)obj) && !Object.op_Implicit((Object)(object)obj.GetComponent<T>()))
		{
			obj.AddComponent<T>();
		}
	}

	private static GameObject GetChildGameObject(GameObject fromGameObject, string withName)
	{
		Transform[] componentsInChildren = fromGameObject.GetComponentsInChildren<Transform>();
		foreach (Transform val in componentsInChildren)
		{
			if (((Object)val).name.StartsWith(withName))
			{
				return ((Component)val).gameObject;
			}
		}
		return null;
	}
}