Decompiled source of MinecraftSword v0.1.0

BepInEx/plugins/MinecraftSword/MinecraftDiamondSword.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("MinecraftDiamondSword")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+9a234b57e11b0a416b0fed6d2438457d3e5d5716")]
[assembly: AssemblyProduct("MinecraftDiamondSword")]
[assembly: AssemblyTitle("MinecraftDiamondSword")]
[assembly: AssemblyVersion("0.1.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 MinecraftDiamondSwordMod
{
	internal static class DiamondSword
	{
		private const string SourcePrefabName = "SwordIron";

		private const string ItemPrefabName = "minecraftdiamondsword";

		private const string VisualPrefabName = "MinecraftDiamondSword_Visual";

		private const string BundleResourceSuffix = ".Assets.AssetBundles.minecraft_diamond_sword";

		private const string IconName = "MinecraftDiamondSword_Icon";

		private static AssetBundle _bundle;

		private static bool _registered;

		internal static void Register()
		{
			if (_registered)
			{
				return;
			}
			_registered = true;
			PrefabManager.OnVanillaPrefabsAvailable -= Register;
			try
			{
				RegisterCore();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Minecraft Diamond Sword registration failed without stopping game startup: {arg}");
			}
		}

		private static void RegisterCore()
		{
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			GameObject prefab = Cache.GetPrefab<GameObject>("SwordIron");
			if ((Object)(object)prefab == (Object)null)
			{
				Plugin.Log.LogError((object)"Cannot register Minecraft Diamond Sword: vanilla prefab 'SwordIron' was not found.");
				return;
			}
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null)
			{
				Plugin.Log.LogError((object)"Cannot register Minecraft Diamond Sword: the Iron Sword has no usable ItemDrop.");
				return;
			}
			_bundle = LoadEmbeddedBundle();
			if ((Object)(object)_bundle == (Object)null)
			{
				return;
			}
			GameObject val = ((IEnumerable<GameObject>)_bundle.LoadAllAssets<GameObject>()).FirstOrDefault((Func<GameObject, bool>)((GameObject asset) => (Object)(object)asset != (Object)null && string.Equals(((Object)asset).name, "MinecraftDiamondSword_Visual", StringComparison.OrdinalIgnoreCase) && asset.GetComponentsInChildren<MeshFilter>(true).Any((MeshFilter filter) => (Object)(object)filter.sharedMesh != (Object)null)));
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"Cannot register Minecraft Diamond Sword: no mesh-bearing visual prefab was found in the bundle.");
				return;
			}
			Sprite val2 = ((IEnumerable<Sprite>)_bundle.LoadAllAssets<Sprite>()).FirstOrDefault((Func<Sprite, bool>)((Sprite sprite) => (Object)(object)sprite != (Object)null && string.Equals(((Object)sprite).name, "MinecraftDiamondSword_Icon", StringComparison.OrdinalIgnoreCase)));
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogError((object)"Cannot register Minecraft Diamond Sword: MinecraftDiamondSword_Icon is missing from the bundle.");
				return;
			}
			ItemConfig val3 = CopyVanillaConfig(component, val2);
			val3.Name = "Minecraft Diamond Sword";
			val3.Description = "A diamond sword from Minecraft.";
			CustomItem val4 = new CustomItem("minecraftdiamondsword", "SwordIron", val3);
			if ((Object)(object)val4.ItemPrefab == (Object)null)
			{
				Plugin.Log.LogError((object)"Cannot register Minecraft Diamond Sword: Jotunn could not clone 'SwordIron'.");
				return;
			}
			if (!ReplaceVisual(val4.ItemPrefab, val))
			{
				Plugin.Log.LogError((object)"Cannot register Minecraft Diamond Sword: no compatible mesh renderer was found.");
				return;
			}
			ItemManager.Instance.AddItem(val4);
			Plugin.Log.LogInfo((object)"Registered Minecraft Diamond Sword using the Iron Sword item, attacks, attachment, and recipe.");
		}

		private static bool ReplaceVisual(GameObject itemPrefab, GameObject visualPrefab)
		{
			//IL_0114: 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_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: 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_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: 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_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: 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_024b: 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_0295: Unknown result type (might be due to invalid IL or missing references)
			MeshFilter val = (from filter in itemPrefab.GetComponentsInChildren<MeshFilter>(true)
				where (Object)(object)filter.sharedMesh != (Object)null && (Object)(object)((Component)filter).GetComponent<Renderer>() != (Object)null
				select filter).OrderByDescending(delegate(MeshFilter filter)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				Bounds bounds2 = filter.sharedMesh.bounds;
				Vector3 size2 = ((Bounds)(ref bounds2)).size;
				return ((Vector3)(ref size2)).sqrMagnitude;
			}).FirstOrDefault();
			MeshFilter val2 = (from filter in visualPrefab.GetComponentsInChildren<MeshFilter>(true)
				where (Object)(object)filter.sharedMesh != (Object)null && (Object)(object)((Component)filter).GetComponent<Renderer>() != (Object)null
				select filter).OrderByDescending(delegate(MeshFilter filter)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				Bounds bounds2 = filter.sharedMesh.bounds;
				Vector3 size2 = ((Bounds)(ref bounds2)).size;
				return ((Vector3)(ref size2)).sqrMagnitude;
			}).FirstOrDefault();
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				return false;
			}
			Mesh val3 = Object.Instantiate<Mesh>(val2.sharedMesh);
			Vector3[] vertices = val3.vertices;
			Vector3[] normals = val3.normals;
			Vector4[] tangents = val3.tangents;
			for (int num = 0; num < vertices.Length; num++)
			{
				vertices[num] = new Vector3(vertices[num].x, 0f - vertices[num].z, vertices[num].y);
				if (normals.Length == vertices.Length)
				{
					normals[num] = new Vector3(normals[num].x, 0f - normals[num].z, normals[num].y);
				}
				if (tangents.Length == vertices.Length)
				{
					tangents[num] = new Vector4(tangents[num].x, 0f - tangents[num].z, tangents[num].y, tangents[num].w);
				}
			}
			val3.vertices = vertices;
			if (normals.Length == vertices.Length)
			{
				val3.normals = normals;
			}
			else
			{
				val3.RecalculateNormals();
			}
			if (tangents.Length == vertices.Length)
			{
				val3.tangents = tangents;
			}
			val3.RecalculateBounds();
			Bounds bounds = val.sharedMesh.bounds;
			Vector3 size = ((Bounds)(ref bounds)).size;
			float magnitude = ((Vector3)(ref size)).magnitude;
			bounds = val3.bounds;
			size = ((Bounds)(ref bounds)).size;
			float magnitude2 = ((Vector3)(ref size)).magnitude;
			if (magnitude <= 0.0001f || magnitude2 <= 0.0001f)
			{
				return false;
			}
			Transform transform = ((Component)val).transform;
			transform.localScale *= magnitude / magnitude2;
			if ((Object)(object)((Component)val).transform.parent != (Object)null && string.Equals(((Object)((Component)val).transform.parent).name, "attach", StringComparison.Ordinal))
			{
				((Component)val).transform.localPosition = Vector3.zero;
			}
			val.sharedMesh = val3;
			((Component)val).GetComponent<Renderer>().sharedMaterials = ((Component)val2).GetComponent<Renderer>().sharedMaterials;
			MeshFilter[] componentsInChildren = itemPrefab.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val4 in componentsInChildren)
			{
				if (!((Object)(object)val4 == (Object)(object)val))
				{
					Renderer component = ((Component)val4).GetComponent<Renderer>();
					if ((Object)(object)component != (Object)null)
					{
						component.enabled = false;
					}
				}
			}
			return true;
		}

		private static ItemConfig CopyVanillaConfig(ItemDrop sourceDrop, Sprite icon)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			ItemConfig val = new ItemConfig
			{
				Icon = icon
			};
			ObjectDB menuObjectDatabase = GetMenuObjectDatabase();
			Recipe val2 = ((menuObjectDatabase != null) ? menuObjectDatabase.GetRecipe(sourceDrop.m_itemData) : null);
			if ((Object)(object)val2 == (Object)null)
			{
				val.Enabled = false;
				Plugin.Log.LogError((object)"Iron Sword recipe was unavailable; Minecraft Diamond Sword crafting is disabled.");
				return val;
			}
			val.CraftingStation = (((Object)(object)val2.m_craftingStation == (Object)null) ? null : ((Object)val2.m_craftingStation).name);
			val.RepairStation = val.CraftingStation;
			val.MinStationLevel = val2.m_minStationLevel;
			val.Requirements = (RequirementConfig[])((val2.m_resources == null) ? ((Array)new RequirementConfig[0]) : ((Array)val2.m_resources.Where((Requirement requirement) => requirement != null && (Object)(object)requirement.m_resItem != (Object)null).Select((Func<Requirement, RequirementConfig>)((Requirement requirement) => new RequirementConfig(((Object)requirement.m_resItem).name, requirement.m_amount, requirement.m_amountPerLevel, requirement.m_recover))).ToArray()));
			return val;
		}

		private static ObjectDB GetMenuObjectDatabase()
		{
			object obj = typeof(PrefabManager).GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)?.GetValue(null, null);
			PropertyInfo property = typeof(PrefabManager).GetProperty("MenuObjectDB", BindingFlags.Instance | BindingFlags.NonPublic);
			if (obj != null)
			{
				object? obj2 = property?.GetValue(obj, null);
				return (ObjectDB)((obj2 is ObjectDB) ? obj2 : null);
			}
			return null;
		}

		private static AssetBundle LoadEmbeddedBundle()
		{
			Assembly assembly = typeof(DiamondSword).Assembly;
			string text = assembly.GetManifestResourceNames().FirstOrDefault((string name) => name.EndsWith(".Assets.AssetBundles.minecraft_diamond_sword", StringComparison.OrdinalIgnoreCase));
			if (text == null)
			{
				Plugin.Log.LogError((object)"Embedded AssetBundle resource '.Assets.AssetBundles.minecraft_diamond_sword' was not found. Build the Unity bundle before building the DLL.");
				return null;
			}
			using Stream stream = assembly.GetManifestResourceStream(text);
			using MemoryStream memoryStream = new MemoryStream();
			if (stream == null)
			{
				return null;
			}
			stream.CopyTo(memoryStream);
			return AssetBundle.LoadFromMemory(memoryStream.ToArray());
		}
	}
	[BepInPlugin("com.magni.minecraftdiamondsword", "Minecraft Diamond Sword", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string GUID = "com.magni.minecraftdiamondsword";

		public const string NAME = "Minecraft Diamond Sword";

		public const string VERSION = "0.1.0";

		internal static ManualLogSource Log;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			PrefabManager.OnVanillaPrefabsAvailable += DiamondSword.Register;
			Log.LogInfo((object)"Minecraft Diamond Sword 0.1.0 loaded; waiting for vanilla prefabs");
		}

		private void OnDestroy()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= DiamondSword.Register;
		}
	}
}