feat(factions): no raids made only of allies, and allies spare the whole base

A raid whose every spawn is at peace with the player's race is struck from
the list the client sends as possibleEvents, and from the server's valid
event points when raids are world-based.

The structure veto covered only 20 m from the creature, but
FindClosestStaticPriorityTarget searches the whole view range. It now holds
while any allied player is within 100 m, and reads the per-race lists too.
This commit is contained in:
kanym 2026-09-28 21:41:29 +02:00
commit df9c768f92
5 changed files with 291 additions and 107 deletions

View file

@ -86,12 +86,25 @@ namespace RacesOfValheim
public static bool IsSameFaction(Player player, Character monster)
{
if (player == null || monster == null) return false;
string race = GetPlayerRace(player);
if (race == null) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
return IsFactionMob(GetPlayerRace(player), monster.gameObject.name);
}
string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim();
return mobs.Contains(prefabName);
// 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
@ -151,9 +164,13 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
public static class FactionStaticTargetPatch
{
// Comfortably past FindRandomStaticTarget's own 10 m search radius, so a truce holds for
// any piece the mob could have picked in the first place.
private const float FactionCheckRange = 20f;
// 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)
{
@ -167,7 +184,9 @@ namespace RacesOfValheim
foreach (Player player in Player.GetAllPlayers())
{
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;
if (!FactionHostilityPatch.IsSameFaction(player, monster)) 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;

View file

@ -0,0 +1,152 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// No raid made only of your own allies. A swamp raid on an Aswid base used to arrive anyway:
/// the skeletons and draugr ignored the player, as the truce says, and had nothing left to do but
/// wander the base for the rest of the event.
///
/// Vanilla picks raids in two ways, set by the world's raid modifier, and each needs its own door:
///
/// - Player-based raids (global key PlayerEvents). Every client works out which raids it can
/// receive in Player.UpdateEvents and sends the list to the server as
/// m_serverSyncedPlayerData["possibleEvents"]; RandEventSystem.GetValidEventPoints only places
/// a raid on a player whose list names it. Striking allied raids from that list happens on the
/// client, so it works on a dedicated server that does not run the mod.
///
/// - World-based raids (PlayerEvents off). The server ignores that list and decides from world
/// keys alone. Each client also sends the allied raids under AlliedRaidsKey, and the server
/// drops that player's position from GetValidEventPoints for those raids. This half only runs
/// where the server does: single player and a game hosted from the client always, a dedicated
/// server only with the mod installed on it.
///
/// Only a raid whose every spawn is allied is struck. A mixed raid - Eikthyr's boars and necks for
/// an Aswid who has only won the boars over - still comes, and FactionStaticTargetPatch keeps the
/// allied half of it off the buildings.
/// </summary>
public static class FactionRaids
{
public const string AlliedRaidsKey = "RacesOfValheim_AlliedRaids";
public static bool IsAlliedRaid(string race, RandomEvent ev)
{
if (race == null || ev == null || ev.m_spawn == null) return false;
bool anySpawn = false;
foreach (SpawnSystem.SpawnData spawn in ev.m_spawn)
{
if (spawn == null || spawn.m_prefab == null) continue;
if (!FactionHostilityPatch.IsAlliedMob(race, spawn.m_prefab.name)) return false;
anySpawn = true;
}
// An event that spawns nothing is not a raid on anyone; leave it to vanilla.
return anySpawn;
}
private static HashSet<string> AlliedRaidNames(Player player)
{
HashSet<string> allied = new HashSet<string>();
if (!FactionsConfig.Hostility || RandEventSystem.instance == null) return allied;
string race = FactionHostilityPatch.GetPlayerRace(player);
if (race == null) return allied;
foreach (RandomEvent ev in RandEventSystem.instance.m_events)
{
if (IsAlliedRaid(race, ev)) allied.Add(ev.m_name);
}
return allied;
}
[HarmonyPatch(typeof(Player), nameof(Player.UpdateEvents))]
public static class UpdateEventsPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || ZNet.instance == null) return;
HashSet<string> allied = AlliedRaidNames(__instance);
Dictionary<string, string> synced = ZNet.instance.m_serverSyncedPlayerData;
synced[AlliedRaidsKey] = string.Join(",", allied);
Jotunn.Logger.LogInfo($"[Factions] Raids struck as allied: [{synced[AlliedRaidsKey]}]");
if (allied.Count > 0 && synced.TryGetValue("possibleEvents", out string possible) && !string.IsNullOrEmpty(possible))
{
List<string> kept = new List<string>();
foreach (string name in possible.Split(','))
{
if (!allied.Contains(name)) kept.Add(name);
}
synced["possibleEvents"] = string.Join(",", kept);
}
}
}
/// <summary>
/// Player.UpdateEvents only runs on load, on a new player key and on a new item. The race is
/// picked after load, and the Aswid's allies grow with boss kills, which are world keys; neither
/// calls it. So the local player asks again whenever either one changes.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class RefreshPatch
{
private const float CheckInterval = 5f;
private static float nextCheck;
private static string lastRace;
private static int lastState = -1;
private static bool lastHostility = true;
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || Time.time < nextCheck) return;
nextCheck = Time.time + CheckInterval;
string race = FactionHostilityPatch.GetPlayerRace(__instance);
int state = BossProgressionManager.GetCurrentProgressionState();
bool hostility = FactionsConfig.Hostility;
if (race == lastRace && state == lastState && hostility == lastHostility) return;
lastRace = race;
lastState = state;
lastHostility = hostility;
__instance.UpdateEvents();
}
}
// Server side, for world-based raids. RandEventSystem keeps only each player's position and
// raid list, not who sent them, so the allied list is kept here next to the same position
// RetrievePlayerEventData hands vanilla, and GetValidEventPoints is filtered by it.
private static readonly List<KeyValuePair<Vector3, HashSet<string>>> alliedByPosition =
new List<KeyValuePair<Vector3, HashSet<string>>>();
[HarmonyPatch(typeof(RandEventSystem), "RefreshPlayerEventData")]
public static class RefreshPlayerEventDataPatch
{
public static void Prefix() => alliedByPosition.Clear();
}
[HarmonyPatch(typeof(RandEventSystem), "RetrievePlayerEventData")]
public static class RetrievePlayerEventDataPatch
{
public static void Postfix(Dictionary<string, string> playerData, Vector3 position, bool __result)
{
if (!__result || playerData == null) return;
if (!playerData.TryGetValue(AlliedRaidsKey, out string value) || string.IsNullOrEmpty(value)) return;
alliedByPosition.Add(new KeyValuePair<Vector3, HashSet<string>>(position, new HashSet<string>(value.Split(','))));
}
}
[HarmonyPatch(typeof(RandEventSystem), "GetValidEventPoints")]
public static class GetValidEventPointsPatch
{
public static void Postfix(RandomEvent ev, List<Vector3> __result)
{
if (!FactionsConfig.Hostility || ev == null || __result == null || alliedByPosition.Count == 0) return;
__result.RemoveAll(point => alliedByPosition.Exists(entry => entry.Key == point && entry.Value.Contains(ev.m_name)));
}
}
}
}

View file

@ -39,7 +39,8 @@ namespace RacesOfValheim
// get the truce back.
HostilityEnabled = config.Bind(factions, "Faction truce", true,
new ConfigDescription("Mobs your race is at peace with leave you alone - they will not open a fight, " +
"hunt you during events, or smash structures near you. Turn this off and every " +
"hunt you during events, or smash structures while you are nearby, and raids made only " +
"of them are not sent at you. Turn this off and every " +
"creature treats you exactly as vanilla would. Covers BOTH halves, because both " +
"answer the same BaseAI.IsEnemy and a switch over only one of them changes " +
"nothing for most races: the faction rules in FactionHostilityPatch, and the " +