Decompiled source of EmeraudePrestige v1.0.1

plugins/EmeraudePrestige.dll

Decompiled 13 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
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("EmeraudePrestige")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("EmeraudePrestige")]
[assembly: AssemblyTitle("EmeraudePrestige")]
[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 EmeraudePrestige
{
	[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
	internal static class UpdateTargetPatch
	{
		private static readonly FieldRef<MonsterAI, Character> TargetCreature = AccessTools.FieldRefAccess<MonsterAI, Character>("m_targetCreature");

		private static readonly FieldRef<BaseAI, Character> OwnCharacter = AccessTools.FieldRefAccess<BaseAI, Character>("m_character");

		private static readonly Action<BaseAI, bool> SetAlerted = AccessTools.MethodDelegate<Action<BaseAI, bool>>(AccessTools.Method(typeof(BaseAI), "SetAlerted", (Type[])null, (Type[])null), (object)null, true);

		internal static MonsterAI s_ai;

		internal static Character s_monster;

		private static void Prefix(MonsterAI __instance, out Character __state)
		{
			s_ai = __instance;
			s_monster = OwnCharacter.Invoke((BaseAI)(object)__instance);
			__state = TargetCreature.Invoke(__instance);
		}

		private static void Postfix(MonsterAI __instance, Character __state)
		{
			if (__state is Player && (Object)(object)TargetCreature.Invoke(__instance) == (Object)null && Prestige.Ignores(__instance, s_monster, __state))
			{
				SetAlerted((BaseAI)(object)__instance, arg2: false);
			}
		}

		private static void Finalizer()
		{
			s_ai = null;
			s_monster = null;
		}
	}
	[HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[]
	{
		typeof(Character),
		typeof(Character)
	})]
	internal static class IsEnemyPatch
	{
		private static void Postfix(Character a, Character b, ref bool __result)
		{
			if (__result && Object.op_Implicit((Object)(object)UpdateTargetPatch.s_ai) && (Object)(object)a == (Object)(object)UpdateTargetPatch.s_monster && Prestige.Ignores(UpdateTargetPatch.s_ai, a, b))
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(MonsterAI), "OnDamaged")]
	internal static class OnDamagedPatch
	{
		private static void Prefix(MonsterAI __instance, Character attacker)
		{
			Prestige.Provoke(((Component)__instance).GetComponent<Character>(), attacker);
		}
	}
	[HarmonyPatch(typeof(Character), "Damage")]
	internal static class DamagePatch
	{
		private static void Prefix(Character __instance, HitData hit)
		{
			if (__instance is Player)
			{
				Character attacker = hit.GetAttacker();
				if (attacker != null && attacker.GetBaseAI() is MonsterAI)
				{
					Prestige.Provoke(attacker, __instance);
				}
			}
		}
	}
	[BepInPlugin("emeraude.prestige", "Emeraude Prestige", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	[SynchronizationMode(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "emeraude.prestige";

		public const string Name = "Emeraude Prestige";

		public const string Version = "1.0.1";

		internal const int TierCount = 8;

		private static readonly string[] Biomes = new string[8] { "Meadows / Prairies", "Black Forest / Forêt Noire", "Swamp / Marais", "Mountains / Montagnes", "Plains / Plaines", "Mistlands / Brumes", "Ashlands / Terres cendrées", "Deep North / Grand Nord" };

		private static readonly string[] DefaultArmor = new string[8] { "ArmorRagsChest,ArmorRagsLegs,HelmetLeather,ArmorLeatherChest,ArmorLeatherLegs", "HelmetTrollLeather,ArmorTrollLeatherChest,ArmorTrollLeatherLegs,HelmetBronze,ArmorBronzeChest,ArmorBronzeLegs,HelmetBerserkerHood,ArmorBerserkerChest,ArmorBerserkerLegs", "HelmetIron,ArmorIronChest,ArmorIronLegs,HelmetRoot,ArmorRootChest,ArmorRootLegs", "HelmetDrake,ArmorWolfChest,ArmorWolfLegs,HelmetFenring,ArmorFenringChest,ArmorFenringLegs", "HelmetPadded,ArmorPaddedCuirass,ArmorPaddedGreaves,HelmetLox,ArmorLoxChest,ArmorLoxLegs,HelmetBerserkerUndead,ArmorBerserkerUndeadChest,ArmorBerserkerUndeadLegs", "HelmetCarapace,ArmorCarapaceChest,ArmorCarapaceLegs,HelmetMage,ArmorMageChest,ArmorMageLegs", "HelmetFlametal,ArmorFlametalChest,ArmorFlametalLegs,HelmetAshlandsMediumHood,ArmorAshlandsMediumChest,ArmorAshlandsMediumlegs,HelmetMage_Ashlands,ArmorMageChest_Ashlands,ArmorMageLegs_Ashlands", "HelmetDNHeavy,ArmorDeepNorthHeavyChest,ArmorDeepNorthHeavylegs,HelmetDNMediumHood,ArmorDeepNorthMediumChest,ArmorDeepNorthMediumlegs,HelmetDNMage,ArmorDeepNorthMageChest,ArmorDeepNorthMagelegs" };

		private static readonly string[] DefaultMonsters = new string[8] { "Greyling,Neck,Greydwarf", "Greydwarf_Elite,Greydwarf_Shaman,Troll,Troll_sleeping,Ghost,Ghost_sleeping,Bjorn,Bjorn_sleeping,Skeleton,Skeleton_NoArcher,Skeleton_Poison,Skeleton_Meadows,Skeleton_Meadows_noarcher,Skeleton_Swamps,Skeleton_Swamps_noarcher,Skeleton_Mountains,Skeleton_Mountains_noarcher", "Draugr,Draugr_sleeping,Draugr_Elite,Draugr_Elite_sleeping,Draugr_Ranged,Draugr_Ranged_sleeping,Blob,BlobElite,Leech,Surtling,Wraith,Abomination,Bat_Swamp", "Wolf,Hatchling,StoneGolem,Fenring,Fenring_Cultist,Ulv,Bat", "Deathsquito,Goblin,GoblinArcher,GoblinBrute,GoblinShaman,BlobTar,Unbjorn,Lox", "Seeker,SeekerBrute,SeekerBrood,Gjall,Tick", "Charred_Melee,Charred_Archer,Charred_Mage,Charred_Twitcher,Morgen,Morgen_NonSleeping,FallenValkyrie,Asksvin,Volture,BlobLava", "" };

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<int> Gap;

		internal static ConfigEntry<float> ForgetSeconds;

		internal static ConfigEntry<bool> StarredStayAggressive;

		internal static ConfigEntry<bool> RaidsStayAggressive;

		internal static readonly ConfigEntry<string>[] ArmorTiers = new ConfigEntry<string>[8];

		internal static readonly ConfigEntry<string>[] MonsterTiers = new ConfigEntry<string>[8];

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			ConfigurationManagerAttributes val = new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			};
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Prestige", "Enabled", true, new ConfigDescription("Monsters ignore players whose armor is ahead of their biome. / Les monstres ignorent les joueurs dont l'armure a de l'avance sur leur biome.", (AcceptableValueBase)null, new object[1] { val }));
			Gap = ((BaseUnityPlugin)this).Config.Bind<int>("Prestige", "Gap", 1, new ConfigDescription("Biomes of advance needed: a monster ignores a player whose armor tier is at least the monster's tier + Gap. With 1, Iron armor (Swamp) makes Black Forest monsters ignore you. / Biomes d'avance nécessaires : un monstre ignore un joueur dont l'armure atteint le niveau du monstre + Gap. Avec 1, l'armure de Fer (Marais) fait ignorer les monstres de la Forêt Noire.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 8), new object[1] { val }));
			ForgetSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Prestige", "ForgetSeconds", 30f, new ConfigDescription("A monster hit by a player fights back, and forgets them after this many seconds without a blow either way. / Un monstre frappé par un joueur riposte, puis l'oublie après ce nombre de secondes sans coup échangé.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 600f), new object[1] { val }));
			StarredStayAggressive = ((BaseUnityPlugin)this).Config.Bind<bool>("Prestige", "StarredStayAggressive", true, new ConfigDescription("Starred monsters always attack. / Les monstres étoilés attaquent toujours.", (AcceptableValueBase)null, new object[1] { val }));
			RaidsStayAggressive = ((BaseUnityPlugin)this).Config.Bind<bool>("Prestige", "RaidsStayAggressive", true, new ConfigDescription("Raid monsters always attack. / Les monstres des raids attaquent toujours.", (AcceptableValueBase)null, new object[1] { val }));
			for (int i = 0; i < 8; i++)
			{
				ArmorTiers[i] = ((BaseUnityPlugin)this).Config.Bind<string>("Armor", $"Tier{i + 1}", DefaultArmor[i], new ConfigDescription($"Armor pieces of tier {i + 1}, {Biomes[i]} (item names, comma separated). / " + $"Pièces d'armure de niveau {i + 1} (noms d'objets, séparés par des virgules).", (AcceptableValueBase)null, new object[1] { val }));
				MonsterTiers[i] = ((BaseUnityPlugin)this).Config.Bind<string>("Monsters", $"Tier{i + 1}", DefaultMonsters[i], new ConfigDescription($"Monsters of tier {i + 1}, {Biomes[i]} (prefab names, comma separated). Unlisted " + $"monsters always attack. / Monstres de niveau {i + 1} (noms de prefab, séparés par des virgules). " + "Un monstre absent des listes attaque toujours.", (AcceptableValueBase)null, new object[1] { val }));
				ArmorTiers[i].SettingChanged += delegate
				{
					Prestige.Rebuild();
				};
				MonsterTiers[i].SettingChanged += delegate
				{
					Prestige.Rebuild();
				};
			}
			Prestige.Rebuild();
			ItemManager.OnItemsRegistered += Prestige.CheckArmorNames;
			PrefabManager.OnPrefabsRegistered += Prestige.CheckMonsterNames;
			new Harmony("emeraude.prestige").PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Emeraude Prestige 1.0.1 loaded");
		}
	}
	internal static class Prestige
	{
		private static readonly Dictionary<int, int> s_armorTiers = new Dictionary<int, int>();

		private static readonly Dictionary<int, int> s_monsterTiers = new Dictionary<int, int>();

		internal static void Rebuild()
		{
			Fill(s_armorTiers, Plugin.ArmorTiers);
			Fill(s_monsterTiers, Plugin.MonsterTiers);
		}

		private static void Fill(Dictionary<int, int> tiers, ConfigEntry<string>[] entries)
		{
			tiers.Clear();
			for (int i = 0; i < entries.Length; i++)
			{
				foreach (string item in Names(entries[i].Value))
				{
					tiers[StringExtensionMethods.GetStableHashCode(item)] = i + 1;
				}
			}
		}

		private static IEnumerable<string> Names(string list)
		{
			return from name in list.Split(',')
				select name.Trim() into name
				where name.Length > 0
				select name;
		}

		internal static bool Ignores(MonsterAI ai, Character monster, Character target)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.Enabled.Value)
			{
				Player val = (Player)(object)((target is Player) ? target : null);
				if (val != null)
				{
					if (monster.IsBoss() || monster.IsTamed())
					{
						return false;
					}
					if (Plugin.StarredStayAggressive.Value && monster.GetLevel() > 1)
					{
						return false;
					}
					if (Plugin.RaidsStayAggressive.Value && ai.IsEventCreature())
					{
						return false;
					}
					ZDO zDO = ZDOMan.instance.GetZDO(monster.GetZDOID());
					if (zDO == null || !s_monsterTiers.TryGetValue(zDO.GetPrefab(), out var value))
					{
						return false;
					}
					if (IsProvoked(zDO, val))
					{
						return false;
					}
					return PlayerTier(val) >= value + Plugin.Gap.Value;
				}
			}
			return false;
		}

		internal static int PlayerTier(Player player)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = ZDOMan.instance.GetZDO(((Character)player).GetZDOID());
			if (zDO == null)
			{
				return 0;
			}
			return Mathf.Min(ArmorTier(zDO.GetInt(ZDOVars.s_helmetItem, 0)), Mathf.Min(ArmorTier(zDO.GetInt(ZDOVars.s_chestItem, 0)), ArmorTier(zDO.GetInt(ZDOVars.s_legItem, 0))));
		}

		private static int ArmorTier(int itemHash)
		{
			if (!s_armorTiers.TryGetValue(itemHash, out var value))
			{
				return 0;
			}
			return value;
		}

		internal static void Provoke(Character monster, Character attacker)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (attacker is Player && Object.op_Implicit((Object)(object)monster))
			{
				ZDO zDO = ZDOMan.instance.GetZDO(monster.GetZDOID());
				if (zDO != null && zDO.IsOwner())
				{
					zDO.Set(ProvokedKey(attacker), ZNet.instance.GetTime().Ticks);
				}
			}
		}

		private static bool IsProvoked(ZDO monsterZdo, Player player)
		{
			long num = monsterZdo.GetLong(ProvokedKey((Character)(object)player), 0L);
			if (num != 0L)
			{
				return (ZNet.instance.GetTime() - new DateTime(num)).TotalSeconds < (double)Plugin.ForgetSeconds.Value;
			}
			return false;
		}

		private static int ProvokedKey(Character player)
		{
			//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)
			ZDOID zDOID = player.GetZDOID();
			return StringExtensionMethods.GetStableHashCode("emeraude_prestige_provoked_" + ((ZDOID)(ref zDOID)).UserID);
		}

		internal static void CheckArmorNames()
		{
			ItemManager.OnItemsRegistered -= CheckArmorNames;
			HashSet<string> known = new HashSet<string>(from item in ObjectDB.instance.m_items
				where Object.op_Implicit((Object)(object)item)
				select ((Object)item).name);
			Warn("Armor", from name in Plugin.ArmorTiers.SelectMany((ConfigEntry<string> entry) => Names(entry.Value))
				where !known.Contains(name)
				select name);
			List<string> list = (from item in ObjectDB.instance.m_items
				select (!Object.op_Implicit((Object)(object)item)) ? null : item.GetComponent<ItemDrop>() into drop
				where Object.op_Implicit((Object)(object)drop) && IsArmor(drop.m_itemData.m_shared) && !s_armorTiers.ContainsKey(StringExtensionMethods.GetStableHashCode(((Object)drop).name))
				select ((Object)drop).name).ToList();
			if (list.Count > 0)
			{
				Plugin.Log.LogInfo((object)("Pièces d'armure sans niveau (valent 0) : " + string.Join(", ", list)));
			}
		}

		private static bool IsArmor(SharedData shared)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			if (shared.m_armor > 0f)
			{
				if ((int)shared.m_itemType != 6 && (int)shared.m_itemType != 7)
				{
					return (int)shared.m_itemType == 11;
				}
				return true;
			}
			return false;
		}

		internal static void CheckMonsterNames()
		{
			PrefabManager.OnPrefabsRegistered -= CheckMonsterNames;
			HashSet<string> known = new HashSet<string>(from prefab in ZNetScene.instance.m_prefabs
				where Object.op_Implicit((Object)(object)prefab)
				select ((Object)prefab).name);
			Warn("Monsters", from name in Plugin.MonsterTiers.SelectMany((ConfigEntry<string> entry) => Names(entry.Value))
				where !known.Contains(name)
				select name);
			List<string> list = (from prefab in ZNetScene.instance.m_prefabs
				where Object.op_Implicit((Object)(object)prefab) && Object.op_Implicit((Object)(object)prefab.GetComponent<MonsterAI>()) && Object.op_Implicit((Object)(object)prefab.GetComponent<Character>()) && !s_monsterTiers.ContainsKey(StringExtensionMethods.GetStableHashCode(((Object)prefab).name))
				select ((Object)prefab).name).ToList();
			if (list.Count > 0)
			{
				Plugin.Log.LogInfo((object)("Créatures sans niveau (attaquent toujours) : " + string.Join(", ", list)));
			}
		}

		private static void Warn(string section, IEnumerable<string> unknown)
		{
			List<string> list = unknown.ToList();
			if (list.Count > 0)
			{
				Plugin.Log.LogWarning((object)("[" + section + "] noms inconnus du jeu, ignorés : " + string.Join(", ", list)));
			}
		}
	}
}