Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of SakeysNeutralGuard v0.0.1
BepInEx/plugins/Sakey’s Neutral Guard/Sakey's Neutral Guard.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; 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("Sakey's Neutral Guard")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Sakey's Neutral Guard")] [assembly: AssemblyTitle("Sakey's Neutral Guard")] [assembly: AssemblyVersion("1.0.0.0")] namespace SakeysNeutralGuard; [BepInPlugin("com.sakey.neutralguard", "Sakey's Neutral Guard", "0.0.1")] public sealed class SakeysNeutralGuardPlugin : BaseUnityPlugin { private sealed class LocalizedText { internal readonly string Japanese; internal readonly string English; internal readonly string German; internal readonly string French; internal readonly string Korean; internal LocalizedText(string japanese, string english, string german, string french, string korean) { Japanese = japanese; English = english; German = german; French = french; Korean = korean; } } private sealed class LocalizedConfigMetadata { internal ConfigEntryBase Entry; internal LocalizedText Category; internal LocalizedText DisplayName; internal LocalizedText Description; } public const string PluginGuid = "com.sakey.neutralguard"; public const string PluginName = "Sakey's Neutral Guard"; public const string PluginVersion = "0.0.1"; internal static ConfigEntry<string> DisplayLanguage; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> ProtectAoeAndChain; internal static ConfigEntry<bool> BlockAllNeutralDamage; internal static ConfigEntry<bool> ProtectProjectileExplosions; internal static ConfigEntry<bool> ProtectTamedCreatures; internal static ConfigEntry<bool> EnableDebugLogs; internal static ManualLogSource ModLog; private Harmony _harmony; private static readonly List<LocalizedConfigMetadata> LocalizedConfigEntries = new List<LocalizedConfigMetadata>(); private static string CachedLanguage = "en"; private static bool LanguageCacheInitialized; private bool _pocketRecallPatchFailureLogged; private static int _guardErrorLogged; private static ConfigFile _config; private static ConfigFile InstanceConfig => _config; private void Awake() { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_03a1: Expected O, but got Unknown ModLog = ((BaseUnityPlugin)this).Logger; _config = ((BaseUnityPlugin)this).Config; DisplayLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("UI", "Display Language", "自動", new ConfigDescription("表示言語を選択します。「自動」ではValheimの設定言語を読み取ります。", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[6] { "自動", "日本語", "English", "Deutsch", "Français", "한국어" }), new object[1] { new ConfigurationManagerAttributes { Category = "全般", DispName = "表示言語", DefaultValue = "自動", Description = "表示言語を選択します。「自動」ではValheimの設定言語を読み取ります。" } })); DisplayLanguage.SettingChanged += delegate { LanguageCacheInitialized = false; RefreshLanguageCache(); ApplyConfigManagerLocalization(); }; RefreshLanguageCache(); Enabled = BindLocalized("General", "Enabled", defaultValue: true, new LocalizedText("全般", "General", "Allgemein", "Général", "일반"), new LocalizedText("保護機能を有効化", "Enable Protections", "Schutz aktivieren", "Activer les protections", "보호 기능 활성화"), new LocalizedText("Neutral Guardの保護機能全体を有効にします。", "Enables or disables all Neutral Guard protection features.", "Aktiviert oder deaktiviert alle Schutzfunktionen von Neutral Guard.", "Active ou désactive toutes les protections de Neutral Guard.", "Neutral Guard의 모든 보호 기능을 활성화하거나 비활성화합니다.")); ProtectAoeAndChain = BindLocalized("Protection", "ProtectAoeAndChain", defaultValue: true, new LocalizedText("保護", "Protection", "Schutz", "Protection", "보호"), new LocalizedText("範囲攻撃・連鎖攻撃から中立生物を保護", "Protect Neutrals from AOE and Chain Attacks", "Neutrale Kreaturen vor Flächen- und Kettenangriffen schützen", "Protéger les créatures neutres des attaques de zone et en chaîne", "범위 및 연쇄 공격으로부터 중립 생물 보호"), new LocalizedText("プレイヤー由来の範囲攻撃・連鎖攻撃の対象から、中立で敵対化可能な生物を除外します。通常の近接攻撃や投射物の直撃ダメージは防ぎません。", "Excludes neutral, aggravatable creatures from player-owned AOE and chain-attack targeting. Does not block ordinary melee damage or direct projectile hits.", "Schließt neutrale, reizbare Kreaturen aus Flächen- und Kettenangriffen des Spielers aus. Verhindert weder normalen Nahkampfschaden noch direkte Projektiltreffer.", "Exclut des attaques de zone et en chaîne du joueur les créatures neutres pouvant être provoquées. Ne bloque pas les dégâts des attaques de mêlée normales ni les impacts directs de projectiles.", "플레이어가 발생시킨 범위 및 연쇄 공격의 대상에서 중립적이며 적대화될 수 있는 생물을 제외합니다. 일반 근접 공격 피해나 투사체 직접 타격은 막지 않습니다.")); BlockAllNeutralDamage = BindLocalized("Protection", "BlockAllNeutralDamage", defaultValue: false, new LocalizedText("保護", "Protection", "Schutz", "Protection", "보호"), new LocalizedText("中立生物への全ダメージを無効化", "Block All Damage to Neutral Creatures", "Jeglichen Schaden an neutralen Kreaturen blockieren", "Bloquer tous les dégâts aux créatures neutres", "중립 생물에 대한 모든 피해 차단"), new LocalizedText("ONにすると、通常の近接物理攻撃・投射物の直撃・範囲攻撃・爆発などを含む、プレイヤー由来のダメージを中立生物に一切与えません。被弾通知による警戒・敵対化に加え、Pocket Dvergrが所有者自身をAIの攻撃対象に設定する処理も抑止します。敵対中または敵対陣営の生物には適用しません。攻撃音や視認など、被弾以外を原因とする反応は対象外です。テイム済み生物は「テイム済み生物も保護」の設定に従います。", "When enabled, blocks all player-caused damage to neutral creatures, including ordinary physical melee hits, direct projectile hits, AOE attacks, and explosions. It also suppresses hit-triggered alerting/hostility and prevents Pocket Dvergr companions from selecting their own owner as an AI target. Reactions caused by attack noise or sight are not covered. Hostile creatures and enemy factions are unaffected. Tamed creatures follow the Protect Tamed Creatures setting.", "Wenn aktiviert, blockiert diese Option sämtlichen vom Spieler verursachten Schaden an neutralen Kreaturen, einschließlich normaler physischer Nahkampftreffer, direkter Projektiltreffer, Flächenangriffe und Explosionen. Außerdem unterdrückt sie trefferbedingte Alarmierung/Feindseligkeit und verhindert, dass Pocket-Dvergr-Begleiter ihren eigenen Besitzer als KI-Ziel auswählen. Reaktionen auf Angriffslärm oder Sichtkontakt sind nicht abgedeckt. Feindliche Kreaturen und feindliche Fraktionen sind nicht betroffen. Gezähmte Kreaturen richten sich nach der Einstellung zum Schutz gezähmter Kreaturen.", "Activée, cette option bloque tous les dégâts infligés par le joueur aux créatures neutres, y compris les coups physiques de mêlée, les impacts directs de projectiles, les attaques de zone et les explosions. Elle supprime également l'alerte/l'hostilité déclenchée par les coups et empêche les compagnons Pocket Dvergr de choisir leur propre propriétaire comme cible de l'IA. Les réactions causées par le bruit d'une attaque ou par la vue ne sont pas couvertes. Les créatures hostiles et les factions ennemies ne sont pas concernées. Les créatures apprivoisées suivent le réglage de protection correspondant.", "활성화하면 일반 물리 근접 공격, 투사체 직접 타격, 범위 공격 및 폭발을 포함하여 플레이어가 중립 생물에게 주는 모든 피해를 차단합니다. 피격으로 발생하는 경계 및 적대화뿐 아니라 Pocket Dvergr 동료가 자신의 주인을 AI 공격 대상으로 선택하는 것도 막습니다. 공격 소리나 시야로 인한 반응은 대상이 아닙니다. 이미 적대적인 생물과 적대 진영에는 적용되지 않습니다. 길들인 생물은 길들인 생물 보호 설정을 따릅니다.")); ProtectProjectileExplosions = BindLocalized("Protection", "ProtectProjectileExplosions", defaultValue: true, new LocalizedText("保護", "Protection", "Schutz", "Protection", "보호"), new LocalizedText("投射物の爆発から中立生物を保護", "Protect Neutrals from Projectile Explosions", "Neutrale Kreaturen vor Projektil-Explosionen schützen", "Protéger les créatures neutres des explosions de projectiles", "투사체 폭발로부터 중립 생물 보호"), new LocalizedText("プレイヤーが発射した投射物の爆発範囲から、敵対していない敵対化可能な生物を除外します。「範囲攻撃・連鎖攻撃から中立生物を保護」とは別に切り替えられます。", "Excludes non-hostile, aggravatable creatures from the explosion area of player-fired projectiles. This option is independent of the AOE and chain-attack protection setting.", "Schließt nicht feindliche, reizbare Kreaturen aus dem Explosionsbereich von Projektilen des Spielers aus. Diese Option ist unabhängig vom Schutz vor Flächen- und Kettenangriffen.", "Exclut les créatures non hostiles pouvant être provoquées de la zone d'explosion des projectiles tirés par le joueur. Cette option est indépendante de la protection contre les attaques de zone et en chaîne.", "플레이어가 발사한 투사체의 폭발 범위에서 비적대적이며 적대화될 수 있는 생물을 제외합니다. 범위 및 연쇄 공격 보호 설정과 별도로 작동합니다.")); ProtectTamedCreatures = BindLocalized("Protection", "ProtectTamedCreatures", defaultValue: true, new LocalizedText("保護", "Protection", "Schutz", "Protection", "보호"), new LocalizedText("テイム済み生物も保護", "Also Protect Tamed Creatures", "Gezähmte Kreaturen ebenfalls schützen", "Protéger également les créatures apprivoisées", "길들인 생물도 보호"), new LocalizedText("ONにすると、テイム済み生物も範囲攻撃・連鎖攻撃・投射物の爆発、および「中立生物への全ダメージを無効化」の保護対象にします。", "When enabled, tamed creatures are also protected from AOE and chain attacks, projectile explosions, and the Block All Damage to Neutral Creatures option.", "Wenn aktiviert, werden gezähmte Kreaturen ebenfalls vor Flächen- und Kettenangriffen, Projektil-Explosionen sowie vor der Option zum Blockieren sämtlichen Schadens an neutralen Kreaturen geschützt.", "Activée, cette option protège également les créatures apprivoisées des attaques de zone et en chaîne, des explosions de projectiles et du blocage de tous les dégâts aux créatures neutres.", "활성화하면 길들인 생물도 범위 및 연쇄 공격, 투사체 폭발과 중립 생물에 대한 모든 피해 차단 기능의 보호 대상이 됩니다.")); EnableDebugLogs = BindLocalized("Diagnostics", "EnableDebugLogs", defaultValue: true, new LocalizedText("診断", "Diagnostics", "Diagnose", "Diagnostic", "진단"), new LocalizedText("診断ログを出力", "Enable Diagnostic Logs", "Diagnoseprotokoll aktivieren", "Activer les journaux de diagnostic", "진단 로그 활성화"), new LocalizedText("攻撃対象の判定とダメージ遮断について、保護または許可した結果をログに出力します。同じ経路・対象のログは3秒間隔に制限されます。", "Logs whether attack targets and damage events are blocked or allowed. Repeated messages for the same route and target are limited to one every 3 seconds.", "Protokolliert, ob Angriffsziele und Schadensereignisse blockiert oder zugelassen werden. Wiederholte Meldungen für denselben Pfad und dasselbe Ziel werden auf eine Meldung alle 3 Sekunden begrenzt.", "Indique dans les journaux si les cibles d'attaque et les événements de dégâts sont bloqués ou autorisés. Les messages répétés pour une même route et une même cible sont limités à un toutes les 3 secondes.", "공격 대상 및 피해 이벤트가 차단되거나 허용되었는지 로그에 기록합니다. 동일한 경로와 대상에 대한 반복 로그는 3초에 한 번으로 제한됩니다.")); RefreshLanguageCache(); ApplyConfigManagerLocalization(); OwnerFieldAccessor.LogFieldAvailability(((BaseUnityPlugin)this).Logger); _harmony = new Harmony("com.sakey.neutralguard"); _harmony.PatchAll(Assembly.GetExecutingAssembly()); ((MonoBehaviour)this).StartCoroutine(RefreshLanguageAfterStartup()); ((MonoBehaviour)this).StartCoroutine(InstallPocketDvergrEmergencyRecallGuard()); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Sakey's Neutral Guard 0.0.1 loaded."); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Installed patches: Character.Damage, Character.RPC_Damage, MonsterAI.OnDamaged, Pocket Dvergr owner-target guards (MonsterAI.SetTarget / BaseAI.GetTargetCreature), Aoe.ShouldHit, Projectile.DoAOE scope, Projectile.IsValidTarget."); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Pocket Dvergr friendly-fire emergency recall guard: runtime installation pending."); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Pocket Dvergr AI guard target methods resolved: SetTarget=" + NeutralGuardPocketCompanionSetTargetPatch.ResolvedTargetMethodCount() + "; GetTargetCreature=" + NeutralGuardPocketCompanionGetTargetPatch.ResolvedTargetMethodCount() + ". Companion ownership is resolved at runtime without a Pocket Dvergr dependency.")); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Diagnostics: " + (EnableDebugLogs.Value ? "ON" : "OFF") + "; candidate decisions are rate-limited to one line per route/target every 3 seconds.")); ((BaseUnityPlugin)this).Logger.LogInfo((object)("BlockAllNeutralDamage=" + BlockAllNeutralDamage.Value + "; AOE/chain and projectile-area target filters remain independently configurable.")); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Config Manager localization: " + GetLanguageCode() + " (Auto follows Valheim language; Japanese, English, German, French, Korean are supported).")); } private IEnumerator InstallPocketDvergrEmergencyRecallGuard() { for (int attempt = 0; attempt < 120; attempt++) { if (TryInstallPocketDvergrEmergencyRecallGuard() || _pocketRecallPatchFailureLogged) { yield break; } yield return (object)new WaitForSecondsRealtime(0.25f); } if (ModLog != null) { ModLog.LogWarning((object)"Pocket Dvergr EmergencyRecall.Trigger was not found after 30 seconds. Friendly-fire recall suppression is unavailable; other Neutral Guard protections remain active."); } } private bool TryInstallPocketDvergrEmergencyRecallGuard() { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Expected O, but got Unknown if (_harmony == null) { return false; } Type type = AccessTools.TypeByName("SakeysPocketDverger.PocketDvergerEmergencyRecall") ?? AccessTools.TypeByName("PocketDvergerEmergencyRecall"); if (type == null) { return false; } MethodInfo methodInfo = AccessTools.Method(type, "Trigger", new Type[2] { typeof(Player), typeof(string) }, (Type[])null); if (methodInfo == null) { return false; } try { MethodInfo methodInfo2 = AccessTools.Method(typeof(NeutralGuardPocketDvergerEmergencyRecallPatch), "Prefix", (Type[])null, (Type[])null); if (methodInfo2 == null) { throw new MissingMethodException("NeutralGuardPocketDvergerEmergencyRecallPatch.Prefix"); } _harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (ModLog != null) { ModLog.LogInfo((object)"Installed Pocket Dvergr EmergencyRecall.Trigger guard. Suppression scope: reason='friendly fire' while BlockAllNeutralDamage is enabled."); } return true; } catch (Exception ex) { _pocketRecallPatchFailureLogged = true; if (ModLog != null) { ModLog.LogError((object)("Failed to install Pocket Dvergr EmergencyRecall.Trigger guard: " + ex)); } return false; } } internal static void LogGuardErrorOnce(string message) { if (Interlocked.Exchange(ref _guardErrorLogged, 1) == 0 && ModLog != null) { ModLog.LogError((object)message); } } internal static bool IsFullDamageProtectionEnabled() { if (Enabled != null && Enabled.Value && BlockAllNeutralDamage != null) { return BlockAllNeutralDamage.Value; } return false; } private static ConfigEntry<T> BindLocalized<T>(string section, string key, T defaultValue, LocalizedText category, LocalizedText displayName, LocalizedText description) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { Category = ConfigText(category), DispName = ConfigText(displayName), DefaultValue = defaultValue, Description = ConfigText(description) }; ConfigEntry<T> val = InstanceConfig.Bind<T>(section, key, defaultValue, new ConfigDescription(description.Japanese, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes })); LocalizedConfigEntries.Add(new LocalizedConfigMetadata { Entry = (ConfigEntryBase)(object)val, Category = category, DisplayName = displayName, Description = description }); return val; } private static string GetLanguageCode() { if (!LanguageCacheInitialized) { RefreshLanguageCache(); } return CachedLanguage; } private static string ConfigText(LocalizedText text) { if (text == null) { return string.Empty; } return GetLanguageCode() switch { "ja" => text.Japanese, "de" => text.German, "fr" => text.French, "ko" => text.Korean, _ => text.English, }; } private static void RefreshLanguageCache() { switch ((DisplayLanguage != null) ? DisplayLanguage.Value : "自動") { case "日本語": CachedLanguage = "ja"; LanguageCacheInitialized = true; return; case "English": CachedLanguage = "en"; LanguageCacheInitialized = true; return; case "Deutsch": CachedLanguage = "de"; LanguageCacheInitialized = true; return; case "Français": CachedLanguage = "fr"; LanguageCacheInitialized = true; return; case "한국어": CachedLanguage = "ko"; LanguageCacheInitialized = true; return; } string text = null; try { Type type = AccessTools.TypeByName("Localization"); if (type != null) { object obj = type.GetProperty("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null, null) ?? type.GetField("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); MethodInfo method = type.GetMethod("GetSelectedLanguage", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method != null && obj != null) { text = method.Invoke(obj, null) as string; } if (string.IsNullOrEmpty(text)) { MethodInfo method2 = type.GetMethod("GetLanguage", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method2 != null && obj != null) { text = method2.Invoke(obj, null) as string; } } } } catch (Exception ex) { if (ModLog != null) { ModLog.LogDebug((object)("Could not read the selected Valheim language through Localization: " + ex.Message)); } } if (string.IsNullOrEmpty(text)) { try { text = PlayerPrefs.GetString("language", (string)null); } catch { } } if (!string.IsNullOrEmpty(text)) { if (text.IndexOf("Japanese", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("日本語", StringComparison.OrdinalIgnoreCase) >= 0) { CachedLanguage = "ja"; } else if (text.IndexOf("German", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Deutsch", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("ドイツ", StringComparison.OrdinalIgnoreCase) >= 0) { CachedLanguage = "de"; } else if (text.IndexOf("French", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Français", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("フランス", StringComparison.OrdinalIgnoreCase) >= 0) { CachedLanguage = "fr"; } else if (text.IndexOf("Korean", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("한국어", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("韓国", StringComparison.OrdinalIgnoreCase) >= 0) { CachedLanguage = "ko"; } else { CachedLanguage = "en"; } } else { CachedLanguage = "en"; } LanguageCacheInitialized = true; } private IEnumerator RefreshLanguageAfterStartup() { yield return (object)new WaitForSecondsRealtime(0.25f); RefreshLanguageCache(); ApplyConfigManagerLocalization(); yield return (object)new WaitForSecondsRealtime(0.75f); RefreshLanguageCache(); ApplyConfigManagerLocalization(); } internal static void RefreshConfigManagerLocalizationNow() { if (DisplayLanguage == null || !(DisplayLanguage.Value != "自動")) { LanguageCacheInitialized = false; RefreshLanguageCache(); ApplyConfigManagerLocalization(); } } private static void ApplyConfigManagerLocalization() { object[] tags; foreach (LocalizedConfigMetadata localizedConfigEntry in LocalizedConfigEntries) { if (localizedConfigEntry == null || localizedConfigEntry.Entry == null || localizedConfigEntry.Entry.Description == null || localizedConfigEntry.Entry.Description.Tags == null) { continue; } tags = localizedConfigEntry.Entry.Description.Tags; for (int i = 0; i < tags.Length; i++) { if (tags[i] is ConfigurationManagerAttributes configurationManagerAttributes) { configurationManagerAttributes.Category = ConfigText(localizedConfigEntry.Category); configurationManagerAttributes.DispName = ConfigText(localizedConfigEntry.DisplayName); configurationManagerAttributes.Description = ConfigText(localizedConfigEntry.Description); } } } if (DisplayLanguage == null || ((ConfigEntryBase)DisplayLanguage).Description == null || ((ConfigEntryBase)DisplayLanguage).Description.Tags == null) { return; } tags = ((ConfigEntryBase)DisplayLanguage).Description.Tags; for (int i = 0; i < tags.Length; i++) { if (tags[i] is ConfigurationManagerAttributes configurationManagerAttributes2) { configurationManagerAttributes2.Category = ConfigText(new LocalizedText("全般", "General", "Allgemein", "Général", "일반")); configurationManagerAttributes2.DispName = ConfigText(new LocalizedText("表示言語", "Display Language", "Anzeigesprache", "Langue d'affichage", "표시 언어")); configurationManagerAttributes2.Description = ConfigText(new LocalizedText("表示言語を選択します。「自動」ではValheimの設定言語を読み取ります。", "Select the display language. Auto follows Valheim's selected language.", "Wähle die Anzeigesprache. Automatisch wird die in Valheim ausgewählte Sprache verwendet.", "Choisissez la langue d'affichage. Le mode automatique suit la langue sélectionnée dans Valheim.", "표시 언어를 선택합니다. 자동 모드는 Valheim에서 선택한 언어를 따릅니다.")); } } } private void OnDestroy() { if (_harmony != null) { _harmony.UnpatchSelf(); _harmony = null; } } } internal sealed class ConfigurationManagerAttributes { public bool? Browsable; public string Category; public object DefaultValue; public bool? HideDefaultButton; public bool? HideSettingName; public string Description; public string DispName; public int? Order; public bool? ReadOnly; public bool? IsAdvanced; public bool? ShowRangeAsPercent; public Func<object, string> ObjToStr; public Func<string, object> StrToObj; public Action<ConfigEntryBase> CustomDrawer; } [HarmonyPatch(typeof(Localization), "SetLanguage")] internal static class NeutralGuardLocalizationLanguagePatch { [HarmonyPostfix] private static void Postfix(string language) { SakeysNeutralGuardPlugin.RefreshConfigManagerLocalizationNow(); } } internal static class OwnerFieldAccessor { private static readonly FieldInfo ProjectileOwnerField = AccessTools.Field(typeof(Projectile), "m_owner"); private static readonly FieldInfo AoeOwnerField = AccessTools.Field(typeof(Aoe), "m_owner"); private static int _readFailureLogged; internal static Character GetProjectileOwner(Projectile instance) { return ReadCharacterField(ProjectileOwnerField, instance, "Projectile.m_owner"); } internal static Character GetAoeOwner(Aoe instance) { return ReadCharacterField(AoeOwnerField, instance, "Aoe.m_owner"); } internal static void LogFieldAvailability(ManualLogSource log) { if (ProjectileOwnerField == null) { log.LogError((object)"Could not find Projectile.m_owner. Projectile protection will be inactive."); } if (AoeOwnerField == null) { log.LogError((object)"Could not find Aoe.m_owner. AOE/chain protection will be inactive."); } } private static Character ReadCharacterField(FieldInfo field, object instance, string fieldName) { if (field == null || instance == null) { return null; } try { object? value = field.GetValue(instance); return (Character)((value is Character) ? value : null); } catch (Exception ex) { if (Interlocked.Exchange(ref _readFailureLogged, 1) == 0 && SakeysNeutralGuardPlugin.ModLog != null) { SakeysNeutralGuardPlugin.ModLog.LogError((object)("Failed to read " + fieldName + " through reflection; affected protection checks will be skipped. " + ex)); } return null; } } } internal static class NeutralGuardRules { internal static bool ShouldProtect(Character owner, Character target, out string reason) { reason = "Unknown"; if (SakeysNeutralGuardPlugin.Enabled == null || !SakeysNeutralGuardPlugin.Enabled.Value) { reason = "ProtectionDisabled"; return false; } if ((Object)(object)owner == (Object)null || (Object)(object)target == (Object)null || (Object)(object)owner == (Object)(object)target) { reason = "OwnerOrTargetMissingOrSame"; return false; } if (!owner.IsPlayer()) { reason = "OwnerNotPlayer"; return false; } if (target.IsPlayer()) { reason = "PlayerTarget"; return false; } if (target.IsTamed()) { bool flag = SakeysNeutralGuardPlugin.ProtectTamedCreatures != null && SakeysNeutralGuardPlugin.ProtectTamedCreatures.Value; reason = (flag ? "TamedCreatureProtection" : "TamedProtectionDisabled"); return flag; } BaseAI baseAI = target.GetBaseAI(); if ((Object)(object)baseAI == (Object)null) { reason = "NoBaseAI"; return false; } if (!baseAI.IsAggravatable()) { reason = "NotAggravatable"; return false; } if (BaseAI.IsEnemy(owner, target)) { reason = "AlreadyHostileOrEnemyFaction"; return false; } reason = "NeutralAggravatableCreature"; return true; } } internal static class NeutralGuardDamageRules { internal static bool ShouldBlockPlayerDamageToNeutral(Character attacker, Character target, out string reason) { reason = "Unknown"; if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled()) { reason = "FullDamageProtectionDisabled"; return false; } if ((Object)(object)attacker == (Object)null || (Object)(object)target == (Object)null || (Object)(object)attacker == (Object)(object)target || !attacker.IsPlayer()) { reason = "NotPlayerDamage"; return false; } if (target.IsPlayer()) { reason = "PlayerTarget"; return false; } if (target.IsTamed()) { bool flag = SakeysNeutralGuardPlugin.ProtectTamedCreatures != null && SakeysNeutralGuardPlugin.ProtectTamedCreatures.Value; reason = (flag ? "TamedCreatureProtection" : "TamedProtectionDisabled"); return flag; } if ((Object)(object)target.GetBaseAI() == (Object)null) { reason = "NoBaseAI"; return false; } if (BaseAI.IsEnemy(attacker, target)) { reason = "AlreadyHostileOrEnemyFaction"; return false; } reason = "NeutralDamageBlocked"; return true; } internal static bool AllowPlayerDamage(Character attacker, Character target, string route) { if (!ShouldBlockPlayerDamageToNeutral(attacker, target, out var reason)) { return true; } NeutralGuardDiagnostics.LogDecision(route, attacker, target, "BLOCK", reason); return false; } } [HarmonyPatch(typeof(Character), "Damage", new Type[] { typeof(HitData) })] internal static class NeutralGuardCharacterDamagePatch { [HarmonyPrefix] [HarmonyPriority(800)] private static bool Prefix(Character __instance, HitData hit) { if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled() || (Object)(object)__instance == (Object)null || hit == null) { return true; } return NeutralGuardDamageRules.AllowPlayerDamage(hit.GetAttacker(), __instance, "Character.Damage"); } } [HarmonyPatch(typeof(Character), "RPC_Damage", new Type[] { typeof(long), typeof(HitData) })] internal static class NeutralGuardCharacterRpcDamagePatch { [HarmonyPrefix] [HarmonyPriority(800)] private static bool Prefix(Character __instance, long sender, HitData hit) { if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled() || (Object)(object)__instance == (Object)null || hit == null) { return true; } return NeutralGuardDamageRules.AllowPlayerDamage(hit.GetAttacker(), __instance, "Character.RPC_Damage"); } } [HarmonyPatch(typeof(MonsterAI), "OnDamaged", new Type[] { typeof(float), typeof(Character) })] internal static class NeutralGuardMonsterAiOnDamagedPatch { [HarmonyPrefix] [HarmonyPriority(800)] private static bool Prefix(MonsterAI __instance, float damage, Character attacker) { if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled() || (Object)(object)__instance == (Object)null) { return true; } Character component = ((Component)__instance).GetComponent<Character>(); if ((Object)(object)component == (Object)null) { return true; } return NeutralGuardDamageRules.AllowPlayerDamage(attacker, component, "MonsterAI.OnDamaged"); } } internal static class PocketCompanionOwnerTargetGuard { private static Type _companionType; private static MethodInfo _getOwnerIdMethod; private static readonly FieldInfo TargetCreatureField = AccessTools.Field(typeof(MonsterAI), "m_targetCreature"); private static readonly FieldInfo TargetStaticField = AccessTools.Field(typeof(MonsterAI), "m_targetStatic"); private static readonly MethodInfo SetAlertedMethod = AccessTools.Method(typeof(BaseAI), "SetAlerted", new Type[1] { typeof(bool) }, (Type[])null); private static readonly MethodInfo SetTargetInfoMethod = AccessTools.Method(typeof(BaseAI), "SetTargetInfo", new Type[1] { typeof(ZDOID) }, (Type[])null); internal static bool IsOwnedPocketCompanionTarget(BaseAI ai, Character candidate, out Player owner) { owner = null; if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled() || (Object)(object)ai == (Object)null || (Object)(object)candidate == (Object)null) { return false; } Player val = (Player)(object)((candidate is Player) ? candidate : null); if ((Object)(object)val == (Object)null) { return false; } Type companionType = GetCompanionType(); if (companionType == null) { return false; } Component component = ((Component)ai).GetComponent(companionType); if ((Object)(object)component == (Object)null) { return false; } MethodInfo ownerIdMethod = GetOwnerIdMethod(companionType); if (ownerIdMethod == null) { return false; } try { long num = Convert.ToInt64(ownerIdMethod.Invoke(component, null)); if (num == 0L || val.GetPlayerID() != num) { return false; } owner = val; return true; } catch (Exception ex) { SakeysNeutralGuardPlugin.LogGuardErrorOnce("Failed to resolve Pocket Dvergr owner identity; owner-target suppression is unavailable. " + ex); return false; } } internal static Character GetCompanionCharacter(BaseAI ai) { if (!((Object)(object)ai != (Object)null)) { return null; } return ((Component)ai).GetComponent<Character>(); } internal static void ClearCombatTarget(BaseAI ai) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ai == (Object)null) { return; } try { MonsterAI val = (MonsterAI)(object)((ai is MonsterAI) ? ai : null); if ((Object)(object)val != (Object)null) { if (TargetCreatureField != null) { TargetCreatureField.SetValue(val, null); } if (TargetStaticField != null) { TargetStaticField.SetValue(val, null); } } if (SetAlertedMethod != null) { SetAlertedMethod.Invoke(ai, new object[1] { false }); } if (SetTargetInfoMethod != null) { SetTargetInfoMethod.Invoke(ai, new object[1] { ZDOID.None }); } } catch (Exception ex) { SakeysNeutralGuardPlugin.LogGuardErrorOnce("Failed to clear a Pocket Dvergr owner combat target. " + ex); } } private static Type GetCompanionType() { if (_companionType != null) { return _companionType; } _companionType = AccessTools.TypeByName("SakeysPocketDverger.PocketDvergerCompanion") ?? AccessTools.TypeByName("PocketDvergerCompanion"); if (_companionType != null) { _getOwnerIdMethod = _companionType.GetMethod("GetOwnerID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } return _companionType; } private static MethodInfo GetOwnerIdMethod(Type companionType) { if (_getOwnerIdMethod == null && companionType != null) { _getOwnerIdMethod = companionType.GetMethod("GetOwnerID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } return _getOwnerIdMethod; } } [HarmonyPatch] internal static class NeutralGuardPocketCompanionSetTargetPatch { internal static int ResolvedTargetMethodCount() { int num = 0; foreach (MethodBase item in TargetMethods()) { _ = item; num++; } return num; } private static IEnumerable<MethodBase> TargetMethods() { Type[] aiTypes = new Type[2] { typeof(BaseAI), typeof(MonsterAI) }; for (int t = 0; t < aiTypes.Length; t++) { MethodInfo[] methods = aiTypes[t].GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name != "SetTarget" || methodInfo.ReturnType != typeof(void)) { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); bool flag = false; for (int j = 0; j < parameters.Length; j++) { if (parameters[j].ParameterType == typeof(Character)) { flag = true; break; } } if (flag) { yield return methodInfo; } } } } [HarmonyPrefix] [HarmonyPriority(800)] private static bool Prefix(object __instance, object[] __args) { BaseAI val = (BaseAI)((__instance is BaseAI) ? __instance : null); if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled() || (Object)(object)val == (Object)null || __args == null) { return true; } Character val2 = null; foreach (object obj in __args) { val2 = (Character)((obj is Character) ? obj : null); if ((Object)(object)val2 != (Object)null) { break; } } if (!PocketCompanionOwnerTargetGuard.IsOwnedPocketCompanionTarget(val, val2, out var owner)) { return true; } Character companionCharacter = PocketCompanionOwnerTargetGuard.GetCompanionCharacter(val); NeutralGuardDiagnostics.LogDecision("MonsterAI.SetTarget", (Character)(object)owner, companionCharacter, "BLOCK", "PocketDvergrOwnerTarget"); PocketCompanionOwnerTargetGuard.ClearCombatTarget(val); return false; } } [HarmonyPatch] internal static class NeutralGuardPocketCompanionGetTargetPatch { internal static int ResolvedTargetMethodCount() { int num = 0; foreach (MethodBase item in TargetMethods()) { _ = item; num++; } return num; } private static IEnumerable<MethodBase> TargetMethods() { Type[] aiTypes = new Type[2] { typeof(BaseAI), typeof(MonsterAI) }; for (int t = 0; t < aiTypes.Length; t++) { MethodInfo[] methods = aiTypes[t].GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name == "GetTargetCreature" && methodInfo.ReturnType == typeof(Character) && methodInfo.GetParameters().Length == 0) { yield return methodInfo; } } } } [HarmonyPostfix] private static void Postfix(object __instance, ref Character __result) { BaseAI val = (BaseAI)((__instance is BaseAI) ? __instance : null); if (!((Object)(object)val == (Object)null) && !((Object)(object)__result == (Object)null) && PocketCompanionOwnerTargetGuard.IsOwnedPocketCompanionTarget(val, __result, out var owner)) { Character companionCharacter = PocketCompanionOwnerTargetGuard.GetCompanionCharacter(val); NeutralGuardDiagnostics.LogDecision("BaseAI.GetTargetCreature", (Character)(object)owner, companionCharacter, "BLOCK", "PocketDvergrOwnerTargetCleared"); __result = null; PocketCompanionOwnerTargetGuard.ClearCombatTarget(val); } } } internal static class NeutralGuardPocketDvergerEmergencyRecallPatch { private static bool Prefix(Player __0, string __1) { if (!SakeysNeutralGuardPlugin.IsFullDamageProtectionEnabled() || (Object)(object)__0 == (Object)null) { return true; } if (!string.Equals(__1, "friendly fire", StringComparison.OrdinalIgnoreCase)) { return true; } if (SakeysNeutralGuardPlugin.EnableDebugLogs != null && SakeysNeutralGuardPlugin.EnableDebugLogs.Value && SakeysNeutralGuardPlugin.ModLog != null) { SakeysNeutralGuardPlugin.ModLog.LogInfo((object)("[TargetCheck] BLOCK route=PocketDvergerEmergencyRecall.Trigger owner=" + ((Object)((Component)__0).gameObject).name + " reason=friendly fire")); } return false; } } internal static class NeutralGuardDiagnostics { private static readonly object Sync = new object(); private static readonly Dictionary<string, float> LastLogTimes = new Dictionary<string, float>(); private const float LogIntervalSeconds = 3f; internal static void LogDecision(string route, Character owner, Character target, string outcome, string reason) { if (SakeysNeutralGuardPlugin.EnableDebugLogs == null || !SakeysNeutralGuardPlugin.EnableDebugLogs.Value || SakeysNeutralGuardPlugin.ModLog == null || (Object)(object)target == (Object)null) { return; } string key = route + ":" + ((Object)target).GetInstanceID(); float unscaledTime = Time.unscaledTime; lock (Sync) { if (LastLogTimes.TryGetValue(key, out var value) && unscaledTime - value < 3f) { return; } LastLogTimes[key] = unscaledTime; if (LastLogTimes.Count > 512) { LastLogTimes.Clear(); } } string text = SafeObjectName(owner); string text2 = SafeObjectName(target); string text3 = ((object)Unsafe.As<Faction, Faction>(ref target.m_faction)/*cast due to .constrained prefix*/).ToString(); SakeysNeutralGuardPlugin.ModLog.LogInfo((object)("[TargetCheck] " + outcome + " route=" + route + " owner=" + text + " target=" + text2 + " targetFaction=" + text3 + " targetId=" + ((Object)target).GetInstanceID() + " reason=" + reason)); } internal static void LogProjectileAoeScope(Projectile projectile, Character owner) { if (SakeysNeutralGuardPlugin.EnableDebugLogs == null || !SakeysNeutralGuardPlugin.EnableDebugLogs.Value || SakeysNeutralGuardPlugin.ModLog == null || (Object)(object)projectile == (Object)null || (Object)(object)owner == (Object)null || !owner.IsPlayer()) { return; } string key = "Projectile.DoAOE:" + ((Object)projectile).GetInstanceID(); float unscaledTime = Time.unscaledTime; lock (Sync) { if (LastLogTimes.TryGetValue(key, out var value) && unscaledTime - value < 3f) { return; } LastLogTimes[key] = unscaledTime; if (LastLogTimes.Count > 512) { LastLogTimes.Clear(); } } SakeysNeutralGuardPlugin.ModLog.LogInfo((object)("[ProjectileAOE] scope=PLAYER_ACTIVE owner=" + SafeObjectName(owner) + " projectile=" + (((Object)(object)((Component)projectile).gameObject != (Object)null) ? ((Object)((Component)projectile).gameObject).name : ((object)projectile).GetType().Name) + " projectileId=" + ((Object)projectile).GetInstanceID())); } private static string SafeObjectName(Character character) { if ((Object)(object)character == (Object)null) { return "<null>"; } try { return ((Object)(object)((Component)character).gameObject != (Object)null) ? ((Object)((Component)character).gameObject).name : ((object)character).GetType().Name; } catch { return ((object)character).GetType().Name; } } } [HarmonyPatch(typeof(Aoe), "ShouldHit")] internal static class AoeShouldHitPatch { [HarmonyPostfix] private static void Postfix(Aoe __instance, Collider collider, ref bool __result) { if ((Object)(object)__instance == (Object)null || SakeysNeutralGuardPlugin.ProtectAoeAndChain == null || !SakeysNeutralGuardPlugin.ProtectAoeAndChain.Value || !__instance.m_hitCharacters || (Object)(object)collider == (Object)null) { return; } Character aoeOwner = OwnerFieldAccessor.GetAoeOwner(__instance); if ((Object)(object)aoeOwner == (Object)null || !aoeOwner.IsPlayer()) { return; } GameObject val = Projectile.FindHitObject(collider); Character val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Character>() : null); if ((Object)(object)val2 == (Object)null) { val2 = ((Component)collider).GetComponentInParent<Character>(); } if ((Object)(object)val2 == (Object)null) { return; } if (!__result) { NeutralGuardDiagnostics.LogDecision("Aoe.ShouldHit", aoeOwner, val2, "VANILLA_REJECT", "VanillaTargetFilterRejected"); return; } string reason; bool flag = NeutralGuardRules.ShouldProtect(aoeOwner, val2, out reason); NeutralGuardDiagnostics.LogDecision("Aoe.ShouldHit", aoeOwner, val2, flag ? "BLOCK" : "ALLOW", reason); if (flag) { __result = false; } } } internal static class ProjectileAoeScope { [ThreadStatic] private static Projectile _activePlayerAoe; internal static Projectile ActivePlayerAoe { get { return _activePlayerAoe; } set { _activePlayerAoe = value; } } } [HarmonyPatch(typeof(Projectile), "DoAOE")] internal static class ProjectileDoAoeScopePatch { [HarmonyPrefix] private static void Prefix(Projectile __instance, out Projectile __state) { __state = ProjectileAoeScope.ActivePlayerAoe; Character projectileOwner = OwnerFieldAccessor.GetProjectileOwner(__instance); if ((Object)(object)projectileOwner != (Object)null && projectileOwner.IsPlayer()) { ProjectileAoeScope.ActivePlayerAoe = __instance; NeutralGuardDiagnostics.LogProjectileAoeScope(__instance, projectileOwner); } else { ProjectileAoeScope.ActivePlayerAoe = null; } } [HarmonyFinalizer] private static Exception Finalizer(Exception __exception, Projectile __state) { ProjectileAoeScope.ActivePlayerAoe = __state; return __exception; } } [HarmonyPatch(typeof(Projectile), "IsValidTarget")] internal static class ProjectileIsValidTargetPatch { [HarmonyPostfix] private static void Postfix(Projectile __instance, IDestructible destr, ref bool __result) { if ((Object)(object)__instance == (Object)null || SakeysNeutralGuardPlugin.ProtectProjectileExplosions == null || !SakeysNeutralGuardPlugin.ProtectProjectileExplosions.Value || ProjectileAoeScope.ActivePlayerAoe != __instance) { return; } Character val = (Character)(object)((destr is Character) ? destr : null); Character projectileOwner = OwnerFieldAccessor.GetProjectileOwner(__instance); if ((Object)(object)val == (Object)null || (Object)(object)projectileOwner == (Object)null || !projectileOwner.IsPlayer()) { return; } if (!__result) { NeutralGuardDiagnostics.LogDecision("Projectile.IsValidTarget", projectileOwner, val, "VANILLA_REJECT", "VanillaProjectileTargetFilterRejected"); return; } string reason; bool flag = NeutralGuardRules.ShouldProtect(projectileOwner, val, out reason); NeutralGuardDiagnostics.LogDecision("Projectile.IsValidTarget", projectileOwner, val, flag ? "BLOCK" : "ALLOW", reason); if (flag) { __result = false; } } }