The grudge was a dictionary in the owner's memory: when another client took over the creature mid-fight, its copy made peace on the next UpdateTarget. Grudge spreads to kin also skipped kin owned by another client. The grudge now lives on the creature's ZDO (attacker ZDOID and an end time in network time), written only by the owner; kin owned elsewhere get an RPC that their owner handles.
233 lines
12 KiB
C#
233 lines
12 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 LIVES. On the creature's own ZDO: who it is angry at and until when, in network time.
|
|
/// The AI that reads it runs on whichever machine owns the creature, and that can change in the
|
|
/// middle of a fight (the owner walks off or logs out). A grudge kept in one machine's memory
|
|
/// went with it, and the new owner's copy of the creature made peace on its next UpdateTarget.
|
|
/// On the ZDO the new owner reads the same grudge. Only the owner writes it: a hit reaches the
|
|
/// owner through Character.Damage's RPC anyway, and kin owned elsewhere are told by an RPC of
|
|
/// our own (RpcName), so no client writes a ZDO it does not own.
|
|
///
|
|
/// 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 const string RpcName = "RacesOfValheim_Grudge";
|
|
|
|
// One grudge per creature, against the last player 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 KeyValuePair<int, int> AttackerKey = ZDO.GetHashZDOID("RacesOfValheim_GrudgeAttacker");
|
|
private static readonly int UntilKey = "RacesOfValheim_GrudgeUntil".GetStableHashCode();
|
|
|
|
private static float Duration => FactionsConfig.GrudgeSeconds;
|
|
|
|
// Network time, the same on every machine, so an end time written by one owner means the
|
|
// same thing to the next. Milliseconds in a long: ZDO has no double.
|
|
private static long NowMs => ZNet.instance != null ? (long)(ZNet.instance.GetTimeSeconds() * 1000.0) : 0L;
|
|
|
|
private static ZDO ZdoOf(Character character)
|
|
{
|
|
if (character == null || ZDOMan.instance == null) return null;
|
|
ZDOID id = character.GetZDOID();
|
|
return id.IsNone() ? null : ZDOMan.instance.GetZDO(id);
|
|
}
|
|
|
|
/// <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. Read on any
|
|
/// machine; it only matters on the owner's.
|
|
/// </summary>
|
|
public static bool Holds(Character monster, Character player)
|
|
{
|
|
if (monster == null || player == null) return false;
|
|
if (Duration <= 0f) return false;
|
|
|
|
ZDO zdo = ZdoOf(monster);
|
|
if (zdo == null) return false;
|
|
|
|
long until = zdo.GetLong(UntilKey, 0L);
|
|
if (until == 0L || NowMs >= until) return false;
|
|
|
|
return zdo.GetZDOID(AttackerKey) == player.GetZDOID();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes the grudge on the creature's ZDO if this machine owns it, and otherwise asks the
|
|
/// owner to. Returns true when it was written here.
|
|
/// </summary>
|
|
public static bool Remember(Character monster, Character attacker)
|
|
{
|
|
if (monster == null || attacker == null) return false;
|
|
if (Duration <= 0f) return false;
|
|
|
|
ZNetView nview = monster.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid()) return false;
|
|
|
|
if (!nview.IsOwner())
|
|
{
|
|
nview.InvokeRPC(RpcName, attacker.GetZDOID());
|
|
return false;
|
|
}
|
|
|
|
Write(nview.GetZDO(), attacker.GetZDOID());
|
|
return true;
|
|
}
|
|
|
|
private static void Write(ZDO zdo, ZDOID attacker)
|
|
{
|
|
zdo.Set(AttackerKey, attacker);
|
|
zdo.Set(UntilKey, NowMs + (long)(Duration * 1000f));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Every creature can be told about a grudge by a machine that does not own it. ZNetView's
|
|
/// InvokeRPC routes to the owner, so the handler always runs where the ZDO may be written,
|
|
/// and the owner checks it is still the owner: ownership can move while the RPC travels.
|
|
/// </summary>
|
|
[HarmonyPatch(typeof(Character), "Awake")]
|
|
public static class Character_Awake_GrudgeRpc_Patch
|
|
{
|
|
public static void Postfix(Character __instance)
|
|
{
|
|
if (__instance.IsPlayer()) return;
|
|
ZNetView nview = __instance.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid()) return;
|
|
|
|
nview.Register<ZDOID>(RpcName, (sender, attacker) =>
|
|
{
|
|
if (__instance == null || !nview.IsValid() || !nview.IsOwner()) return;
|
|
if (attacker.IsNone() || Duration <= 0f) return;
|
|
Write(nview.GetZDO(), attacker);
|
|
__instance.GetBaseAI()?.Alert();
|
|
});
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
}
|
|
}
|
|
|
|
// How deep we are inside one of vanilla's hit filters (see StrikeScope). A counter rather
|
|
// than a bool because Projectile.OnHit calls DoAOE, and the inner exit must not end the
|
|
// outer scope.
|
|
private static int strikeDepth = 0;
|
|
|
|
/// <summary>
|
|
/// True while vanilla is deciding whether <paramref name="attacker"/>'s own weapon, arrow or
|
|
/// area hit lands. Both truce postfixes stand down for that question: the truce is about
|
|
/// who a creature attacks, never about whether the player is allowed to strike it.
|
|
/// </summary>
|
|
public static bool PlayerStrikes(Character attacker)
|
|
{
|
|
return strikeDepth > 0 && attacker != null && attacker.IsPlayer();
|
|
}
|
|
|
|
/// <summary>
|
|
/// THE PLAYER COULD NOT HIT THEIR OWN FACTION AT ALL. Valheim 1.0's hit filters (Attack's
|
|
/// melee and area swings, Projectile's direct hit, its AoE and its IsValidTarget, Aoe's
|
|
/// ShouldHit) ask BaseAI.IsEnemy(attacker, target) and skip the target when it answers false
|
|
/// and the attacker is a player without PvP on - vanilla's guard for tames. Our truce
|
|
/// answers false for every allied creature, so the blow passed through it, it took no
|
|
/// damage, BaseAI.OnDamaged never ran and no grudge was ever born. That is both reports at
|
|
/// once: "it will not allow me" to attack, and kin that never fight back, group grudge on or
|
|
/// off, because nobody was ever hit. With PvP on the filter let the hit through, which is
|
|
/// why it looked fine in some tests.
|
|
///
|
|
/// The scope is open only around those six methods, so everything else that asks IsEnemy
|
|
/// with the player first keeps the truce: the green health bar on allied creatures, sneaking
|
|
/// past them, the Aswid's aura leaving kin alone.
|
|
/// </summary>
|
|
[HarmonyPatch]
|
|
public static class StrikeScope
|
|
{
|
|
public static IEnumerable<System.Reflection.MethodBase> TargetMethods()
|
|
{
|
|
yield return AccessTools.Method(typeof(Attack), "DoMeleeAttack");
|
|
yield return AccessTools.Method(typeof(Attack), "DoAreaAttack");
|
|
yield return AccessTools.Method(typeof(Projectile), "DoAOE");
|
|
yield return AccessTools.Method(typeof(Projectile), "IsValidTarget");
|
|
yield return AccessTools.Method(typeof(Projectile), "OnHit");
|
|
yield return AccessTools.Method(typeof(Aoe), "ShouldHit");
|
|
}
|
|
|
|
public static void Prefix() => strikeDepth++;
|
|
|
|
// Finalizer rather than Postfix: the count has to come down even when the method
|
|
// throws, or every IsEnemy afterwards would ignore the truce.
|
|
public static void Finalizer() => strikeDepth--;
|
|
}
|
|
|
|
/// <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.
|
|
///
|
|
/// Kin this machine owns are written here; kin owned by another player's machine are told
|
|
/// through RpcName, and their owner writes the grudge and alerts them.
|
|
/// </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 (Vector3.Distance(other.transform.position, center) > radius) continue;
|
|
if (!FactionHostilityPatch.IsAlliedMob(race, other.gameObject.name)) continue;
|
|
|
|
if (Remember(other, player)) other.GetBaseAI()?.Alert();
|
|
}
|
|
}
|
|
}
|
|
}
|