RacesOfValheim/JotunnModStub/RaceGrudge.cs
kanym 5530f7dc3d feat(factions): optional group grudge, kin within 20 m join the fight
Joacwoo's request. With "Grudge spreads to kin" on (off by default),
hitting a creature at peace with you gives the same grudge to every
creature of that faction within "Grudge spread radius" (20 m) and
alerts them, like vanilla's Dvergr with a human. Only creatures whose
AI runs on this machine are told, since that is where a grudge is
read.
2026-11-05 13:05:03 +01:00

156 lines
7.2 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Hit something that is at peace with you and it hits back.
///
/// WHY THIS HAS TO EXIST. Both truce patches answer BaseAI.IsEnemy with false, and the comment
/// they each carried - that retaliation runs through BaseAI.OnDamaged and no truce has a say
/// over it - is wrong. Read out of assembly_valheim:
///
/// MonsterAI.OnDamaged calls SetTarget(attacker), so the mob does take the hit
/// personally, exactly as those comments said, and then
/// MonsterAI.UpdateTarget on its very next tick does
/// if (!IsEnemy(m_targetCreature)) m_targetCreature = null;
///
/// so the target is thrown away a frame later. A truced mob could not fight back at all: it
/// stood there being hit, or - hurt, with no enemy it was allowed to have - fell into
/// UpdateAI's flee branches and ran away. That is what testers saw and reported.
///
/// WHAT THIS DOES. It remembers who hit whom, for a while, and both truce postfixes stand down
/// for that one pair while the memory lasts. The mob is an enemy again by vanilla's own rules,
/// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla
/// behaviour rather than anything reimplemented here.
///
/// WHERE IT RUNS. On the client that owns the mob's AI, which is the only one whose UpdateTarget
/// matters and the only one that runs Character.ApplyDamage for it. BaseAI.OnDamaged is reached
/// through the character's damage callback on exactly that machine, so the record is made where
/// it will be read. Nothing is replicated and nothing needs to be: another client's copy of the
/// same mob is not the one deciding who it chases.
///
/// Vanilla has its own version of this idea in BaseAI.SetAggravated, and it is not usable here:
/// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers
/// do.
/// </summary>
public static class RaceGrudge
{
private struct Grudge
{
public ZDOID Attacker;
public float Until;
}
// One grudge per mob, against the last thing that hit it. A creature can only chase one
// target anyway, and if two players of the same race are both poking it, the one it wants
// is whoever hit it last.
private static readonly Dictionary<ZDOID, Grudge> grudges = new Dictionary<ZDOID, Grudge>();
private static float lastSweep = 0f;
private static float Duration => FactionsConfig.GrudgeSeconds;
/// <summary>
/// True while <paramref name="monster"/> is owed a hit by <paramref name="player"/>. Both
/// truce postfixes ask this first and leave IsEnemy alone when it answers yes.
/// </summary>
public static bool Holds(Character monster, Character player)
{
if (monster == null || player == null) return false;
if (Duration <= 0f) return false;
if (!grudges.TryGetValue(monster.GetZDOID(), out Grudge grudge)) return false;
if (Time.time >= grudge.Until) return false;
return grudge.Attacker == player.GetZDOID();
}
public static void Remember(Character monster, Character attacker)
{
if (monster == null || attacker == null) return;
if (Duration <= 0f) return;
grudges[monster.GetZDOID()] = new Grudge
{
Attacker = attacker.GetZDOID(),
Until = Time.time + Duration
};
Sweep();
}
/// <summary>
/// Drops grudges nobody is owed any more. At most once per duration: a fight is a burst of
/// damage events and the list should not be walked on each one.
/// </summary>
private static void Sweep()
{
if (Time.time - lastSweep < Duration) return;
lastSweep = Time.time;
List<ZDOID> expired = null;
foreach (var entry in grudges)
{
if (Time.time < entry.Value.Until) continue;
if (expired == null) expired = new List<ZDOID>();
expired.Add(entry.Key);
}
if (expired == null) return;
foreach (ZDOID id in expired) grudges.Remove(id);
}
/// <summary>
/// The one place a grudge is born. BaseAI.OnDamaged is the base every AI's own override
/// calls first, so patching it here covers MonsterAI and AnimalAI both, and it lands before
/// MonsterAI.OnDamaged's SetTarget on the same hit - the grudge is on the books by the time
/// UpdateTarget next asks whether that target is allowed.
///
/// Only a player's hit counts. A greydwarf caught in another greydwarf's swing has vanilla's
/// own rules for that and no truce of ours in the way.
/// </summary>
[HarmonyPatch(typeof(BaseAI), "OnDamaged")]
public static class BaseAI_OnDamaged_Grudge_Patch
{
public static void Postfix(BaseAI __instance, Character attacker)
{
if (!FactionsConfig.Hostility) return;
if (attacker == null || !attacker.IsPlayer()) return;
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null || monster.IsPlayer()) return;
Remember(monster, attacker);
if (FactionsConfig.GrudgeSpreads && attacker is Player player) SpreadToKin(monster, player);
}
}
/// <summary>
/// Vanilla's Dvergr camp, for every faction ("Grudge spreads to kin", off by default): hit
/// a creature that is at peace with you and its kin around it take up the same grudge.
///
/// Only the creatures this machine runs the AI for are told, because a grudge is read where
/// the AI runs (see WHERE IT RUNS above). The creatures around the one that was hit are
/// nearly always simulated by the same client; one owned by another player's machine stays
/// at peace until it is hit itself.
/// </summary>
private static void SpreadToKin(Character monster, Player player)
{
string race = FactionHostilityPatch.GetPlayerRace(player);
if (!FactionHostilityPatch.IsAlliedMob(race, monster.gameObject.name)) return;
Vector3 center = monster.transform.position;
float radius = FactionsConfig.GrudgeSpreadMeters;
foreach (Character other in Character.GetAllCharacters())
{
if (other == null || other == monster || other.IsPlayer() || other.IsDead() || other.IsTamed()) continue;
if (!other.IsOwner()) continue;
if (Vector3.Distance(other.transform.position, center) > radius) continue;
if (!FactionHostilityPatch.IsAlliedMob(race, other.gameObject.name)) continue;
Remember(other, player);
other.GetBaseAI()?.Alert();
}
}
}
}