RacesOfValheim/JotunnModStub/Factions/FactionHostilityPatch.cs
kanym 4ee98d90cb fix(factions): the player can strike allied creatures again
Valheim 1.0's hit filters (Attack melee/area, Projectile OnHit/DoAOE/
IsValidTarget, Aoe.ShouldHit) skip a target when BaseAI.IsEnemy says
false and the attacker is a player without PvP. The truce said false
for every allied creature, so the blow passed through: no damage, no
grudge, nothing for kin to join. RaceGrudge.StrikeScope opens a scope
around those six methods in which both truce patches stand down for
the player's own hit; everything else keeps the truce.
2026-11-06 21:21:20 +01:00

285 lines
16 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
// "Mobs of a faction don't attack players of the same faction" - the core Factions
// rule from the brainstorm. RaceHostilityManager.cs already grants some of this
// (Fenrir/Aswid/Draugh/Trenta), but several races have no coverage at all (Trol,
// Furling, Skadi, Dvergar, Skeleton), and none of it lines up race-for-race with the
// three Factions groupings. Both patches postfix the same vanilla method, so this one
// simply layers the full, faction-consistent ruleset on top without touching the
// older file - a player already exempted there stays exempted, this only adds pairs.
//
// Without this, a matching-faction mob keeps fighting the player, which is why the
// Trader's "E to use" prompt never has a chance to come up: BaseAI.UpdateAI() is
// still busy chasing/attacking every frame.
[HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })]
public static class FactionHostilityPatch
{
// "Fuling" was in this set and is not a prefab: the Fuling family is named Goblin* in code,
// so the basic Fuling and the Archer were never exempted for any of the three races that
// read this set (Trenta, Trol, Furling) while the Berserker and Shaman were. In a camp that
// is the same as no truce at all - the unexempted Fulings open fire, the player defends
// themselves, and every Berserker in earshot joins in through damage retaliation, which
// IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names.
// Matching is by exact prefab name, so every variant of a creature has to be named here in
// its own right - a family left half-listed is what made the truce look random by biome
// (see PaludeMobs below for the report that turned this up). "Greyling" is the Meadows
// greydwarf and was missing outright: a Trol or a Furling was at peace with the whole
// Black Forest and still fought the smallest thing in it. The Trenta never noticed,
// because its own list in RaceHostilityManager matches on substrings instead.
private static readonly HashSet<string> NeraForestaMobs = new HashSet<string>
{
"Greyling",
"Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman",
"Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman",
"Troll",
};
private static readonly HashSet<string> MontagnaMobs = new HashSet<string>
{
"Hatchling", // Drake
"Wolf", "Ulv", "Fenring", "Fenring_Cultist",
"Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands",
};
// Skeleton_NoArcher and Draugr_Ranged are the two that were missing, and they are why an
// Aswid reported skeletons that were peaceful in one biome and hostile in another: it was
// never the biome, it was which variant that particular spawner places. Skeleton_NoArcher
// is vanilla's guaranteed-melee skeleton (the same one SkeletonBonePile borrows), so a
// spawner using it produced hostile skeletons standing next to peaceful ones. Draugr_Ranged
// is the bow draugr, left out while the melee and elite ones were exempt.
//
// Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the
// Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin.
//
// Valheim 1.0 added a skeleton per region (the green swamp ones and the blue mountain ones
// players noticed first), each with a melee-only twin, and spawners place those instead
// of the plain Skeleton. Left out, they fought a Skeleton player the plain ones ignored.
private static readonly HashSet<string> PaludeMobs = new HashSet<string>
{
"Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains
"Skeleton_Meadows", "Skeleton_Meadows_noarcher",
"Skeleton_Swamps", "Skeleton_Swamps_noarcher",
"Skeleton_Mountains", "Skeleton_Mountains_noarcher",
"Skeleton_DeepNorth",
"Draugr", "Draugr_Elite", "Draugr_Ranged",
"Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
};
// Every race id ever assigned to m_customData["Race"] for the nine playable races,
// grouped by which faction's mobs they get along with (see RacesOfValheim.cs for
// where each string is set, and DvergarRace.cs's LegacyRaceId for the old save value).
private static readonly Dictionary<string, HashSet<string>> RaceFactionMobs = new Dictionary<string, HashSet<string>>
{
{ TrentaConfig.RaceId, NeraForestaMobs },
{ "Trol", NeraForestaMobs },
{ "Furling", NeraForestaMobs },
{ "Skadi", MontagnaMobs },
{ "Fenrir", MontagnaMobs },
{ DvergarConfig.RaceId, MontagnaMobs },
{ DvergarRace.LegacyRaceId, MontagnaMobs },
{ "Aswid", PaludeMobs },
{ "Draugh", PaludeMobs },
{ SkeletonVisuals.RaceId, PaludeMobs },
};
// Shared with FactionMerchantHoverPatch: a player should only get the "E - Talk"
// hover prompt for a mob whose faction actually matches their own race.
public static bool IsSameFaction(Player player, Character monster)
{
if (player == null || monster == null) return false;
return IsFactionMob(GetPlayerRace(player), monster.gameObject.name);
}
// The same answer by name alone, for callers that only have a prefab and no live creature -
// the raid filter reads RandomEvent.m_spawn, which holds prefabs that were never spawned.
public static bool IsFactionMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
return mobs.Contains(prefabName.Replace("(Clone)", "").Trim());
}
// Faction set or per-race list, whichever says yes: the two questions IsEnemy is asked
// through these two files, answered without a Character. Grudges are not in here - a grudge
// is held by one creature, not by a prefab.
public static bool IsAlliedMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
return IsFactionMob(race, prefabName) || RaceHostilityManager.IsRaceKin(race, prefabName);
}
// m_customData is the local save file's dictionary: it is only ever populated for
// the client's own m_localPlayer, so IsEnemy running on a remote AI owner (a
// dedicated server, or any other nearby player who ends up owning the mob's ZDO)
// read an empty dictionary here and treated every truce as hostile. Every other
// race-aware patch in this project reads "RacesOfValheim_Race" off the ZDO instead
// because that field actually replicates - check it first, and only fall back to
// m_customData for the single-player/local-owner case where the ZDO hasn't been
// written yet (e.g. brand new character before the race pick's Set() call runs).
public static string GetPlayerRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace;
}
return player.m_customData.TryGetValue("Race", out string race) ? race : null;
}
// The truce used to cover the player only. A thrall is tamed, so it sits in the Players
// faction, and a wild mob of the player's own faction still saw it as fair game: a wild
// Rancid Remains walked up to a Skeleton's bone pile, ignored the Skeleton and tore into
// the garrison. The thrall's own race is on the prefab (m_commandingRace), so the same
// faction sets answer for it without needing its owner nearby.
//
// The truce breaks the moment that wild mob holds a grudge against any player: it is
// fighting the thralls' master, and the thralls should fight back.
private static bool IsThrallTruce(Character thrallSide, Character wildSide)
{
if (wildSide.IsPlayer() || wildSide.IsTamed()) return false;
RaisedThrall thrall = thrallSide.GetComponent<RaisedThrall>();
if (thrall == null || string.IsNullOrEmpty(thrall.m_commandingRace)) return false;
if (wildSide.GetComponent<RaisedThrall>() != null) return false;
if (!IsAlliedMob(thrall.m_commandingRace, wildSide.gameObject.name)) return false;
foreach (Player player in Player.GetAllPlayers())
{
if (RaceGrudge.Holds(wildSide, player)) return false;
}
return true;
}
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!FactionsConfig.Hostility) return;
if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return;
// The player's own blow. Peace is the creature's choice, not a shield. See
// RaceGrudge.StrikeScope.
if (RaceGrudge.PlayerStrikes(a)) return;
if (IsThrallTruce(a, b) || IsThrallTruce(b, a))
{
__result = false;
return;
}
Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null);
Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null);
if (!(playerCharacter is Player p) || monster == null) return;
// Same stand-down as the per-race truces get: hit your own faction and it hits back
// until the grudge runs out. See RaceGrudge.
if (RaceGrudge.Holds(monster, p)) return;
if (IsSameFaction(p, monster))
{
__result = false;
}
}
}
/// <summary>
/// The truce above only ever touches BaseAI.IsEnemy - a mob's decision to smash a nearby
/// piece runs on a completely separate track. MonsterAI.UpdateTarget gates that on
/// m_attackPlayerObjects (a flag baked into the prefab, true for Troll among others) and
/// never once calls IsEnemy: a Troll with nothing to fight picks a m_targetStatic and
/// swings at it regardless of who is standing next to it. That is how a Trol player,
/// exempt from that very Troll's hostility, could still watch it flatten a workbench built
/// two seconds earlier in its own cave.
///
/// A postfix on UpdateTarget rather than trying to intercept FindClosestStaticPriorityTarget
/// or FindRandomStaticTarget (both private, both called from more than one branch inside it):
/// simpler to let vanilla pick whatever it wants and veto the pick once, right after, than to
/// duplicate its target-selection logic to stop it picking in the first place.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
public static class FactionStaticTargetPatch
{
// This used to be 20 m, sized against FindRandomStaticTarget's 10 m search. The other pick,
// FindClosestStaticPriorityTarget, searches the mob's whole m_viewRange, so a skeleton 25 m
// from an Aswid could still lock onto a piece and the veto never ran - and it never ran at
// all once the player stepped away from the base mid-raid. The rule is now "an ally is
// around, the whole base is safe": 100 m is roughly a raid's own area (RandomEvent's
// m_eventRange), so anyone still inside the raid covers every piece in it, whoever built it.
private const float FactionCheckRange = 100f;
public static void Postfix(MonsterAI __instance)
{
if (!FactionsConfig.Hostility) return;
Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic");
// GetValue() hands back a plain object, and object == null skips Unity's destroyed
// check: a piece smashed or removed while targeted stays non-null here, and touching
// its gameObject throws. That throw escapes into MonoUpdaters.FixedUpdate and stops
// every AI after this one for the frame, every frame, until the field changes.
Component target = targetStatic.GetValue() as Component;
if (target == null)
{
if (targetStatic.GetValue() != null) targetStatic.SetValue(null);
return;
}
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null) return;
// A piece an allied race built is never a target, with or without anyone around.
// See FactionPieceTruce.
if (FactionPieceTruce.Protects(target.gameObject, monster))
{
targetStatic.SetValue(null);
return;
}
foreach (Player player in Player.GetAllPlayers())
{
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;
// A player this creature holds a grudge against is no ally of it right now.
if (RaceGrudge.Holds(monster, player)) continue;
if (!FactionHostilityPatch.IsAlliedMob(FactionHostilityPatch.GetPlayerRace(player), monster.gameObject.name)) continue;
targetStatic.SetValue(null);
return;
}
}
}
// IsEnemy is not the only way a mob picks the player, and the other way ignores it
// completely. BaseAI.FindEnemy() walks every character asking IsEnemy - which both truce
// patches above answer - but when that walk comes up empty and the creature HuntPlayer()s,
// it falls through to Player.GetClosestPlayer(transform.position, 200f) and returns whoever
// it finds, without asking anything about factions.
//
// That fall-through is why the Black Forest truce looked broken to the Trol's testers:
// MonsterAI.UpdateAI turns hunting on for every IsEventCreature() while an event is running,
// and the events that reach a Trol are "the forest is moving" (Greydwarves), "you are being
// hunted" (Trolls) and the Fuling army - the exact three they named. Anything a SpawnSystem
// entry or a TriggerSpawner flags with huntPlayer arrives by the same door.
//
// Filtering the RESULT rather than restating the rule keeps one source of truth: the public
// instance IsEnemy(Character) calls the static overload both postfixes above hook, so this
// honours whatever the faction sets and RaceHostilityManager's per-race lists already agree
// on. Retaliation does not come through here either way - a mob the player hits is targeted
// through BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. That target only
// SURVIVES because of RaceGrudge, though: UpdateTarget drops anything IsEnemy refuses.
[HarmonyPatch(typeof(BaseAI), "FindEnemy")]
public static class FactionHuntPlayerPatch
{
public static void Postfix(BaseAI __instance, ref Character __result)
{
if (!FactionsConfig.Hostility) return;
if (__result == null || !__result.IsPlayer()) return;
if (!__instance.IsEnemy(__result)) __result = null;
}
}
}