fix: Alfar drones go back to work after a fight, and say what they skip

A tamed MonsterAI never drops a target for distance, so an enemy that ran
off but stayed loaded kept the drone fighting forever. The drone now drops
a target past its leash and clears vanilla's target and alert when the
fight ends.

Drones now talk over their heads and in chat (40 m): an item in the
Inngangskista with nowhere to go, an item kept there for a station, and an
idle kiln whose wood is in a plain chest instead of the Eldividarkista.
Texts in English, Italian and Russian.

F8 lists each worker drone's state and why each entry-chest item stays or
moves.
This commit is contained in:
kanym 2026-10-30 17:41:37 +01:00
commit 97e25dabe9
5 changed files with 257 additions and 6 deletions

View file

@ -58,6 +58,13 @@ namespace RacesOfValheim
public const string KeyStatus = "RoV_alfarStatus";
public const string KeyDest = "RoV_alfarDest";
// What the drone last said: a counter every client watches, the text key and the item.
// Each client builds the line in its own language, so only the token travels.
public const string KeySaySeq = "RoV_alfarSaySeq";
public const string KeySayKey = "RoV_alfarSayKey";
public const string KeySayItem = "RoV_alfarSayItem";
public const string KeySayStation = "RoV_alfarSayStation";
/// <summary>Every drone alive in the loaded zones: the repairs look at each other through it.</summary>
public static readonly List<AlfarDroneAI> All = new List<AlfarDroneAI>();
@ -141,6 +148,7 @@ namespace RacesOfValheim
private float m_nextFightScan;
private float m_fightUntil;
private bool m_fighting;
private ZNetView m_nview;
private Character m_character;
@ -168,6 +176,11 @@ namespace RacesOfValheim
private ZDOID m_sortDest;
private float m_scannedAt = -99f;
// Speech: the last line this client showed, and when to look for a new one.
private int m_heardSeq;
private float m_nextListen;
private float m_nextKilnCheck;
private Job m_job;
private float m_nextPlan;
private float m_jobDeadline;
@ -200,6 +213,16 @@ namespace RacesOfValheim
All.Add(this);
ReadPayload();
// A line said before this object loaded is old news: do not replay it on a zone reload.
if (m_nview != null && m_nview.IsValid()) m_heardSeq = m_nview.GetZDO().GetInt(KeySaySeq, 0);
}
private void Update()
{
if (Time.time < m_nextListen) return;
m_nextListen = Time.time + 0.5f;
Listen();
}
private void OnDestroy()
@ -293,7 +316,17 @@ namespace RacesOfValheim
if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false;
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
// A tamed MonsterAI with no patrol point and no follow target never drops its target for
// distance (UpdateTarget, IL): only after 30 s unsensed or 60 s without a swing. The drone
// hears far, so an enemy that ran off kept "being sensed" and held the tick for vanilla.
// Past the leash it is no longer this drone's fight.
Character target = m_ai.GetTargetCreature();
if (target != null && !target.IsDead() && !InFightReach(target))
{
m_ai.MakeTame();
target = null;
}
if (target != null && !target.IsDead())
{
m_fightUntil = Time.time + FightLinger;
@ -311,14 +344,33 @@ namespace RacesOfValheim
}
}
if (Time.time >= m_fightUntil) return false;
if (Time.time >= m_fightUntil)
{
// The fight is over: clear what vanilla still holds (target, alert), or the next
// GetTargetCreature hands the tick straight back to it. MakeTame is the public door
// that nulls both targets and the alert in one call; the drone is tamed already.
if (m_fighting) { m_fighting = false; m_ai.MakeTame(); }
return false;
}
m_fighting = true;
m_job = null;
m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
SetStatus("Fighting.");
return true;
}
/// <summary>Close to the drone, and not past the edge of the base it works.</summary>
private bool InFightReach(Character enemy)
{
Vector3 at = enemy.transform.position;
if (Vector3.Distance(at, transform.position) > FightRange * 2f) return false;
Vector3? anchor = Anchor;
float leash = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus + FightRange;
return anchor == null || Vector3.Distance(at, anchor.Value) <= leash;
}
// ================================================================ the tick
/// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary>
@ -393,6 +445,7 @@ namespace RacesOfValheim
Scan(anchor.Value);
ExpirePenalties();
CheckIdleKiln();
// A harvest is in progress: wait for the drops to land, then gather them and replant.
if (m_farmSpot != null)
@ -1422,16 +1475,25 @@ namespace RacesOfValheim
if (inventory == null) return null;
string sigil = AlfarSigil.PrefabName;
bool spoke = false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (name == sigil) continue;
if (!IsWood(name) && AnyStationAccepts(name)) continue;
if (!IsWood(name) && AnyStationAccepts(name))
{
if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_keep", name, KeepRepeatSeconds);
continue;
}
Container destination = DestinationFor(name);
if (destination == null) continue;
if (destination == null)
{
if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_nowhere", name, NowhereRepeatSeconds);
continue;
}
m_sortItem = name;
m_sortDest = ZdoOf(destination);
@ -1447,6 +1509,119 @@ namespace RacesOfValheim
return null;
}
// ================================================================ speech
/// <summary>When each item may be mentioned again, shared by every drone on this client, so
/// five drones looking at the same stone say it once and not five times.</summary>
private static readonly Dictionary<string, float> s_nextMention = new Dictionary<string, float>();
private const float NowhereRepeatSeconds = 300f;
private const float KeepRepeatSeconds = 1800f;
private const float SpeechRange = 40f;
/// <summary>Owner side: says the line once per cooldown per item, by writing it into the ZDO
/// where every client in range picks it up. Returns whether it spoke, so one plan says one
/// line and the bubbles do not overwrite each other.</summary>
private bool Say(string key, string item, float repeatSeconds, string station = "")
{
string mention = key + "|" + item;
float next;
if (s_nextMention.TryGetValue(mention, out next) && Time.time < next) return false;
s_nextMention[mention] = Time.time + repeatSeconds;
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeySayKey, key);
zdo.Set(KeySayItem, item);
zdo.Set(KeySayStation, station);
zdo.Set(KeySaySeq, zdo.GetInt(KeySaySeq, 0) + 1);
return true;
}
/// <summary>Every client: a new line in the ZDO goes over the drone's head, the way vanilla's
/// NPCs talk, and into the chat window, for players close enough to care.</summary>
private void Listen()
{
if (m_nview == null || !m_nview.IsValid()) return;
ZDO zdo = m_nview.GetZDO();
int seq = zdo.GetInt(KeySaySeq, 0);
if (seq == m_heardSeq) return;
m_heardSeq = seq;
Player player = Player.m_localPlayer;
if (player == null || Chat.instance == null) return;
if (Vector3.Distance(player.transform.position, transform.position) > SpeechRange) return;
string item = zdo.GetString(KeySayItem, "");
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(item) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
string itemName = drop != null ? drop.m_itemData.m_shared.m_name : item;
string text = ModText.Get(zdo.GetString(KeySayKey, ""), itemName,
"$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_eldividarkista_name",
zdo.GetString(KeySayStation, ""));
string speaker = m_character != null ? Localization.instance.Localize(m_character.m_name) : "";
Chat.instance.SetNpcText(gameObject, Vector3.up * 1.5f, SpeechRange, 8f, speaker, text, false);
Chat.instance.AddString(speaker, text, Talker.Type.Normal);
}
/// <summary>
/// The mistake players make with the kiln: the wood is in a plain chest (vanilla even calls
/// one "Wood chest"), and only the Eldividarkista's wood is ever burnt. A station that takes
/// wood, standing idle with nothing for it in the Eldividarkista while the right wood sits in
/// another chest, gets a line explaining that. Every 30 s is plenty for something the player
/// fixes by hand.
/// </summary>
private void CheckIdleKiln()
{
if (Time.time < m_nextKilnCheck) return;
m_nextKilnCheck = Time.time + 30f;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || !station.Operable || station.HasWork || station.FreeSlots <= 0) continue;
if (m_wood != null && FirstAccepted(station, m_wood) != null) continue;
string misplaced = WoodElsewhereFor(station);
if (misplaced == null) continue;
// The station's own name token, so every language says "kiln" the game's way.
Piece piece = station.Behaviour.GetComponent<Piece>();
string stationName = piece != null ? piece.m_name : "";
if (Say("rov_msg_alfar_drone_kiln_wood", misplaced, NowhereRepeatSeconds, stationName)) return;
}
}
/// <summary>Wood the station would take, lying in the entry chest or a storage chest.</summary>
private string WoodElsewhereFor(ButlerStation station)
{
if (m_entry != null)
{
string found = WoodIn(m_entry, station);
if (found != null) return found;
}
foreach (Container chest in m_chests)
{
string found = WoodIn(chest, station);
if (found != null) return found;
}
return null;
}
private static string WoodIn(Container chest, ButlerStation station)
{
Inventory inventory = chest != null ? chest.GetInventory() : null;
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (IsWood(name) && station.Accepts(name)) return name;
}
return null;
}
private bool DoSortFetch()
{
if (m_sortItem == null || m_sortDest == ZDOID.None) return false;
@ -1467,6 +1642,72 @@ namespace RacesOfValheim
// ================================================================ moving
/// <summary>Vanilla pathing, through the private MoveTo. True the moment it has arrived.</summary>
/// <summary>F8 readout: what each worker within 60 m is doing and what vanilla still holds, and
/// for the nearest one, why each thing in the entry chest is (or is not) being sorted.</summary>
public static void DebugReport(Player player)
{
var lines = new List<string>();
AlfarDroneAI nearest = null;
float nearestDistance = 60f;
foreach (AlfarDroneAI drone in All)
{
if (drone == null || drone.m_ai == null) continue;
float distance = Vector3.Distance(drone.transform.position, player.transform.position);
if (distance > 60f) continue;
if (distance < nearestDistance) { nearestDistance = distance; nearest = drone; }
Character target = drone.m_ai.GetTargetCreature();
string targetText = target != null
? $"{Utils.GetPrefabName(target.gameObject)} {Vector3.Distance(target.transform.position, drone.transform.position):0}m"
: "none";
lines.Add($"[RoV drone] {distance:0}m: '{drone.Status}' job {(drone.m_job != null ? drone.m_job.Kind : "none")} " +
$"carry {drone.PayloadCount()} fight {drone.m_fighting} vanilla target {targetText} " +
$"alerted {drone.m_ai.IsAlerted()} flying {drone.m_character.IsFlying()} owner {drone.m_nview.IsOwner()}");
}
if (nearest == null) lines.Add("[RoV drone] no worker drone within 60m");
else lines.AddRange(nearest.SortReport());
foreach (string line in lines)
{
Debug.Log(line);
player.Message(MessageHud.MessageType.TopLeft, line);
}
}
private IEnumerable<string> SortReport()
{
if (m_entry == null) { yield return "[RoV sort] no entry chest in range"; yield break; }
if (m_entry.IsInUse()) yield return "[RoV sort] entry chest is open";
if (IsPenalised(ZdoOf(m_entry))) yield return "[RoV sort] entry chest is set aside (penalty)";
Inventory inventory = m_entry.GetInventory();
if (inventory == null) yield break;
var seen = new HashSet<string>();
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null) continue;
if (item.m_dropPrefab == null) { yield return $"[RoV sort] {item.m_shared.m_name}: no drop prefab"; continue; }
string name = item.m_dropPrefab.name;
if (!seen.Add(name)) continue;
string verdict;
if (name == AlfarSigil.PrefabName) verdict = "sigil, stays";
else if (!IsWood(name) && AnyStationAccepts(name)) verdict = "a station takes it, stays as work";
else
{
Container destination = DestinationFor(name);
verdict = destination != null
? $"goes to chest at {Vector3.Distance(destination.transform.position, m_entry.transform.position):0}m"
: $"nowhere: no storage chest holds it and none is empty ({m_chests.Count} chests)";
}
yield return $"[RoV sort] {name}: {verdict}";
}
}
private bool MoveToPoint(float dt, Vector3 point, float distance, bool run)
{
if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place

View file

@ -125,6 +125,7 @@ namespace RacesOfValheim
RaceMeleeReach.DebugOn = !RaceMeleeReach.DebugOn;
__instance.Message(MessageHud.MessageType.TopLeft, $"[RoV reach] debug {(RaceMeleeReach.DebugOn ? "on" : "off")}");
AlfarMiner.DebugReport(__instance);
AlfarDroneAI.DebugReport(__instance);
}
}
}

View file

@ -238,5 +238,8 @@
"rov_msg_build_limit_alfar_chest": "This core already has one of these within reach.",
"rov_msg_build_limit_alfar_ljosgard": "This core already has its Ljosgard."
,
"rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now."
"rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now.",
"rov_msg_alfar_drone_sort_nowhere": "I have nowhere to put $1. Give me an empty chest, or one that already holds $1.",
"rov_msg_alfar_drone_sort_keep": "I leave $1 in the $2: a station here works with it.",
"rov_msg_alfar_drone_kiln_wood": "The $4 is idle. I only burn wood from the $3, and the $1 is in another chest."
}

View file

@ -238,5 +238,8 @@
"rov_msg_build_limit_alfar_chest": "Questo nucleo ne ha gia' una nel suo raggio.",
"rov_msg_build_limit_alfar_ljosgard": "Questo nucleo ha gia' il suo Ljosgard."
,
"rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso."
"rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso.",
"rov_msg_alfar_drone_sort_nowhere": "Non so dove mettere $1. Dammi una cassa vuota, o una che contenga già $1.",
"rov_msg_alfar_drone_sort_keep": "Lascio $1 nella $2: una stazione qui lo usa.",
"rov_msg_alfar_drone_kiln_wood": "$4 è fermo. Brucio solo la legna della $3, e $1 è in un'altra cassa."
}

View file

@ -238,5 +238,8 @@
"rov_msg_build_limit_alfar_chest": "У этого ядра уже есть такой сундук в радиусе.",
"rov_msg_build_limit_alfar_ljosgard": "У этого ядра уже есть свой Льосгард."
,
"rov_msg_alfar_nexus_no_store": "У ядра сейчас нечего предложить."
"rov_msg_alfar_nexus_no_store": "У ядра сейчас нечего предложить.",
"rov_msg_alfar_drone_sort_nowhere": "Мне некуда положить $1. Дай мне пустой сундук или тот, где уже лежит $1.",
"rov_msg_alfar_drone_sort_keep": "Оставляю $1 в «$2»: с этим работает станция здесь.",
"rov_msg_alfar_drone_kiln_wood": "«$4» простаивает. Я жгу только дрова из «$3», а $1 лежит в другом сундуке."
}