Decompiled source of Lanca Retornante v1.0.1

LancaRetornante.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("LancaRetornante")]
[assembly: AssemblyProduct("Lanca Retornante")]
[assembly: AssemblyCompany("Lanca Retornante contributors")]
[assembly: AssemblyCopyright("Copyright (c) 2026")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyVersion("1.0.1.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 LancaRetornante
{
	internal static class ModText
	{
		internal const string Portuguese = "Português";

		internal const string English = "English";

		internal static bool IsEnglish
		{
			get
			{
				if ((Object)(object)Plugin.Instance != (Object)null && Plugin.Instance.Language != null)
				{
					return Plugin.Instance.Language.Value == "English";
				}
				return false;
			}
		}

		internal static string Get(string portuguese, string english)
		{
			if (!IsEnglish)
			{
				return portuguese;
			}
			return english;
		}
	}
	[BepInPlugin("br.gleydson.valheim.lancaretornante", "Lanca Retornante", "1.0.1")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class PendingSpear
		{
			public object Owner { get; }

			public object Item { get; }

			public ReturnToken Token { get; }

			public PendingSpear(object owner, object item, ReturnToken token)
			{
				Owner = owner;
				Item = item;
				Token = token;
			}
		}

		private sealed class ReturnToken
		{
			public int State;
		}

		public const string PluginGuid = "br.gleydson.valheim.lancaretornante";

		public const string PluginName = "Lanca Retornante";

		public const string PluginVersion = "1.0.1";

		private static readonly ConditionalWeakTable<object, PendingSpear> Pending = new ConditionalWeakTable<object, PendingSpear>();

		private static readonly ConditionalWeakTable<object, ReturnToken> Throws = new ConditionalWeakTable<object, ReturnToken>();

		private Harmony _harmony;

		private ConfigEntry<bool> _enabled;

		internal static Plugin Instance { get; private set; }

		internal ConfigEntry<string> Language { get; private set; }

		private void Awake()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			Instance = this;
			Language = ((BaseUnityPlugin)this).Config.Bind<string>("Geral", "Idioma / Language", "Português", new ConfigDescription("Idioma dos textos do mod. / Language used by the mod.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "Português", "English" }), Array.Empty<object>()));
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Geral", "Ativado", true, "Devolve ao inventario a mesma lanca depois que o arremesso atinge algo. / Returns the same spear to the inventory after impact.");
			try
			{
				PatchProjectileMethods();
				((BaseUnityPlugin)this).Logger.LogInfo((object)ModText.Get("Lanca Retornante 1.0.1 carregado. A lança agora conhece o caminho de casa.", "Lanca Retornante 1.0.1 loaded. The spear now knows the way home."));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)(ModText.Get("Não foi possível aplicar os patches de projétil. ", "Could not apply projectile patches. ") + ex));
			}
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
			Instance = null;
		}

		private void PatchProjectileMethods()
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("Projectile");
			Type itemDataType = AccessTools.TypeByName("ItemDrop+ItemData");
			if (type == null || itemDataType == null)
			{
				throw new TypeLoadException("Projectile ou ItemDrop.ItemData nao foi encontrado no Valheim.");
			}
			List<MethodInfo> list = (from method in AccessTools.GetDeclaredMethods(type)
				where method.Name == "Setup"
				where method.GetParameters().Any((ParameterInfo parameter) => itemDataType.IsAssignableFrom(parameter.ParameterType))
				select method).ToList();
			MethodInfo methodInfo = AccessTools.GetDeclaredMethods(type).FirstOrDefault((MethodInfo method) => method.Name == "OnHit");
			if (list.Count == 0 || methodInfo == null)
			{
				throw new MissingMethodException("A API atual de Projectile nao possui Setup/OnHit compativeis.");
			}
			_harmony = new Harmony("br.gleydson.valheim.lancaretornante");
			HarmonyMethod val = new HarmonyMethod(typeof(Plugin), "ProjectileSetupPostfix", (Type[])null);
			HarmonyMethod val2 = new HarmonyMethod(typeof(Plugin), "ProjectileOnHitPrefix", (Type[])null);
			foreach (MethodInfo item in list)
			{
				_harmony.Patch((MethodBase)item, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			_harmony.Patch((MethodBase)methodInfo, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Patches aplicados: {list.Count} Setup e 1 OnHit.");
		}

		private static void ProjectileSetupPostfix(object __instance, object[] __args)
		{
			Plugin plugin = FindPlugin();
			if ((Object)(object)plugin == (Object)null || !plugin._enabled.Value || __instance == null || __args == null)
			{
				return;
			}
			try
			{
				object localPlayer = GetLocalPlayer();
				if (localPlayer == null || !__args.Any((object argument) => argument == localPlayer))
				{
					return;
				}
				object obj = __args.FirstOrDefault(SpearItemLogic.IsSpearItem);
				if (obj == null)
				{
					return;
				}
				FieldInfo fieldInfo = AccessTools.Field(__instance.GetType(), "m_spawnItem");
				if (fieldInfo == null || fieldInfo.GetValue(__instance) == null)
				{
					return;
				}
				object obj2 = SpearItemLogic.CloneItemData(obj);
				if (obj2 != null)
				{
					if (!Throws.TryGetValue(obj, out var value) || value.State != 0)
					{
						Throws.Remove(obj);
						value = new ReturnToken();
						Throws.Add(obj, value);
					}
					Pending.Remove(__instance);
					Pending.Add(__instance, new PendingSpear(localPlayer, obj2, value));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)plugin).Logger.LogWarning((object)(ModText.Get("Não foi possível registrar a lança arremessada: ", "Could not register the thrown spear: ") + ex.Message));
			}
		}

		private static void ProjectileOnHitPrefix(object __instance)
		{
			Plugin plugin = FindPlugin();
			if ((Object)(object)plugin == (Object)null || !plugin._enabled.Value || __instance == null || !Pending.TryGetValue(__instance, out var value))
			{
				return;
			}
			Pending.Remove(__instance);
			if (Interlocked.CompareExchange(ref value.Token.State, 1, 0) != 0)
			{
				FieldInfo fieldInfo = AccessTools.Field(__instance.GetType(), "m_spawnItem");
				if (fieldInfo != null)
				{
					fieldInfo.SetValue(__instance, null);
				}
				return;
			}
			try
			{
				object localPlayer = GetLocalPlayer();
				if (localPlayer == null || localPlayer != value.Owner)
				{
					return;
				}
				MethodInfo methodInfo = AccessTools.Method(localPlayer.GetType(), "GetInventory", Type.EmptyTypes, (Type[])null);
				object obj = ((methodInfo == null) ? null : methodInfo.Invoke(localPlayer, null));
				if (obj == null)
				{
					return;
				}
				FieldInfo fieldInfo2 = AccessTools.Field(__instance.GetType(), "m_spawnItem");
				if (fieldInfo2 == null)
				{
					return;
				}
				object value2 = fieldInfo2.GetValue(__instance);
				if (value2 == null || !SpearItemLogic.CanAdd(obj, value.Item))
				{
					return;
				}
				MethodInfo methodInfo2 = SpearItemLogic.FindSingleItemMethod(obj.GetType(), "AddItem", value.Item.GetType());
				if (methodInfo2 == null)
				{
					return;
				}
				fieldInfo2.SetValue(__instance, null);
				bool flag = false;
				try
				{
					object obj2 = methodInfo2.Invoke(obj, new object[1] { value.Item });
					flag = methodInfo2.ReturnType == typeof(void) || (obj2 is bool && (bool)obj2);
				}
				finally
				{
					if (!flag)
					{
						fieldInfo2.SetValue(__instance, value2);
					}
				}
				if (flag)
				{
					TryShowMessage(localPlayer, "$msg_added " + SpearItemLogic.GetItemDisplayName(value.Item));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)plugin).Logger.LogWarning((object)(ModText.Get("A lança não conseguiu voltar; o Valheim manterá o drop normal. ", "The spear could not return; Valheim will keep the normal drop. ") + ex.Message));
			}
		}

		private static object GetLocalPlayer()
		{
			Type type = AccessTools.TypeByName("Player");
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "m_localPlayer"));
			if (!(fieldInfo == null))
			{
				return fieldInfo.GetValue(null);
			}
			return null;
		}

		private static void TryShowMessage(object player, string message)
		{
			try
			{
				MethodInfo methodInfo = AccessTools.GetDeclaredMethods(player.GetType()).FirstOrDefault((MethodInfo candidate) => candidate.Name == "Message" && candidate.GetParameters().Length >= 2);
				if (!(methodInfo == null))
				{
					ParameterInfo[] parameters = methodInfo.GetParameters();
					object[] array = new object[parameters.Length];
					array[0] = Enum.Parse(parameters[0].ParameterType, "TopLeft");
					array[1] = message;
					for (int num = 2; num < parameters.Length; num++)
					{
						array[num] = (parameters[num].HasDefaultValue ? parameters[num].DefaultValue : (parameters[num].ParameterType.IsValueType ? Activator.CreateInstance(parameters[num].ParameterType) : null));
					}
					methodInfo.Invoke(player, array);
				}
			}
			catch
			{
			}
		}

		private static Plugin FindPlugin()
		{
			if (!Chainloader.PluginInfos.TryGetValue("br.gleydson.valheim.lancaretornante", out var value))
			{
				return null;
			}
			return value.Instance as Plugin;
		}
	}
	internal static class SpearItemLogic
	{
		internal static bool IsSpearItem(object candidate)
		{
			if (candidate == null || !HasTypeInHierarchy(candidate.GetType(), "ItemDrop+ItemData"))
			{
				return false;
			}
			object fieldValue = GetFieldValue(GetFieldValue(candidate, "m_shared"), "m_skillType");
			if (fieldValue == null)
			{
				return false;
			}
			string a = fieldValue.ToString();
			if (!string.Equals(a, "Spears", StringComparison.OrdinalIgnoreCase))
			{
				return string.Equals(a, "Spear", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		internal static object CloneItemData(object source)
		{
			MethodInfo methodInfo = FindMethod(source.GetType(), "Clone", Type.EmptyTypes);
			if (methodInfo == null)
			{
				return null;
			}
			object obj = methodInfo.Invoke(source, null);
			if (obj == null)
			{
				return null;
			}
			DeepCopyDictionaryField(source, obj, "m_customData");
			SetFieldIfPresent(obj, "m_equiped", false);
			SetFieldIfPresent(obj, "m_equipped", false);
			SetFieldIfPresent(obj, "m_lastProjectile", null);
			SetFieldIfPresent(obj, "m_stack", 1);
			FieldInfo fieldInfo = FindField(obj.GetType(), "m_gridPos");
			if (fieldInfo != null && fieldInfo.FieldType.IsValueType)
			{
				fieldInfo.SetValue(obj, Activator.CreateInstance(fieldInfo.FieldType));
			}
			return obj;
		}

		internal static bool CanAdd(object inventory, object item)
		{
			MethodInfo methodInfo = GetInstanceMethods(inventory.GetType()).FirstOrDefault(delegate(MethodInfo candidate)
			{
				if (candidate.Name != "CanAddItem")
				{
					return false;
				}
				ParameterInfo[] parameters = candidate.GetParameters();
				return parameters.Length >= 1 && parameters[0].ParameterType.IsAssignableFrom(item.GetType()) && parameters.Skip(1).All((ParameterInfo parameter) => parameter.ParameterType == typeof(int));
			});
			if (methodInfo == null)
			{
				return true;
			}
			object[] array = new object[methodInfo.GetParameters().Length];
			array[0] = item;
			for (int num = 1; num < array.Length; num++)
			{
				array[num] = 1;
			}
			object obj = methodInfo.Invoke(inventory, array);
			if (obj is bool)
			{
				return (bool)obj;
			}
			return true;
		}

		internal static MethodInfo FindSingleItemMethod(Type inventoryType, string name, Type itemType)
		{
			return GetInstanceMethods(inventoryType).FirstOrDefault(delegate(MethodInfo method)
			{
				ParameterInfo[] parameters = method.GetParameters();
				return method.Name == name && parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(itemType);
			});
		}

		internal static string GetItemDisplayName(object item)
		{
			object fieldValue = GetFieldValue(GetFieldValue(item, "m_shared"), "m_name");
			if (fieldValue != null)
			{
				return fieldValue.ToString();
			}
			return "lanca";
		}

		private static void DeepCopyDictionaryField(object source, object copy, string fieldName)
		{
			FieldInfo fieldInfo = FindField(source.GetType(), fieldName);
			if (fieldInfo == null || !(fieldInfo.GetValue(source) is IDictionary dictionary) || !(Activator.CreateInstance(dictionary.GetType()) is IDictionary dictionary2))
			{
				return;
			}
			foreach (DictionaryEntry item in dictionary)
			{
				dictionary2.Add(item.Key, item.Value);
			}
			fieldInfo.SetValue(copy, dictionary2);
		}

		private static object GetFieldValue(object instance, string fieldName)
		{
			if (instance == null)
			{
				return null;
			}
			FieldInfo fieldInfo = FindField(instance.GetType(), fieldName);
			if (!(fieldInfo == null))
			{
				return fieldInfo.GetValue(instance);
			}
			return null;
		}

		private static void SetFieldIfPresent(object instance, string fieldName, object value)
		{
			FieldInfo fieldInfo = FindField(instance.GetType(), fieldName);
			if (fieldInfo != null)
			{
				fieldInfo.SetValue(instance, value);
			}
		}

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

		private static MethodInfo FindMethod(Type type, string name, Type[] parameterTypes)
		{
			while (type != null)
			{
				MethodInfo method = type.GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null);
				if (method != null)
				{
					return method;
				}
				type = type.BaseType;
			}
			return null;
		}

		private static IEnumerable<MethodInfo> GetInstanceMethods(Type type)
		{
			while (type != null)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				for (int i = 0; i < methods.Length; i++)
				{
					yield return methods[i];
				}
				type = type.BaseType;
			}
		}

		private static bool HasTypeInHierarchy(Type type, string fullName)
		{
			while (type != null)
			{
				if (string.Equals(type.FullName, fullName, StringComparison.Ordinal))
				{
					return true;
				}
				type = type.BaseType;
			}
			return false;
		}
	}
}