diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealBeforeStamina.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealBeforeStamina.cs
new file mode 100644
index 0000000..99affff
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealBeforeStamina.cs
@@ -0,0 +1,113 @@
+// ============================================================================
+// RynthSuite - Combat/BuffManager.HealBeforeStamina.cs
+// Health falling: a heal before the next stamina kit or Revitalize.
+//
+// A stamina kit takes about 2.4 s to land and nothing else happens for the vitals meanwhile (KitPending);
+// Revitalize out of Magic is a wand swap and a cast. The vitals only asked "is health under a heal
+// line now?" before each one, so a Re-stam To run took kit after kit with a monster hitting: Drakkon
+// (DreamWeave, 2026-11-11 16:24:54 - 16:25:04: Heal At 1, Emergency Heal At 30, Re-stam To 90) went
+// from 100% to dead over three stamina kits in a row, each started while health was still over 30%
+// (the owner, 2026-11-17: "it will ignore healing and use the stamina kit ... a second time").
+//
+// Now health is sampled every vitals check (the last HealthTrendWindowMs). Before a stamina use,
+// health is projected over the use (StaminaUseBlindMs) at the rate it has been falling since its
+// latest high; at or under the highest heal line (Heal At, Emergency Heal At, Stamina To Health At)
+// the heal chain goes first. Health steady, or nothing that can heal: the stamina use goes as before.
+// ============================================================================
+
+using System;
+using System.Collections.Generic;
+
+namespace RynthCore.Plugin.RynthAi;
+
+public partial class BuffManager
+{
+ /// How far back the health samples go.
+ internal const int HealthTrendWindowMs = 4000;
+ /// A stamina use with nothing else for the vitals: a kit's 2.4 s and the pass after it.
+ internal const int StaminaUseBlindMs = 3000;
+ /// The fall's rate is never taken over less than this (one hit just now is no rate).
+ internal const int HealthTrendMinSpanMs = 1000;
+ /// Nothing could heal first: the stamina uses go for this long without asking again.
+ private const int HealFirstUnavailableMs = 3000;
+
+ private readonly List<(DateTime At, int Pct)> _healthSamples = new();
+ private DateTime _healFirstUnavailableUntil = DateTime.MinValue;
+ private DateTime _healFirstLoggedAt = DateTime.MinValue;
+
+ /// One health reading per vitals check (CheckVitalsCore, before anything can return).
+ private void RecordHealthSample(int pct, DateTime now)
+ {
+ if (_vitals.MaxHealth == 0 || _vitals.CurrentHealth == 0)
+ {
+ _healthSamples.Clear(); // no reading, or dead: a fall from before the death is no trend
+ return;
+ }
+ _healthSamples.Add((now, pct));
+ int old = 0;
+ while (old < _healthSamples.Count && (now - _healthSamples[old].At).TotalMilliseconds > HealthTrendWindowMs) old++;
+ if (old > 0) _healthSamples.RemoveRange(0, old);
+ if (_healthSamples.Count > 512) _healthSamples.RemoveRange(0, _healthSamples.Count - 512);
+ }
+
+ ///
+ /// Health in at the rate it has fallen since its latest high in
+ /// (that rate over at least ). Not
+ /// falling: . Pure (host tests).
+ ///
+ internal static int ProjectedHealthPct(IReadOnlyList<(DateTime At, int Pct)> samples, DateTime now, int cur, int horizonMs)
+ {
+ int peak = cur;
+ DateTime peakAt = now;
+ foreach (var s in samples)
+ {
+ if ((now - s.At).TotalMilliseconds > HealthTrendWindowMs || s.At > now) continue;
+ // The latest time health stood at its highest: the fall from there is the one under way.
+ if (s.Pct > peak || (s.Pct == peak && s.Pct > cur && s.At > peakAt)) { peak = s.Pct; peakAt = s.At; }
+ }
+ int drop = peak - cur;
+ if (drop <= 0) return cur;
+ double spanMs = Math.Max(HealthTrendMinSpanMs, (now - peakAt).TotalMilliseconds);
+ return (int)Math.Floor(cur - drop * horizonMs / spanMs);
+ }
+
+ /// The highest heal line set: Heal At (in a fight), Emergency Heal At, Stamina To Health At.
+ private int HealLineBeforeStamina(bool inCombat)
+ => Math.Max(inCombat ? _settings.HealAt : 0, Math.Max(_settings.EmergencyHealAt, _settings.StaminaToHealthAt));
+
+ ///
+ /// Called right before a stamina use (a kit, Revitalize, a potion). Health falling to a heal line
+ /// within the use: the heal chain goes now instead. True = it healed (or a heal is under way).
+ ///
+ private bool HealBeforeStaminaUse(int curHealthPct, bool inCombat)
+ {
+ DateTime now = Clock();
+ if (now < _healFirstUnavailableUntil) return false;
+ int line = HealLineBeforeStamina(inCombat);
+ if (line <= 0 || curHealthPct >= 100) return false;
+ int projected = ProjectedHealthPct(_healthSamples, now, curHealthPct, StaminaUseBlindMs);
+ if (projected > line) return false;
+
+ bool healed = AttemptHealChain(itemsBeforeSpell: CurrentCombatMode != CombatMode.Magic, allowSpell: true,
+ out string kitWhy, out string spellWhy, out string potionWhy);
+ bool log = (now - _healFirstLoggedAt).TotalSeconds >= 10;
+ if (healed)
+ {
+ if (log)
+ {
+ _healFirstLoggedAt = now;
+ _host.Log($"[RynthAi] Vitals: health {curHealthPct}% is falling (about {Math.Max(0, projected)}% after a stamina kit's {StaminaUseBlindMs / 1000} s, " +
+ $"at or under the heal line {line}%): a heal first, the stamina after it.");
+ }
+ return true;
+ }
+ _healFirstUnavailableUntil = now.AddMilliseconds(HealFirstUnavailableMs);
+ if (log)
+ {
+ _healFirstLoggedAt = now;
+ _host.Log($"[RynthAi] Vitals: health {curHealthPct}% is falling to about {Math.Max(0, projected)}% within a stamina use, but nothing could heal first " +
+ $"(kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}): the stamina goes.");
+ }
+ return false;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
index 1598f8f..665273c 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
@@ -84,6 +84,12 @@ public partial class BuffManager
// Health and he died (2026-11-07).
allowed = $"health {_vitals.HealthPct}% at or under Emergency Heal At {_settings.EmergencyHealAt}%";
}
+ else if (what == "Stamina to Health Self" && StaminaToHealthAllowed(_settings, _vitals.HealthPct, _vitals.StaminaPct))
+ {
+ // Its own line asks for the spell (2026-11-13): Stamina To Health At set over Emergency Heal At
+ // means "this is my emergency heal", kit or no kit.
+ allowed = $"health {_vitals.HealthPct}% at or under Stamina To Health At {_settings.StaminaToHealthAt}%";
+ }
else
{
bool stamina = label == LabelStamina;
@@ -187,7 +193,17 @@ public partial class BuffManager
}
/// A stamina kit AttemptStaminaKitUse could pick.
- private bool HasUsableStaminaKit() => _host.HasUseObjectOn && HasPackKit("Stamina Kit");
+ // Only one Stamina Kit Min Success % lets through (2026-11-13): a kit under it is never used, so it
+ // must not refuse Revitalize's swap either (that left a melee character with no stamina source, and
+ // the old last resort then used the kit anyway).
+ private bool HasUsableStaminaKit()
+ {
+ if (!_host.HasUseObjectOn || !HasPackKit("Stamina Kit")) return false;
+ if (BestPackStaminaKit() is not WorldObject kit) return true;
+ uint missing = _vitals.MaxStamina > _vitals.CurrentStamina ? _vitals.MaxStamina - _vitals.CurrentStamina : 0;
+ return KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch,
+ _settings.StaminaKitMinSuccessPct, log: false);
+ }
/// A kit named "... " in the pack the gate still counts (BestPack*Kit's match).
private bool HasPackKit(string suffix)
@@ -222,19 +238,13 @@ public partial class BuffManager
///
private bool AttemptStaminaRestore(bool listedPotionFirst = false, bool allowCast = true)
{
- if (AttemptStaminaKit(false, out bool underMinSuccess)
+ // No last resort under Stamina Kit Min Success % (2026-11-13, Tom: it has to respect the %): a kit
+ // under it is never used; 0 = always use the kit. Instead the wand comes out and Revitalize goes,
+ // the between-fights top-off too (allowCast false only spares a swap a good kit makes needless).
+ return AttemptStaminaKit(false, out bool underMinSuccess)
|| (listedPotionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
- || (allowCast && AttemptVitalCast("Revitalize Self"))
- || AttemptPotion("StaminaPotion", "Stamina"))
- return true;
- // Last resort, as the heal chain's: the stamina kit Stamina Kit Min Success % skipped. With
- // Revitalize refused by the wand gate (or not cast) and no potion, nothing else restores stamina.
- if (underMinSuccess && AttemptStaminaKit(true, out _))
- {
- _host.Log("[RynthAi] Vitals: no spell or potion could restore stamina; using the stamina kit despite Stamina Kit Min Success %.");
- return true;
- }
- return false;
+ || ((allowCast || underMinSuccess) && AttemptVitalCast("Revitalize Self"))
+ || AttemptPotion("StaminaPotion", "Stamina");
}
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
index 0ef396e..c906f88 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
@@ -2122,6 +2122,9 @@ public partial class BuffManager : IDisposable
_isRechargingMana = false;
_isRechargingStamina = false;
+ // Every check, kits in flight too: how fast health is falling (BuffManager.HealBeforeStamina.cs).
+ RecordHealthSample(curHealthPct, Clock());
+
// A kit's heal hasn't landed yet: nothing else for vitals until it has (see KitPending).
if (KitPending())
{
@@ -2206,6 +2209,13 @@ public partial class BuffManager : IDisposable
bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _);
if (manaLow)
{
+ // Stamina too low for Stamina to Mana: the refill starts with a stamina use, so a falling
+ // health heals first (BuffManager.HealBeforeStamina.cs).
+ if (curStamPct <= StaminaToManaFloorPct() && TopStaminaToManaId() != 0 && HealBeforeStaminaUse(curHealthPct, inCombat))
+ {
+ _isHealingSelf = true;
+ return true;
+ }
_vitalWhy = "";
if (AttemptManaRefill(curStamPct, out bool refilledStamina))
{
@@ -2244,6 +2254,13 @@ public partial class BuffManager : IDisposable
// regenerates otherwise. Under Re-stam At, or in a Re-stam To run, the cast goes as before.
bool castNeedsSwap = !inCombat && !_restamRun && curStamPct >= _settings.RestamAt
&& CurrentCombatMode != CombatMode.Magic && !FightsWithMagic();
+ // Health falling to a heal line within the stamina use (a kit's 2.4 s, Revitalize's swap and
+ // cast): the heal first. A Re-stam To run took kit after kit while a monster hit (BuffManager.HealBeforeStamina.cs).
+ if (curStamPct < stamThreshold && HealBeforeStaminaUse(curHealthPct, inCombat))
+ {
+ _isHealingSelf = true;
+ return true;
+ }
int sentBefore = _vitalActionsSent;
if (curStamPct < stamThreshold && AttemptStaminaChain(allowCast: !castNeedsSwap))
{
@@ -2392,6 +2409,15 @@ public partial class BuffManager : IDisposable
bool stamToHealth = StaminaToHealthAllowed(_settings, curHealthPct, curStamPct);
if (!emergencyKit && !stamToHealth) return false;
+ // 0. Under Stamina To Health At but still over Emergency Heal At (2026-11-13): Stamina to
+ // Health Self is the heal, with no kit ahead of it. A melee character with Stamina To
+ // Health At set above Emergency Heal At wants the spell there; the kit-first step below
+ // used to take every such heal while a kit was carried, so the spell's own line never
+ // did anything out of Magic mode. Not castable (no stamina, Life Magic, parked): the
+ // normal chain runs. Under Emergency Heal At the order below is unchanged.
+ if (stamToHealth && !emergencyKit)
+ return AttemptVitalCast("Stamina to Health Self");
+
// 1. Out of Magic mode a kit first (no wand swap at critical health), then a health
// potion: Heal Self from melee is a wand swap, the Magic stance and the cast, 4-5 s
// with nothing healing. Drakkon, 2026-10-14: 69% to 15% in 0.2 s among Depraved
@@ -3004,12 +3030,15 @@ public partial class BuffManager : IDisposable
/// points is at least that. Below it the caller falls through
/// to the spell, as VTank does.
///
- private bool KitChanceOk(int kitId, string kitName, uint missing, bool willBePeace, int minPct)
+ private bool KitChanceOk(int kitId, string kitName, uint missing, bool willBePeace, int minPct, bool log = true)
{
// A weapon out: the spell is a wand swap, the Magic stance and the cast first (4 s and more
- // from melee), so a kit gets a lower bar. Drakkon, 2026-10-14 13:50: a 51% kit was skipped
- // for Heal Self from melee and he died before the cast went out.
- if (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile)
+ // from melee), so a healing kit gets a lower bar. Drakkon, 2026-10-14 13:50: a 51% kit was
+ // skipped for Heal Self from melee and he died before the cast went out. Not stamina kits
+ // (2026-11-13): low stamina doesn't kill, and the bar hid Stamina Kit Min Success % (50 read
+ // as 30, a 16% Greater Stamina Kit every 3 s).
+ bool staminaKit = kitName.EndsWith("Stamina Kit", StringComparison.OrdinalIgnoreCase);
+ if (!staminaKit && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
minPct = Math.Min(minPct, WeaponOutKitMinPct);
if (minPct <= 0 || _charSkills == null) return true;
@@ -3028,10 +3057,10 @@ public partial class BuffManager : IDisposable
double chance = 1.0 - 1.0 / (1.0 + Math.Exp(0.03 * (skill - difficulty)));
int pct = (int)Math.Floor(Math.Clamp(chance, 0, 1) * 100);
bool ok = pct >= minPct;
- if (!ok && (RynthClock.Now - _lastKitChanceLog).TotalSeconds >= 10)
+ if (!ok && log && (RynthClock.Now - _lastKitChanceLog).TotalSeconds >= 10)
{
_lastKitChanceLog = RynthClock.Now;
- _host.Log($"[RynthAi] Vitals: {kitName} would work {pct}% of the time on {missing} missing (skill {skill} vs {difficulty}), under {minPct}%: using the spell.");
+ _host.Log($"[RynthAi] Vitals: {kitName} would work {pct}% of the time on {missing} missing (skill {skill} vs {difficulty}), under {minPct}%: not used{(staminaKit ? " (Revitalize or a potion instead, if any)" : "; the spell instead")}.");
}
return ok;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatLatencyTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatLatencyTracker.cs
index 9b5b38a..7043653 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatLatencyTracker.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatLatencyTracker.cs
@@ -15,6 +15,11 @@ namespace RynthCore.Plugin.RynthAi;
///
/// [CombatLatency] lock->attack 180 ms (stance 0, face 60, busy 0, cast 120, interval 0, other 0) Magic 'Olthoi Nymph', kill->attack 210 ms
///
+/// Time combat didn't tick at all because the arbiter gave the tick to something else (a heal in
+/// the Buffing slot) is 's, and the line names it: ", held 3281 ms by Buffing".
+/// It was charged to "other" when combat next ticked (2026-11-15, R-20261115-165857-1de7: "other
+/// 3281" was a healing kit the arbiter ran ahead of the attack, readable only from the lines around).
+///
/// Pure: the caller passes the clock. Pump thread only.
///
internal sealed class CombatLatencyTracker
@@ -46,6 +51,8 @@ internal sealed class CombatLatencyTracker
private double _killAtMs = double.NaN;
private double _lastLineAtMs = double.NegativeInfinity;
private int _suppressed;
+ private double _heldMs; // OnHeld: combat didn't tick, the arbiter ran something else
+ private string _heldBy = "";
/// True between a lock and its first attack.
public bool Pending => !double.IsNaN(_lockAtMs);
@@ -59,6 +66,8 @@ internal sealed class CombatLatencyTracker
_lastTickMs = nowMs;
_killAtMs = killAtMs;
Array.Clear(_waits);
+ _heldMs = 0;
+ _heldBy = "";
}
/// The lock was dropped before any attack went out.
@@ -79,6 +88,19 @@ internal sealed class CombatLatencyTracker
_lastTickMs = nowMs;
}
+ /// A tick combat didn't run (the arbiter gave it to , its BotAction):
+ /// the time since the previous tick is charged to the hold, not to the next combat tick's wait.
+ public void OnHeld(int targetId, double nowMs, string? holder)
+ {
+ if (!Pending) return;
+ if (targetId != _targetId) { OnDrop(); return; }
+ double dt = nowMs - _lastTickMs;
+ if (dt > 0) _heldMs += dt;
+ _lastTickMs = nowMs;
+ if (!string.IsNullOrEmpty(holder) && !_heldBy.Contains(holder, StringComparison.Ordinal))
+ _heldBy = _heldBy.Length == 0 ? holder : _heldBy + "/" + holder;
+ }
+
/// The first attack or cast went out. Returns the log line, or null when nothing was
/// pending for this target or the line is throttled.
public string? OnAttack(int targetId, double nowMs, string mode, string? targetName)
@@ -107,14 +129,18 @@ internal sealed class CombatLatencyTracker
.Append(", busy ").Append(Ms(_waits[(int)Wait.Busy]))
.Append(", cast ").Append(Ms(_waits[(int)Wait.Cast]))
.Append(", interval ").Append(Ms(_waits[(int)Wait.Interval]))
- .Append(", other ").Append(Ms(_waits[(int)Wait.Other]))
- .Append(") ").Append(mode);
+ .Append(", other ").Append(Ms(_waits[(int)Wait.Other]));
+ if (_heldMs >= 1) sb.Append(", held ").Append(Ms(_heldMs)).Append(" ms by ").Append(_heldBy.Length > 0 ? _heldBy : "another activity");
+ sb.Append(") ").Append(mode);
if (!string.IsNullOrEmpty(targetName)) sb.Append(" '").Append(targetName).Append('\'');
if (!double.IsNaN(killToAttack)) sb.Append(", kill->attack ").Append(Ms(killToAttack)).Append(" ms");
if (_suppressed > 0) { sb.Append(" (+").Append(_suppressed).Append(" engagements not logged)"); _suppressed = 0; }
return sb.ToString();
}
+ /// The time combat was held by another activity so far (tests and diagnostics).
+ public double Held => _heldMs;
+
/// The time charged to one wait so far (tests and diagnostics).
public double Waited(Wait wait) => _waits[(int)wait];
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
index 4ebe3f2..8b023ff 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
@@ -872,6 +872,16 @@ public partial class CombatManager : IDisposable
/// True only when actively attacking a specific target. Unlike HasTargets, this is false between kills even when more monsters are scanned nearby.
public bool IsActivelyEngaged => activeTargetId != 0;
+ ///
+ /// How long ago the current target was locked while its first attack or cast hasn't gone out
+ /// ([CombatLatency]'s pending engagement); -1 when there is none. The looter's starved turn holds
+ /// a corpse open for it (CorpseOpenController, StarvedOpenYieldsMs; 2026-11-15).
+ ///
+ public double FirstAttackPendingMs =>
+ _latency.Pending && activeTargetId != 0 && _targetLockedAt != DateTime.MinValue
+ ? Math.Max(0, (RynthClock.Now - _targetLockedAt).TotalMilliseconds)
+ : -1;
+
/// Yards inside which a scanned mob counts as "on top of me".
private const double CloseAttackYards = 5.0;
@@ -1243,7 +1253,8 @@ public partial class CombatManager : IDisposable
// here. A test character locked golems 6 m up in a building and swung under them until they
// came down. Not counted as a monster nearby out of sight, so navigation (the hunt's walk up
// the stairs) isn't held for it.
- if (hasMobPos && OutOfMeleeReachUpOrDown(dist, tz - meZ) && MeleeIsTheAttackOn(wo, attackType))
+ if (hasMobPos && (OutOfMeleeReachUpOrDown(dist, tz - meZ) || OtherFloorInside(meCell, (uint)wo.Id, tz - meZ))
+ && MeleeIsTheAttackOn(wo, attackType))
{
if (notePassed) NotePassedOver(wo.Id, dist, PassedOverOtherLevel);
continue;
@@ -1445,12 +1456,47 @@ public partial class CombatManager : IDisposable
private void ObserveOffensiveAnswer()
{
if (_pendingOffensiveErr >= 0 || !_host.HasUseDoneSeq) return;
+ uint answer;
try
{
- if (_host.TryGetLastUseDone(out int seq, out uint err) && seq == _pendingOffensiveSeqAtSend + 1)
- _pendingOffensiveErr = err;
+ if (!_host.TryGetLastUseDone(out int seq, out uint err) || seq != _pendingOffensiveSeqAtSend + 1) return;
+ _pendingOffensiveErr = answer = err;
}
- catch { }
+ catch { return; }
+ NoteOffensiveAnswer(_pendingOffensiveTargetId, answer);
+ }
+
+ // ── The server doesn't have the target (2026-11-15, R-20261115-172110-9e6a) ─────────────────
+ // A Carenzi Stalker 29.8 m off and 3.6 m up: every Blade Arc at it came back UseDone 0x42C
+ // (TargetNotAcquired: ACE's Player_Magic finds no such object on the landblock) about 70 ms
+ // after the send, and combat cast again at once, 13 casts in 0.85 s (the hourglass "going nuts"),
+ // then, after a 15 s 'too busy' latch, the same again. The target was never dropped: the ghost
+ // check only judges swings and no-damage casts, and a refused cast is neither. The server's own
+ // answer says it plainly, so NotAcquiredGhostAfter of them in a row at one target mark it a ghost.
+
+ /// ACE's TargetNotAcquired, as a UseDone error: the server has no such target.
+ internal const uint TargetNotAcquiredErr = 0x42C;
+ /// Casts at one target answered TargetNotAcquired in a row that make it a ghost.
+ internal const int NotAcquiredGhostAfter = 2;
+ private int _notAcquiredTarget, _notAcquiredCount;
+
+ /// The server answered the offensive cast at with .
+ private void NoteOffensiveAnswer(int target, uint err)
+ {
+ if (target == 0) return;
+ if (err != TargetNotAcquiredErr)
+ {
+ // A 'too busy' says nothing about the target; any other answer means the server has it.
+ if (target == _notAcquiredTarget && err != ActionPacer.TooBusyErr) { _notAcquiredTarget = 0; _notAcquiredCount = 0; }
+ return;
+ }
+ if (target != _notAcquiredTarget) { _notAcquiredTarget = target; _notAcquiredCount = 0; }
+ if (++_notAcquiredCount < NotAcquiredGhostAfter) return;
+ _notAcquiredTarget = 0;
+ _notAcquiredCount = 0;
+ MarkGhost(target, _worldFilter[target]?.Name, ServerSilentMs(target, RynthClock.Now),
+ $"the server answered {NotAcquiredGhostAfter} casts at it in a row 'target not acquired' (UseDone 0x{TargetNotAcquiredErr:X})",
+ serverSaid: true);
}
private const double OFFENSIVE_NOCHAT_TIMEOUT_MS = 5000.0;
// ACE doesn't emit "You cast X" chat for offensive war magic, so we infer
@@ -2546,6 +2592,18 @@ public partial class CombatManager : IDisposable
_blacklistManager.ReportFailure(tid);
if (_blacklistManager.IsBlacklisted(tid))
{
+ // A melee target on the other side of a building's wall: the scan's skip for that needs a
+ // raycast to call it blocked, and it may not (2026-11-15, a Thread: the character in a
+ // building, a mage 2.5 m off outside it, losBlk=0). Three swings for nothing, 30 s off,
+ // locked again, round and round, and an open chest waited on that fight. Off for
+ // AcrossWallBlacklistSec instead: the hunt walks round through a door meanwhile.
+ if (CurrentCombatMode != CombatMode.Magic && _playerId != 0
+ && _host.TryGetObjectPosition(_playerId, out uint meCellNow, out _, out _, out _)
+ && AcrossBuildingWall(meCellNow, (uint)tid))
+ {
+ _blacklistManager.BlacklistFor(tid, AcrossWallBlacklistSec);
+ _host.Log($"[Blacklist] 0x{(uint)tid:X8} is across a building's wall (one inside, one out): off {AcrossWallBlacklistSec} s");
+ }
string what = CurrentCombatMode == CombatMode.Magic ? "casts" : "attacks";
_host.WriteToChat($"[RynthAi] {_consecutiveCastMisses} {what} with no damage — blacklisting 0x{(uint)tid:X8}", 2);
_consecutiveCastMisses = 0;
@@ -4411,7 +4469,7 @@ public partial class CombatManager : IDisposable
/// when the engine can (v83). Its no-damage blacklist entry, if any, is dropped (the ghost
/// mark outlives it).
///
- internal void MarkGhost(int id, string? name, double silentMs, string why)
+ internal void MarkGhost(int id, string? name, double silentMs, string why, bool serverSaid = false)
{
if (id == 0) return;
uint pid = _playerId != 0 ? _playerId : _host.GetPlayerId();
@@ -4420,7 +4478,8 @@ public partial class CombatManager : IDisposable
Ghosts.Mark(id, name ?? "", spot, lb, RynthClock.Now);
_blacklistManager.ClearFailure(id);
string silent = silentMs < 0 ? "nothing from the server about it since it was first seen" : $"nothing from the server about it for {silentMs / 1000:0}s";
- _host.Log($"[Ghost] 0x{id:X8} '{name}' is a ghost: {why}, {silent}, it hasn't moved [{DescribeTargetPos(id)}]. " +
+ // serverSaid: the server's own answer is the evidence (TargetNotAcquired), not stillness.
+ _host.Log($"[Ghost] 0x{id:X8} '{name}' is a ghost: {why}, {silent}{(serverSaid ? "" : ", it hasn't moved")} [{DescribeTargetPos(id)}]. " +
$"Skipped until the server sends anything about it or the landblock changes (ghosts now: {Ghosts.Count}).");
if (id == activeTargetId || id == _lockedTargetId)
DropTarget("ghost (the server doesn't have it)");
@@ -4784,7 +4843,14 @@ public partial class CombatManager : IDisposable
|| _settings.BotAction == "Combat"
|| _settings.BotAction == "Navigating"
|| (_settings.BotAction == "Looting" && !_settings.BoostLootPriority);
- if (!canRun) return;
+ if (!canRun)
+ {
+ // [CombatLatency]: a locked target waiting on another activity's tick (2026-11-15,
+ // R-20261115-165857-1de7: a heal's 3.3 s read as "other").
+ if (_latency.Pending && activeTargetId != 0)
+ _latency.OnHeld(activeTargetId, Environment.TickCount64, _settings.BotAction);
+ return;
+ }
if (_settings.EnableCombat)
{
@@ -7067,10 +7133,31 @@ public partial class CombatManager : IDisposable
return aIn != bIn;
}
+ /// How long a melee target that took no damage across a building's wall stays off (see JudgePendingCast).
+ internal const int AcrossWallBlacklistSec = 300;
+
private bool AcrossBuildingWall(uint meCell, uint targetId)
=> meCell != 0 && _host.TryGetObjectPosition(targetId, out uint tc, out _, out _, out _) && tc != 0
&& InsideVersusOutside(meCell, tc);
+ /// Inside and in another cell, a monster more than this above or below is on another floor. A
+ /// building's floor above can be 3.0 m up: "more than MeleeMaxRiseM" let it through (2026-11-16 17:11, a
+ /// Thread: two monsters 3.0 m up in the next cell were locked and swung at from the floor below).
+ internal const double OtherFloorRiseM = 2.5;
+
+ ///
+ /// Both inside (a building's rooms or a dungeon's cells), in different cells, and the monster more than
+ /// OtherFloorRiseM above or below: another floor or a balcony. The slope rule (OutOfMeleeReachUpOrDown)
+ /// lets one 8 m off through as a gentle ramp, and it was locked and chased round in circles under it
+ /// (2026-11-16, a Thread: 5.5 m up in a building). Left to the hunt or the patrol, which walk up the stairs.
+ ///
+ private bool OtherFloorInside(uint meCell, uint targetId, double dz)
+ {
+ if (!(Math.Abs(dz) > OtherFloorRiseM) || (meCell & 0xFFFF) < 0x0100) return false;
+ return _host.TryGetObjectPosition(targetId, out uint tc, out _, out _, out _) && tc != 0
+ && (tc & 0xFFFF) >= 0x0100 && (tc >> 16) == (meCell >> 16) && tc != meCell;
+ }
+
internal static bool OutOfMeleeReachUpOrDown(double dist, double dz)
{
double rise = Math.Abs(dz);
@@ -7845,6 +7932,15 @@ public partial class CombatManager : IDisposable
// A ring or a wall hits several monsters: its damage isn't the fight target's alone.
bool multiTarget = isRing || castShape == ShapeWall;
if (offensiveSpellId != 0 && ManaHoldsCast(offensiveSpellId)) return; // mana reserve
+ // The last cast's answer first, while it is still that cast's: a recast in the tick its
+ // UseDone came in would drop it unread. A second TargetNotAcquired at this target marks it
+ // a ghost and drops it (NoteOffensiveAnswer): then nothing is cast at it (2026-11-15).
+ if (offensiveSpellId != 0)
+ {
+ int castAt = activeTargetId;
+ ObserveOffensiveAnswer();
+ if (activeTargetId != castAt || activeTargetId == 0) return;
+ }
if (offensiveSpellId != 0)
{
LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
index b7ad61a..d51ab7d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
@@ -96,6 +96,21 @@ internal sealed class PetManager
// get parked so we advance to the next configured essence instead of looping.
private readonly Dictionary _deviceCooldownUntil = new();
+ // The summon cooldown every essence shares (2026-11-13, R-20261113-130755-35ae: "proper pet is
+ // not spawned ... goes back to random pet spawns"). Nearly every ACE combat essence carries
+ // SharedCooldown 213 / 45 s (231 of the 310 "... Essence" weenies in the world data; 6 carry
+ // another group, the rest none), so a summon that lands puts EVERY essence on cooldown, not
+ // only its own; the report's log shows it: "You have used this item too recently" for an
+ // essence last used 48 s before, 37 s after another essence's summon. Only its own was parked, so when the pet died
+ // before 45 s the loop skipped the chosen essence and used the next listed one, another element:
+ // refused "You have used this item too recently" (an 8 s timeout each) for most of the window,
+ // and summoned for real when it was tried at the window's edge, a few hundred ms before the
+ // chosen essence's own park ran out. Until this time no essence is used; then the chosen one is.
+ private long _summonCooldownUntil;
+ private long _summonCooldownLogged; // the _summonCooldownUntil whose wait was logged
+ /// A summon refused "used this item too recently": the chosen essence is tried again after this.
+ private const long TooRecentlyRetryMs = 5_000;
+
// The server's word over a stale Structure read (2026-10-05). A read
// can say 0 while the server holds a full essence; the server then answers a refill with
// "already full" (or refills it and the read still lags), and deciding from the read alone
@@ -241,6 +256,7 @@ internal sealed class PetManager
{
_summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId),
_objectCache[_activeDeviceId]?.Name ?? "");
+ _summonCooldownUntil = _actionIssuedAt + DeviceUseCooldownMs; // every essence's, not only this one's
AssumePetFor(now, AssumeActiveAfterSummonMs);
// Judge the essence again now its pet is out: one used before its appraisal landed
// (it waits only AppraisalWaitMs) may turn out no combat pet device.
@@ -284,7 +300,10 @@ internal sealed class PetManager
if (_state != PetState.Summoning && _activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs; // refill timeout: park as before
if (summonConfirmed)
+ {
+ _summonCooldownUntil = _actionIssuedAt + DeviceUseCooldownMs;
AssumePetFor(now, AssumeActiveAfterSummonMs);
+ }
else if (_state == PetState.Summoning)
_assumePetActiveUntil = 0;
Reset();
@@ -320,6 +339,22 @@ internal sealed class PetManager
GoIdle();
return;
}
+ // "You have used this item too recently" (2026-11-13, R-20261113-130755-35ae): the cooldown
+ // every essence shares is still running (a summon by hand, or the server's clock a little
+ // behind ours at the window's edge). The refusal started nothing, so this essence is not
+ // parked for 45 s, which sent the next try to another element's essence; every essence
+ // waits a moment and the chosen one is tried again. No 8 s timeout either.
+ if (text.Contains("used this item too recently", StringComparison.OrdinalIgnoreCase))
+ {
+ long now = NowMs;
+ if (_activeDeviceId != 0) _deviceCooldownUntil.Remove(_activeDeviceId);
+ _summonCooldownUntil = Math.Max(_summonCooldownUntil, now + TooRecentlyRetryMs);
+ _summonCooldownLogged = _summonCooldownUntil; // this line is the wait's log
+ _host.Log($"[RynthAi] Pet: the server refused essence 0x{(uint)_activeDeviceId:X8}: used too recently (the summon cooldown " +
+ $"every essence shares); trying the chosen essence again in {TooRecentlyRetryMs / 1000}s, not another one.");
+ GoIdle();
+ return;
+ }
// "... does not have enough charges to function!" — essence is empty.
// Drop to Idle; the next think tick reads Structure==0 and refills it.
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
@@ -463,6 +498,22 @@ internal sealed class PetManager
if (!_host.HasUseObject) return;
+ // The summon cooldown every essence shares is running (the last pet died or went before it
+ // ended): wait for it rather than try the next listed essence, another element the server
+ // refuses or, at the window's edge, summons (R-20261113-130755-35ae).
+ if (now < _summonCooldownUntil)
+ {
+ if (_summonCooldownLogged != _summonCooldownUntil)
+ {
+ _summonCooldownLogged = _summonCooldownUntil;
+ long since = now - (_summonCooldownUntil - DeviceUseCooldownMs);
+ _host.Log($"[RynthAi] Pet: no pet out {since / 1000}s after the last summon (it died or went); every essence " +
+ $"shares the {DeviceUseCooldownMs / 1000}s summon cooldown, so the next summon waits " +
+ $"{(_summonCooldownUntil - now + 999) / 1000}s for the chosen essence instead of using another.");
+ }
+ return;
+ }
+
// Best essence for the monster being fought first (Damage panel pet choice:
// a specific essence, an element, or Auto = lowest learned resist), then the
// rest in Items-panel order as fallbacks.
@@ -945,6 +996,7 @@ internal sealed class PetManager
}
_claimNewPetsUntil = 0;
_assumePetActiveUntil = 0;
+ _summonCooldownUntil = 0; // a passive pet's essence carries no shared cooldown (ACE world data)
_host.Log($"[RynthAi] Pet: essence 0x{(uint)dev:X8} '{_objectCache[dev]?.Name ?? "?"}' brought out {pets} pet(s) but is no combat pet device " +
"(no charges, no Summoning requirement, no summoning-gem icon); not used for combat again this session, and its pet holds nothing.");
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
index ff03112..1487f99 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
@@ -526,6 +526,7 @@ public sealed partial class RynthAiPlugin
NoteContainerOpened(sid);
NoteChestKeyOpened(sid); // the Item Tool's chest looter waits for this
NoteManualChestOpened(sid); // Pickup with macro off (RynthAiPlugin.ChestLoot.cs)
+ NoteNearbyChestOpened(sid); // Loot Nearby Chests waits for this (RynthAiPlugin.NearbyChests.cs)
return;
}
@@ -773,9 +774,12 @@ public sealed partial class RynthAiPlugin
_lootSkipWhy = !settings.IsMacroRunning ? "the macro is off"
: !settings.EnableLooting ? "looting is off" : "Boost Nav Priority is on and a nav route runs (RynthAi only follows it)";
ResetCorpseTarget();
+ StandDownNearbyChests(_lootSkipWhy); // Loot Nearby Chests (RynthAiPlugin.NearbyChests.cs)
return;
}
NoteLootSettings(settings);
+ // Loot Nearby Chests reads its answers every tick, a fight's included (RynthAiPlugin.NearbyChests.cs).
+ TickNearbyChests(settings);
// Wedge halt: AC's item-action state is locked (consecutive open
// timeouts). Stop firing opens into a dead client until the halt window
@@ -863,6 +867,14 @@ public sealed partial class RynthAiPlugin
if (_targetCorpseId == 0 && _lootNameTargetId != 0 && TryLootByName(settings, CorpseNowMs))
return;
+ // Loot Nearby Chests is unlocking or opening a chest: no corpse is claimed meanwhile (its open
+ // would close the chest; RynthAiPlugin.NearbyChests.cs).
+ if (_targetCorpseId == 0 && NearbyChestHoldsTick())
+ {
+ _lootSkipWhy = "Loot Nearby Chests is on a chest";
+ return;
+ }
+
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
double minMeters = GetCorpseApproachRangeMinMeters(settings, maxMeters);
if (maxMeters <= 0.25)
@@ -897,6 +909,9 @@ public sealed partial class RynthAiPlugin
// No corpses in range. Loose ground items that match the loot profile
// get their turn here; HasLootWork keeps Looting while any remain.
TickGroundLoot(settings, maxMeters);
+ // Then a chest in loot range (Loot Nearby Chests, RynthAiPlugin.NearbyChests.cs).
+ if (_groundTargetId == 0)
+ TryStartNearbyChest(settings);
return;
}
@@ -1003,6 +1018,28 @@ public sealed partial class RynthAiPlugin
}
return;
}
+ // A starved turn's open waits for combat's first attack at a target it has just locked
+ // (2026-11-15, R-20261115-165857-1de7). A monster came into range 0.4 s after the claim,
+ // the starved turn kept Looting (none within 5 yd), and the open went out 0.3 s after the
+ // lock, ahead of combat's first cast. The server didn't answer that use for 5 s (likely a monster's
+ // hit or swing stopping the server's turn to the corpse, see AttemptOpenCorpse), and the pacer
+ // rightly held every action behind it: 5.5 s standing with "Combat" showing and the monster
+ // walking in. The fight's first attack goes out first now; the open follows between casts,
+ // as starvation always meant. At most StarvedOpenYieldsMs, so a lock that can't attack
+ // (out of reach, no stance) doesn't stop looting again.
+ if (_lootStarveTurn && _combatManager?.FirstAttackPendingMs is double attackPending
+ && attackPending >= 0 && attackPending < StarvedOpenYieldsMs)
+ {
+ FreezeCorpseTimeout(now);
+ if (_openHeldForAttackLoggedFor != _targetCorpseId)
+ {
+ _openHeldForAttackLoggedFor = _targetCorpseId;
+ LootDiag($"[RynthAi] Corpse loot: open of 0x{(uint)_targetCorpseId:X8} waits for combat's first attack at " +
+ $"0x{(uint)_combatManager.activeTargetId:X8} '{_objectCache[_combatManager.activeTargetId]?.Name}' " +
+ $"(locked {attackPending:0} ms ago; at most {StarvedOpenYieldsMs / 1000.0:0.0} s).");
+ }
+ return;
+ }
_openHeldBySalvageLogged = false;
_corpseHoldFrozenAge = -1;
@@ -1071,6 +1108,11 @@ public sealed partial class RynthAiPlugin
private long _corpseOpenBusyWaitSince;
private bool _openHeldBySalvageLogged;
+ private int _openHeldForAttackLoggedFor; // the corpse whose open waited for combat's first attack (logged once)
+
+ /// A starved turn's open waits this long at most for combat's first attack at a fresh lock
+ /// (the slowest healthy lock->attack in R-20261115-165857-1de7 was 2.6 s, a cast's recoil).
+ internal const long StarvedOpenYieldsMs = 3000;
// Peace before the open: one request per claimed corpse, only with no monster within
// LootStarveCloseYards (the same test that gives looting its turn while combat still has a
@@ -3221,6 +3263,13 @@ public sealed partial class RynthAiPlugin
return true;
}
+ // Loot Nearby Chests is unlocking or opening a chest (RynthAiPlugin.NearbyChests.cs).
+ if (NearbyChestBusy(settings))
+ {
+ _lootWorkWhy = "Loot Nearby Chests is on a chest";
+ return true;
+ }
+
// Loot grace: combat just ended and the corpse CreateObject has not
// arrived yet. Hold Looting across that gap so nav doesn't walk away
// from a body that is about to exist.
@@ -3269,6 +3318,12 @@ public sealed partial class RynthAiPlugin
_lootWorkWhy = "ground loot";
return true;
}
+ // A chest in loot range (Loot Nearby Chests), after corpses; never while fighting.
+ if (HasNearbyChestWork(settings))
+ {
+ _lootWorkWhy = "a chest in loot range (Loot Nearby Chests)";
+ return true;
+ }
return false;
}
@@ -4281,7 +4336,13 @@ public sealed partial class RynthAiPlugin
_useRefusals.OnOpenSent(corpseId, now, seqBefore);
// An open on a no-bend-down call: its answer says whether the server was free (DistrustJumpNoMotion).
_openInAirWindowSeq = watch && sent && JumpPickupInAir(now) ? seqBefore : -1;
- LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}.");
+ // The distance says whether the server has to walk the character there or only turn it
+ // (an unanswered open's two cases; 2026-11-15, R-20261115-165857-1de7).
+ double openDist = _objectCache?.Distance(unchecked((int)_playerId), corpseId) ?? double.MaxValue;
+ LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}"
+ + (openDist < 1000 ? $" (d={openDist:0.0} m)" : "")
+ + (_combatManager?.activeTargetId is int fight && fight != 0 ? $", combat locked on 0x{(uint)fight:X8}" : "")
+ + ".");
// The finished corpse held open (MarkCorpseCompleted): this use closes it on the server.
if (sent && _closeDeferredFor != 0 && _closeDeferredFor != corpseId)
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs
index ae66508..5636fc0 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DoorInteractionController.cs
@@ -380,6 +380,7 @@ public sealed partial class RynthAiPlugin
if (_doorAttempts >= DoorMaxAttempts)
{
Host.Log($"[RynthAi] Door: 0x{(uint)_doorTargetId:X8} still closed after {_doorAttempts} uses ({why}), cooldown");
+ NoteExploreDoorRefused(unchecked((uint)_doorTargetId), "wouldn't open");
EnterDoorCooldown(now);
return true;
}
@@ -419,6 +420,7 @@ public sealed partial class RynthAiPlugin
private void EnterDoorCooldown(long now, bool locked = false)
{
if (locked && _doorTargetId != 0) _doorLockedRecently[_doorTargetId] = now;
+ if (locked && _doorTargetId != 0) NoteExploreDoorRefused(unchecked((uint)_doorTargetId), "locked");
_doorState = DoorState.Cooldown;
_doorActionAt = now;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
index b2e2f26..68de652 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
@@ -297,11 +297,11 @@ internal sealed class DungeonGeometry
public bool TryGetDoorway(uint a, uint b, out DungeonDoorway door) => _doorways.TryGetValue(EdgeKey(a, b), out door!);
- /// Openings whose centre is within r (horizontally) of (x, y) and 2 m of height z.
- public IEnumerable DoorwaysNear(double x, double y, double z, double r)
+ /// Openings whose centre is within r (horizontally) of (x, y) and of height z.
+ public IEnumerable DoorwaysNear(double x, double y, double z, double r, double dz = 2.0)
{
foreach (var d in _doorways.Values)
- if ((d.X - x) * (d.X - x) + (d.Y - y) * (d.Y - y) <= r * r && Math.Abs(d.Z - z) < 2.0) yield return d;
+ if ((d.X - x) * (d.X - x) + (d.Y - y) * (d.Y - y) <= r * r && Math.Abs(d.Z - z) < dz) yield return d;
}
public bool HasFloor(uint cell) => _floors.ContainsKey(cell);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs
new file mode 100644
index 0000000..27d851f
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs
@@ -0,0 +1,132 @@
+// DungeonPathfinder, blocked doorways half (2026-11-16).
+//
+// A dungeon's cells can place static objects (the EnvCells' stabs), and the dungeon map has none of
+// them: it is the cells' walls, floors and openings only. DreamWeave Thread 0x5456 has twelve spider
+// webs (model 0x02000D34: 5.3 m wide, 0.55 to 3.75 m off the floor, physics polygons and all) placed in
+// its doorways. The map had those doorways open, the explore walked into a web, was stuck, and the
+// stuck fallback (TryFindStuckOpening) gave the doorway up a minute later, a web at a time.
+//
+// GetGeometry closes each doorway a placed object stands across (both ways, as a wall), before the
+// ledges are looked at, so every walk laid on the map (patrol, explore, dunroute, the stuck detours)
+// goes round. Blocked: walking lines straight through the doorway, 0.25 m apart across it, hit an
+// object's physics polygons within 1.2 m of the doorway at some body height (0.6 to 1.5 m: a web's
+// strands leave gaps a line slips through and a character doesn't), leaving no free gap of
+// BlockedGapMeters. An arch or a frame round a doorway leaves its
+// middle free; a pillar to one side leaves a gap. The objects come from StaticMeshSource (the plugin
+// points it at GeometryLoader.GetDungeonStaticMeshes once the raycast is up; null: nothing closed).
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using RynthCore.Plugin.RynthAi.Raycasting;
+
+namespace RynthCore.Plugin.RynthAi;
+
+internal static partial class DungeonPathfinder
+{
+ /// The static objects a dungeon's cells place, as physics meshes in world metres (GeometryLoader
+ /// .GetDungeonStaticMeshes). Null: no doorway is closed for them.
+ internal static Func>? StaticMeshSource;
+
+ /// A doorway with no free gap this wide left at body height is blocked.
+ internal const double BlockedGapMeters = 1.0;
+ // Lanes this far apart across the doorway, none nearer its sides than the margin; each looked along from
+ // BlockedNear before the doorway to BlockedNear past it (a web 0.8 m into the next cell is in it).
+ private const double BlockedLaneStep = 0.25, BlockedEdgeMargin = 0.4, BlockedNear = 1.2;
+ // A body's height: a web's strands leave gaps a thin line slips through, a character doesn't.
+ private static readonly double[] BlockedHeights = { 0.6, 0.9, 1.2, 1.5 };
+
+ /// What closing the blocked doorways did in the last dungeon (one line, for the build log), or null.
+ internal static string? BlockedNote;
+ internal static uint BlockedNoteLandblock;
+
+ ///
+ /// Every doorway (narrower than a room's own openings) that a placed object stands across: one entry per
+ /// cell pair, with the objects' model ids.
+ ///
+ internal static List<(uint A, uint B, uint[] Setups)> FindBlockedDoorways(Dictionary graph, DungeonGeometry geo,
+ IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)> statics)
+ {
+ var list = new List<(uint, uint, uint[])>();
+ if (statics.Count == 0) return list;
+ var seen = new HashSet();
+ foreach (var n in graph.Values)
+ foreach (uint nb in n.Neighbors)
+ {
+ if (!graph.ContainsKey(nb) || !seen.Add(EdgeKey(n.CellId, nb))) continue;
+ if (!geo.TryGetDoorway(n.CellId, nb, out var d) || d.IsWide) continue;
+ var near = statics.Where(s => s.Mesh.Max.X >= d.X - 4 && s.Mesh.Min.X <= d.X + 4 && s.Mesh.Max.Y >= d.Y - 4 && s.Mesh.Min.Y <= d.Y + 4
+ && s.Mesh.Max.Z >= d.Z && s.Mesh.Min.Z <= d.Z + 2.5).ToList();
+ if (near.Count == 0) continue;
+ if (DoorwayBlocked(d, near, out var by)) list.Add((d.CellA, d.CellB, by));
+ }
+ // The other cell pairs of each blocked opening (a portal higher up in it, a stacked cell's: OpeningPairs).
+ var have = new HashSet(list.Select(x => EdgeKey(x.Item1, x.Item2)));
+ foreach (var (a, b, by) in list.ToList())
+ foreach (ulong k in OpeningPairs(graph, geo, a, b))
+ if (have.Add(k)) list.Add(((uint)(k >> 32), (uint)k, by));
+ return list;
+ }
+
+ private static bool DoorwayBlocked(DungeonDoorway d, List<(uint SetupId, uint CellId, BoundingVolume Mesh)> near, out uint[] by)
+ {
+ var setups = new HashSet();
+ double tx = -d.Ny, ty = d.Nx, half = d.Width / 2 - BlockedEdgeMargin;
+ var dir = new Vector3((float)d.Nx, (float)d.Ny, 0f);
+ double run = 0, bestRun = 0;
+ for (double o = -half; o <= half + 1e-6; o += BlockedLaneStep)
+ {
+ // Shut when something is in the way at two body heights or more (a step or a low kerb meets the lowest only).
+ int heights = 0;
+ foreach (double h in BlockedHeights)
+ {
+ var start = new Vector3((float)(d.X + tx * o - d.Nx * BlockedNear), (float)(d.Y + ty * o - d.Ny * BlockedNear), (float)(d.Z + h));
+ foreach (var s in near)
+ if (s.Mesh.RayIntersect(start, dir, (float)(2 * BlockedNear), out _)) { heights++; setups.Add(s.SetupId); break; }
+ }
+ bool shut = heights >= 2;
+ if (shut) run = 0;
+ else { run += BlockedLaneStep; bestRun = Math.Max(bestRun, run); }
+ }
+ by = setups.ToArray();
+ return bestRun < BlockedGapMeters && setups.Count > 0;
+ }
+
+ /// GetGeometry's step: the cached graph of loses the doorways placed
+ /// objects stand across (both ways), then its ledges.
+ private static void CloseMapBlocksOf(uint landblockKey, Dictionary graph, DungeonGeometry geo)
+ {
+ CloseBlockedDoorwaysOf(landblockKey, graph, geo);
+ CloseLedgesOf(landblockKey, graph, geo);
+ }
+
+ private static void CloseBlockedDoorwaysOf(uint landblockKey, Dictionary graph, DungeonGeometry geo)
+ {
+ BlockedNoteLandblock = landblockKey;
+ BlockedNote = null;
+ var source = StaticMeshSource;
+ if (source == null) return;
+ try
+ {
+ var statics = source(landblockKey);
+ if (statics == null || statics.Count == 0) return;
+ var blocked = FindBlockedDoorways(graph, geo, statics);
+ if (blocked.Count == 0) return;
+ foreach (var (a, b, _) in blocked)
+ {
+ if (graph.TryGetValue(a, out var na)) na.Neighbors.RemoveAll(c => c == b);
+ if (graph.TryGetValue(b, out var nb)) nb.Neighbors.RemoveAll(c => c == a);
+ }
+ var inv = CultureInfo.InvariantCulture;
+ var models = blocked.SelectMany(x => x.Setups).GroupBy(s => s).Select(g => string.Format(inv, "0x{0:X8}", g.Key));
+ BlockedNote = string.Format(inv, "{0} doorway cell pair(s) closed: something the cells place stands across them (model {1}), walked round: {2}",
+ blocked.Count, string.Join(", ", models),
+ string.Join(", ", blocked.Take(8).Select(x => string.Format(inv, "{0:X8}>{1:X8}", x.A, x.B))) + (blocked.Count > 8 ? ", ..." : ""));
+ }
+ catch (Exception e)
+ {
+ BlockedNote = "placed objects not looked at: " + e.GetType().Name;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs
new file mode 100644
index 0000000..c4f6269
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs
@@ -0,0 +1,435 @@
+// DungeonPathfinder, explore half: one walk through every room of the dungeon, then stop (2026-11-13).
+//
+// Why: Tom wanted a script that explores a dungeon: every room once, what turned up listed at the
+// end. The patrol is a loop for hunting: it goes round for ever, and a reroute (a hazard sighted,
+// a portal coming into view: in a dungeon nobody has walked yet that is every few rooms) lays the
+// whole lap again from where the character stands, so a walk that should end would keep crossing
+// rooms it has already been through.
+//
+// The explore (/ra dunnav-explore, RynthAiPlugin.DunExplore.cs) is a Once route over the same rooms
+// as the patrol with coverage Everything (DungeonRooms: cells joined by wide openings; each cell its
+// own room until the dungeon map is loaded), laid by the patrol's own pieces: doorways taken straight
+// on, rooms crossed directly, big rooms looked into (EmitSteps, lookIn), lava/acid and drops left out,
+// portals kept out of (LayAroundPortals). What is new is the order:
+// - from the room the character is in, the next room is a room next door not yet entered; of
+// several, the one with the fewest new rooms beyond it (a closet or a dead end first, so it is
+// never walked back to from far away later);
+// - with none next door, the shortest way (in doorways) to the nearest room not yet entered;
+// - it ends in the middle of the last new room (no walk back to the start).
+// The rooms already entered (visitedCells: the cells the character has stood in on this explore)
+// count as done, so a reroute lays only the walk through the rest.
+// Shut doors (a door the character can't use: a lever opens it) are left out by the caller (their
+// openings closed in the graph); when one opens, the rooms behind it (preferCells) are walked first,
+// since it shuts again on its own (8 s to 5 min in ACE's data).
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi;
+
+/// The rooms an explore walk was laid over, numbered as its .
+internal sealed class ExplorePlan
+{
+ /// Every cell of the graph in a room (the map's rooms, or one cell each without the map).
+ public DungeonRooms Rooms = new();
+ /// The rooms the walk is meant to enter: every room the character can walk to from where it
+ /// stood (no lava/acid, no drop, no opening a portal closes).
+ public readonly HashSet PlanRooms = new();
+ /// Of PlanRooms, those entered before this walk was laid (it doesn't go back to them).
+ public readonly HashSet DoneRooms = new();
+ /// The rooms the walk goes into, in order (the start room not included).
+ public readonly List Order = new();
+ /// Laid on the dungeon map's rooms (false: the cell walk, each cell a room).
+ public bool ByRoom;
+ /// The room middles the walk goes to (look-ins, the last room's): waited at (DungeonPathfinder.ExploreScanMs).
+ public readonly List ScanMiddles = new();
+
+ public int RoomOf(uint cell) => Rooms.RoomOf.TryGetValue(cell, out int r) ? r : -1;
+}
+
+internal static partial class DungeonPathfinder
+{
+ ///
+ /// A Once route from through every room the character can walk to and
+ /// has not entered yet (: cells it has stood in), ending in the
+ /// middle of the last one. The patrol settings in apply but for the
+ /// coverage, always Everything. Empty when there is nothing left to walk to.
+ ///
+ public static NavRouteParser BuildExploreRoute(
+ Dictionary graph,
+ uint startCell,
+ IReadOnlySet? hazardCells,
+ DungeonGeometry? geo,
+ DungeonPatrolOptions? options,
+ IReadOnlyList? portals,
+ (double X, double Y, double Z)? startAt,
+ IReadOnlySet? visitedCells,
+ out ExplorePlan plan,
+ IReadOnlySet? preferCells = null)
+ {
+ LastPortalAvoidance = null;
+ var o = ((options ?? DungeonPatrolOptions.Default) with { Coverage = PatrolCoverage.Everything }).Clamped();
+ NavRouteParser route;
+ if (portals is not { Count: > 0 })
+ route = LayExplore(graph, startCell, hazardCells, geo, o, visitedCells, out plan, preferCells);
+ else
+ {
+ ExplorePlan? last = null;
+ route = LayAroundPortals(graph, startCell, hazardCells, geo, portals, startAt, o.WallClearance, loop: false,
+ g =>
+ {
+ var r = LayExplore(g, startCell, hazardCells, geo, o, visitedCells, out var p, preferCells);
+ last = p;
+ return r;
+ });
+ plan = last ?? new ExplorePlan();
+ }
+ // The waits go in last, on the finished walk (the portal step moves points out of a portal's circle; a
+ // middle it moved gets no wait).
+ int scans = ExploreScanMs > 0 && plan.ScanMiddles.Count > 0 ? AddScanPauses(route.Points, plan.ScanMiddles, ExploreScanMs) : 0;
+ if (scans > 0) MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ") + $"scans: {scans} room middle(s) waited at {ExploreScanMs / 1000.0:0.#} s";
+ return route;
+ }
+
+ // ── Steps nav can't walk (2026-11-16) ──────────────────────────────────────────────────────────
+ // DreamWeave Thread 0x0278: the explore crossed a two-level room straight, from its doorway at the foot
+ // (z -42) to the opening on the level above (z -36), 1 m off on the map. Nav takes a point as reached by
+ // the flat distance, so it skipped the upper one and ran from the lower floor at the next point, 50 m off
+ // on the level above: into the wall under it, until it was stopped. A step rising (or dropping) more than
+ // StackedRiseMeters within StackedFlatMeters is no stair (a stair's steps here are 3 m up over 2 m): the
+ // doorway at its end is closed for this walk (all its cell pairs) and the walk laid again.
+
+ internal const double StackedRiseMeters = 4.5, StackedFlatMeters = 2.5;
+ /// Off: the walk as laid (tests compare the two).
+ internal static bool CloseStackedSteps = true;
+ private const int StackedRetries = 4;
+
+ /// The walk's steps nav can't walk as laid (see above), and the doorways at their ends (all
+ /// their cell pairs) to close.
+ internal static HashSet StackedStepOpenings(List pts, Dictionary graph, DungeonGeometry geo, out int steps)
+ {
+ var keys = new HashSet();
+ steps = 0;
+ for (int i = 0; i + 1 < pts.Count; i++)
+ {
+ NavPoint a = pts[i], b = pts[i + 1];
+ if (!NavRouteParser.IsPlainWaypoint(a.Type) || !NavRouteParser.IsPlainWaypoint(b.Type)) continue;
+ double ax = DungeonGeometry.NavToWorld(a.EW), ay = DungeonGeometry.NavToWorld(a.NS);
+ double bx = DungeonGeometry.NavToWorld(b.EW), by = DungeonGeometry.NavToWorld(b.NS);
+ double rise = Math.Abs(b.Z - a.Z) * 240.0, flat = Math.Sqrt(Sq(bx - ax) + Sq(by - ay));
+ if (rise <= StackedRiseMeters || flat >= StackedFlatMeters) continue;
+ steps++;
+ var at = DoorwayAt(graph, geo, ax, ay, a.Z * 240.0, 1.5, out _);
+ if (at.Count == 0) at = DoorwayAt(graph, geo, bx, by, b.Z * 240.0, 1.5, out _);
+ keys.UnionWith(at);
+ }
+ return keys;
+ }
+
+ private static NavRouteParser LayExplore(
+ Dictionary graph, uint startCell, IReadOnlySet? hazardCells,
+ DungeonGeometry? geo, DungeonPatrolOptions o, IReadOnlySet? visitedCells, out ExplorePlan plan,
+ IReadOnlySet? preferCells = null)
+ {
+ string? note = MainRouteNote;
+ var route = LayExploreOnce(graph, startCell, hazardCells, geo, o, visitedCells, out plan, preferCells);
+ if (geo == null || !plan.ByRoom || !CloseStackedSteps) return route;
+ HashSet? cut = null;
+ var cur = graph;
+ int stacked = 0;
+ for (int round = 0; round < StackedRetries; round++)
+ {
+ var keys = StackedStepOpenings(route.Points, cur, geo, out int steps);
+ if (steps == 0) break;
+ stacked += steps;
+ cut ??= new HashSet();
+ int before = cut.Count;
+ cut.UnionWith(keys);
+ if (cut.Count == before) break; // no doorway to close: the walk stays as it is
+ cur = WithoutOpenings(graph, cut, startCell);
+ string? laid = MainRouteNote;
+ MainRouteNote = note;
+ var again = LayExploreOnce(cur, startCell, hazardCells, geo, o, visitedCells, out var p, preferCells);
+ if (again.Points.Count == 0) { MainRouteNote = laid; break; } // nothing left to walk: keep the first
+ route = again;
+ plan = p;
+ }
+ if (stacked > 0)
+ MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ")
+ + $"stacked steps: {stacked} found, {cut?.Count ?? 0} opening pair(s) closed for the walk";
+ return route;
+ }
+
+ private static NavRouteParser LayExploreOnce(
+ Dictionary graph, uint startCell, IReadOnlySet? hazardCells,
+ DungeonGeometry? geo, DungeonPatrolOptions o, IReadOnlySet? visitedCells, out ExplorePlan plan,
+ IReadOnlySet? preferCells = null)
+ {
+ var route = new NavRouteParser { RouteType = NavRouteType.Once };
+ bool byRoom = geo != null && geo.DoorwayCount > 0;
+ var rooms = byRoom ? BuildRooms(graph, geo!, hazardCells) : CellRooms(graph);
+ plan = new ExplorePlan { Rooms = rooms, ByRoom = byRoom };
+
+ // Coverage Everything: every cell walkable to from the start, dead ends included.
+ foreach (uint c in GetMainRouteNodes(graph, startCell, hazardCells, o, byRoom ? rooms : null))
+ if (rooms.RoomOf.TryGetValue(c, out int r)) plan.PlanRooms.Add(r);
+ if (!rooms.RoomOf.TryGetValue(startCell, out int startRoom) || !plan.PlanRooms.Contains(startRoom))
+ return route;
+
+ var entered = new HashSet { startRoom };
+ if (visitedCells != null)
+ foreach (uint c in visitedCells)
+ if (rooms.RoomOf.TryGetValue(c, out int vr) && plan.PlanRooms.Contains(vr)) entered.Add(vr);
+ plan.DoneRooms.UnionWith(entered);
+
+ var adj = RoomAdjacency(graph, rooms, plan.PlanRooms, hazardCells, out _);
+ HashSet? prefer = null;
+ if (preferCells is { Count: > 0 })
+ {
+ prefer = new HashSet();
+ foreach (uint c in preferCells)
+ if (rooms.RoomOf.TryGetValue(c, out int pr) && plan.PlanRooms.Contains(pr) && !entered.Contains(pr)) prefer.Add(pr);
+ }
+ var walk = ExploreWalk(adj, startRoom, entered, plan.Order, prefer);
+ if (walk.Count == 0) return route;
+
+ var steps = new List(walk.Count);
+ foreach (var e in walk) steps.Add(new Step(e.From, e.To, e.Key));
+ if (byRoom)
+ {
+ // Into the middle of the last room, so the walk ends inside it, not just past its doorway.
+ int lastRoom = walk[walk.Count - 1].Room;
+ var mid = RoomMiddle(graph, geo!, rooms.Cells[lastRoom], o.WallClearance, out uint midCell);
+ if (mid != null && midCell == 0) midCell = walk[walk.Count - 1].To;
+ var middles = plan.ScanMiddles;
+ ScanMiddles = middles;
+ List pts;
+ try { pts = EmitSteps(graph, geo!, rooms, steps, closed: false, null, 0, mid, midCell, o, out _, lookIn: true); }
+ finally { ScanMiddles = null; }
+ if (mid != null) { Append(pts, Tag(mid, "explore-end")); middles.Add(mid); }
+ // Round a hole in a cell's floor, not over it (DungeonPathfinder.Holes.cs): before the
+ // straightening, so its legs keep the clearance the walk round has.
+ int holes = WalkRoundHoles(pts, geo!);
+ if (holes > 0 || HolesLeft > 0)
+ MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ") + $"holes: {holes} walked round" + (HolesLeft > 0 ? $", {HolesLeft} with no way round" : "");
+ // Fewer turns: straight legs over the room boundaries a corridor of small rooms is cut into
+ // (DungeonPathfinder.Straighten.cs), every room still walked through.
+ int straightened = StraightenWalk(pts, graph, geo!, rooms, o.WallClearance, middles);
+ if (straightened > 0) MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ") + $"straightened: {straightened} turn(s) taken out";
+ route.Points.AddRange(pts);
+ }
+ else
+ {
+ foreach (var s in steps)
+ if (graph.TryGetValue(s.From, out var a) && graph.TryGetValue(s.To, out var b)) AddPortalWaypoints(route, a, b);
+ if (steps.Count > 0 && graph.TryGetValue(steps[steps.Count - 1].To, out var end))
+ route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = end.NS, EW = end.EW, Z = end.Z / 240.0 });
+ SimplifyRoute(route);
+ }
+ return route;
+ }
+
+ ///
+ /// The doorway steps of the explore walk: from , into a room next door not
+ /// yet (the one with the fewest new rooms beyond it first), else the
+ /// shortest way to the nearest room not yet entered, until every room it can reach is entered.
+ /// is added to as it goes; gets each new room.
+ ///
+ private static List ExploreWalk(Dictionary> adj, int startRoom, HashSet entered, List? order = null,
+ HashSet? prefer = null)
+ {
+ var walk = new List();
+ int cur = startRoom;
+ // Behind a door that just opened first: the shortest way to the nearest of those rooms (it shuts again).
+ if (prefer is { Count: > 0 })
+ {
+ var first = RoomBfs(adj, cur, r => prefer.Contains(r) && !entered.Contains(r));
+ if (first != null)
+ {
+ foreach (var e in first)
+ {
+ walk.Add(e);
+ if (entered.Add(e.Room)) order?.Add(e.Room);
+ }
+ cur = first[first.Count - 1].Room;
+ }
+ }
+ // Every pass enters one new room (or stops), so this bounds it.
+ int guard = adj.Count + 16;
+ while (guard-- > 0)
+ {
+ RoomEdge? next = null;
+ int fewest = int.MaxValue;
+ if (adj.TryGetValue(cur, out var doors))
+ foreach (var e in doors)
+ {
+ if (entered.Contains(e.Room)) continue;
+ int beyond = NewRoomsBeyond(adj, e.Room, cur, entered);
+ if (beyond < fewest) { fewest = beyond; next = e; }
+ }
+
+ if (next is RoomEdge step)
+ {
+ walk.Add(step);
+ entered.Add(step.Room);
+ order?.Add(step.Room);
+ cur = step.Room;
+ continue;
+ }
+
+ var hop = RoomBfs(adj, cur, r => !entered.Contains(r));
+ if (hop == null) break; // every room it can reach is entered
+ walk.AddRange(hop);
+ cur = hop[hop.Count - 1].Room;
+ entered.Add(cur);
+ order?.Add(cur);
+ }
+ return walk;
+ }
+
+ // The rooms next to `room` (but `from`) not yet entered.
+ private static int NewRoomsBeyond(Dictionary> adj, int room, int from, HashSet entered)
+ {
+ if (!adj.TryGetValue(room, out var doors)) return 0;
+ var seen = new HashSet();
+ foreach (var e in doors)
+ if (e.Room != from && !entered.Contains(e.Room)) seen.Add(e.Room);
+ return seen.Count;
+ }
+
+ /// The key the graph's openings are closed by ().
+ internal static ulong OpeningKey(uint a, uint b) => EdgeKey(a, b);
+
+ // ── Enter and scan (2026-11-16) ─────────────────────────────────────────
+ // A room's monsters reach the client as it comes into view: DreamWeave Thread 0x00B5's boss was known with no
+ // position while the walk touched its room's doorway and turned back, so the fight never started. The explore
+ // walks into every dead end (LooksIn, enterDeadEnds) and waits at each room middle it walks to (and the last
+ // room's), a nav Pause point after it: the room's monsters arrive and the fight starts before it walks on.
+
+ /// How long the explore waits at a room middle it walks to (0: no waits).
+ internal static int ExploreScanMs = 2000;
+
+ // The room middles EmitSteps walks to (CrossRoom's look-in), while the explore's walk is laid.
+ [ThreadStatic] private static List? ScanMiddles;
+
+ /// A Pause after each point of still at one of (the
+ /// clean-up passes keep or drop whole points), once per middle. The number put in.
+ private static int AddScanPauses(List pts, List middles, int ms)
+ {
+ int added = 0;
+ var left = new List(middles);
+ for (int i = 0; i < pts.Count && left.Count > 0; i++)
+ {
+ var p = pts[i];
+ if (p.Type != NavPointType.Point) continue;
+ int m = left.FindIndex(q => NavPointYd(q, p) < 0.3 && Math.Abs(q.Z - p.Z) * 240.0 < 1.0);
+ if (m < 0) continue;
+ left.RemoveAt(m);
+ pts.Insert(i + 1, new NavPoint { Type = NavPointType.Pause, NS = p.NS, EW = p.EW, Z = p.Z, PauseTimeMs = ms });
+ i++;
+ added++;
+ }
+ return added;
+ }
+
+ // Another cell pair's portal is in the same opening when its centre is this close (horizontally, and in
+ // height: 0x5456's 0174>0177 is 3 m over 0173>0177) and it faces the same way.
+ private const double SameOpeningMeters = 1.0, SameOpeningRise = 3.5;
+
+ ///
+ /// Every cell pair whose portal is in the one opening - is (its key
+ /// first). A cell stacked on another at a room's edge (two cells with one centre, each with its own
+ /// portal in the doorway) gives the doorway a second pair. DreamWeave Thread 0x5456 (2026-11-16): 014F and
+ /// 0150 both join 0148 at (16133, 16492); the explore stuck there closed 014F>0148 only, laid the walk
+ /// again through 0150>0148 (the same gap), and was stuck there again, three times over.
+ ///
+ internal static HashSet OpeningPairs(Dictionary graph, DungeonGeometry? geo, uint a, uint b)
+ {
+ var keys = new HashSet { EdgeKey(a, b) };
+ if (geo == null || !geo.TryGetDoorway(a, b, out var d)) return keys;
+ foreach (var o in geo.DoorwaysNear(d.X, d.Y, d.Z, SameOpeningMeters, SameOpeningRise))
+ {
+ if (o.CellA != a && o.CellA != b && o.CellB != a && o.CellB != b) continue; // another opening's
+ if (Math.Abs(o.Nx * d.Nx + o.Ny * d.Ny) < 0.9) continue; // across it, not through it
+ if (!graph.TryGetValue(o.CellA, out var na) || !na.Neighbors.Contains(o.CellB)) continue;
+ keys.Add(EdgeKey(o.CellA, o.CellB));
+ }
+ return keys;
+ }
+
+ ///
+ /// The doorway something at (x, y, z) (world metres) stands in: the nearest opening narrower than a room's
+ /// own (not IsWide) whose middle is within of it, 3 m in height, its cells joined
+ /// in the graph; as all its cell pairs (). Empty when it stands in none.
+ ///
+ internal static HashSet DoorwayAt(Dictionary graph, DungeonGeometry geo, double x, double y, double z,
+ double within, out DungeonDoorway? doorway)
+ {
+ doorway = null;
+ double best = double.MaxValue;
+ foreach (var d in geo.DoorwaysNear(x, y, z, within, 3.0))
+ {
+ if (d.IsWide || !graph.TryGetValue(d.CellA, out var na) || !graph.ContainsKey(d.CellB) || !na.Neighbors.Contains(d.CellB)) continue;
+ double dist = Sq(d.X - x) + Sq(d.Y - y);
+ if (dist < best) { best = dist; doorway = d; }
+ }
+ return doorway == null ? new HashSet() : OpeningPairs(graph, geo, doorway.CellA, doorway.CellB);
+ }
+
+ /// Every cell walkable to from (no drops, no lava/acid): what a shut
+ /// door's rooms behind it are measured with.
+ internal static HashSet ReachableCells(Dictionary graph, uint startCell, IReadOnlySet? hazardCells)
+ => ReachableAndCore(graph, startCell, hazardCells).Reachable;
+
+ ///
+ /// The opening(s) a door at (x, y, z) (world metres, in ) stands in: the map's
+ /// doorway nearest it within 3 m on its level (and any within 0.75 m of that one: a double door);
+ /// without the map, the step from its cell to the neighbour whose shared midpoint is nearest it.
+ /// Empty when nothing is near enough (the door isn't in an opening the graph knows).
+ ///
+ internal static HashSet DoorOpenings(Dictionary graph, DungeonGeometry? geo,
+ uint cell, double x, double y, double z)
+ {
+ var edges = new HashSet();
+ if (geo != null && geo.DoorwayCount > 0)
+ {
+ var near = geo.DoorwaysNear(x, y, z, 3.0)
+ .Where(d => graph.ContainsKey(d.CellA) && graph.ContainsKey(d.CellB))
+ .Select(d => (d, dist: Math.Sqrt(Sq(d.X - x) + Sq(d.Y - y))))
+ .OrderBy(t => t.dist).ToList();
+ if (near.Count > 0)
+ {
+ double best = near[0].dist;
+ foreach (var (d, dist) in near)
+ if (dist <= best + 0.75) edges.Add(EdgeKey(d.CellA, d.CellB));
+ return edges;
+ }
+ }
+ if (!graph.TryGetValue(cell, out var n)) return edges;
+ double wx = DungeonGeometry.WorldToNav(x), wy = DungeonGeometry.WorldToNav(y);
+ uint pick = 0;
+ double bestD = double.MaxValue;
+ foreach (uint nb in n.Neighbors)
+ {
+ if (!graph.TryGetValue(nb, out var m)) continue;
+ double d = Sq((n.EW + m.EW) / 2 - wx) + Sq((n.NS + m.NS) / 2 - wy);
+ if (d < bestD) { bestD = d; pick = nb; }
+ }
+ if (pick != 0) edges.Add(EdgeKey(cell, pick));
+ return edges;
+ }
+
+ /// Each cell its own room: the explore without the dungeon map.
+ private static DungeonRooms CellRooms(Dictionary graph)
+ {
+ var rooms = new DungeonRooms();
+ foreach (uint c in graph.Keys.OrderBy(k => k))
+ {
+ rooms.RoomOf[c] = rooms.Cells.Count;
+ rooms.Cells.Add(new List { c });
+ }
+ return rooms;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs
new file mode 100644
index 0000000..4fb32d8
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs
@@ -0,0 +1,208 @@
+// DungeonPathfinder, holes (2026-11-15).
+//
+// The walks are laid on the dungeon map: cell to cell through their openings, a room's openings
+// string-pulled. Nothing looks at the floor inside a cell. DreamWeave Thread 0x039B has a walkway at
+// z 6 through two square rooms, each with a 5 x 5 m pit in the middle down to the z -6 rooms below
+// and a 2 m rim round it. The explore went doorway to doorway, straight over each pit ("trying to
+// navigate over a big hole", Tom). LegClearance read 0 on those legs: a floor edge counts as a wall.
+// A ledge between two cells is closed in the graph (DungeonPathfinder.Ledges.cs); a hole inside one
+// cell is not an opening, so that never saw it.
+//
+// WalkRoundHoles goes over a laid walk. A leg whose straight line leaves the floor it is on (a sample
+// with no floor within a step of the last, or a drop of more than a step) is replaced by a walk round
+// on the floor. That is an A* over floor samples 0.5 m apart, in a box round the leg, at the floor's
+// own height (up and down ramps and stairs, a step at a time), on samples clear of walls and floor
+// edges by HoleKeepOff. The A* path is then pulled straight wherever a leg stays on the floor and
+// keeps that clearance. With no way round, the leg stays as laid (a drop the walk can't do
+// otherwise) and the note says so.
+
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi;
+
+internal static partial class DungeonPathfinder
+{
+ /// Off: the walk as laid (tests compare the two).
+ internal static bool HolesEnabled = true;
+
+ private const double HoleSample = 0.5; // the grid, and the samples along a leg (metres)
+ private const double HoleStep = 0.6; // floor heights this far apart are one walkable step
+ private const double HoleKeepOff = 0.6; // a grid sample this clear of walls and floor edges
+ private const double HolePad = 10.0; // the box round the leg (metres each way)
+ private const int HoleMaxGrid = 160 * 160;
+ private const double HoleStartBand = 3.0; // a walk point's floor, looked for this far above or below it
+
+ /// How many legs over a hole the last walk had walked round, and how many it couldn't.
+ internal static int HolesWalkedRound, HolesLeft;
+
+ ///
+ /// Replaces each leg of that leaves the floor with a walk round on it
+ /// (see the file's comment). Returns how many legs were walked round.
+ ///
+ internal static int WalkRoundHoles(List pts, DungeonGeometry geo)
+ {
+ HolesWalkedRound = HolesLeft = 0;
+ if (!HolesEnabled || pts.Count < 2) return 0;
+ var outPts = new List(pts.Count + 16) { pts[0] };
+ for (int i = 0; i + 1 < pts.Count; i++)
+ {
+ var a = pts[i];
+ var b = pts[i + 1];
+ double ax = DungeonGeometry.NavToWorld(a.EW), ay = DungeonGeometry.NavToWorld(a.NS), az = a.Z * 240.0;
+ double bx = DungeonGeometry.NavToWorld(b.EW), by = DungeonGeometry.NavToWorld(b.NS), bz = b.Z * 240.0;
+ if (OnFloorAll(geo, ax, ay, az, bx, by, bz))
+ {
+ outPts.Add(b);
+ continue;
+ }
+ var round = FloorPath(geo, ax, ay, az, bx, by, bz);
+ if (round == null)
+ {
+ HolesLeft++;
+ outPts.Add(b);
+ continue;
+ }
+ HolesWalkedRound++;
+ foreach (var (x, y, z) in round)
+ outPts.Add(new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 });
+ outPts.Add(b);
+ }
+ if (HolesWalkedRound > 0)
+ {
+ pts.Clear();
+ pts.AddRange(outPts);
+ }
+ return HolesWalkedRound;
+ }
+
+ // The straight walk a-b stays on the floor all the way: every sample has a floor within a step of
+ // the last one's (following ramps and stairs). The ends are where the walk already stands.
+ private static bool OnFloorAll(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
+ {
+ double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy);
+ if (len < HoleSample) return true;
+ if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double zf)) zf = az; // a point's height can be off a little
+ int steps = (int)Math.Ceiling(len / HoleSample);
+ for (int s = 1; s <= steps; s++)
+ {
+ double t = (double)s / steps, x = ax + dx * t, y = ay + dy * t;
+ if (!geo.TryFloorHeight(x, y, zf, HoleStep, out double h))
+ {
+ // The far end on another level (the leg's own end): a stair the samples skipped.
+ if (s == steps && Math.Abs(bz - zf) <= 1.5 && geo.TryFloorHeight(x, y, bz, HoleStep, out _)) return true;
+ return false;
+ }
+ zf = h;
+ }
+ return true;
+ }
+
+ // A* round on the floor from a to b; the points between (pulled straight), or null with no way.
+ private static List<(double X, double Y, double Z)>? FloorPath(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
+ {
+ double x0 = Math.Min(ax, bx) - HolePad, y0 = Math.Min(ay, by) - HolePad;
+ int nx = (int)Math.Ceiling((Math.Abs(bx - ax) + 2 * HolePad) / HoleSample) + 1;
+ int ny = (int)Math.Ceiling((Math.Abs(by - ay) + 2 * HolePad) / HoleSample) + 1;
+ if (nx * ny > HoleMaxGrid) return null;
+ int Idx(int i, int j) => j * nx + i;
+ double Gx(int i) => x0 + i * HoleSample;
+ double Gy(int j) => y0 + j * HoleSample;
+ int si = (int)Math.Round((ax - x0) / HoleSample), sj = (int)Math.Round((ay - y0) / HoleSample);
+ int ti = (int)Math.Round((bx - x0) / HoleSample), tj = (int)Math.Round((by - y0) / HoleSample);
+
+ var height = new double[nx * ny];
+ var state = new byte[nx * ny]; // 0 unknown, 1 floor and clear, 2 no
+ var g = new double[nx * ny];
+ var from = new int[nx * ny];
+ for (int k = 0; k < g.Length; k++) { g[k] = double.MaxValue; from[k] = -1; }
+
+ if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double sh)) sh = az;
+ int start = Idx(si, sj), goal = Idx(ti, tj);
+ height[start] = sh; state[start] = 1; // the walk stands there already
+ g[start] = 0;
+
+ // Floor at a step from `fromH`, and clear of walls and edges (the goal: only its floor).
+ bool Walkable(int i, int j, double fromH, bool isGoal, out double h)
+ {
+ h = 0;
+ if (i < 0 || j < 0 || i >= nx || j >= ny) return false;
+ int k = Idx(i, j);
+ if (!geo.TryFloorHeight(Gx(i), Gy(j), fromH, HoleStep, out h)) return false;
+ if (isGoal) return true;
+ if (state[k] == 2) return false;
+ if (state[k] == 1 && Math.Abs(height[k] - h) < 0.05) return true;
+ if (geo.ClearanceMemo(Gx(i), Gy(j), h, HoleKeepOff + 0.1) < HoleKeepOff) { state[k] = 2; return false; }
+ state[k] = 1;
+ height[k] = h;
+ return true;
+ }
+
+ var open = new PriorityQueue();
+ open.Enqueue(start, HoleDist(ax, ay, bx, by));
+ var closed = new bool[nx * ny];
+ int[] di = { 1, -1, 0, 0, 1, 1, -1, -1 }, dj = { 0, 0, 1, -1, 1, -1, 1, -1 };
+ bool reached = false;
+ int expanded = 0;
+ while (open.Count > 0)
+ {
+ int k = open.Dequeue();
+ if (closed[k]) continue;
+ closed[k] = true;
+ if (k == goal) { reached = true; break; }
+ if (++expanded > HoleMaxGrid) break;
+ int ci = k % nx, cj = k / nx;
+ for (int d = 0; d < 8; d++)
+ {
+ int i2 = ci + di[d], j2 = cj + dj[d];
+ if (i2 < 0 || j2 < 0 || i2 >= nx || j2 >= ny) continue;
+ int k2 = Idx(i2, j2);
+ if (closed[k2]) continue;
+ bool isGoal = k2 == goal;
+ if (!Walkable(i2, j2, height[k], isGoal, out double h2)) continue;
+ if (isGoal) height[k2] = h2;
+ // A diagonal step only between two floor samples (not across a corner of the hole).
+ if (d >= 4 && !(Walkable(ci + di[d], cj, height[k], false, out _) && Walkable(ci, cj + dj[d], height[k], false, out _))) continue;
+ double ng = g[k] + (d >= 4 ? 1.41421356 : 1.0) * HoleSample;
+ if (ng >= g[k2]) continue;
+ g[k2] = ng;
+ from[k2] = k;
+ open.Enqueue(k2, ng + HoleDist(Gx(i2), Gy(j2), bx, by));
+ }
+ }
+ if (!reached) return null;
+
+ var cells = new List();
+ for (int k = goal; k != -1; k = from[k]) cells.Add(k);
+ cells.Reverse();
+ var path = new List<(double X, double Y, double Z)>(cells.Count);
+ foreach (int k in cells) path.Add((Gx(k % nx), Gy(k / nx), height[k]));
+ path[0] = (ax, ay, az);
+ path[path.Count - 1] = (bx, by, bz);
+
+ // Pulled straight: from each point, the farthest one a straight leg reaches on the floor, clear.
+ var kept = new List<(double X, double Y, double Z)>();
+ int at = 0;
+ while (at < path.Count - 1)
+ {
+ int best = at + 1;
+ for (int j = path.Count - 1; j > at + 1; j--)
+ {
+ var p = path[at];
+ var q = path[j];
+ if (OnFloorAll(geo, p.X, p.Y, p.Z, q.X, q.Y, q.Z)
+ && geo.LegClearance(p.X, p.Y, p.Z, q.X, q.Y, q.Z, HoleKeepOff, 0.3, out _, out _, out _) >= HoleKeepOff - 0.15)
+ {
+ best = j;
+ break;
+ }
+ }
+ if (best < path.Count - 1) kept.Add(path[best]);
+ at = best;
+ }
+ return kept;
+ }
+
+ private static double HoleDist(double ax, double ay, double bx, double by) => Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs
new file mode 100644
index 0000000..dce5fc0
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs
@@ -0,0 +1,147 @@
+// DungeonPathfinder, ledges half (2026-11-15).
+//
+// A ledge is an opening between two cells whose floors, just inside it on either side, are more
+// than LedgeMeters apart. AC won't walk a character off one (it slides along the edge: only a jump
+// goes over), and nobody walks up one. DreamWeave Thread 0x0192: twelve 6 m ledges in pairs (a row of
+// pits on two levels). The explore laid a walk from 019201C4 (floor 0) to 019201C6 (floor -6), the
+// character snagged on the edge every time, and the detours (laid on the same map) never got past
+// either. IsDropEdge only sees cells stacked over each other (centres within a metre, or steeper
+// than 45 degrees centre to centre), not a ledge between two cells side by side.
+//
+// GetGeometry closes every ledge in the cached graph (both ways, as if it were a wall), so every walk
+// laid on the dungeon map (patrol, explore, dunroute, the stuck detours) goes round by the stairs. A
+// ledge whose closing would cut cells off from the rest is the only way on: it stays as it was (a jump
+// down would be needed, which the walks don't do yet) and LedgeNote names it. 0x0192: all 194 cells
+// stay reachable with its twelve ledges closed.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+
+namespace RynthCore.Plugin.RynthAi;
+
+/// An opening whose floors on either side are more than DungeonPathfinder.LedgeMeters apart.
+internal readonly record struct DungeonLedge(uint High, uint Low, double Step, double X, double Y, double Z);
+
+internal static partial class DungeonPathfinder
+{
+ /// Floors this far apart across an opening make it a ledge (well above a stair's step).
+ internal const double LedgeMeters = 1.5;
+
+ /// Off: a ledge is judged by the two cells' own floors only (tests compare).
+ internal static bool LedgeFloorFallback = true;
+
+ // The floor is looked for this far inside the opening on each side (the first that has one).
+ private static readonly double[] LedgeInsets = { 0.6, 1.0, 1.5 };
+ // ... at these heights from the opening's lowest vertex (a floor 6 m below a ledge's opening, say).
+ private static readonly double[] LedgeZRefs = { 0, 3, -3, 6, -6, 12, -12 };
+ // ... and, for a cell with no floor there, below the opening only.
+ private static readonly double[] LedgeDownRefs = { 0, -3, -6, -9, -12, -18 };
+
+ /// What closing the ledges did in the last dungeon (one line, for the build log), or null.
+ internal static string? LedgeNote;
+ internal static uint LedgeNoteLandblock;
+
+ /// Every ledge of the dungeon: each pair of cells joined by an opening whose floors just
+ /// inside it differ by more than (one entry per pair).
+ internal static List FindLedges(Dictionary graph, DungeonGeometry geo)
+ {
+ var list = new List();
+ var seen = new HashSet();
+ foreach (var n in graph.Values)
+ foreach (uint nb in n.Neighbors)
+ {
+ if (!graph.ContainsKey(nb) || !seen.Add(EdgeKey(n.CellId, nb))) continue;
+ if (!geo.TryGetDoorway(n.CellId, nb, out var d)) continue;
+ var (nx, ny) = d.NormalFrom(n.CellId); // out of n, into nb
+ double? ha = FloorInside(geo, n.CellId, d, -nx, -ny), hb = FloorInside(geo, nb, d, nx, ny);
+ if (ha is not { } a || hb is not { } b || Math.Abs(a - b) <= LedgeMeters) continue;
+ list.Add(a > b ? new DungeonLedge(n.CellId, nb, a - b, d.X, d.Y, d.Z) : new DungeonLedge(nb, n.CellId, b - a, d.X, d.Y, d.Z));
+ }
+ return list;
+ }
+
+ private static double? FloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy)
+ {
+ foreach (double inset in LedgeInsets)
+ {
+ double x = d.X + ux * inset, y = d.Y + uy * inset;
+ foreach (double dz in LedgeZRefs)
+ if (geo.TryCellFloorHeight(cell, x, y, d.Z + dz, out double h)) return h;
+ }
+ if (!LedgeFloorFallback) return null;
+ // A cell with no floor of its own there (the air of a tall room the opening looks into: Thread
+ // 0x039B's corridor at -6 opens through 0143 into a round room whose floor, at -12, is its other
+ // cells'): the floor UNDER that side, whichever cell it is. Only under it: a level above is no
+ // floor to land on (Tiny Hive's floorless tube cells found the next level's floor 5 m up).
+ foreach (double inset in LedgeInsets)
+ {
+ double x = d.X + ux * inset, y = d.Y + uy * inset;
+ foreach (double dz in LedgeDownRefs)
+ if (geo.TryFloorHeight(x, y, d.Z + dz, 0.6, out double h) && h <= d.Z + 0.6) return h;
+ }
+ return null;
+ }
+
+ ///
+ /// Closes each ledge in (both ways) unless that leaves its two cells with no
+ /// other way between them; those are returned (the only way on). The graph is changed in place.
+ ///
+ internal static List CloseLedges(Dictionary graph, IReadOnlyList ledges, out int closed)
+ {
+ closed = 0;
+ var kept = new List();
+ foreach (var l in ledges)
+ {
+ if (!graph.TryGetValue(l.High, out var hi) || !graph.TryGetValue(l.Low, out var lo)) continue;
+ int hiLinks = hi.Neighbors.RemoveAll(c => c == l.Low);
+ int loLinks = lo.Neighbors.RemoveAll(c => c == l.High);
+ if (hiLinks + loLinks == 0) continue;
+ if (Linked(graph, l.High, l.Low)) { closed++; continue; }
+ // The only way between them: put it back.
+ for (int i = 0; i < Math.Max(1, hiLinks); i++) hi.Neighbors.Add(l.Low);
+ for (int i = 0; i < Math.Max(1, loLinks); i++) lo.Neighbors.Add(l.High);
+ kept.Add(l);
+ }
+ return kept;
+ }
+
+ // a and b joined by a walk (no drop edges).
+ private static bool Linked(Dictionary graph, uint a, uint b)
+ {
+ var seen = new HashSet { a };
+ var queue = new Queue();
+ queue.Enqueue(a);
+ while (queue.Count > 0)
+ {
+ uint c = queue.Dequeue();
+ if (c == b) return true;
+ if (!graph.TryGetValue(c, out var n)) continue;
+ foreach (uint nb in n.Neighbors)
+ if (graph.TryGetValue(nb, out var o) && !IsDropEdge(n, o) && seen.Add(nb)) queue.Enqueue(nb);
+ }
+ return false;
+ }
+
+ /// GetGeometry's step: the cached graph of loses its ledges.
+ private static void CloseLedgesOf(uint landblockKey, Dictionary graph, DungeonGeometry geo)
+ {
+ try
+ {
+ var ledges = FindLedges(graph, geo);
+ LedgeNoteLandblock = landblockKey;
+ if (ledges.Count == 0) { LedgeNote = null; return; }
+ var kept = CloseLedges(graph, ledges, out int closed);
+ var inv = CultureInfo.InvariantCulture;
+ LedgeNote = string.Format(inv, "{0} ledge(s) (floors over {1:0.#} m apart across an opening): {2} closed, walked round",
+ ledges.Count, LedgeMeters, closed)
+ + (kept.Count == 0 ? "" : string.Format(inv, "; {0} left open, the only way on (a jump down is needed): {1}", kept.Count,
+ string.Join(", ", kept.Take(6).Select(k => string.Format(inv, "{0:X8}>{1:X8} {2:F1} m", k.High, k.Low, k.Step)))));
+ }
+ catch (Exception e)
+ {
+ LedgeNote = "ledges not looked at: " + e.GetType().Name;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs
index 26e1b33..64c2cc5 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs
@@ -64,6 +64,8 @@ internal sealed class PortalAvoidance
public int Moved, Dropped, Bent;
/// The character stood inside the circle when the patrol was built (led out first).
public bool StartInside;
+ /// It stood inside, and no checked spot was found to walk out to (built from where it stood).
+ public bool NoWalkOut;
/// The finished route's nearest point or leg on the portal's level (metres; +infinity: none).
public double Nearest = double.PositiveInfinity;
/// How many times the patrol was laid (1 + the rounds with cells cut off), and how long the
@@ -83,7 +85,7 @@ internal sealed class PortalAvoidance
return string.Format(inv,
"portal 0x{0:X8} '{1}' ({2:F1},{3:F1},{4:F1}) cell {5:X8}, kept {6:F1} m out: openings closed {7}{8}; points moved {9}, dropped {10}; legs bent {11}{12}; nearest {13}{14}",
p.Id, p.Name, p.X, p.Y, p.Z, p.Cell, p.Radius, closed, cut, Moved, Dropped, Bent,
- StartInside ? "; start inside it: walked out first" : "", near, Clear ? "" : " (STILL INSIDE: no way round found)")
+ StartInside ? (NoWalkOut ? "; start inside it: no clear spot to walk out to" : "; start inside it: walked out first") : "", near, Clear ? "" : " (STILL INSIDE: no way round found)")
+ string.Format(inv, " [patrol laid {0}x, {1:F0} ms, of it {2:F0} ms splitting rooms]", Laid, BuildMs, SplitMs);
}
}
@@ -130,6 +132,18 @@ internal static partial class DungeonPathfinder
Dictionary graph, uint startCell, IReadOnlySet? hazardCells,
DungeonGeometry? geo, DungeonPatrolOptions o, IReadOnlyList portals,
(double X, double Y, double Z)? startAt)
+ => LayAroundPortals(graph, startCell, hazardCells, geo, portals, startAt, o.WallClearance, loop: true,
+ g => BuildPatrolRoute(g, startCell, hazardCells, geo, o));
+
+ ///
+ /// Steps 1-3 above for any walk puts on a graph: the patrol (a loop) and the
+ /// explore (DungeonPathfinder.Explore.cs, a walk that ends). is called on the
+ /// graph without the closed openings, again for each round that cuts more off.
+ ///
+ internal static NavRouteParser LayAroundPortals(
+ Dictionary graph, uint startCell, IReadOnlySet? hazardCells,
+ DungeonGeometry? geo, IReadOnlyList portals, (double X, double Y, double Z)? startAt,
+ double wall, bool loop, Func, NavRouteParser> lay)
{
foreach (var p in portals)
{
@@ -147,10 +161,10 @@ internal static partial class DungeonPathfinder
for (int round = 0; ; round++)
{
g = WithoutOpenings(graph, closed, startCell);
- route = BuildPatrolRoute(g, startCell, hazardCells, geo, o);
+ route = lay(g);
laid++;
foreach (var r in reports) r.Moved = r.Dropped = r.Bent = 0; // the last laying's
- var unresolved = KeepOutOfPortals(route.Points, closed: true, g, geo, portals, reports, o.WallClearance);
+ var unresolved = KeepOutOfPortals(route.Points, closed: loop, g, geo, portals, reports, wall);
if (unresolved.Count == 0 || round >= PortalMaxRounds) break;
// Legs no bend gets round: cut off the cell there (never the start), and lay it again.
@@ -169,7 +183,7 @@ internal static partial class DungeonPathfinder
}
foreach (var r in reports)
{
- r.Nearest = NearestApproach(route.Points, closed: true, r.Portal);
+ r.Nearest = NearestApproach(route.Points, closed: loop, r.Portal);
r.Laid = laid;
r.BuildMs = clock.Elapsed.TotalMilliseconds;
r.SplitMs = splitMs;
@@ -550,14 +564,24 @@ internal static partial class DungeonPathfinder
}
///
- /// Where the character at (px, py, pz) walks first when it stands inside a portal's circle:
- /// straight away from the portal (else turned up to 90 degrees either way) to just past the
- /// circle's edge, on walkable floor with some clearance, out of every circle. Null when it
- /// stands in none. BuildDunPatrol builds the patrol from there (its cell, its part of a room the
+ /// Where the character at (px, py, pz) walks first when it stands inside a portal's circle: to just
+ /// past the circle's edge, on walkable floor with some clearance, reached in a straight walk through
+ /// no wall, out of every circle. Null when it stands in none, or when no such spot is found (the
+ /// patrol is then built from where it stands, and its points and legs keep out as usual).
+ /// The way out is looked for all round (every degrees, three distances),
+ /// nearest the preferred heading first: straight away from the portal; for a character standing on
+ /// the portal itself (within of its centre, where "away" is just
+ /// noise) towards the doorways of (from ), else
+ /// away. A second pass takes less clearance from the walls. 2026-11-15, DreamWeave Thread 0x00B5:
+ /// the character arrives on top of the Thread Exit in a one-cell room whose only way out is a
+ /// doorway north; the old ±90 degree search round a random heading found nothing and fell back to
+ /// an UNCHECKED spot in the wall, the character stuck on it and the stuck escape ran it through
+ /// the portal. BuildDunPatrol builds the patrol from the spot (its cell, its part of a room the
/// portal splits). Tagged "portal-lead".
///
internal static NavPoint? PortalWalkOut(DungeonGeometry? geo, IReadOnlyList portals, double px, double py, double pz,
- double wall, List? reports = null)
+ double wall, List? reports = null,
+ Dictionary? graph = null, uint startCell = 0)
{
var here = WorldPoint(px, py, pz, false);
NavPoint? result = null;
@@ -568,31 +592,72 @@ internal static partial class DungeonPathfinder
if (k < 0) break;
if (reports != null && k < reports.Count) reports[k].StartInside = true;
var p = portals[k];
- double hx = X(here), hy = Y(here), hz = here.Z * 240.0, d = Dist(hx, hy, p.X, p.Y);
- double ux = d > 0.05 ? (hx - p.X) / d : 1, uy = d > 0.05 ? (hy - p.Y) / d : 0;
- double want = p.Radius + PortalPointOut;
- double ox = p.X + ux * want, oy = p.Y + uy * want, oz = hz;
- foreach (double deg in new[] { 0.0, 20, -20, 40, -40, 60, -60, 90, -90 })
+ double hx = X(here), hy = Y(here), hz = here.Z * 240.0;
+ var spot = WalkOutSpot(geo, portals, p, hx, hy, hz, wall, graph, pass == 0 ? startCell : 0);
+ if (spot is not { } s)
{
- double a = deg * Math.PI / 180.0, c = Math.Cos(a), s = Math.Sin(a);
- double cx = p.X + (ux * c - uy * s) * want, cy = p.Y + (ux * s + uy * c) * want, cz = hz;
- if (geo != null)
- {
- if (geo.TryFloorHeight(cx, cy, hz, 1.5, out double h)) cz = h;
- if (!geo.OnWalkableFloor(cx, cy, cz) || geo.ClearanceMemo(cx, cy, cz, wall + 0.5) < Math.Min(wall, PortalCornerClearMin)) continue;
- if (geo.LegClearance(hx, hy, hz, cx, cy, cz, 1.0, 0.3, out _, out _, out _) < 0.1) continue; // through a wall
- }
- if (InsideAny(portals, cx, cy, cz)) continue;
- ox = cx; oy = cy; oz = cz;
+ // No checked spot: build from here rather than walk into a wall.
+ if (reports != null && k < reports.Count) reports[k].NoWalkOut = true;
break;
}
- here = Tag(WorldPoint(ox, oy, oz, false), "portal-lead");
+ here = Tag(WorldPoint(s.X, s.Y, s.Z, false), "portal-lead");
NotePortal(here, "out-of-portal");
result = here;
}
return result;
}
+ /// Walk-out headings are tried this many degrees apart, all round.
+ internal const double WalkOutStepDeg = 15.0;
+ /// A character this close to a portal's centre stands on it: "away from it" says nothing.
+ internal const double WalkOutOnTopMeters = 0.75;
+ // Past the circle's edge by PortalPointOut, then this much further (a doorway's mouth may be tight).
+ private static readonly double[] WalkOutExtra = { 0.0, 0.6, 1.2 };
+
+ // The spot PortalWalkOut walks to out of portal p, or null (see there).
+ private static (double X, double Y, double Z)? WalkOutSpot(DungeonGeometry? geo, IReadOnlyList portals, PatrolPortal p,
+ double hx, double hy, double hz, double wall,
+ Dictionary? graph, uint startCell)
+ {
+ double d = Dist(hx, hy, p.X, p.Y);
+ double away = d > 0.05 ? Math.Atan2(hy - p.Y, hx - p.X) : 0.0;
+ // The headings that matter, best first: away from the portal, or (standing on it) the start's doorways.
+ var prefer = new List();
+ if (d < WalkOutOnTopMeters && geo != null && graph != null && startCell != 0 && graph.TryGetValue(startCell, out var node))
+ foreach (uint nb in node.Neighbors)
+ if (geo.TryGetDoorway(startCell, nb, out var door) && SameLevel(p, door.Z) && Dist(door.X, door.Y, p.X, p.Y) > 0.05)
+ prefer.Add(Math.Atan2(door.Y - p.Y, door.X - p.X));
+ if (prefer.Count == 0) prefer.Add(away);
+
+ int steps = (int)Math.Round(360.0 / WalkOutStepDeg);
+ var headings = new List<(double Ang, double Off)>(steps);
+ for (int i = 0; i < steps; i++)
+ {
+ double ang = i * WalkOutStepDeg * Math.PI / 180.0, off = double.MaxValue;
+ foreach (double pr in prefer) off = Math.Min(off, Math.Abs(Math.IEEERemainder(ang - pr, 2 * Math.PI)));
+ headings.Add((ang, off));
+ }
+ foreach (double pr in prefer) headings.Add((pr, 0)); // each preferred heading exactly, too
+ headings.Sort((a, b) => a.Off.CompareTo(b.Off));
+
+ foreach (double clearMin in new[] { Math.Min(wall, PortalCornerClearMin), PortalLegWalkMin })
+ foreach (var (ang, _) in headings)
+ foreach (double extra in WalkOutExtra)
+ {
+ double want = p.Radius + PortalPointOut + extra;
+ double cx = p.X + Math.Cos(ang) * want, cy = p.Y + Math.Sin(ang) * want, cz = hz;
+ if (geo != null)
+ {
+ if (geo.TryFloorHeight(cx, cy, hz, 1.5, out double h)) cz = h;
+ if (!geo.OnWalkableFloor(cx, cy, cz) || geo.ClearanceMemo(cx, cy, cz, wall + 0.5) < clearMin) continue;
+ if (geo.LegClearance(hx, hy, hz, cx, cy, cz, 1.0, 0.3, out _, out _, out _) < 0.1) continue; // through a wall
+ }
+ if (InsideAny(portals, cx, cy, cz)) continue;
+ return (cx, cy, cz);
+ }
+ return null;
+ }
+
///
/// The corners to walk between (the character, or where it walked out of
/// a circle to) and the route's first point so the way there keeps out of
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
index 0d221bc..9da6433 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
@@ -73,6 +73,8 @@ internal static partial class DungeonPathfinder
private static uint _geoLandblock;
private static DungeonGeometry? _cachedGeometry;
+ // The graph instance whose ledges are closed (CloseLedgesOf).
+ private static Dictionary? _ledgesClosedOn;
///
/// The openings, floors and walls of the landblock's dungeon (cached per landblock), from
@@ -81,7 +83,13 @@ internal static partial class DungeonPathfinder
public static DungeonGeometry? GetGeometry(uint landblockKey, DatDatabase cellDat, DungeonLOS? los)
{
if (los == null) return null;
- if (_cachedGeometry != null && _geoLandblock == landblockKey) return _cachedGeometry;
+ if (_cachedGeometry != null && _geoLandblock == landblockKey)
+ {
+ // The graph may have been built again since (another landblock in between): its ledges too.
+ var g = GetGraph(landblockKey, cellDat);
+ if (!ReferenceEquals(_ledgesClosedOn, g)) { CloseMapBlocksOf(landblockKey, g, _cachedGeometry); _ledgesClosedOn = g; }
+ return _cachedGeometry;
+ }
var graph = GetGraph(landblockKey, cellDat);
var portals = new List<(uint, Vector3[])>();
var walls = new List<(uint, Vector3[])>();
@@ -102,6 +110,9 @@ internal static partial class DungeonPathfinder
}
_cachedGeometry = DungeonGeometry.Build(graph, portals, floors, walls);
_geoLandblock = landblockKey;
+ // Doorways placed objects stand across (a spider web: DungeonPathfinder.Blocked.cs), then ledges
+ // (DungeonPathfinder.Ledges.cs): closed in the cached graph, so every walk goes round them.
+ if (ReferenceEquals(graph, _cachedGraph)) { CloseMapBlocksOf(landblockKey, graph, _cachedGeometry); _ledgesClosedOn = graph; }
return _cachedGeometry;
}
@@ -189,25 +200,7 @@ internal static partial class DungeonPathfinder
foreach (uint c in mainRoute)
if (rooms.RoomOf.TryGetValue(c, out int r)) patrolRooms.Add(r);
- var adj = new Dictionary>();
- var edges = new HashSet();
- foreach (int r in patrolRooms)
- {
- foreach (uint c in rooms.Cells[r])
- {
- if (hazardCells != null && hazardCells.Contains(c)) continue;
- if (!graph.TryGetValue(c, out var cn)) continue;
- foreach (uint nb in cn.Neighbors)
- {
- if (!rooms.RoomOf.TryGetValue(nb, out int rn) || rn == r || !patrolRooms.Contains(rn)) continue;
- if (hazardCells != null && hazardCells.Contains(nb)) continue;
- if (!graph.TryGetValue(nb, out var nbn) || IsDropEdge(cn, nbn)) continue;
- if (!adj.TryGetValue(r, out var list)) adj[r] = list = new List();
- list.Add(new RoomEdge(rn, EdgeKey(c, nb), c, nb));
- edges.Add(EdgeKey(c, nb));
- }
- }
- }
+ var adj = RoomAdjacency(graph, rooms, patrolRooms, hazardCells, out var edges);
if (edges.Count == 0) return null;
// Start in the player's room if it has a doorway on the patrol, else the nearest that does.
@@ -265,6 +258,37 @@ internal static partial class DungeonPathfinder
return route;
}
+ ///
+ /// The doorways between 's rooms, both ways round (a step from cell From in
+ /// one room to cell To in the next): none into or out of a lava/acid cell, none down a drop.
+ /// : every doorway once.
+ ///
+ private static Dictionary> RoomAdjacency(
+ Dictionary graph, DungeonRooms rooms, HashSet among,
+ IReadOnlySet? hazardCells, out HashSet edges)
+ {
+ var adj = new Dictionary>();
+ edges = new HashSet();
+ foreach (int r in among)
+ {
+ foreach (uint c in rooms.Cells[r])
+ {
+ if (hazardCells != null && hazardCells.Contains(c)) continue;
+ if (!graph.TryGetValue(c, out var cn)) continue;
+ foreach (uint nb in cn.Neighbors)
+ {
+ if (!rooms.RoomOf.TryGetValue(nb, out int rn) || rn == r || !among.Contains(rn)) continue;
+ if (hazardCells != null && hazardCells.Contains(nb)) continue;
+ if (!graph.TryGetValue(nb, out var nbn) || IsDropEdge(cn, nbn)) continue;
+ if (!adj.TryGetValue(r, out var list)) adj[r] = list = new List();
+ list.Add(new RoomEdge(rn, EdgeKey(c, nb), c, nb));
+ edges.Add(EdgeKey(c, nb));
+ }
+ }
+ }
+ return adj;
+ }
+
private static bool HasUnused(Dictionary> adj, int room, HashSet remaining)
{
if (!adj.TryGetValue(room, out var list)) return false;
@@ -361,7 +385,8 @@ internal static partial class DungeonPathfinder
///
private static List EmitSteps(
Dictionary graph, DungeonGeometry geo, DungeonRooms rooms, List steps, bool closed,
- NavPoint? start, uint startCell, NavPoint? dest, uint destCell, DungeonPatrolOptions o, out int doorways)
+ NavPoint? start, uint startCell, NavPoint? dest, uint destCell, DungeonPatrolOptions o, out int doorways,
+ bool lookIn = false)
{
doorways = 0;
var pts = new List();
@@ -396,9 +421,10 @@ internal static partial class DungeonPathfinder
if (narrow) doorways++;
if (prev != null)
{
- // Only the patrol looks into rooms; a path to somewhere (dunnav, a detour) doesn't.
+ // Only the patrol and the explore (lookIn) look into rooms; a path to somewhere (dunnav,
+ // a detour) doesn't.
string? why = null;
- bool revisit = i > 0 && (closed ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach, o.LookInRoomMeters, out why) : steps[i - 1].Key == steps[i].Key);
+ bool revisit = i > 0 && (closed || lookIn ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach, o.LookInRoomMeters, out why, enterDeadEnds: lookIn && !closed) : steps[i - 1].Key == steps[i].Key);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[i].From], prev, prevCell, approach, steps[i].From, revisit, wall, why);
}
else firstApproach = approach;
@@ -531,7 +557,8 @@ internal static partial class DungeonPathfinder
// Once per room per lap: a hub room with many doorways was otherwise walked to its middle
// again every time the patrol passed between two of its doorways.
private static bool LooksIn(Dictionary graph, DungeonRooms rooms, HashSet lookedInto,
- Step inStep, Step outStep, NavPoint entered, NavPoint leaving, double lookInMeters, out string why)
+ Step inStep, Step outStep, NavPoint entered, NavPoint leaving, double lookInMeters, out string why,
+ bool enterDeadEnds = false)
{
why = "cross";
if (!rooms.RoomOf.TryGetValue(outStep.From, out int r)) return false;
@@ -539,7 +566,9 @@ internal static partial class DungeonPathfinder
bool big = spread >= lookInMeters;
bool sameDoor = inStep.Key == outStep.Key;
double skirt = NavPointYd(entered, leaving);
- bool look = (sameDoor && (big || rooms.Cells[r].Count == 1))
+ // The explore (enter and scan, 2026-11-16) walks into every dead end, small ones too: DreamWeave Thread
+ // 0x00B5's boss stood in a 6-cell dead end the walk only touched the doorway of, and was never seen.
+ bool look = (sameDoor && (big || rooms.Cells[r].Count == 1 || enterDeadEnds))
|| (big && skirt < LookInMaxSkirtMeters);
bool first = look && lookedInto.Add(r);
if (PointLog != null)
@@ -750,6 +779,7 @@ internal static partial class DungeonPathfinder
Note(mid, midCell);
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, mid, midCell, wall);
Append(pts, mid);
+ ScanMiddles?.Add(mid);
PullThrough(pts, graph, geo, rooms, cells, mid, midCell, to, toCell, wall);
NoteCrossing(pts, before, room, why ?? "look-in");
return;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs
new file mode 100644
index 0000000..22280b2
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs
@@ -0,0 +1,166 @@
+// DungeonPathfinder, straightening (2026-11-15).
+//
+// The explore's walk is laid room by room: the openings between one room's cells are string-pulled
+// (PullThrough), the doorways between rooms are taken straight on. A corridor the dungeon map splits
+// into many small rooms (DreamWeave Thread 0x00ED: zig-zag corridors of 3-5 cell rooms; 182 of the
+// walk's 334 points sat at openings) gets a point at every room boundary, and the character turned at
+// each one, 2.5-5 m apart ("the nav point does a lot of unnecessary turning", Tom).
+//
+// StraightenWalk goes over the whole walk once it is laid: from each point, the farthest point ahead
+// (at most StraightenLookAhead) that a straight leg reaches
+// - on walkable floor, keeping the walk's wall clearance, or at least as much as the legs it
+// replaces had (LegClearance: a floor edge counts as a wall, so never over a ledge or a pit), and
+// - passing through the room of every point it skips (the explore must still walk into each room
+// it was laid through).
+// Only plain waypoints are skipped, and never one in keepPoints: the middles of the rooms the explore walks
+// into (2026-11-16, enter and scan). A look into a dead end, in and out by one doorway, passes "through" the
+// room at its doorway: Thread 0x00B5's boss room lost its middle here and was only touched at the door.
+
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi;
+
+internal static partial class DungeonPathfinder
+{
+ /// Off: the walk as laid (tests compare the two).
+ internal static bool StraightenEnabled = true;
+
+ /// How many points ahead a straightened leg may reach.
+ internal const int StraightenLookAhead = 16;
+ // Samples along a leg for the rooms it passes through (metres apart).
+ private const double StraightenSampleMeters = 0.5;
+
+ ///
+ /// Straightens in place (see the file's comment). Returns how many points
+ /// were taken out.
+ ///
+ internal static int StraightenWalk(List pts, Dictionary graph, DungeonGeometry geo,
+ DungeonRooms rooms, double wall, IReadOnlyCollection? keepPoints = null)
+ {
+ var keepSet = keepPoints is { Count: > 0 } ? new HashSet(keepPoints, ReferenceEqualityComparer.Instance) : null;
+ if (pts.Count < 3 || !StraightenEnabled) return 0;
+ var cells = new uint[pts.Count];
+ for (int k = 0; k < pts.Count; k++) cells[k] = CellAt(graph, geo, pts[k]);
+ // The clearance of each leg as laid (leg k joins point k and k + 1).
+ var legClear = new double[pts.Count - 1];
+ for (int k = 0; k + 1 < pts.Count; k++) legClear[k] = LegLeast(geo, pts[k], pts[k + 1], wall, out _, out _, out _);
+
+ // The rooms each leg as laid passes through (a room can be crossed with no point in it), by
+ // either way of judging it: the straightened walk must cross each of them by both.
+ var legRooms = new HashSet[pts.Count - 1];
+ for (int k = 0; k + 1 < pts.Count; k++) legRooms[k] = RoomsAlong(pts[k], pts[k + 1], NearCells(cells, k, k + 1, graph), geo, rooms, graph, both: false);
+
+ var keep = new List(pts.Count) { pts[0] };
+ int i = 0, removed = 0;
+ while (i < pts.Count - 1)
+ {
+ int best = i + 1;
+ double least = legClear[i];
+ for (int j = i + 2; j < pts.Count && j <= i + StraightenLookAhead; j++)
+ {
+ if (!NavRouteParser.IsPlainWaypoint(pts[j - 1].Type)) break; // a special point: never skipped
+ if (keepSet != null && keepSet.Contains(pts[j - 1])) break; // a room middle the explore walks into
+ least = Math.Min(least, legClear[j - 1]);
+ if (CanStraighten(pts, cells, legRooms, i, j, graph, geo, rooms, Math.Max(PortalLegWalkMin, Math.Min(wall, least)), wall))
+ best = j;
+ }
+ removed += best - i - 1;
+ keep.Add(pts[best]);
+ i = best;
+ }
+ if (removed > 0)
+ {
+ pts.Clear();
+ pts.AddRange(keep);
+ }
+ return removed;
+ }
+
+ // The straight leg from point i to point j: clear enough, and through every room the legs it
+ // replaces passed through (the rooms of the points between included).
+ private static bool CanStraighten(List pts, uint[] cells, HashSet[] legRooms, int i, int j,
+ Dictionary graph, DungeonGeometry geo, DungeonRooms rooms,
+ double needClear, double wall)
+ {
+ if (LegLeast(geo, pts[i], pts[j], wall, out _, out _, out _) < needClear - 0.01) return false;
+ var must = new HashSet();
+ for (int k = i; k < j; k++) must.UnionWith(legRooms[k]);
+ for (int k = i + 1; k < j; k++)
+ {
+ if (cells[k] == 0 || !rooms.RoomOf.TryGetValue(cells[k], out int r)) return false;
+ must.Add(r);
+ }
+ if (must.Count == 0) return true;
+ var along = RoomsAlong(pts[i], pts[j], NearCells(cells, i, j, graph), geo, rooms, graph, both: true);
+ must.ExceptWith(along);
+ return must.Count == 0;
+ }
+
+ // The cells of points from..to and their neighbours: where a leg among them can be.
+ private static HashSet NearCells(uint[] cells, int from, int to, Dictionary graph)
+ {
+ var near = new HashSet();
+ for (int k = from; k <= to; k++)
+ {
+ uint c = cells[k];
+ if (c == 0) continue;
+ near.Add(c);
+ if (!graph.TryGetValue(c, out var n)) continue;
+ foreach (uint nb in n.Neighbors)
+ {
+ near.Add(nb);
+ if (graph.TryGetValue(nb, out var m)) foreach (uint nb2 in m.Neighbors) near.Add(nb2);
+ }
+ }
+ return near;
+ }
+
+ // The rooms the straight walk a-b passes through (sampled every StraightenSampleMeters), judged two
+ // ways: following the floor, and by the cell at the leg's straight height (CellAt, as the explore's
+ // tests do). On a ramp or a stair room the two can differ. both: crossed by both (what a new leg
+ // must manage); else by either (what a leg as laid is taken to cross).
+ private static HashSet RoomsAlong(NavPoint a, NavPoint b, HashSet near, DungeonGeometry geo, DungeonRooms rooms,
+ Dictionary graph, bool both)
+ {
+ var floor = RoomsAlongFloor(a, b, near, geo, rooms);
+ var flat = new HashSet();
+ double len = Math.Sqrt(Math.Pow(DungeonGeometry.NavToWorld(b.EW) - DungeonGeometry.NavToWorld(a.EW), 2)
+ + Math.Pow(DungeonGeometry.NavToWorld(b.NS) - DungeonGeometry.NavToWorld(a.NS), 2));
+ int n = Math.Max(1, (int)Math.Ceiling(len / StraightenSampleMeters));
+ for (int k = 0; k <= n; k++)
+ {
+ double t = (double)k / n;
+ var q = new NavPoint { NS = a.NS + (b.NS - a.NS) * t, EW = a.EW + (b.EW - a.EW) * t, Z = a.Z + (b.Z - a.Z) * t };
+ uint c = CellAt(graph, geo, q);
+ if (c != 0 && rooms.RoomOf.TryGetValue(c, out int r)) flat.Add(r);
+ }
+ if (both) floor.IntersectWith(flat); else floor.UnionWith(flat);
+ return floor;
+ }
+
+ private static HashSet RoomsAlongFloor(NavPoint a, NavPoint b, HashSet near, DungeonGeometry geo, DungeonRooms rooms)
+ {
+ var found = new HashSet();
+ double x0 = DungeonGeometry.NavToWorld(a.EW), y0 = DungeonGeometry.NavToWorld(a.NS), z0 = a.Z * 240.0;
+ double x1 = DungeonGeometry.NavToWorld(b.EW), y1 = DungeonGeometry.NavToWorld(b.NS), z1 = b.Z * 240.0;
+ double len = Math.Sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
+ int steps = Math.Max(1, (int)Math.Ceiling(len / StraightenSampleMeters));
+ double zf = z0;
+ for (int s = 0; s <= steps; s++)
+ {
+ double t = (double)s / steps, x = x0 + (x1 - x0) * t, y = y0 + (y1 - y0) * t, zl = z0 + (z1 - z0) * t;
+ if (geo.TryFloorHeight(x, y, zf, 0.6, out double h)) zf = h;
+ else if (geo.TryFloorHeight(x, y, zl, 0.6, out h)) zf = h;
+ else zf = zl;
+ foreach (uint c in near)
+ {
+ if (!geo.OnCellFloor(c, x, y, zf)) continue;
+ if (rooms.RoomOf.TryGetValue(c, out int r)) found.Add(r);
+ break;
+ }
+ }
+ return found;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
index 4cea5c6..4ca5bf3 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
@@ -96,6 +96,7 @@ internal static partial class DungeonPathfinder
_cachedLandblockKey = 0;
_cachedGeometry = null;
_geoLandblock = 0;
+ _ledgesClosedOn = null;
}
// ── Graph construction ──────────────────────────────────────────────────
@@ -527,6 +528,44 @@ internal static partial class DungeonPathfinder
/// dungeon) are left out of the patrol by default (Settings: Skip Dead Ends Up To).
internal const int PatrolMaxDeadEndCells = DungeonPatrolOptions.MaxDeadEndCellsDefault;
+ ///
+ /// The lava/acid floor cells (, the floor textures) shut the patrol in:
+ /// it stands on one, or keeping out of leaves under half of the cells
+ /// the dungeon's openings join to where it is. DreamWeave Thread 0x0199 (2026-11-16): it arrived on
+ /// lava, 14 of its cells were reachable round 9 lava cells, the explore was "done" with 8 of 75
+ /// rooms in 6 s and stopped. / : the counts.
+ ///
+ internal static bool HazardFloorsShutIn(Dictionary graph, uint start, IReadOnlySet? hazards,
+ IReadOnlyCollection? floorCells, out int reachable, out int joined)
+ {
+ reachable = joined = 0;
+ if (floorCells == null || floorCells.Count == 0 || hazards == null || hazards.Count == 0 || !graph.ContainsKey(start)) return false;
+ joined = Reach(graph, start, null);
+ reachable = Reach(graph, start, hazards);
+ bool onOne = false;
+ foreach (uint c in floorCells) if (c == start) { onOne = true; break; }
+ return onOne || reachable * 2 < joined;
+ }
+
+ // Cells reached from start through the openings, not into a cell of `keepOut` (the start always counts).
+ private static int Reach(Dictionary graph, uint start, IReadOnlySet? keepOut)
+ {
+ var seen = new HashSet { start };
+ var queue = new Queue();
+ queue.Enqueue(start);
+ while (queue.Count > 0)
+ {
+ uint c = queue.Dequeue();
+ if (!graph.TryGetValue(c, out var n)) continue;
+ foreach (uint nb in n.Neighbors)
+ {
+ if (!graph.ContainsKey(nb) || (keepOut != null && keepOut.Contains(nb)) || !seen.Add(nb)) continue;
+ queue.Enqueue(nb);
+ }
+ }
+ return seen.Count;
+ }
+
///
/// The hazard cells the patrol keeps out of: (the live set: floor
/// textures, pools sighted, cells marked by hand), less the lava/acid floor cells
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
index 0726452..4ccddd1 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
@@ -16,6 +16,14 @@ internal sealed class LegacyAdvancedSettingsUi
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
+ /// Loot Nearby Chests' tooltip (the engine's Settings row says the same).
+ internal const string NearbyChestsTooltip =
+ "While the macro runs with Looting on and you're not fighting, walks to a chest within loot range\n" +
+ "(Corpse Max range), opens it and loots it by your loot profile, then leaves it alone until it resets\n" +
+ "(it locks again, or the chest relock wait passes). A locked chest: a key you carry that fits is used;\n" +
+ "else a lockpick, if your Lockpick skill gives you at least 50% against its lock; else it's skipped\n" +
+ "and tried again in 10 minutes. Corpses come first. Off by default. Status: /ra chests.";
+
///
/// The environment-impact throttle's shared numbers (one set for missiles and magic), drawn
/// under each response combo. keeps the two copies' ImGui ids apart.
@@ -1150,6 +1158,9 @@ internal sealed class LegacyAdvancedSettingsUi
"RynthAi closes the chest when it's done (some chests lock again on close).");
ImGui.Unindent();
}
+ ImGui.Checkbox("Loot Nearby Chests", ref _settings.LootNearbyChests);
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(NearbyChestsTooltip);
ImGui.Checkbox("Jump When Looting", ref _settings.LootJumpEnabled);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Hop (the keyboard jump) just before each pickup, so the server skips the\n" +
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
index fc41557..7978c56 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
@@ -1466,6 +1466,7 @@ internal sealed partial class LegacyDashboardRenderer
LootJumpEnabled = s.LootJumpEnabled,
LootChestsMacroOff = s.LootChestsMacroOff,
LootChestsMacroOffLeaveOpen = s.LootChestsMacroOffLeaveOpen,
+ LootNearbyChests = s.LootNearbyChests,
ChestRelockWaitSec = s.ChestRelockWaitSec,
LootJumpHeight = s.LootJumpHeight,
LootOwnership = s.LootOwnership,
@@ -1759,6 +1760,7 @@ internal sealed partial class LegacyDashboardRenderer
s.LootJumpEnabled = p.LootJumpEnabled;
s.LootChestsMacroOff = p.LootChestsMacroOff;
s.LootChestsMacroOffLeaveOpen = p.LootChestsMacroOffLeaveOpen;
+ if (p.LootNearbyChests is bool nearbyChests) s.LootNearbyChests = nearbyChests; // absent = unchanged
if (p.ChestRelockWaitSec is int relockSec) s.ChestRelockWaitSec = ItemTool.ChestKeyLooter.ClampRelockWaitSec(relockSec); // absent = unchanged
s.LootJumpHeight = p.LootJumpHeight;
s.LootOwnership = p.LootOwnership;
@@ -2158,6 +2160,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.LootJumpEnabled = tmp.LootJumpEnabled;
dst.LootChestsMacroOff = tmp.LootChestsMacroOff;
dst.LootChestsMacroOffLeaveOpen = tmp.LootChestsMacroOffLeaveOpen;
+ dst.LootNearbyChests = tmp.LootNearbyChests;
dst.ChestRelockWaitSec = ItemTool.ChestKeyLooter.ClampRelockWaitSec(tmp.ChestRelockWaitSec);
dst.LootJumpHeight = tmp.LootJumpHeight;
dst.SalvageOpenDelayFirstMs = tmp.SalvageOpenDelayFirstMs;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
index 75bf20a..4e57501 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
@@ -176,6 +176,13 @@ public sealed class LegacyUiSettings
///
public bool LootChestsMacroOffLeaveOpen = false;
///
+ /// Loot Nearby Chests (2026-11-14, off by default): while the macro runs with Looting on and no
+ /// fight, a chest within loot range is walked to, opened and looted by the loot profile, then
+ /// left alone until it resets. A locked one: a carried key that fits, else a lockpick when the
+ /// Lockpick skill is good enough, else skipped for 10 minutes. NearbyChestLooter.cs.
+ ///
+ public bool LootNearbyChests = false;
+ ///
/// Item Tool > Chest re-lock wait (s) (2026-11-05): the chest looter's next key goes on the chest
/// this long after it was opened (sooner when the client reads it locked again). 125 s covers ACE's
/// default chest reset (120 s); a chest with a shorter timer can use less. 5..600
@@ -1557,6 +1564,7 @@ public sealed class SettingsBridgePayload
public bool LootJumpEnabled { get; set; }
public bool LootChestsMacroOff { get; set; } = true; // an engine that doesn't know it leaves it on
public bool LootChestsMacroOffLeaveOpen { get; set; } // off: an engine that doesn't know it closes, as before
+ public bool? LootNearbyChests { get; set; } // Loot Nearby Chests; absent (an engine without the row) = unchanged
public int? ChestRelockWaitSec { get; set; } // Item Tool's re-lock wait; absent (the engine has no row for it) = unchanged
public int LootJumpHeight { get; set; }
public int LootOwnership { get; set; }
diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
index 064779d..9c7917b 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
@@ -253,6 +253,7 @@ public sealed partial class RynthAiPlugin
["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off
["lootchestsmacrooff"] = "LootChestsMacroOff",
["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls
+ ["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
["switchwandstodebuff"] = "UseDispelItems",
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
index 7101b69..7368948 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
@@ -226,6 +226,15 @@ internal sealed partial class ExpressionEngine
// keeps opening it until this is its id: an open use can go unanswered, and a chest can close mid-loot.
internal Func? LastChestLooted { get; set; }
+ // radunexplore[], radunexplorerooms[], radunexplorevisited[] (RynthAi only, 2026-11-13): the dungeon
+ // explore (/ra dunnav-explore). State 0 none yet, 1 exploring, 2 paused (macro or navigation off),
+ // 3 done (its walk ended), 4 stopped (stopped, another route, left the dungeon); the rooms it means to
+ // walk through and those entered so far (both 0 before the first). Lua reads them with rynth.ai.Evaluate.
+ internal Func<(int State, int Rooms, int Visited)>? DunExploreStatus { get; set; }
+ // radunexploreinfo[]: the explore as JSON (state, rooms, the shut doors and the rooms behind each, the
+ // lever errand, the last lever's result), "{}" before the first. For the Lua script's json.decode.
+ internal Func? DunExploreInfo { get; set; }
+
// ── Backward-compat shim ──────────────────────────────────────────────────
/// Executes an expression for its side effects. Always returns true.
@@ -409,6 +418,10 @@ internal sealed partial class ExpressionEngine
"secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture),
"ratargetcount" => (CombatTargetCount?.Invoke() ?? -1).ToString(CultureInfo.InvariantCulture),
"ralastchestlooted" => (LastChestLooted?.Invoke() ?? 0u).ToString(CultureInfo.InvariantCulture),
+ "radunexplore" => (DunExploreStatus?.Invoke().State ?? 0).ToString(CultureInfo.InvariantCulture),
+ "radunexplorerooms" => (DunExploreStatus?.Invoke().Rooms ?? 0).ToString(CultureInfo.InvariantCulture),
+ "radunexplorevisited" => (DunExploreStatus?.Invoke().Visited ?? 0).ToString(CultureInfo.InvariantCulture),
+ "radunexploreinfo" => DunExploreInfo?.Invoke() ?? "{}",
// ── World object queries ──────────────────────────────────────────
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),
@@ -3793,6 +3806,7 @@ internal sealed partial class ExpressionEngine
["BoostNavPriority"] = (() => B(s.BoostNavPriority), v => s.BoostNavPriority = ToDouble(v) != 0),
["BoostLootPriority"] = (() => B(s.BoostLootPriority), v => s.BoostLootPriority = ToDouble(v) != 0),
["LootChestsMacroOff"] = (() => B(s.LootChestsMacroOff), v => s.LootChestsMacroOff = ToDouble(v) != 0),
+ ["LootNearbyChests"] = (() => B(s.LootNearbyChests), v => s.LootNearbyChests = ToDouble(v) != 0),
};
return _settingsMap;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
index d756098..8aae30a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
@@ -230,6 +230,16 @@ internal sealed partial class MetaManager
if (_expressions != null) _expressions.LastChestLooted = lastChest;
}
+ // The dungeon explore's state and rooms, for radunexplore[] / radunexplorerooms[] / radunexplorevisited[].
+ private Func<(int State, int Rooms, int Visited)>? _dunExploreStatus;
+ private Func? _dunExploreInfo;
+ public void SetDunExploreStatus(Func<(int State, int Rooms, int Visited)>? status, Func? info = null)
+ {
+ _dunExploreStatus = status;
+ _dunExploreInfo = info;
+ if (_expressions != null) { _expressions.DunExploreStatus = status; _expressions.DunExploreInfo = info; }
+ }
+
public void SetPlayerId(uint id)
{
_playerId = id;
@@ -352,6 +362,8 @@ internal sealed partial class MetaManager
engine.CorpseOpenedByMe = _corpseOpenedByMe;
engine.CombatTargetCount = _combatTargetCount;
engine.LastChestLooted = _lastChestLooted;
+ engine.DunExploreStatus = _dunExploreStatus;
+ engine.DunExploreInfo = _dunExploreInfo;
// vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does.
engine.VtOptionSetter = TrySetVtOption;
engine.VtOptionGetter = GetVtOption;
@@ -1599,6 +1611,7 @@ internal sealed partial class MetaManager
["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off
["lootchestsmacrooff"] = "LootChestsMacroOff",
["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls
+ ["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
["switchwandstodebuff"] = "UseDispelItems",
diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs
index 7069216..5a32fe1 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
@@ -190,6 +191,11 @@ internal sealed class NavigationEngine
private double OffTrackYards => Math.Max(OffTrackMinYards, _settings.NavOffTrackYards);
private int MaxDetourAttempts => Math.Clamp(_settings.NavMaxDetourAttempts, 1, 10);
+ /// Every detour for the current waypoint has been tried and the character is still stuck there
+ /// (only the escapes are left, for as long as it takes): the dungeon explore takes this as a way it can't
+ /// get through, something the map doesn't have standing in it (a spider web spawned in a doorway).
+ public bool DetoursUsedUpAndStuck => _detour == null && _detourAttempts >= MaxDetourAttempts && _stuckCount >= 2;
+
private INavRecoveryPlanner? _planner;
private Detour? _detour;
private int _detourAttempts; // detours tried (or failed to plan) for the current waypoint
@@ -2387,6 +2393,85 @@ internal sealed class NavigationEngine
_watchdogEw = ew;
}
+ // ── Escapes and portals (2026-11-15) ────────────────────────────────────
+ // DreamWeave Thread 0x00B5: the character arrives on the Thread Exit; stuck on a bad first point
+ // beside it, the +75 degree burst ran it through the portal and out of the Thread, twice. A portal
+ // fires the moment the character touches it, so every burst heading is checked against the
+ // portals near before it is run.
+
+ /// The portals near the character (world x east, y north, z), for the stuck escapes; null or
+ /// empty: none known. RynthAiPlugin sets it (the landscape's portals within EscapePortalRangeMeters).
+ public Func>? EscapePortals { get; set; }
+
+ /// Portals farther than this are left out of the escape check.
+ internal const double EscapePortalRangeMeters = 25.0;
+ /// How far a burst can carry the character (RecoveryBurstMs at a run, rounded well up).
+ internal const double EscapeBurstMeters = 7.0;
+ /// A burst keeps at least this far from a portal (DungeonPathfinder.PortalKeepOutDefault).
+ internal const double EscapePortalKeepMeters = DungeonPathfinder.PortalKeepOutDefault;
+ private const double EscapePortalLevelMeters = DungeonPathfinder.PortalLevelBand;
+ // Tried after the rung's own heading, in this order.
+ private static readonly double[] EscapeFallbackDeg = { +SideStepDeg, -SideStepDeg, BackOutDeg, -BackOutDeg, +120, -120, +40, -40, +100, -100, +20, -20 };
+
+ ///
+ /// Keeps the escape burst at heading curDeg + offset away from every portal near: true with
+ /// left alone when it is clear (note null), or changed to the first
+ /// fallback that is (note says so); false when every heading runs at one (note: the portal).
+ /// A burst is clear when, over its EscapeBurstMeters, it never comes nearer a portal on its level
+ /// than EscapePortalKeepMeters, or (the character already that near) than it is now.
+ ///
+ internal bool PortalSafeEscapeOffset(double curDeg, ref double offset, out string? note)
+ {
+ note = null;
+ var near = EscapePortals?.Invoke();
+ if (near == null || near.Count == 0) return true;
+ if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || cell == 0) return true;
+ double px = ((cell >> 24) & 0xFF) * 192.0 + lx, py = ((cell >> 16) & 0xFF) * 192.0 + ly;
+ return EscapeOffsetClear(px, py, lz, curDeg, near, ref offset, out note);
+ }
+
+ /// The pure half of (world position given).
+ internal static bool EscapeOffsetClear(double px, double py, double pz, double curDeg,
+ IReadOnlyList<(double X, double Y, double Z)> portals, ref double offset, out string? note)
+ {
+ note = null;
+ double first = offset;
+ string? worst = null;
+ foreach (double off in new[] { first }.Concat(EscapeFallbackDeg.Where(f => Math.Abs(f - first) > 0.01)))
+ {
+ double h = (curDeg + off) * Math.PI / 180.0;
+ double ex = px + Math.Sin(h) * EscapeBurstMeters, ey = py + Math.Cos(h) * EscapeBurstMeters; // 0 = north, clockwise
+ bool clear = true;
+ foreach (var p in portals)
+ {
+ if (Math.Abs(p.Z - pz) > EscapePortalLevelMeters) continue;
+ double now = Math.Sqrt((p.X - px) * (p.X - px) + (p.Y - py) * (p.Y - py));
+ double keep = Math.Min(EscapePortalKeepMeters, now) - 0.05;
+ if (SegmentDistance(px, py, ex, ey, p.X, p.Y) < keep)
+ {
+ clear = false;
+ worst ??= $"portal at ({p.X:F1},{p.Y:F1}) {now:F1} m away";
+ break;
+ }
+ }
+ if (!clear) continue;
+ if (Math.Abs(off - first) > 0.01)
+ note = $"escape burst turned {off:+0;-0}° instead of {first:+0;-0}° (that way runs at the {worst})";
+ offset = off;
+ return true;
+ }
+ note = worst;
+ return false;
+ }
+
+ private static double SegmentDistance(double ax, double ay, double bx, double by, double x, double y)
+ {
+ double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
+ double t = l2 < 1e-12 ? 0 : Math.Clamp(((x - ax) * dx + (y - ay) * dy) / l2, 0, 1);
+ double cx = ax + dx * t - x, cy = ay + dy * t - y;
+ return Math.Sqrt(cx * cx + cy * cy);
+ }
+
private void BeginRecovery(NavRouteParser route)
{
// The waypoint is in another area: no detour or escape can reach it, and
@@ -2439,6 +2524,19 @@ internal sealed class NavigationEngine
_ => BackOutDeg,
};
+ // A burst must not run the character into a portal (it fires on touch): the rung's heading if
+ // it keeps away from every portal near, else the nearest one that does; none: the jump instead.
+ if (!PortalSafeEscapeOffset(curDeg, ref offset, out string? portalNote))
+ {
+ _host.Log($"Nav: stuck x{_stuckCount} — every escape heading runs at a portal ({portalNote}): jumping instead.");
+ _recoveryKind = RecoveryKind.Jump;
+ _recoveryUntil = Now + (long)RecoveryMs;
+ _inRecovery = true;
+ _host.JumpNonAutonomous(0.5f);
+ return;
+ }
+ if (portalNote != null) _host.Log($"Nav: stuck x{_stuckCount} — {portalNote}.");
+
double escapeHeading = curDeg + offset;
if (escapeHeading >= 360.0) escapeHeading -= 360.0; else if (escapeHeading < 0.0) escapeHeading += 360.0;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/NearbyChestLooter.cs b/Plugins/RynthCore.Plugin.RynthAi/NearbyChestLooter.cs
new file mode 100644
index 0000000..83923f2
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/NearbyChestLooter.cs
@@ -0,0 +1,790 @@
+// ============================================================================
+// NearbyChestLooter.cs - Loot Nearby Chests (2026-11-14).
+//
+// The owner's words: while the macro runs, Looting is on and he isn't fighting, the character
+// walks to a chest within loot range, opens it and loots it by the current loot profile. Then it
+// leaves the chest alone until it respawns or relocks. A locked chest: a carried key that fits is
+// used; else, with a lockpick and a Lockpick skill good enough for that chest, it is picked; else
+// it is skipped and tried again in about 10 minutes. Off by default (LootNearbyChests).
+//
+// A pure state machine: everything it touches goes through INearbyChestEnv (the plugin implements
+// it in RynthAiPlugin.NearbyChests.cs; the host tests fake it). It never walks: every step is a
+// use the server answers, and ACE walks the character to the chest first for each of them
+// (Player.HandleActionUseItem / HandleActionUseWithTarget -> CreateMoveToChain), the way the
+// corpse looter's far open works. Once the chest's ViewContents arrives, the corpse looter takes
+// the open chest as its loot container (RynthAiPlugin.ChestLoot.cs: the loot profile's rules, the
+// same TickOpenCorpseLooting as a corpse) and this waits for it to finish.
+//
+// One chest:
+// Appraise - an ID of the chest (one request), for its lock: PropertyBool Locked (3),
+// ResistLockpick (int 38) and the server's own AppraisalLockpickSuccessPercent
+// (int 173), all three AssessmentProperty in ACE (AppraiseInfo.cs 135-163).
+// Key - a locked chest: each carried key not yet tried on it, one at a time. The client
+// can't know up front which key fits: a key's KeyCode and a chest's LockCode
+// (PropertyString 13/12) are not sent to clients (no AssessmentProperty,
+// PropertyString.cs 30-31). So a key is tried and the server's answer decides:
+// 0 = unlocked (one use spent), 0x4AF already unlocked, 0x4B2 KeyDoesntFitThisLock
+// (nothing spent: LockHelper.Unlock returns IncorrectKey, Lock.cs 248-281).
+// At most MaxKeyTries keys per chest per attempt; a key that didn't fit is never
+// tried on that chest again.
+// Pick - no key fitted: a lockpick, when the Lockpick skill is good enough (CanPick).
+// ACE's roll (LockHelper.Unlock, Lock.cs 282-313) is SkillCheck.GetSkillChance(
+// skill, ResistLockpick) = 1 - 1/(1 + e^(0.03 (skill - resist))) (SkillCheck.cs 7).
+// "Good enough" = at least MinPickPercent (50 %, skill >= resistance). A failed
+// pick spends one use of the lockpick, so at most MaxPicks a chest per attempt.
+// Open - the chest is used; its ViewContents is the proof.
+// Looting - the corpse looter has the open chest; this waits for it to let go.
+// Then the chest is Done (left alone) until it leaves the world, reads locked again, or the
+// re-lock wait passes (the Item Tool's "Chest re-lock wait (s)", 125 s: ACE's Chest.Reset runs
+// ResetInterval, default 120 s, after the open; it re-locks a DefaultLocked chest and
+// regenerates its contents, Chest.cs 184-266). A chest that was locked is appraised before it is
+// used again: still unlocked means it hasn't reset, so it waits another round without a use.
+// Skipped (no key fits, can't pick, won't open...): tried again after SkipMs (10 minutes).
+//
+// Never spams the server: one request at a time, each waits for its answer (UseDone / the ID),
+// nothing goes out while HoldReason says so (the arbiter's turn, a busy client, a pending action),
+// and every step is bounded.
+// ============================================================================
+
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+namespace RynthCore.Plugin.RynthAi;
+
+/// A chest in loot range that may be looted (the host has checked what it is).
+internal readonly record struct NearbyChest(int Id, string Name, double Meters);
+
+/// A carried key or lockpick.
+internal readonly record struct ChestTool(int Id, string Name);
+
+internal interface INearbyChestEnv
+{
+ long Now { get; }
+ /// The setting is on and the bot may loot chests now (macro, Looting, nothing else owns chests).
+ bool Enabled { get; }
+ /// A fight is on (combat has targets in range): no chest is started, one not yet sent to is dropped.
+ bool Fighting { get; }
+ /// Eligible chests in loot range now (not house storage, a vendor, a corpse, a player or a pack).
+ IReadOnlyList ScanChests();
+ /// The object is still in the client's world.
+ bool InWorld(int id);
+ /// The chest is still a chest to loot and within reach (the loot range, with slack).
+ bool StillEligible(int id, out string why);
+ /// Why nothing may be sent now (null = free).
+ string? HoldReason();
+
+ // The chest's lock, as the client reads it.
+ bool CanAppraise { get; }
+ bool RequestAppraisal(int chestId);
+ /// Changes when appraisal data for the object arrives (0 = none yet).
+ long AppraisalStamp(int chestId);
+ bool? Locked(int chestId);
+ int? LockResistance(int chestId);
+ int? PickSuccessPercent(int chestId);
+
+ // The character.
+ /// Lockpick skill (buffed) and whether it is trained; false = unreadable.
+ bool LockpickSkill(out int buffed, out bool trained);
+ IReadOnlyList Keys();
+ ChestTool? Lockpick();
+
+ // The server.
+ bool HasUseDone { get; }
+ int UseDoneSeq();
+ bool LastUseDone(out int seq, out uint error);
+ bool SendUseWith(int toolId, int chestId, string why);
+ bool SendOpen(int chestId);
+ /// When the server last opened this chest for us (its ViewContents); 0 = not seen.
+ long OpenedAt(int chestId);
+ /// The corpse looter has the chest (open and being looted, or about to be taken).
+ bool Looting(int chestId);
+ void Log(string text);
+}
+
+internal sealed class NearbyChestLooter
+{
+ public enum Phase { Idle, Appraise, AppraiseOut, Key, KeyOut, Pick, PickOut, Open, OpenOut, Looting }
+
+ // ACE WeenieError codes (WeenieError.cs; UnlockerHelper.UseUnlocker, Lock.cs 119-196).
+ internal const uint ErrTooBusy = 0x1D, ErrLockAlreadyUnlocked = 0x4AF, ErrCannotLockOrUnlock = 0x4B0,
+ ErrCannotLockWhatIsOpen = 0x4B1, ErrKeyDoesntFit = 0x4B2, ErrNotTrainedInLockpicking = 0x4B4,
+ ErrCannotUseThatItem = 0x58D;
+
+ /// A skipped chest (no key fits, can't pick it, won't open) is tried again after this.
+ public const long SkipMs = 600_000;
+ /// "Skill good enough": the chance ACE rolls is at least this (50 % = skill equal to the lock's resistance).
+ public const int MinPickPercent = 50;
+ /// Lockpick uses per chest per attempt (each failed pick spends one use of the lockpick).
+ public const int MaxPicks = 3;
+ /// ... when the lock's resistance can't be read (no appraisal): a couple of tries, then skip.
+ public const int MaxPicksUnknown = 2;
+ /// Different keys tried on one chest per attempt.
+ public const int MaxKeyTries = 4;
+ /// A use waits this long for the server's answer (the walk to the chest is part of it).
+ public const long AnswerMaxMs = 12_000;
+ /// The chest's appraisal gets this long.
+ public const long AppraiseMaxMs = 4_000;
+ /// After an answer, the chat line / lock update that goes with it gets this long.
+ public const long SettleMs = 300;
+ /// After the open's answer, the chest gets this long to show its contents.
+ public const long OpenSettleMs = 1_500;
+ /// The corpse looter has this long to take the open chest, and the loot this long at most.
+ public const long LootStartMs = 8_000, LootMaxMs = 300_000;
+ /// A chest that reads locked again this soon after its open is a candidate again.
+ public const long MinRelockMs = 15_000;
+ /// Between scans for a new chest.
+ public const long ScanMs = 500;
+ /// Nothing could be sent this long (the server busy, the turn elsewhere): the chest is dropped for now.
+ public const long HoldMaxMs = 30_000;
+ public const int MaxTimeouts = 2, MaxBusy = 3, MaxOpenFails = 2;
+
+ private static readonly Regex PickedText = new(@"successfully picked the lock", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
+ private static readonly Regex PickFailedText = new(@"failed to pick the lock", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
+ private static readonly Regex KeyUnlockedText = new(@"\bhas been unlocked\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
+
+ private readonly INearbyChestEnv _env;
+ public NearbyChestLooter(INearbyChestEnv env) => _env = env;
+
+ /// "Chest re-lock wait (s)" (the host sets it from the settings): a looted chest is left this long at most.
+ public int RelockWaitSec { get; set; } = ItemTool.ChestKeyLooter.DefaultRelockWaitSec;
+ private long RelockWaitMs => ItemTool.ChestKeyLooter.ClampRelockWaitSec(RelockWaitSec) * 1000L;
+
+ public Phase State { get; private set; } = Phase.Idle;
+ public int ChestId { get; private set; }
+ public string ChestName { get; private set; } = "";
+ /// Past picking: a request is out or the chest is being opened/looted (the corpse looter must wait).
+ public bool Busy => State != Phase.Idle;
+ public int Looted { get; private set; }
+ public string LastResult { get; private set; } = "";
+
+ // ── Which objects are chests ──────────────────────────────────────────
+
+ internal const uint BfStuck = 0x00000004, BfPlayer = 0x00000008, BfVendor = 0x00000200, BfDoor = 0x00001000, BfCorpse = 0x00002000;
+
+ ///
+ /// Why an object in loot range is not a chest to walk to and loot (null = it is one). A chest is
+ /// a container lying in the world that can't be picked up: ACE's chests are Stuck (the
+ /// PublicWeenieDesc bitfield's 0x4); a pack someone dropped is not, so it is never looted here.
+ /// Never a corpse (the corpse looter's), a vendor, a player, a door, house storage (HouseOwner,
+ /// or named Storage / a hook, as RynthAiPlugin.ChestLoot.cs's JudgeChest), or anything held.
+ ///
+ internal static string? ChestRefusal(RynthCore.Loot.AcObjectClass cls, bool bitfieldKnown, uint bitfield,
+ uint houseOwner, string? name, bool ownershipKnown, uint container, uint wielder)
+ {
+ if (cls == RynthCore.Loot.AcObjectClass.Corpse) return "a corpse";
+ if (cls != RynthCore.Loot.AcObjectClass.Container) return "not a container";
+ if (!bitfieldKnown) return "the engine can't tell a chest from a dropped pack";
+ if ((bitfield & BfCorpse) != 0) return "a corpse";
+ if ((bitfield & BfVendor) != 0) return "a vendor";
+ if ((bitfield & BfPlayer) != 0) return "a player";
+ if ((bitfield & BfDoor) != 0) return "a door";
+ if (houseOwner != 0) return $"house storage (house owner 0x{houseOwner:X8})";
+ if (RynthAiPlugin.IsHouseStorageName(name)) return $"house storage (named '{name}')";
+ if ((bitfield & BfStuck) == 0) return "it can be picked up (a pack, not a chest)";
+ if (!ownershipKnown) return "who holds it isn't readable";
+ if (container != 0 || wielder != 0) return "someone holds it";
+ return null;
+ }
+
+ // ── What happened to each chest ────────────────────────────────────────
+
+ private sealed class Memory
+ {
+ public string Name = "";
+ public long LeaveUntil; // left alone until then (Done or Skipped)
+ public bool Done; // looted (else skipped)
+ public bool WasLocked; // it was locked when we got to it: it is ready again when it re-locks
+ public long OpenedAt;
+ public string Why = "";
+ public readonly HashSet KeysThatDontFit = new(StringComparer.OrdinalIgnoreCase);
+ }
+
+ private readonly Dictionary _memory = new();
+
+ /// The chest is being left alone now (looted and not reset yet, or skipped).
+ public bool IsLeftAlone(int id, long now)
+ {
+ if (!_memory.TryGetValue(id, out var m) || now >= m.LeaveUntil) return false;
+ // Looted and locked when we found it: ready again as soon as it reads locked (it has reset).
+ if (m.Done && m.WasLocked && now - m.OpenedAt >= MinRelockMs && _env.Locked(id) == true) return false;
+ return true;
+ }
+
+ /// For the status line: the chests left alone and why.
+ public IEnumerable<(int Id, string Name, bool Done, long LeftMs, string Why)> LeftAlone()
+ {
+ long now = _env.Now;
+ foreach (var (id, m) in _memory)
+ if (IsLeftAlone(id, now))
+ yield return (id, m.Name, m.Done, m.LeaveUntil - now, m.Why);
+ }
+
+ private Memory Mem(int id)
+ {
+ if (!_memory.TryGetValue(id, out var m)) _memory[id] = m = new Memory();
+ return m;
+ }
+
+ // ── The current chest ─────────────────────────────────────────────────
+
+ private long _lastScan, _sentAt, _answeredAt, _phaseSince, _holdSince, _appraiseStamp, _lootStartedAt;
+ private int _seqAtSend, _toolId, _keyTries, _picks, _pickLimit, _timeouts, _busy, _openFails;
+ private string _toolName = "";
+ private bool _answered, _unlocked, _triedUnlock, _lockedAtStart, _appraisedFresh, _pickedSaid, _pickFailSaid, _keyUnlockSaid, _lootSeen;
+ private uint _answerErr;
+ private int _fightLoggedFor;
+
+ /// A chest to start on now (HasLootWork asks): nearest eligible one not left alone. 0 = none.
+ public int Candidate()
+ {
+ if (!_env.Enabled || _env.Fighting) return 0;
+ if (Busy) return ChestId;
+ long now = _env.Now;
+ if (now - _lastScan < ScanMs && _pick == 0) return 0;
+ if (now - _lastScan >= ScanMs)
+ {
+ _lastScan = now;
+ Prune();
+ _pick = 0;
+ double best = double.MaxValue;
+ foreach (var c in _env.ScanChests())
+ {
+ if (IsLeftAlone(c.Id, now) || c.Meters >= best) continue;
+ _pick = c.Id;
+ _pickName = c.Name;
+ best = c.Meters;
+ }
+ }
+ else if (_pick != 0 && IsLeftAlone(_pick, now)) _pick = 0;
+ return _pick;
+ }
+
+ private int _pick;
+ private string _pickName = "";
+
+ private void Prune()
+ {
+ List? gone = null;
+ foreach (int id in _memory.Keys)
+ if (!_env.InWorld(id)) (gone ??= new()).Add(id);
+ if (gone == null) return;
+ foreach (int id in gone)
+ {
+ _memory.Remove(id);
+ _env.Log($"[RynthAi] Nearby chests: chest 0x{(uint)id:X8} left the world; forgotten (a new one is looted when it comes).");
+ }
+ }
+
+ /// The setting went off, the macro stopped, Looting went off...: drop the chest (nothing is marked).
+ public void StandDown(string why)
+ {
+ if (State == Phase.Idle) { _pick = 0; return; }
+ _env.Log($"[RynthAi] Nearby chests: stopped on chest 0x{(uint)ChestId:X8} '{ChestName}' - {why}; it will be tried again.");
+ Reset();
+ _pick = 0;
+ }
+
+ private void Reset()
+ {
+ State = Phase.Idle;
+ ChestId = 0;
+ ChestName = "";
+ _holdSince = 0;
+ }
+
+ /// A server chat line (the lockpick's and the key's answers).
+ public void OnChat(string? text)
+ {
+ if (State is not (Phase.KeyOut or Phase.PickOut) || string.IsNullOrEmpty(text) || text.Length > 200) return;
+ if (PickedText.IsMatch(text)) _pickedSaid = true;
+ else if (PickFailedText.IsMatch(text)) _pickFailSaid = true;
+ else if (KeyUnlockedText.IsMatch(text)) _keyUnlockSaid = true;
+ }
+
+ ///
+ /// Every loot tick, whoever has the tick (answers and timeouts are read even while a fight holds
+ /// the sends). : a new chest may be started (the host passes true only
+ /// where no corpse is waiting: corpses go first).
+ ///
+ public void Tick(bool mayStart = false)
+ {
+ long now = _env.Now;
+ if (State == Phase.Idle)
+ {
+ if (!mayStart) return;
+ int id = Candidate();
+ if (id == 0) return;
+ if (_env.HoldReason() != null) return; // its turn has not come yet (nothing is claimed)
+ Begin(id, _pickName, now);
+ }
+
+ if (!_env.InWorld(ChestId)) { Leave(now, "it left the world", skip: false); return; }
+
+ // A fight: a chest nothing has been sent to is dropped (picked again when the fight is over);
+ // an answer that is owed is waited for, and the corpse looter decides about an open chest.
+ if (_env.Fighting && State is Phase.Appraise or Phase.Key or Phase.Pick or Phase.Open)
+ {
+ if (_fightLoggedFor != ChestId)
+ {
+ _fightLoggedFor = ChestId;
+ _env.Log($"[RynthAi] Nearby chests: leaving chest 0x{(uint)ChestId:X8} '{ChestName}' for the fight; it is tried again when the fight is over.");
+ }
+ Reset();
+ return;
+ }
+ if (State is Phase.Appraise or Phase.Key or Phase.Pick or Phase.Open && !_env.StillEligible(ChestId, out string why))
+ {
+ Leave(now, why, skip: false);
+ return;
+ }
+
+ switch (State)
+ {
+ case Phase.Appraise: TickAppraise(now); break;
+ case Phase.AppraiseOut: TickAppraiseOut(now); break;
+ case Phase.Key: TickKey(now); break;
+ case Phase.KeyOut: TickKeyOut(now); break;
+ case Phase.Pick: TickPick(now); break;
+ case Phase.PickOut: TickPickOut(now); break;
+ case Phase.Open: TickOpen(now); break;
+ case Phase.OpenOut: TickOpenOut(now); break;
+ case Phase.Looting: TickLooting(now); break;
+ }
+ }
+
+ private void Begin(int id, string name, long now)
+ {
+ ChestId = id;
+ ChestName = name.Length > 0 ? name : "the chest";
+ _keyTries = _picks = _timeouts = _busy = _openFails = 0;
+ _pickLimit = 0;
+ _unlocked = _triedUnlock = _lockedAtStart = _appraisedFresh = false;
+ _holdSince = 0;
+ _pick = 0;
+ Mem(id).Name = ChestName;
+ _env.Log($"[RynthAi] Nearby chests: going to chest 0x{(uint)id:X8} '{ChestName}' (in loot range, not looted since it last reset).");
+ Enter(_env.CanAppraise ? Phase.Appraise : Phase.Open, now);
+ }
+
+ private void Enter(Phase p, long now)
+ {
+ State = p;
+ _phaseSince = now;
+ _holdSince = 0;
+ }
+
+ /// True while nothing may go out; the chest is dropped (not marked) after HoldMaxMs of it.
+ private bool Held(long now)
+ {
+ string? why = _env.HoldReason();
+ if (why == null) { _holdSince = 0; return false; }
+ if (_holdSince == 0) _holdSince = now;
+ else if (now - _holdSince >= HoldMaxMs)
+ {
+ _env.Log($"[RynthAi] Nearby chests: chest 0x{(uint)ChestId:X8} '{ChestName}' waited {HoldMaxMs / 1000} s to send ({why}); dropped for now.");
+ Reset();
+ }
+ return true;
+ }
+
+ // ── Appraise ──────────────────────────────────────────────────────────
+
+ private void TickAppraise(long now)
+ {
+ if (Held(now)) return;
+ _appraiseStamp = _env.AppraisalStamp(ChestId);
+ if (!_env.RequestAppraisal(ChestId))
+ {
+ _env.Log($"[RynthAi] Nearby chests: the client wouldn't appraise chest 0x{(uint)ChestId:X8}; trying it as it is.");
+ AfterAppraisal(now, fresh: false);
+ return;
+ }
+ _sentAt = now;
+ Enter(Phase.AppraiseOut, now);
+ }
+
+ private void TickAppraiseOut(long now)
+ {
+ bool arrived = _env.AppraisalStamp(ChestId) != _appraiseStamp;
+ if (!arrived && now - _sentAt < AppraiseMaxMs) return;
+ if (!arrived)
+ _env.Log($"[RynthAi] Nearby chests: no appraisal of chest 0x{(uint)ChestId:X8} in {AppraiseMaxMs / 1000} s; going by what the client knows.");
+ AfterAppraisal(now, arrived);
+ }
+
+ private void AfterAppraisal(long now, bool fresh)
+ {
+ _appraisedFresh = fresh;
+ bool? locked = _env.Locked(ChestId);
+ var m = Mem(ChestId);
+ // Looted before, locked then, unlocked now: it hasn't reset yet (ACE re-locks it as it regenerates).
+ if (locked == false && m.Done && m.WasLocked)
+ {
+ Leave(now, "still unlocked since we looted it: it hasn't reset yet", skip: false, again: true);
+ return;
+ }
+ _lockedAtStart = locked == true;
+ if (_lockedAtStart)
+ {
+ _env.Log($"[RynthAi] Nearby chests: chest 0x{(uint)ChestId:X8} '{ChestName}' is locked{LockText()}; trying carried keys first.");
+ _triedUnlock = true;
+ Enter(Phase.Key, now);
+ return;
+ }
+ Enter(Phase.Open, now);
+ }
+
+ private string LockText()
+ {
+ int? resist = _env.LockResistance(ChestId);
+ int? pct = _env.PickSuccessPercent(ChestId);
+ if (resist == null) return "";
+ return pct != null ? $" (lock resistance {resist}, the server gives your Lockpick skill {pct}%)" : $" (lock resistance {resist})";
+ }
+
+ // ── Keys ──────────────────────────────────────────────────────────────
+
+ private ChestTool? NextKey()
+ {
+ var m = Mem(ChestId);
+ foreach (var k in _env.Keys())
+ if (!m.KeysThatDontFit.Contains(k.Name)) return k;
+ return null;
+ }
+
+ private void TickKey(long now)
+ {
+ ChestTool? key = _keyTries < MaxKeyTries ? NextKey() : null;
+ if (key == null)
+ {
+ if (_keyTries >= MaxKeyTries)
+ _env.Log($"[RynthAi] Nearby chests: {MaxKeyTries} keys tried on chest 0x{(uint)ChestId:X8}; none fitted.");
+ Enter(Phase.Pick, now);
+ return;
+ }
+ if (Held(now)) return;
+ if (!Send(now, key.Value, $"Loot Nearby Chests: try {key.Value.Name} on the locked chest")) return;
+ _keyTries++;
+ Enter(Phase.KeyOut, now);
+ }
+
+ private bool Send(long now, ChestTool tool, string why)
+ {
+ _seqAtSend = _env.UseDoneSeq();
+ _pickedSaid = _pickFailSaid = _keyUnlockSaid = false;
+ if (!_env.SendUseWith(tool.Id, ChestId, why))
+ {
+ Leave(now, $"the client wouldn't send the use of {tool.Name}", skip: true);
+ return false;
+ }
+ _toolId = tool.Id;
+ _toolName = tool.Name;
+ _sentAt = now;
+ _answered = false;
+ return true;
+ }
+
+ /// The server answered the last use (a UseDone since it went out), after the settle time for its chat line.
+ private bool Answer(long now, out uint err, out bool timedOut)
+ {
+ err = 0;
+ timedOut = false;
+ if (!_answered)
+ {
+ bool done;
+ if (!_env.HasUseDone) done = now - _sentAt >= 3000;
+ else done = _env.UseDoneSeq() != _seqAtSend;
+ if (!done)
+ {
+ if (now - _sentAt >= AnswerMaxMs) { timedOut = true; return true; }
+ return false;
+ }
+ _answered = true;
+ _answeredAt = now;
+ _answerErr = 0;
+ if (_env.HasUseDone && _env.LastUseDone(out int seq, out uint e) && seq == _seqAtSend + 1) _answerErr = e;
+ return false;
+ }
+ if (now - _answeredAt < SettleMs) return false;
+ err = _answerErr;
+ return true;
+ }
+
+ private void TickKeyOut(long now)
+ {
+ if (!Answer(now, out uint err, out bool timedOut)) return;
+ if (timedOut) { _keyTries--; Timeout(now, Phase.Key, $"no answer to {_toolName}"); return; }
+ var m = Mem(ChestId);
+ switch (err)
+ {
+ case 0:
+ case ErrLockAlreadyUnlocked:
+ _env.Log(err == 0
+ ? $"[RynthAi] Nearby chests: {_toolName} unlocked chest 0x{(uint)ChestId:X8}{(_keyUnlockSaid ? "" : " (the answer had no 'has been unlocked' line)")}; opening it."
+ : $"[RynthAi] Nearby chests: chest 0x{(uint)ChestId:X8} is already unlocked; opening it.");
+ _unlocked = true;
+ Enter(Phase.Open, now);
+ return;
+ case ErrKeyDoesntFit:
+ case ErrCannotUseThatItem:
+ m.KeysThatDontFit.Add(_toolName);
+ _env.Log(err == ErrKeyDoesntFit
+ ? $"[RynthAi] Nearby chests: {_toolName} doesn't fit chest 0x{(uint)ChestId:X8}; it won't be tried on it again."
+ : $"[RynthAi] Nearby chests: the server says {_toolName} can't be used; trying the next key.");
+ Enter(Phase.Key, now);
+ return;
+ case ErrCannotLockOrUnlock:
+ _env.Log($"[RynthAi] Nearby chests: the server says chest 0x{(uint)ChestId:X8} can't be unlocked with a key; a lockpick next.");
+ Enter(Phase.Pick, now);
+ return;
+ case ErrCannotLockWhatIsOpen:
+ Leave(now, "it is open (someone else is using it)", skip: true);
+ return;
+ case ErrTooBusy:
+ _keyTries--;
+ TooBusy(now, Phase.Key);
+ return;
+ default:
+ m.KeysThatDontFit.Add(_toolName);
+ _env.Log($"[RynthAi] Nearby chests: the server answered {_toolName} on chest 0x{(uint)ChestId:X8} with error 0x{err:X}; trying the next key.");
+ Enter(Phase.Key, now);
+ return;
+ }
+ }
+
+ // ── Lockpick ──────────────────────────────────────────────────────────
+
+ ///
+ /// Whether to pick this chest, and how many tries: null = no (why says it). Untrained can't pick
+ /// (ACE refuses: UseUnlocker, Lock.cs 125-131). A lock with no resistance, or 9999 and up,
+ /// can't be picked (LockHelper.IsPickable, Lock.cs 203-216). Else the chance the server rolls:
+ /// its own AppraisalLockpickSuccessPercent when the appraisal has it, or GetSkillChance from the
+ /// skill and the resistance; at least MinPickPercent picks MaxPicks times. Unknown resistance (no
+ /// appraisal): MaxPicksUnknown tries.
+ ///
+ internal static int? PickTries(bool skillKnown, int skill, bool trained, bool appraised, bool? locked, int? resist, int? serverPercent, out string why)
+ {
+ why = "";
+ if (skillKnown && !trained) { why = "your Lockpick skill isn't trained"; return null; }
+ if (appraised && locked == true && resist == null) { why = "its lock can't be picked (no lockpick resistance)"; return null; }
+ if (resist is int r && r >= 9999) { why = "its lock can't be picked (resistance 9999)"; return null; }
+ if (resist is int res)
+ {
+ int pct = serverPercent ?? (skillKnown ? (int)(PickChance(skill, res) * 100) : -1);
+ if (pct < 0) { why = "your Lockpick skill can't be read"; return null; }
+ if (pct < MinPickPercent)
+ {
+ why = $"your Lockpick skill{(skillKnown ? $" ({skill})" : "")} is too low for it: {pct}% against resistance {res} (it picks at {MinPickPercent}% or better)";
+ return null;
+ }
+ why = $"{pct}% against resistance {res}";
+ return MaxPicks;
+ }
+ why = "its lock resistance is unknown";
+ return MaxPicksUnknown;
+ }
+
+ /// ACE SkillCheck.GetSkillChance (factor 0.03), clamped 0..1.
+ internal static double PickChance(int skill, int difficulty)
+ => Math.Clamp(1.0 - 1.0 / (1.0 + Math.Exp(0.03 * (skill - difficulty))), 0.0, 1.0);
+
+ private void TickPick(long now)
+ {
+ if (_pickLimit == 0)
+ {
+ bool skillKnown = _env.LockpickSkill(out int skill, out bool trained);
+ // Only a fresh appraisal counts: ACE leaves the resistance out of an unlocked chest's.
+ int? tries = PickTries(skillKnown, skill, trained, _appraisedFresh, _env.Locked(ChestId),
+ _env.LockResistance(ChestId), _env.PickSuccessPercent(ChestId), out string why);
+ if (tries == null) { Leave(now, $"no key fits and {why}", skip: true); return; }
+ if (_env.Lockpick() == null) { Leave(now, "no key fits and you carry no lockpick (Consumable Items or your pack)", skip: true); return; }
+ _pickLimit = tries.Value;
+ _env.Log($"[RynthAi] Nearby chests: picking chest 0x{(uint)ChestId:X8} '{ChestName}' ({why}; up to {_pickLimit} tries).");
+ }
+ if (_picks >= _pickLimit) { Leave(now, $"the lock held after {_picks} lockpick tries", skip: true); return; }
+ ChestTool? pick = _env.Lockpick();
+ if (pick == null) { Leave(now, "the lockpicks ran out", skip: true); return; }
+ if (Held(now)) return;
+ if (!Send(now, pick.Value, "Loot Nearby Chests: pick the locked chest")) return;
+ _picks++;
+ Enter(Phase.PickOut, now);
+ }
+
+ private void TickPickOut(long now)
+ {
+ if (!Answer(now, out uint err, out bool timedOut)) return;
+ if (timedOut) { _picks--; Timeout(now, Phase.Pick, "no answer to the lockpick"); return; }
+ switch (err)
+ {
+ case 0:
+ // ACE answers a success and a failure alike (ConsumeUnlocker sends UseDone 0); the chat
+ // line, or the chest's Locked update, says which.
+ bool picked = _pickedSaid || (!_pickFailSaid && _env.Locked(ChestId) == false);
+ if (picked)
+ {
+ _env.Log($"[RynthAi] Nearby chests: picked the lock of chest 0x{(uint)ChestId:X8} (try {_picks}); opening it.");
+ _unlocked = true;
+ Enter(Phase.Open, now);
+ return;
+ }
+ _env.Log($"[RynthAi] Nearby chests: the lockpick failed on chest 0x{(uint)ChestId:X8} (try {_picks} of {_pickLimit}).");
+ Enter(Phase.Pick, now);
+ return;
+ case ErrLockAlreadyUnlocked:
+ _unlocked = true;
+ Enter(Phase.Open, now);
+ return;
+ case ErrNotTrainedInLockpicking:
+ Leave(now, "the server says your Lockpick skill isn't trained", skip: true);
+ return;
+ case ErrCannotLockOrUnlock:
+ Leave(now, "the server says its lock can't be picked", skip: true);
+ return;
+ case ErrCannotLockWhatIsOpen:
+ Leave(now, "it is open (someone else is using it)", skip: true);
+ return;
+ case ErrTooBusy:
+ _picks--;
+ TooBusy(now, Phase.Pick);
+ return;
+ default:
+ Leave(now, $"the server refused the lockpick (error 0x{err:X})", skip: true);
+ return;
+ }
+ }
+
+ // ── Open and loot ─────────────────────────────────────────────────────
+
+ private void TickOpen(long now)
+ {
+ if (Held(now)) return;
+ _seqAtSend = _env.UseDoneSeq();
+ if (!_env.SendOpen(ChestId)) { Leave(now, "the client wouldn't send the open", skip: true); return; }
+ _sentAt = now;
+ _answered = false;
+ Enter(Phase.OpenOut, now);
+ }
+
+ private void TickOpenOut(long now)
+ {
+ if (_env.OpenedAt(ChestId) >= _sentAt || _env.Looting(ChestId)) { OnOpened(now); return; }
+ if (!_answered)
+ {
+ bool done = _env.HasUseDone ? _env.UseDoneSeq() != _seqAtSend : now - _sentAt >= 3000;
+ if (done) { _answered = true; _answeredAt = now; }
+ else if (now - _sentAt < AnswerMaxMs) return;
+ }
+ if (_answered && now - _answeredAt < OpenSettleMs) return;
+
+ // Answered (or not at all) and nothing opened.
+ if (!_triedUnlock && !_unlocked)
+ {
+ // The client didn't read it as locked, but it wouldn't open: take it as locked.
+ _env.Log($"[RynthAi] Nearby chests: chest 0x{(uint)ChestId:X8} '{ChestName}' didn't open; taking it as locked (keys, then a lockpick).");
+ _triedUnlock = true;
+ _lockedAtStart = true;
+ Enter(Phase.Key, now);
+ return;
+ }
+ if (++_openFails >= MaxOpenFails) { Leave(now, $"it didn't open ({_openFails} tries)", skip: true); return; }
+ _env.Log($"[RynthAi] Nearby chests: chest 0x{(uint)ChestId:X8} didn't open (try {_openFails} of {MaxOpenFails}); trying again.");
+ Enter(Phase.Open, now);
+ }
+
+ private void OnOpened(long now)
+ {
+ var m = Mem(ChestId);
+ m.OpenedAt = now;
+ m.WasLocked = _lockedAtStart;
+ _lootStartedAt = now;
+ _lootSeen = _env.Looting(ChestId);
+ _env.Log($"[RynthAi] Nearby chests: chest 0x{(uint)ChestId:X8} '{ChestName}' is open; the loot profile decides what is taken.");
+ Enter(Phase.Looting, now);
+ }
+
+ private void TickLooting(long now)
+ {
+ if (_env.Looting(ChestId))
+ {
+ _lootSeen = true;
+ if (now - _lootStartedAt >= LootMaxMs) Leave(now, $"looting it took more than {LootMaxMs / 60000} minutes", skip: false, done: true);
+ return;
+ }
+ if (!_lootSeen && now - _lootStartedAt < LootStartMs) return;
+ if (!_lootSeen) { Leave(now, "the looter never took it", skip: true); return; }
+ Looted++;
+ Leave(now, "looted", skip: false, done: true);
+ }
+
+ // ── Endings ───────────────────────────────────────────────────────────
+
+ private void Timeout(long now, Phase back, string why)
+ {
+ if (++_timeouts >= MaxTimeouts) { Leave(now, $"{why} ({_timeouts} times)", skip: true); return; }
+ _env.Log($"[RynthAi] Nearby chests: {why} on chest 0x{(uint)ChestId:X8}; trying again ({_timeouts} of {MaxTimeouts}).");
+ Enter(back, now);
+ }
+
+ private void TooBusy(long now, Phase back)
+ {
+ if (++_busy >= MaxBusy) { Leave(now, "the server keeps answering 'too busy'", skip: true); return; }
+ Enter(back, now);
+ }
+
+ ///
+ /// Ends the chest. done: looted, left alone until it resets (the re-lock wait, or it reads
+ /// locked again). skip: left alone SkipMs (10 minutes). Neither: nothing marked (it is picked
+ /// again on a later scan). again: looted before and not reset yet - another re-lock wait.
+ ///
+ private void Leave(long now, string why, bool skip, bool done = false, bool again = false)
+ {
+ int id = ChestId;
+ string name = ChestName;
+ var m = Mem(id);
+ m.Why = why;
+ if (done || again)
+ {
+ m.Done = true;
+ if (done) m.OpenedAt = m.OpenedAt == 0 ? now : m.OpenedAt;
+ m.LeaveUntil = now + RelockWaitMs;
+ LastResult = $"{name}: {why}";
+ _env.Log(again
+ ? $"[RynthAi] Nearby chests: chest 0x{(uint)id:X8} '{name}' {why}; left alone another {RelockWaitMs / 1000} s."
+ : $"[RynthAi] Nearby chests: done with chest 0x{(uint)id:X8} '{name}' ({why}); left alone until it resets " +
+ $"({(m.WasLocked ? "it reads locked again, or " : "")}{RelockWaitMs / 1000} s, the chest re-lock wait).");
+ }
+ else if (skip)
+ {
+ m.Done = false;
+ m.LeaveUntil = now + SkipMs;
+ LastResult = $"{name}: skipped - {why}";
+ _env.Log($"[RynthAi] Nearby chests: skipping chest 0x{(uint)id:X8} '{name}' - {why}; trying it again in {SkipMs / 60000} minutes.");
+ }
+ else
+ {
+ // Nothing marked; a chest that left the world is forgotten (its keys too).
+ if (!_env.InWorld(id) || (!m.Done && m.KeysThatDontFit.Count == 0)) _memory.Remove(id);
+ _env.Log($"[RynthAi] Nearby chests: left chest 0x{(uint)id:X8} '{name}' - {why}.");
+ }
+ Reset();
+ }
+
+ /// One line for /ra chests.
+ public string Status
+ {
+ get
+ {
+ string tail = $"{Looted} looted";
+ switch (State)
+ {
+ case Phase.Idle: return LastResult.Length > 0 ? $"idle - {tail}; last: {LastResult}." : $"idle - {tail}.";
+ case Phase.Appraise or Phase.AppraiseOut: return $"looking at {ChestName}'s lock - {tail}.";
+ case Phase.Key or Phase.KeyOut: return $"trying keys on {ChestName} - {tail}.";
+ case Phase.Pick or Phase.PickOut: return $"picking {ChestName} (try {_picks} of {_pickLimit}) - {tail}.";
+ case Phase.Open or Phase.OpenOut: return $"opening {ChestName} - {tail}.";
+ default: return $"looting {ChestName} - {tail}.";
+ }
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs
index 21824a2..823b47d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs
@@ -266,11 +266,17 @@ internal sealed class OutdoorHunt
_path = path;
_buildings = buildings;
_now = now;
+ _meNow = me;
_meBuilding = 0;
if (IsIndoorCell(meCell))
{
int inB = buildings?.BuildingOf(meCell) ?? 0;
if (inB == 0 || buildings!.Doors(inB).Count == 0) return Indoors(now, me, routeDone);
+ // No door of it can be walked to from where the character stands (2026-11-16, a Thread: in
+ // building 1747#1 after a kill, every monster outside was "left out for 120 s: no door of
+ // building 1747#1 it can walk to" and the hunt stood 2 min). That is the spot, not the
+ // monsters: back out the way in, as in a building with no door known, and none left out.
+ if (!AnyDoorOut(me, meCell, inB)) return Indoors(now, me, routeDone);
_meBuilding = inB;
WalkingOut = false; // the doors take it out from here
}
@@ -281,7 +287,21 @@ internal sealed class OutdoorHunt
Candidate? t = null;
foreach (var c in candidates)
if (c.Id == TargetId) { t = c; break; }
- if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && Plannable(target))
+ // The walk is over, it stands where the walk went (under where the monster was), and the monster is
+ // still a floor apart: this walk can't get there (2026-11-16 17:11, a Thread: the walk "through its
+ // rooms" to one on the floor above went to the spot under it; it moved about up there, so each walk
+ // planned again ended a yard or two off, and it was walked again every half second for 20 s; nav's
+ // points count as reached by the flat distance).
+ bool floorApart = t is Candidate under && routeDone && !IsSkipped(under.Id, now)
+ && me.FlatDistanceTo(_plannedTo) <= ReachYd && Math.Abs(under.Pos.Z - me.Z) > ReachRiseYd;
+ if (floorApart)
+ {
+ var u = t!.Value;
+ Skip(u.Id, now);
+ Note = $"'{u.Name}': the walk to it ended {Math.Abs(u.Pos.Z - me.Z):0} yd {(u.Pos.Z > me.Z ? "below" : "above")} it "
+ + $"(another floor, no way there found): left out for {SkipSec:0} s";
+ }
+ else if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && Plannable(target))
{
double since = (now - _lastPlan).TotalSeconds;
bool moved = target.Pos.DistanceTo(_plannedTo) > ReplanMovedYd && since >= ReplanMinSec;
@@ -293,7 +313,7 @@ internal sealed class OutdoorHunt
{
_plannedTo = target.Pos;
_lastPlan = now;
- if (p.Length > ArrivedYd)
+ if (p.Length > ArrivedYd && !EndsHere(p, me))
{
_arrivedSince = DateTime.MinValue;
return new Decision(Act.Walk, p.Corners, target.Id, $"to '{target.Name}' again ({p.Length:0} yd)");
@@ -320,9 +340,9 @@ internal sealed class OutdoorHunt
if ((now - _lastPick).TotalSeconds < PickEverySec)
return new Decision(Act.Idle);
_lastPick = now;
- if (Pick != PickMode.Nearest) return PickPack(now, me, meCell, candidates);
+ if (Pick != PickMode.Nearest) return PickPack(now, me, meCell, candidates, routeDone);
_viable.Clear();
- int asked = 0;
+ int asked = 0, mySide = 0;
foreach (var c in candidates)
{
if (asked >= PickCandidates) break;
@@ -333,12 +353,14 @@ internal sealed class OutdoorHunt
var p = w.P;
if (p.Status == PathStatus.Unavailable) return new Decision(Act.Idle, Why: "no pathfinder");
if (Reaches(p, c.Pos)) _viable.Add((c, w));
+ else if (FailsOnMySide(w)) mySide++;
else
{
Skip(c.Id, now);
Note = $"'{c.Name}' left out for {SkipSec:0} s: {Describe(p, w.Why, c.Pos)}";
}
}
+ if (_viable.Count == 0 && mySide > 0) return Indoors(now, me, routeDone);
if (_viable.Count > 0)
{
var best = _viable[0];
@@ -359,7 +381,7 @@ internal sealed class OutdoorHunt
_plannedTo = c.Pos;
_lastPlan = now;
Note = NextNote(c, w, pack);
- if (w.P.Length > ArrivedYd)
+ if (w.P.Length > ArrivedYd && !EndsHere(w.P, _meNow))
{
_arrivedSince = DateTime.MinValue;
return new Decision(Act.Walk, w.P.Corners, c.Id, Note);
@@ -387,7 +409,7 @@ internal sealed class OutdoorHunt
private readonly List _eligible = new();
- private Decision PickPack(DateTime now, Vec me, uint meCell, IReadOnlyList candidates)
+ private Decision PickPack(DateTime now, Vec me, uint meCell, IReadOnlyList candidates, bool routeDone = true)
{
_eligible.Clear();
foreach (var c in candidates)
@@ -450,7 +472,7 @@ internal sealed class OutdoorHunt
});
var walks = new Dictionary(); // eligible index -> its walk (the ones that reach it)
- int asked = 0;
+ int asked = 0, mySide = 0;
foreach (int i in order)
{
if (asked >= PickCandidates) break;
@@ -459,12 +481,14 @@ internal sealed class OutdoorHunt
var w = PlanWalk(me, meCell, c.Pos, c.Cell);
if (w.P.Status == PathStatus.Unavailable) return new Decision(Act.Idle, Why: "no pathfinder");
if (Reaches(w.P, c.Pos)) walks[i] = w;
+ else if (FailsOnMySide(w)) mySide++;
else
{
Skip(c.Id, now);
Note = $"'{c.Name}' left out for {SkipSec:0} s: {Describe(w.P, w.Why, c.Pos)}";
}
}
+ if (walks.Count == 0 && mySide > 0) return Indoors(now, me, routeDone);
if (walks.Count == 0) return Waiting();
// Scored again by the real walk.
@@ -599,6 +623,13 @@ internal sealed class OutdoorHunt
private bool InArea(Vec p) => RadiusYd <= 0 || p.FlatDistanceTo(Anchor) <= RadiusYd;
+ ///
+ /// The walk ends where the character stands already (within ArrivedYd, across): nothing to walk, whatever
+ /// its corners do round it. Under a monster on the floor above (2026-11-16, a Thread) the walk was two
+ /// corners a yard or so either side, planned again every half second: the character turned in circles.
+ ///
+ private bool EndsHere(PathResult p, Vec me) => p.Corners.Count > 0 && p.Corners[^1].FlatDistanceTo(me) <= ArrivedYd;
+
private bool Reaches(PathResult p, Vec goal) =>
p.Corners.Count > 0 && (p.Status == PathStatus.Ok || (p.Status == PathStatus.Partial && p.Gap <= ReachYd))
&& p.Length <= RangeYd * MaxWalkFactor && Math.Abs(EndRise(p, goal)) <= ReachRiseYd;
@@ -658,6 +689,7 @@ internal sealed class OutdoorHunt
public double DoorstepKeepSec { get; set; } = 60;
private readonly Dictionary<(uint, long, long), (bool Ok, DateTime Until)> _doorsteps = new();
private DateTime _now;
+ private Vec _meNow; // where the character is this tick
///
/// The door's step out is on RynthNav's ground: the map's nearest point to it (a path from it to
@@ -709,7 +741,7 @@ internal sealed class OutdoorHunt
foreach (var d in b!.Doors(from))
{
var p = b.Inside(meCell, me, d.Cell, d.Inner);
- if (p.Status != PathStatus.Ok || !OnGround(d)) continue;
+ if (!DoorWalkOk(p) || !OnGround(d)) continue;
outs.Add((d, p, p.Length + d.Inner.DistanceTo(d.At) + d.At.DistanceTo(d.Outside)));
}
if (to == 0) ins.Add((null, none, 0));
@@ -778,6 +810,26 @@ internal sealed class OutdoorHunt
return new HuntWalk(new PathResult(PathStatus.NoPath, Array.Empty(), 0, 0), From: from, To: to, Why: why);
}
+
+ /// A walk through a building's rooms to a door's inner point that gets there (or within ReachYd).
+ private bool DoorWalkOk(PathResult p)
+ => p.Status == PathStatus.Ok || (p.Status == PathStatus.Partial && p.Corners.Count > 0 && p.Gap <= ReachYd);
+
+ /// Some door of the character's building can be walked to from where it stands, its step out on the ground.
+ private bool AnyDoorOut(Vec me, uint meCell, int building)
+ {
+ foreach (var d in _buildings!.Doors(building))
+ if (DoorWalkOk(_buildings.Inside(meCell, me, d.Cell, d.Inner)) && OnGround(d)) return true;
+ return false;
+ }
+
+ /// The walk fails getting the character out of its own building (no door it can walk to, or
+ /// no way on from any of them), not reaching the monster: none is left out for it.
+ private bool FailsOnMySide(HuntWalk w)
+ => _meBuilding != 0 && w.From == _meBuilding && w.To != _meBuilding
+ && (w.Why.StartsWith("no door of ", StringComparison.Ordinal) && w.Why.EndsWith(" it can walk to", StringComparison.Ordinal)
+ || w.Why.StartsWith("no way to it from a door of ", StringComparison.Ordinal));
+
/// Corners closer than this to the one before are one (RynthNav's way to a doorstep ends on it).
private const double SameCornerYd = 0.3;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs
index 8ceb995..0a31e56 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs
@@ -1553,6 +1553,59 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
};
}
+ ///
+ /// The physics polygons of every static object a dungeon's cells place (the EnvCells' stabs: a spider
+ /// web across a doorway, a pillar), in world metres, one TriangleMesh each. A stab's frame is in the
+ /// landblock's space (its z is the floor's: DreamWeave Thread 0x5456's webs stand at z -24 on a -24
+ /// floor). Objects with no physics polygons (nothing to walk into) are left out.
+ ///
+ public List<(uint SetupId, uint CellId, BoundingVolume Mesh)> GetDungeonStaticMeshes(uint landblockKey)
+ {
+ var list = new List<(uint, uint, BoundingVolume)>();
+ if (_cellDat == null) return list;
+ float gx = ((landblockKey >> 8) & 0xFF) * 192.0f, gy = (landblockKey & 0xFF) * 192.0f;
+ foreach (uint cellId in _cellDat.GetLandblockCellIds(landblockKey))
+ {
+ byte[] data = _cellDat.GetFileData(cellId);
+ if (data == null || data.Length < 20) continue;
+ try
+ {
+ using var ms = new MemoryStream(data);
+ using var reader = new BinaryReader(ms);
+ reader.ReadUInt32();
+ uint flags = reader.ReadUInt32();
+ reader.ReadUInt32();
+ byte numSurfaces = reader.ReadByte();
+ byte numPortals = reader.ReadByte();
+ ushort numVisibleCells = reader.ReadUInt16();
+ for (int i = 0; i < numSurfaces; i++) reader.ReadUInt16();
+ reader.ReadUInt16(); reader.ReadUInt16(); // environment, cell structure
+ for (int i = 0; i < 7; i++) reader.ReadSingle(); // the cell's frame
+ for (int i = 0; i < numPortals; i++) reader.ReadUInt64();
+ for (int i = 0; i < numVisibleCells; i++) reader.ReadUInt16();
+ if ((flags & 0x02) == 0 || ms.Position + 4 > ms.Length) continue;
+ uint numStabs = Math.Min(reader.ReadUInt32(), 500u);
+ for (uint i = 0; i < numStabs && ms.Position + 32 <= ms.Length; i++)
+ {
+ uint setupId = reader.ReadUInt32();
+ var frame = new Frame
+ {
+ OriginX = reader.ReadSingle(), OriginY = reader.ReadSingle(), OriginZ = reader.ReadSingle(),
+ RotW = reader.ReadSingle(), RotX = reader.ReadSingle(), RotY = reader.ReadSingle(), RotZ = reader.ReadSingle()
+ };
+ foreach (var vol in GetBuildingCompositeVolumes(setupId))
+ {
+ if (vol.Type != BoundingVolume.VolumeType.TriangleMesh) continue;
+ var placed = TransformVolume(vol, frame, gx, gy);
+ if (placed != null) list.Add((setupId, cellId, placed));
+ }
+ }
+ }
+ catch (Exception) { }
+ }
+ return list;
+ }
+
///
/// Transforms a local-space bounding volume by a placement frame,
/// producing a world-space AABB for raycasting.
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
index 4d30bd5..dd67f0e 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
@@ -119,7 +119,10 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra autoconfirm [status|on|off|<50-100>] — Yes to the craft-chance prompt at that % or better (Mini Remote > Crafting)");
ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off");
ChatLine("[RynthAi] /ra dunnav — navigate to NS/EW coords through dungeon (no nav file needed)");
+ ChatLine("[RynthAi] /ra dunnav-to
private int FindFirstLineOfSightWaypoint(NavRouteParser route, uint playerCell,
- float playerLocalX, float playerLocalY, float playerZ)
+ float playerLocalX, float playerLocalY, float playerZ,
+ int lookahead = int.MaxValue)
{
if (route?.Points == null || route.Points.Count == 0) return 0;
var geo = _raycast?.GeometryLoader;
@@ -4174,7 +4317,7 @@ public sealed partial class RynthAiPlugin
pBlockY * 192f + playerLocalY,
playerZ + 1.0f);
- for (int i = 0; i < route.Points.Count; i++)
+ for (int i = 0; i < route.Points.Count && i < lookahead; i++)
{
var p = route.Points[i];
if (!NavRouteParser.IsPlainWaypoint(p.Type)) continue; // skip pause/chat/portal-action nodes
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs
index 4613d6d..9d0c90a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs
@@ -12,13 +12,21 @@
//
// The wait: with the macro and Looting on, our kill starts a wait of the monster's learned death (or
// DeathWaitDefaultMs while it isn't learned) plus DeathWaitExtraMs. While it runs, looting counts as
-// work, the arbiter gives Looting the tick over combat (ArbiterInputs.DeathWait, as Boost Loot does)
-// and combat locks no new target (CombatManager.HoldNewTarget), so neither a fight's walk, nor nav,
-// nor the Outdoor Hunt takes the character away. A monster within CloseAttackYards is still fought
-// (HoldNewTarget and CombatEngaged both let it through). It ends when the corpse is looted, when no
+// work and the arbiter gives Looting the tick (ArbiterInputs.DeathWait, as Boost Loot does), so
+// neither nav nor the Outdoor Hunt takes the character away. The next fight is not held (2026-11-15,
+// below): a monster combat can lock is fought at once. It ends when the corpse is looted, when no
// corpse came in the time, or DeathWaitDecideMs after a corpse came that the looter hasn't claimed
// (the loot rules don't take it, or the looter leaves it for the fight: then the fight goes on and the
// looter comes back for it; holding combat there stood the character still, both waiting on the other).
+//
+// No hold on combat's next target (2026-11-15, R-20261115-165857-1de7): the same stand-off, before the
+// corpse came. The wait held the next target (a Marae Ursuin in range, beyond 5 yd) for the 3 s death
+// and 1 s more, but the looter claims no corpse while combat has targets in range (Boost Loot and a
+// starved corpse aside, which have their own rules): "Looting has held the tick 3.0 s with nothing
+// claimed", 3.6 s standing until the monster walked within 5 yd and hit. Combat has a candidate only
+// when it has targets, so the hold could only ever wait on a looter that waits for the fight. The corpse
+// is looted after the fight, as every corpse is with Boost Loot off; the wait still keeps nav and the
+// hunt from walking off when no fight is left (the owner's case: running off from the last kill).
// Pump thread throughout.
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
@@ -174,17 +182,12 @@ public sealed partial class RynthAiPlugin
return Math.Sqrt(dx * dx + dy * dy) <= DeathCorpseNearYd;
}
- /// CombatManager.HoldNewTarget: Boost Loot Priority's hold, or the death wait's.
- private bool LootHoldsNewTarget()
- {
- if (BoostLootHoldsNewTarget()) return true;
- var s = _dashboard?.Settings;
- return s != null && DeathWaitHolds(s);
- }
+ ///
+ /// CombatManager.HoldNewTarget: Boost Loot Priority's hold. The death wait no longer holds the next
+ /// target (2026-11-15, header): with a target to lock, the looter leaves the corpse for the fight.
+ ///
+ private bool LootHoldsNewTarget() => BoostLootHoldsNewTarget();
/// CombatManager.HoldNewTargetWhy: the words for its one log line.
- private string LootHoldWhy()
- => _deathWaitAt != 0 && !BoostLootHoldsNewTarget()
- ? "the kill's corpse comes first (its death animation, then the loot)"
- : "Boost Loot Priority loots the kill first";
+ private string LootHoldWhy() => "Boost Loot Priority loots the kill first";
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs
new file mode 100644
index 0000000..b118ac6
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs
@@ -0,0 +1,1212 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Loot;
+using RynthCore.Plugin.Shared;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// /ra dunnav-explore (2026-11-13): one walk through every room of the dungeon the character is in,
+/// then stop. Laid like the patrol (TryBuildDunPatrol: out of lava/acid and portal circles first, the
+/// first point in sight, round the portals), walked by the navigation engine as a Once route with the
+/// macro on, so fighting, looting and buffing go on as the settings say. The walk itself
+/// (DungeonPathfinder.Explore.cs) enters each room it hasn't entered yet, nearest first.
+/// Here: the rooms entered (the cells the character stands in, each tick), the reroutes the patrol
+/// makes (a hazard sighted, a portal come into view, the dungeon map loaded after the cell walk was
+/// laid) laid over the rooms still to go, a second look for rooms the walk got past without entering,
+/// and the end: done (the walk is over), or stopped (the command, another route, out of the dungeon).
+/// Navigation goes off at the end; the macro is left as it is. radunexplore[] and the two counts
+/// (ExpressionEngine.DunExploreStatus) tell a meta or a Lua script how far it is.
+///
+/// Shut doors (2026-11-14): a door the character can't use (ItemUseable without Remote: in ACE's data
+/// every door a lever opens) or one the door opener gave up on (locked, or still shut after its uses)
+/// is a shut door: its opening is closed for the walk, which goes round it, and the rooms behind it are
+/// counted. When everything else is walked and rooms are left behind shut doors, the explore waits at
+/// the doors (state 5) for a lever: /ra dunnav-explore lever <id> walks to it (through no shut door),
+/// uses it (or steps onto a pressure plate) and watches the door. Opened: the walk is laid again with
+/// the rooms behind that door first (it shuts again on its own); not opened: back to waiting, the
+/// result in radunexploreinfo[]. Which lever is the caller's choice (a script or a meta);
+/// RynthAi only walks, uses and watches. A shut door that opens by itself does the same as a lever.
+///
+/// Stuck (2026-11-14, Tom on DreamWeave: "a spider web thing, definitely not in the dats" in a doorway of
+/// 0x5456): the map is the cells' walls and openings only, so a thing spawned in an opening isn't on it, and
+/// the navigation engine's detours (planned on the same map) went back through it; after its last detour it
+/// only tries its escapes, for good. When every detour for the waypoint is used up and it is still stuck
+/// (NavigationEngine.DetoursUsedUpAndStuck), the explore closes the opening it was heading through (the first
+/// step from the character's cell towards the next waypoint in another cell) and lays the rest round it; rooms
+/// only that way are left out (couldn't be reached). At most DunExploreMaxStuckOpenings a run.
+///
+public sealed partial class RynthAiPlugin
+{
+ internal enum DunExploreState { None = 0, Exploring = 1, Paused = 2, Done = 3, Stopped = 4, AtDoors = 5, Lever = 6 }
+
+ /// The explore starts at the first of this many points in sight (the patrol looks along its whole lap).
+ private const int ExploreSightLookahead = 4;
+ /// The walk over with rooms still not entered: laid again for them this many times (each needs a new room entered since).
+ private const int DunExploreMaxSweeps = 2;
+ /// How often a running explore looks for a new portal, a shut door or the dungeon map.
+ private const long DunExploreCheckMs = 1000;
+ /// Openings closed because the character couldn't get through them, at most this many a run.
+ private const int DunExploreMaxStuckOpenings = 6;
+ /// Stuck for good farther than this from the doorway on its way: the thing in the way is where it stands.
+ internal const double StuckAtDoorwayMeters = 3.0;
+ /// The spot walked round then: this far ahead of it, towards its waypoint, and this big.
+ internal const double StuckSpotAhead = 1.5, StuckSpotRadius = 1.0;
+ /// How far along the route the next waypoint in another cell is looked for.
+ private const int StuckLookAheadPoints = 8;
+
+ /// Tests: the navigation engine's "every detour used up and still stuck" (null: the engine's own).
+ /// The explore and the patrol both ask it.
+ internal Func? ExploreStuckProbe;
+
+ private bool StuckForGood() => ExploreStuckProbe?.Invoke() ?? _navigationEngine?.DetoursUsedUpAndStuck ?? false;
+
+ /// ItemUseable's Remote bit (ACE Usable.Remote): a door without it can't be used from where you stand.
+ private const int UsableRemote = 0x20;
+ /// A lever is used from this close (the server walks the character the last bit); a plate is stepped on.
+ private const double LeverReachMeters = 2.5, LeverUseFromMeters = 6.0, PlateReachMeters = 0.9;
+ /// The door is watched this long after a lever (a plate) before it counts as not opened.
+ // A door shows open about 4.5 s after its lever is pulled (DreamWeave Thread 0x5873, 2026-11-16: lever 0x75873008,
+ // door 0x75873009). A second pull before that flips it shut again (2.5 s here before: it "opened" and shut 5 s
+ // later, twice), so the lever is pulled again only when the door still hasn't opened well after that.
+ private const long LeverWatchMs = 12_000, PlateWatchMs = 4000, LeverReuseMs = 8000, LeverErrandMaxMs = 120_000;
+
+ internal sealed class ExploreDoor
+ {
+ public uint Id;
+ public string Name = "";
+ public uint Cell;
+ /// World metres.
+ public double X, Y, Z;
+ public readonly HashSet Edges = new();
+ /// "can't be used", "locked", "wouldn't open".
+ public string Why = "";
+ /// The cells walkable to with this door open but not with it shut, and their rooms.
+ public HashSet CellsBehind = new();
+ public int RoomsBehind;
+ }
+
+ internal sealed class LeverErrand
+ {
+ public uint Lever, Door;
+ public string LeverName = "";
+ public bool Plate;
+ /// World metres.
+ public double X, Y, Z;
+ public string Phase = "walking";
+ public long StartedAt, PhaseAt;
+ public int Uses;
+ }
+
+ internal sealed class DunExploreRun
+ {
+ public DunExploreState State = DunExploreState.Exploring;
+ public uint Landblock;
+ public NavRouteParser? Route;
+ public ExplorePlan Plan = new();
+ /// The cells the character has stood in on this explore (what a reroute leaves out).
+ public readonly HashSet VisitedCells = new();
+ /// The rooms of those cells are in.
+ public readonly HashSet EnteredRooms = new();
+ public readonly HashSet PortalIds = new();
+ /// Openings it couldn't get through (closed for the walk), and what was said about each.
+ public readonly HashSet StuckEdges = new();
+ /// Spots in a room it got stuck at for good, away from any doorway: walked round like a portal's circle.
+ public readonly List StuckSpots = new();
+ public readonly List StuckNotes = new();
+ /// Shut doors the walk goes round, and their openings (closed in the graph).
+ public readonly Dictionary Doors = new();
+ public readonly HashSet DoorEdges = new();
+ /// Doors found in no opening (left alone: logged once).
+ public readonly HashSet DoorsNowhere = new();
+ /// Things standing in a doorway that the map doesn't have (a spider web), id → name, and the doorways'
+ /// cell pairs (closed for the walk); things in no doorway (left alone); names of things it got stuck on in a
+ /// doorway this run (each other one of that name in a doorway is walked round too).
+ public readonly Dictionary Blockers = new();
+ public readonly HashSet BlockedEdges = new();
+ public readonly HashSet BlockersNowhere = new();
+ public readonly HashSet BlockerNames = new(StringComparer.OrdinalIgnoreCase);
+ /// Monsters still in the dungeon when the walk was over, walked to one at a time (each once), and how many.
+ public readonly HashSet HuntTried = new();
+ public int HuntWalks;
+ /// Behind a door that just opened: walked first, until the character is through.
+ public readonly HashSet PreferCells = new();
+ public LeverErrand? Errand;
+ /// The last lever's result: "opened <door> <lever>", "notopened ...", "unreachable ...".
+ public string LastLever = "";
+ public uint LastCell;
+ public int HazardVersion;
+ public int Sweeps, EnteredAtSweep = -1;
+ public long StartedAt, EndedAt, NextCheckAt;
+ public string EndNote = "";
+ /// The shut doors (and rooms behind) last said in chat when it came to wait at them.
+ public string AtDoorsSaid = "";
+
+ /// The rooms it means to walk through, and those of them (or cut off since) entered.
+ public int Rooms => Plan.PlanRooms.Count + EnteredRooms.Count(r => !Plan.PlanRooms.Contains(r));
+ public int Entered => EnteredRooms.Count;
+ public int RoomsBehindDoors => Doors.Values.Sum(d => d.RoomsBehind);
+ public bool Active => State is DunExploreState.Exploring or DunExploreState.Paused or DunExploreState.AtDoors or DunExploreState.Lever;
+
+ /// A cell stood in: its room counts as entered; past a door that opened, the walk stops preferring it.
+ public void Enter(uint cell)
+ {
+ if (PreferCells.Contains(cell)) PreferCells.Clear();
+ if (!VisitedCells.Add(cell)) return;
+ int r = Plan.RoomOf(cell);
+ if (r >= 0) EnteredRooms.Add(r);
+ }
+
+ /// After a new plan: the rooms entered, in its numbering.
+ public void Recount()
+ {
+ EnteredRooms.Clear();
+ foreach (uint c in VisitedCells)
+ {
+ int r = Plan.RoomOf(c);
+ if (r >= 0) EnteredRooms.Add(r);
+ }
+ }
+
+ public void Shut(ExploreDoor d)
+ {
+ Doors[d.Id] = d;
+ DoorEdges.UnionWith(d.Edges);
+ }
+
+ public void Unshut(uint id)
+ {
+ if (!Doors.Remove(id)) return;
+ DoorEdges.Clear();
+ foreach (var d in Doors.Values) DoorEdges.UnionWith(d.Edges);
+ }
+ }
+
+ private DunExploreRun? _dunExplore;
+ /// Doors the door opener gave up on (id → why), for the explore's next look.
+ private readonly Dictionary _exploreRefusedDoors = new();
+
+ /// The door opener gave up on a door (DoorInteractionController): a shut door to an explore.
+ private void NoteExploreDoorRefused(uint doorId, string why)
+ {
+ if (_dunExplore is not { Active: true } || doorId == 0) return;
+ _exploreRefusedDoors[doorId] = why;
+ _dunExplore.NextCheckAt = 0; // looked at on the next tick
+ }
+
+ /// For radunexplore[], radunexplorerooms[], radunexplorevisited[].
+ private (int State, int Rooms, int Visited) DunExploreStatus()
+ {
+ var run = _dunExplore;
+ return run == null ? (0, 0, 0) : ((int)run.State, run.Rooms, run.Entered);
+ }
+
+ private const string DunExploreUsage = "[RynthAi] Usage: /ra dunnav-explore [stop|status|resume|done] | lever [door ] [at ] [plate] — walk through every room of this dungeon once, then stop";
+
+ private void HandleDunExploreCommand(string[] parts)
+ {
+ string sub = parts.Length > 2 ? parts[2].Trim().ToLowerInvariant() : "";
+ var run = _dunExplore;
+ switch (sub)
+ {
+ case "":
+ case "start":
+ if (run is { Active: true })
+ {
+ ReplyOk($"[RynthAi] DunNav-Explore: already exploring, {run.Entered} of {run.Rooms} rooms. /ra dunnav-explore stop ends it.");
+ return;
+ }
+ StartDunExplore();
+ return;
+ case "resume":
+ ResumeDunExplore(run);
+ return;
+ case "stop":
+ if (run is not { Active: true }) { ReplyFail("[RynthAi] DunNav-Explore: nothing to stop (no explore running)."); return; }
+ EndDunExplore(run, DunExploreState.Stopped, "you stopped it", clearRoute: true);
+ return;
+ case "done":
+ if (run is not { State: DunExploreState.AtDoors }) { ReplyFail("[RynthAi] DunNav-Explore: \"done\" ends an explore waiting at shut doors; none is."); return; }
+ EndDunExplore(run, DunExploreState.Done, "", clearRoute: true);
+ return;
+ case "lever":
+ StartLeverErrand(run, parts.Skip(3).ToArray());
+ return;
+ case "status":
+ ReplyOk(DunExploreStatusLine());
+ return;
+ default:
+ ReplyFail(DunExploreUsage);
+ return;
+ }
+ }
+
+ private string DunExploreStatusLine()
+ {
+ var run = _dunExplore;
+ if (run == null) return "[RynthAi] DunNav-Explore: none yet. /ra dunnav-explore walks through every room of the dungeon you are in.";
+ string took = Took(run);
+ string doors = run.Doors.Count > 0 ? $", {run.RoomsBehindDoors} room(s) behind {run.Doors.Count} shut door(s)" : "";
+ return run.State switch
+ {
+ DunExploreState.Exploring => $"[RynthAi] DunNav-Explore: exploring dungeon 0x{run.Landblock:X4}, {run.Entered} of {run.Rooms} rooms{doors}, {took}.",
+ DunExploreState.Paused => $"[RynthAi] DunNav-Explore: paused (macro or navigation off), {run.Entered} of {run.Rooms} rooms{doors}. Start the macro to carry on.",
+ DunExploreState.AtDoors => $"[RynthAi] DunNav-Explore: waiting at shut doors, {run.Entered} of {run.Rooms} rooms{doors}. /ra dunnav-explore lever pulls one; /ra dunnav-explore done ends it.",
+ DunExploreState.Lever => $"[RynthAi] DunNav-Explore: at a lever ({run.Errand?.LeverName} 0x{run.Errand?.Lever:X8}, {run.Errand?.Phase}), {run.Entered} of {run.Rooms} rooms{doors}.",
+ DunExploreState.Done => $"[RynthAi] DunNav-Explore: done in dungeon 0x{run.Landblock:X4}, {run.Entered} of {run.Rooms} rooms in {took}{doors}.",
+ _ => $"[RynthAi] DunNav-Explore: stopped ({run.EndNote}), {run.Entered} of {run.Rooms} rooms{doors}. /ra dunnav-explore resume carries on.",
+ };
+ }
+
+ private static string Took(DunExploreRun run)
+ {
+ long end = run.EndedAt != 0 ? run.EndedAt : Environment.TickCount64;
+ var t = TimeSpan.FromMilliseconds(Math.Max(0, end - run.StartedAt));
+ return t.TotalMinutes >= 1 ? $"{(int)t.TotalMinutes} min {t.Seconds} s" : $"{t.Seconds} s";
+ }
+
+ private void StartDunExplore()
+ {
+ var run = new DunExploreRun { StartedAt = Environment.TickCount64 };
+ ScanShutDoorsInto(run, CurrentLandblockOrZero());
+ ScanBlockersInto(run, CurrentLandblockOrZero());
+ if (!BuildDunExplore(run, isRebuild: false, why: "")) return;
+ _dunExplore = run;
+ }
+
+ /// /ra dunnav-explore resume: the last explore, in this dungeon, carries on (the rooms entered and the shut doors kept).
+ private void ResumeDunExplore(DunExploreRun? run)
+ {
+ uint lb = CurrentLandblockOrZero();
+ if (run == null || run.Landblock != lb || lb == 0)
+ {
+ ReplyFail("[RynthAi] DunNav-Explore: nothing to resume in this dungeon; /ra dunnav-explore starts one.");
+ return;
+ }
+ if (run.State is DunExploreState.Exploring or DunExploreState.Paused or DunExploreState.Lever)
+ {
+ ReplyOk($"[RynthAi] DunNav-Explore: already exploring, {run.Entered} of {run.Rooms} rooms.");
+ return;
+ }
+ run.Errand = null;
+ run.EndedAt = 0;
+ run.Sweeps = 0;
+ run.EnteredAtSweep = -1;
+ ScanShutDoorsInto(run, lb);
+ ScanBlockersInto(run, lb);
+ BuildDunExplore(run, isRebuild: false, why: "resume");
+ }
+
+ private uint CurrentLandblockOrZero()
+ => Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) && (cell & 0xFFFF) >= 0x0100 ? cell >> 16 : 0;
+
+ ///
+ /// Lays the explore's walk from where the character stands over the rooms it hasn't entered and
+ /// installs it. False when nothing was installed: refused (said), or nothing left to walk to (the
+ /// explore waits at shut doors, or is done).
+ ///
+ private bool BuildDunExplore(DunExploreRun run, bool isRebuild, string why)
+ {
+ bool resume = why == "resume";
+ if (Host.TryGetPlayerPose(out uint here, out _, out _, out _, out _, out _, out _, out _)
+ && (here & 0xFFFF) >= 0x0100 && (!isRebuild || (here >> 16) == run.Landblock))
+ run.VisitedCells.Add(here);
+
+ var b = TryBuildDunPatrol("dunnav-explore", out string error, out var refusal, explore: run);
+ if (b == null)
+ {
+ if (!isRebuild)
+ {
+ if (refusal == DunBuildRefusal.Policy) ChatLine(error); else ReplyFail(error);
+ return false;
+ }
+ // The rebuild couldn't be laid. Out of the dungeon, or the server says no: it ends. The client
+ // not ready (no position, the dats): the old walk goes on, and the next change tries again.
+ if (refusal is DunBuildRefusal.NotInDungeon or DunBuildRefusal.Policy or DunBuildRefusal.EmptyRoute)
+ EndDunExplore(run, DunExploreState.Stopped, refusal == DunBuildRefusal.Policy ? "the server asks for no dungeon patrols here" : "no walk from here", clearRoute: true);
+ Host.Log($"[RynthAi] DunNav-Explore: rebuild ({why}) not laid: {error}");
+ return false;
+ }
+
+ var settings = _dashboard!.Settings;
+ run.Plan = b.Plan ?? new ExplorePlan();
+ run.Landblock = b.World.Landblock;
+ run.HazardVersion = _objectCache?.HazardVersion ?? 0;
+ run.PortalIds.Clear();
+ foreach (var p in b.World.Portals) run.PortalIds.Add(p.Id);
+ run.NextCheckAt = Environment.TickCount64 + DunExploreCheckMs;
+ run.Recount();
+ if (here != 0) run.LastCell = here;
+ MeasureDoorsBehind(run, b.World, b.StartCell);
+
+ var route = b.Route;
+ if (route.Points.Count == 0)
+ {
+ // Every room it can walk to is entered: done, or waiting at the shut doors.
+ if (!isRebuild && !resume && run.Doors.Values.All(d => d.RoomsBehind == 0))
+ {
+ run.State = DunExploreState.Done;
+ run.EndedAt = Environment.TickCount64;
+ _dunExplore = run;
+ ReplyOk($"[RynthAi] DunNav-Explore: nothing to walk to: {run.Rooms} room(s) here, and you are in {(run.Rooms == 1 ? "it" : "all of them")}.");
+ return false;
+ }
+ _dunExplore = run;
+ FinishWalk(run);
+ return false;
+ }
+
+ if (!isRebuild)
+ {
+ if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return false; // one bot per client (Decal bridge)
+ settings.IsMacroRunning = true;
+ // As the patrol: the explore picked its own start; the macro-start "nearest waypoint" pick
+ // on the next tick must not move it (on a walk that ends it would skip rooms).
+ _macroWasRunning = true;
+ // A dungeon patrol running stands down without its "ended" line: the explore is the route now.
+ _dunPatrolActive = false;
+ _dunPatrolRoute = null;
+ }
+ settings.CurrentNavPath = string.Empty;
+ settings.CurrentRoute = route;
+ settings.ActiveNavIndex = b.StartIdx;
+ settings.EnableNavigation = true;
+ run.Route = route;
+ run.Errand = null;
+ run.State = DunExploreState.Exploring;
+
+ int left = run.Rooms - run.Entered;
+ string layout = run.Plan.ByRoom ? "" : " (dungeon map not loaded yet: cell by cell, rooms once it is)";
+ Host.Log($"[RynthAi] DunNav-Explore: {(isRebuild ? "relaid (" + why + ")" : resume ? "resumed" : "started")} in 0x{run.Landblock:X4}: {route.Points.Count} points from {b.StartIdx}, "
+ + $"{run.Entered} of {run.Rooms} rooms entered, {run.Plan.Order.Count} to go{layout}, sweep {run.Sweeps}, "
+ + $"{run.Doors.Count} shut door(s) ({run.RoomsBehindDoors} rooms behind){(run.PreferCells.Count > 0 ? ", behind the opened door first" : "")}");
+ if (!isRebuild)
+ {
+ int hazardCount = b.World.Hazards?.Count ?? 0;
+ string hazardNote = hazardCount > 0 ? $", {hazardCount} lava/acid cell(s) left out" : "";
+ string portalNote = b.World.Portals.Count > 0 ? $", kept out of {b.World.Portals.Count} portal(s)" : "";
+ string doorNote = run.Doors.Count > 0 ? $", round {run.Doors.Count} shut door(s)" : "";
+ ReplyOk($"[RynthAi] DunNav-Explore: {left} room(s) to walk through{layout}, {route.Points.Count} waypoints{hazardNote}{portalNote}{doorNote} → "
+ + (resume ? "exploring again" : "exploring") + "; it stops at the end. Fighting, looting and buffing follow your settings.");
+ }
+ return true;
+ }
+
+ /// The walk is over: monsters still in the dungeon walked to (enter and scan's sweep), then waiting at the
+ /// shut doors when rooms are behind them, else done.
+ private void FinishWalk(DunExploreRun run)
+ {
+ if (WalkToLeftoverMonster(run)) return;
+ var blocking = run.Doors.Values.Where(d => d.RoomsBehind > 0).OrderByDescending(d => d.RoomsBehind).ToList();
+ if (blocking.Count == 0)
+ {
+ EndDunExplore(run, DunExploreState.Done, "", clearRoute: true);
+ return;
+ }
+ var settings = _dashboard?.Settings;
+ if (settings != null)
+ {
+ // Navigation off, and an empty route of its own, so the explore keeps owning it while it waits.
+ settings.EnableNavigation = false;
+ settings.CurrentNavPath = string.Empty;
+ settings.CurrentRoute = new NavRouteParser();
+ settings.ActiveNavIndex = 0;
+ _navigationEngine?.Stop();
+ run.Route = settings.CurrentRoute;
+ }
+ run.State = DunExploreState.AtDoors;
+ run.Errand = null;
+ // Said once per set of doors (a lever that didn't do it comes back here without a new line).
+ string said = string.Join(",", blocking.Select(d => $"{d.Id:X8}:{d.RoomsBehind}"));
+ if (said == run.AtDoorsSaid) return;
+ run.AtDoorsSaid = said;
+ string list = string.Join(", ", blocking.Take(4).Select(d => $"{d.Name} 0x{d.Id:X8} ({d.RoomsBehind})"));
+ if (blocking.Count > 4) list += ", ...";
+ Host.Log($"[RynthAi] DunNav-Explore: at the shut doors in 0x{run.Landblock:X4}: {string.Join("; ", blocking.Select(d => $"0x{d.Id:X8} '{d.Name}' {d.Why}, {d.RoomsBehind} rooms, cell {d.Cell:X8}"))}");
+ ChatLine($"[RynthAi] DunNav-Explore: every room it can walk to is done ({run.Entered} of {run.Rooms}); {run.RoomsBehindDoors} room(s) are behind "
+ + $"{blocking.Count} shut door(s): {list}. /ra dunnav-explore lever pulls a lever; /ra dunnav-explore done ends it.");
+ }
+
+ /// At most this many walks to monsters left in the dungeon, a run.
+ private const int DunExploreMaxHunts = 12;
+ /// The monsters looked for at the end are this close (yards; the dungeon is one landblock).
+ private const double DunExploreHuntYd = 400;
+
+ ///
+ /// The sweep at the end of enter and scan (2026-11-16): a monster the fight would take (combat's hunt list: alive,
+ /// attackable, not blacklisted, on the monster list) still in this dungeon with a position the client knows (one in
+ /// a corner the walk only looked past; Thread 0x00B5's boss) is walked to, the nearest first, by the dungeon map;
+ /// the fight takes it on when it's in range. Each once; one it can't be walked to is left. True: a walk installed.
+ ///
+ /// Tests: the monsters combat would fight (null: combat's own hunt list).
+ internal Func>? LeftoverMonstersProbe;
+
+ private bool WalkToLeftoverMonster(DunExploreRun run)
+ {
+ if (run.HuntWalks >= DunExploreMaxHunts || run.State != DunExploreState.Exploring) return false;
+ var settings = _dashboard?.Settings;
+ if (settings == null || !settings.IsMacroRunning) return false;
+ var found = LeftoverMonstersProbe?.Invoke();
+ if (found == null)
+ {
+ if (_combatManager == null) return false;
+ found = new List();
+ _combatManager.HuntCandidates(DunExploreHuntYd, found);
+ }
+ var left = found.Where(c => (c.Cell >> 16) == run.Landblock && (c.Cell & 0xFFFF) >= 0x0100 && !run.HuntTried.Contains(c.Id)).ToList();
+ if (left.Count == 0) return false;
+ DunRouteWorld? w = null;
+ foreach (var c in left.Take(4))
+ {
+ run.HuntTried.Add(c.Id);
+ if (!Host.TryGetObjectPosition(unchecked((uint)c.Id), out uint cell, out float x, out float y, out float z) || (cell >> 16) != run.Landblock) continue;
+ if (w == null)
+ {
+ w = TryGetDunWorld("dunnav-explore", "DunNav-Explore", out _, out _, out _);
+ if (w == null) return false;
+ foreach (var closed in new[] { run.DoorEdges, run.StuckEdges, run.BlockedEdges })
+ if (closed.Count > 0) w.Graph = DungeonPathfinder.WithoutOpenings(w.Graph, closed, w.StartCell);
+ }
+ var b = DungeonRouteMaker.TryBuildRoute(w, new DunTarget(DunTargetKind.Position, X: x, Y: y, Z: z), out string error);
+ if (b == null || b.Route.Points.Count == 0)
+ {
+ Host.Log($"[RynthAi] DunNav-Explore: '{c.Name}' 0x{c.Id:X8} in cell {cell:X8} is still here but can't be walked to ({error}): left");
+ continue;
+ }
+ run.HuntWalks++;
+ settings.CurrentNavPath = string.Empty;
+ settings.CurrentRoute = b.Route;
+ settings.ActiveNavIndex = 0;
+ settings.EnableNavigation = true;
+ run.Route = b.Route;
+ int more = left.Count - 1;
+ Host.Log($"[RynthAi] DunNav-Explore: the walk is over and '{c.Name}' 0x{c.Id:X8} is still here, {c.Distance:F0} yd away in cell {cell:X8}: "
+ + $"walking to it ({b.Route.Points.Count} points; {more} more known)");
+ ChatLine($"[RynthAi] DunNav-Explore: {c.Name} is still in the dungeon ({c.Distance:F0} yd) → going after it"
+ + (more > 0 ? $"; {more} more after that." : "."));
+ return true;
+ }
+ return false;
+ }
+
+ private void ClearExploreRoute(DunExploreRun run)
+ {
+ var settings = _dashboard?.Settings;
+ if (settings == null || !ReferenceEquals(settings.CurrentRoute, run.Route)) return;
+ settings.EnableNavigation = false;
+ settings.CurrentRoute = new NavRouteParser();
+ settings.ActiveNavIndex = 0;
+ _navigationEngine?.Stop();
+ }
+
+ /// Ends the explore: done or stopped, one chat line. : its walk
+ /// is taken off and navigation switched off (not when another route has taken its place).
+ private void EndDunExplore(DunExploreRun run, DunExploreState state, string note, bool clearRoute)
+ {
+ if (!run.Active && run.State == state) return;
+ run.State = state;
+ run.EndedAt = Environment.TickCount64;
+ run.EndNote = note;
+ run.Errand = null;
+ if (clearRoute) ClearExploreRoute(run);
+ var settings = _dashboard?.Settings;
+ bool macro = settings?.IsMacroRunning == true;
+ int left = run.Rooms - run.Entered;
+ Host.Log($"[RynthAi] DunNav-Explore: {state} ({note}) in 0x{run.Landblock:X4}: {run.Entered} of {run.Rooms} rooms, {Took(run)}, sweeps {run.Sweeps}, "
+ + $"{run.Doors.Count} shut door(s) ({run.RoomsBehindDoors} rooms behind)");
+ if (state == DunExploreState.Done)
+ {
+ string missed = left > 0 ? $" ({left} couldn't be reached)" : "";
+ string doors = run.RoomsBehindDoors > 0 ? $"; {run.RoomsBehindDoors} more behind {run.Doors.Count(d => d.Value.RoomsBehind > 0)} shut door(s)" : "";
+ ChatLine($"[RynthAi] DunNav-Explore: done, {run.Entered} of {run.Rooms} rooms in {Took(run)}{missed}{doors}. Navigation is off; "
+ + (macro ? "the macro is still on (it fights and loots as set)." : "the macro is off."));
+ }
+ else
+ {
+ ChatLine($"[RynthAi] DunNav-Explore stopped ({note}): {run.Entered} of {run.Rooms} rooms entered."
+ + (clearRoute && macro ? " Navigation is off; the macro is still on." : ""));
+ }
+ }
+
+ // ── Shut doors ───────────────────────────────────────────────────────────
+
+ ///
+ /// The doors in that are shut to the character: closed, and either not
+ /// usable from where you stand (a lever opens them) or given up on by the door opener. New ones are
+ /// added to the run (and their openings closed); ones that have opened come back as
+ /// . True when anything changed.
+ ///
+ private bool ScanShutDoorsInto(DunExploreRun run, uint landblock, List? opened = null)
+ {
+ if (_objectCache == null || landblock == 0 || !Host.HasGetObjectPosition) return false;
+ bool changed = false;
+ Dictionary? graph = null;
+ DungeonGeometry? geo = null;
+ bool mapRead = false;
+ foreach (var wo in _objectCache.GetLandscapeObjects())
+ {
+ uint uid = unchecked((uint)wo.Id);
+ bool puzzle = IsPuzzleGate(uid);
+ if (!puzzle && !IsDoorObject(wo, uid)) continue;
+ if (!Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float z) || cell == 0) continue;
+ if ((cell >> 16) != landblock || (cell & 0xFFFF) < 0x0100) continue;
+ bool open = IsDoorOpen(wo.Id);
+ if (run.Doors.TryGetValue(uid, out var known))
+ {
+ if (open)
+ {
+ opened?.Add(known);
+ run.Unshut(uid);
+ _exploreRefusedDoors.Remove(uid);
+ changed = true;
+ Host.Log($"[RynthAi] DunNav-Explore: shut door 0x{uid:X8} '{known.Name}' is open now");
+ }
+ continue;
+ }
+ if (open || run.DoorsNowhere.Contains(uid)) continue;
+ string? why = null;
+ int usable = _objectCache.GetIntProperty(wo.Id, 16, -1); // ItemUseable
+ if (puzzle) why = "a Thread puzzle gate";
+ else if (usable >= 0 && (usable & UsableRemote) == 0) why = "can't be used";
+ else if (_exploreRefusedDoors.TryGetValue(uid, out string? refused)) why = refused;
+ if (why == null) continue;
+
+ if (!mapRead)
+ {
+ mapRead = true;
+ var map = DungeonMapOverride?.Invoke(landblock);
+ var cellDat = DungeonMapOverride == null ? _raycast?.GeometryLoader.CellDat : null;
+ graph = map?.Graph ?? (cellDat is { IsLoaded: true } ? DungeonPathfinder.GetGraph(landblock, cellDat) : null);
+ geo = map != null ? map.Value.Geo : cellDat is { IsLoaded: true } ? DungeonPathfinder.GetGeometry(landblock, cellDat, _raycast?.GeometryLoader?.DungeonLOS) : null;
+ }
+ if (graph == null) return changed;
+ double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
+ var door = new ExploreDoor { Id = uid, Name = wo.Name ?? "Door", Cell = cell, X = wx, Y = wy, Z = z, Why = why };
+ door.Edges.UnionWith(DungeonPathfinder.DoorOpenings(graph, geo, cell, wx, wy, z));
+ if (door.Edges.Count == 0)
+ {
+ run.DoorsNowhere.Add(uid);
+ Host.Log($"[RynthAi] DunNav-Explore: door 0x{uid:X8} '{door.Name}' ({why}) stands in no opening the map knows: left alone");
+ continue;
+ }
+ run.Shut(door);
+ changed = true;
+ Host.Log($"[RynthAi] DunNav-Explore: shut door 0x{uid:X8} '{door.Name}' ({why}) at ({x:F1},{y:F1},{z:F1}) cell {cell:X8}: "
+ + $"{door.Edges.Count} opening(s) closed for the walk");
+ }
+ return changed;
+ }
+
+ // DreamWeave's Thread puzzle gates (PuzzleGateTunables: door, garrison, reinforced, Olthoi, barrier panel, arch hall):
+ // spawned (not a static id), locked, opened or destroyed only by solving their levers' puzzle. A wall to the walk.
+ // Their levers (wcid 1006851) are never pulled: three wrong pulls in an hour ban the connection from Threads.
+ private static readonly HashSet PuzzleGateWcids = new() { 1006850, 1006853, 1006854, 1006855, 1006856, 1007507 };
+ private const uint PuzzleLeverWcid = 1006851;
+
+ private bool IsPuzzleGate(uint uid)
+ => Host.HasGetObjectWcid && Host.TryGetObjectWcid(uid, out uint wcid) && PuzzleGateWcids.Contains(wcid);
+
+ /// A door as the door opener tells one (DoorInteractionController): a static object whose weenie
+ /// bitfield says door (BF_DOOR 0x1000), or by its name when the engine can't read bitfields.
+ private bool IsDoorObject(WorldObject wo, uint uid)
+ {
+ if (uid >= 0x80000000u) return false;
+ if (Host.HasGetObjectBitfield) return Host.TryGetObjectBitfield(uid, out uint bf) && (bf & 0x1000u) != 0;
+ string n = (wo.Name ?? string.Empty).ToLowerInvariant();
+ return n.Contains("door") || n.Contains("gate") || n.Contains("hatch") || n.Contains("portcullis");
+ }
+
+ /// For each shut door, the cells (and rooms) behind it: walkable to with it open, not with it shut.
+ private static void MeasureDoorsBehind(DunExploreRun run, DunRouteWorld w, uint startCell)
+ {
+ if (run.Doors.Count == 0) return;
+ var baseGraph = w.Graph;
+ var now = DungeonPathfinder.ReachableCells(DungeonPathfinder.WithoutOpenings(baseGraph, run.DoorEdges, startCell), startCell, w.Hazards);
+ foreach (var d in run.Doors.Values)
+ {
+ var others = new HashSet(run.Doors.Values.Where(o => o.Id != d.Id).SelectMany(o => o.Edges));
+ var with = DungeonPathfinder.ReachableCells(DungeonPathfinder.WithoutOpenings(baseGraph, others, startCell), startCell, w.Hazards);
+ with.ExceptWith(now);
+ d.CellsBehind = with;
+ var rooms = new HashSet();
+ foreach (uint c in with) { int r = run.Plan.RoomOf(c); rooms.Add(r >= 0 ? r : -(int)(c & 0x7FFF) - 1); }
+ d.RoomsBehind = rooms.Count;
+ }
+ }
+
+ // ── Levers ───────────────────────────────────────────────────────────────
+
+ /// /ra dunnav-explore lever <id> [door <id>] [at <x> <y> <z>] [plate]
+ private void StartLeverErrand(DunExploreRun? run, string[] args)
+ {
+ if (run is not { Active: true }) { ReplyFail("[RynthAi] DunNav-Explore: a lever is pulled for an explore; none is running (/ra dunnav-explore starts one)."); return; }
+ if (run.State == DunExploreState.Lever) { ReplyFail($"[RynthAi] DunNav-Explore: already at a lever (0x{run.Errand?.Lever:X8})."); return; }
+ if (args.Length == 0 || !TryParseId(args[0], out uint lever))
+ {
+ ReplyFail("[RynthAi] Usage: /ra dunnav-explore lever [door ] [at ] [plate] (ids in hex; x y z landblock-local metres)");
+ return;
+ }
+ uint door = 0;
+ bool plate = false;
+ double? ax = null, ay = null, az = null;
+ for (int i = 1; i < args.Length; i++)
+ {
+ string a = args[i].ToLowerInvariant();
+ if (a == "door" && i + 1 < args.Length && TryParseId(args[i + 1], out uint d)) { door = d; i++; }
+ else if (a == "plate") plate = true;
+ else if (a == "at" && i + 3 < args.Length
+ && double.TryParse(args[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out double px)
+ && double.TryParse(args[i + 2], NumberStyles.Float, CultureInfo.InvariantCulture, out double py)
+ && double.TryParse(args[i + 3], NumberStyles.Float, CultureInfo.InvariantCulture, out double pz))
+ { ax = px; ay = py; az = pz; i += 3; }
+ else { ReplyFail($"[RynthAi] DunNav-Explore: \"{args[i]}\" isn't part of a lever command. " + DunExploreUsage); return; }
+ }
+
+ // A Thread puzzle lever is never pulled: a wrong pull resets the puzzle, and three in an hour ban the
+ // connection from Threads (DreamWeave ThreadPuzzleFailPolicy).
+ if (Host.HasGetObjectWcid && Host.TryGetObjectWcid(lever, out uint leverWcid) && leverWcid == PuzzleLeverWcid)
+ {
+ LeverResult(run, $"puzzle {lever:X8} {door:X8}", $"0x{lever:X8} is a Thread puzzle lever: the explore never pulls one (wrong pulls ban you from Threads)");
+ return;
+ }
+
+ // Where the lever is: the client's own position for it, else the one given (ACE's data).
+ double lx, ly, lz;
+ string name = _objectCache?[unchecked((int)lever)]?.Name is { Length: > 0 } n ? n : (plate ? "Pressure Plate" : "Lever");
+ if (Host.TryGetObjectPosition(lever, out uint lcell, out float ox, out float oy, out float oz) && lcell != 0 && (lcell >> 16) == run.Landblock)
+ { lx = ox; ly = oy; lz = oz; }
+ else if (ax.HasValue) { lx = ax.Value; ly = ay!.Value; lz = az!.Value; }
+ else
+ {
+ LeverResult(run, $"notfound {lever:X8} {door:X8}", $"lever 0x{lever:X8} isn't in view and no position was given (at )");
+ return;
+ }
+
+ var w = TryGetDunWorld("dunnav-explore lever", "DunNav-Explore", out _, out string error, out _);
+ if (w == null) { ReplyFail(error); return; }
+ if (run.DoorEdges.Count > 0) w.Graph = DungeonPathfinder.WithoutOpenings(w.Graph, run.DoorEdges, w.StartCell);
+ var b = DungeonRouteMaker.TryBuildRoute(w, new DunTarget(DunTargetKind.Position, X: lx, Y: ly, Z: lz), out error);
+ if (b == null || b.Route.Points.Count == 0)
+ {
+ LeverResult(run, $"unreachable {lever:X8} {door:X8}", $"{name} 0x{lever:X8} can't be walked to from here ({error})");
+ return;
+ }
+
+ var settings = _dashboard!.Settings;
+ if (!settings.IsMacroRunning)
+ {
+ if (RefuseMacroStartForVTank()) return;
+ settings.IsMacroRunning = true;
+ _macroWasRunning = true;
+ }
+ settings.CurrentNavPath = string.Empty;
+ settings.CurrentRoute = b.Route;
+ settings.ActiveNavIndex = 0;
+ settings.EnableNavigation = true;
+ run.Route = b.Route;
+ long now = Environment.TickCount64;
+ uint lb = run.Landblock;
+ run.Errand = new LeverErrand
+ {
+ Lever = lever, Door = door, LeverName = name, Plate = plate,
+ X = ((lb >> 8) & 0xFF) * 192.0 + lx, Y = (lb & 0xFF) * 192.0 + ly, Z = lz,
+ StartedAt = now, PhaseAt = now,
+ };
+ run.State = DunExploreState.Lever;
+ string forDoor = door != 0 && run.Doors.TryGetValue(door, out var sd) ? $" for {sd.Name} 0x{door:X8} ({sd.RoomsBehind} room(s) behind it)" : door != 0 ? $" for door 0x{door:X8}" : "";
+ Host.Log($"[RynthAi] DunNav-Explore: lever errand: {name} 0x{lever:X8}{forDoor} at ({lx:F1},{ly:F1},{lz:F1}){(plate ? " (a plate: stepped on)" : "")}, {b.Route.Points.Count} points, {b.Yards:F0} yd");
+ ReplyOk($"[RynthAi] DunNav-Explore: going to {(plate ? "step on" : "pull")} {name} 0x{lever:X8}{forDoor}, {b.Yards:F0} yd.");
+ }
+
+ private static bool TryParseId(string s, out uint id)
+ {
+ s = s.Trim();
+ if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) s = s.Substring(2);
+ return uint.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id) && id != 0;
+ }
+
+ /// A lever that didn't do it: the result kept for radunexploreinfo[], and the walk goes on (or waits at the doors).
+ private void LeverResult(DunExploreRun run, string result, string said)
+ {
+ run.LastLever = result;
+ run.Errand = null;
+ ChatLine($"[RynthAi] DunNav-Explore: {said}.");
+ Host.Log($"[RynthAi] DunNav-Explore: lever result: {result} ({said})");
+ if (run.State == DunExploreState.Lever || run.State == DunExploreState.AtDoors)
+ {
+ // Carry on with whatever is left to walk (nothing: back to waiting at the doors).
+ run.State = DunExploreState.Exploring;
+ BuildDunExplore(run, isRebuild: true, why: "after a lever");
+ }
+ }
+
+ /// The lever errand, once a tick: walk, use (or stand on the plate), watch the door.
+ private void TickLeverErrand(DunExploreRun run, LegacyUiSettings settings, uint cell, double px, double py, double pz)
+ {
+ var e = run.Errand!;
+ long now = Environment.TickCount64;
+ double d2 = Math.Sqrt((px - e.X) * (px - e.X) + (py - e.Y) * (py - e.Y));
+ double dz = Math.Abs(pz - e.Z);
+ if (now - e.StartedAt > LeverErrandMaxMs)
+ {
+ LeverResult(run, $"unreachable {e.Lever:X8} {e.Door:X8}", $"couldn't get to {e.LeverName} 0x{e.Lever:X8} in {LeverErrandMaxMs / 1000} s");
+ return;
+ }
+ if (e.Phase == "walking")
+ {
+ if (!settings.IsMacroRunning) return; // paused with the macro
+ bool routeOver = run.Route == null || settings.ActiveNavIndex >= run.Route.Points.Count;
+ double reach = e.Plate ? PlateReachMeters : LeverReachMeters;
+ if ((d2 > reach || dz > 2.5) && !routeOver) return;
+ settings.EnableNavigation = false;
+ _navigationEngine?.Stop();
+ if (e.Plate)
+ {
+ if (d2 > 1.5 || dz > 2.5)
+ {
+ LeverResult(run, $"unreachable {e.Lever:X8} {e.Door:X8}", $"couldn't step onto {e.LeverName} 0x{e.Lever:X8} ({d2:F1} m off)");
+ return;
+ }
+ }
+ else
+ {
+ if (d2 > LeverUseFromMeters || dz > 3.0)
+ {
+ LeverResult(run, $"unreachable {e.Lever:X8} {e.Door:X8}", $"couldn't get to {e.LeverName} 0x{e.Lever:X8} ({d2:F1} m off)");
+ return;
+ }
+ e.Uses++;
+ Host.UseFor(e.Lever, "Explore", $"pull the lever for shut door 0x{e.Door:X8}", UseKind.Asked);
+ }
+ e.Phase = "waiting";
+ e.PhaseAt = now;
+ return;
+ }
+
+ // Waiting: the door (or, with none named, any shut door) open?
+ ExploreDoor? openedDoor = null;
+ if (e.Door != 0)
+ {
+ if (IsDoorOpen(unchecked((int)e.Door)))
+ openedDoor = run.Doors.TryGetValue(e.Door, out var kd) ? kd : new ExploreDoor { Id = e.Door, Name = "door" };
+ }
+ else openedDoor = run.Doors.Values.FirstOrDefault(d => IsDoorOpen(unchecked((int)d.Id)));
+ if (openedDoor != null)
+ {
+ var behind = new HashSet(openedDoor.CellsBehind);
+ run.Unshut(openedDoor.Id);
+ _exploreRefusedDoors.Remove(openedDoor.Id);
+ run.LastLever = $"opened {openedDoor.Id:X8} {e.Lever:X8}";
+ run.Errand = null;
+ run.PreferCells.Clear();
+ run.PreferCells.UnionWith(behind);
+ ChatLine($"[RynthAi] DunNav-Explore: {e.LeverName} 0x{e.Lever:X8} opened {openedDoor.Name} 0x{openedDoor.Id:X8} → through it first ({openedDoor.RoomsBehind} room(s) behind it).");
+ run.State = DunExploreState.Exploring;
+ BuildDunExplore(run, isRebuild: true, why: "a lever opened a door");
+ return;
+ }
+ if (!e.Plate && e.Uses < 2 && now - e.PhaseAt > LeverReuseMs)
+ {
+ e.Uses++;
+ Host.UseFor(e.Lever, "Explore", $"pull the lever for shut door 0x{e.Door:X8} (again)", UseKind.Asked);
+ }
+ if (now - e.PhaseAt > (e.Plate ? PlateWatchMs : LeverWatchMs))
+ LeverResult(run, $"notopened {e.Lever:X8} {e.Door:X8}", $"{e.LeverName} 0x{e.Lever:X8} didn't open {(e.Door != 0 ? $"door 0x{e.Door:X8}" : "a shut door")}");
+ }
+
+ // ── The tick ─────────────────────────────────────────────────────────────
+
+ ///
+ /// Once per tick while an explore runs: the room the character is in counts as entered; the walk
+ /// over means a second look for rooms missed, then waiting at the shut doors or done; another route
+ /// or the dungeon left ends it; a hazard, a new portal, a shut door (or one opening) or the map
+ /// loading lays the rest again; a lever errand walks, uses and watches.
+ ///
+ private void TickDunExplore()
+ {
+ var run = _dunExplore;
+ if (run is not { Active: true }) return;
+ var settings = _dashboard?.Settings;
+ if (settings == null) return;
+
+ if (ServerPolicy.PatrolOff(Host))
+ {
+ EndDunExplore(run, DunExploreState.Stopped, "the server asks for no dungeon patrols here", clearRoute: true);
+ ChatLine(ServerPolicy.PatrolOffMessage);
+ return;
+ }
+
+ // Another route took the explore's place (a nav file, a meta's route, the patrol): it ends, that route stays.
+ if (!ReferenceEquals(settings.CurrentRoute, run.Route) || !string.IsNullOrEmpty(settings.CurrentNavPath))
+ {
+ string what = _dunPatrolActive && _dunPatrolRoute != null && ReferenceEquals(settings.CurrentRoute, _dunPatrolRoute)
+ ? "the dungeon patrol" : PatrolReplacementName(settings);
+ EndDunExplore(run, DunExploreState.Stopped, $"{what} is the route now", clearRoute: false);
+ return;
+ }
+
+ if (!Host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float pz, out _, out _, out _, out _) || cell == 0) return;
+ if ((cell >> 16) != run.Landblock || (cell & 0xFFFF) < 0x0100)
+ {
+ EndDunExplore(run, DunExploreState.Stopped, "you left the dungeon", clearRoute: true);
+ return;
+ }
+ if (cell != run.LastCell)
+ {
+ run.LastCell = cell;
+ run.Enter(cell);
+ }
+
+ if (run.State == DunExploreState.Lever && run.Errand != null)
+ {
+ TickLeverErrand(run, settings, cell, ((cell >> 24) & 0xFF) * 192.0 + lx, ((cell >> 16) & 0xFF) * 192.0 + ly, pz);
+ return;
+ }
+
+ long now = Environment.TickCount64;
+ if (run.State == DunExploreState.AtDoors)
+ {
+ // A shut door that opens (someone pulled its lever, it opened on its own): the walk goes through it.
+ if (now < run.NextCheckAt) return;
+ run.NextCheckAt = now + DunExploreCheckMs;
+ var opened = new List();
+ ScanShutDoorsInto(run, run.Landblock, opened);
+ if (opened.Count > 0)
+ {
+ run.PreferCells.Clear();
+ foreach (var d in opened) run.PreferCells.UnionWith(d.CellsBehind);
+ ChatLine($"[RynthAi] DunNav-Explore: {opened[0].Name} 0x{opened[0].Id:X8} is open → through it first.");
+ run.State = DunExploreState.Exploring;
+ BuildDunExplore(run, isRebuild: true, why: "a shut door opened");
+ }
+ return;
+ }
+
+ var route = run.Route!;
+ if (route.Points.Count == 0 || settings.ActiveNavIndex >= route.Points.Count)
+ {
+ // The walk is over (the navigation engine switched navigation off at its end).
+ int left = run.Rooms - run.Entered;
+ if (left > 0 && run.Sweeps < DunExploreMaxSweeps && run.Entered > run.EnteredAtSweep)
+ {
+ run.Sweeps++;
+ run.EnteredAtSweep = run.Entered;
+ ChatLine($"[RynthAi] DunNav-Explore: {left} room(s) passed by without going in → going back for them.");
+ if (BuildDunExplore(run, isRebuild: true, why: "rooms missed")) return;
+ if (!run.Active || run.State == DunExploreState.AtDoors) return;
+ }
+ FinishWalk(run);
+ return;
+ }
+
+ bool running = settings.IsMacroRunning && settings.EnableNavigation;
+ run.State = running ? DunExploreState.Exploring : DunExploreState.Paused;
+ if (!running) return;
+
+ // Stuck for good where the map says the way is open: close that opening and go round it.
+ if (StuckForGood()
+ && run.StuckNotes.Count < DunExploreMaxStuckOpenings
+ && CloseStuckOpening(run, settings, cell, lx, ly, pz))
+ {
+ BuildDunExplore(run, isRebuild: true, why: "couldn't get through");
+ return;
+ }
+
+ bool hazards = _objectCache != null && _objectCache.HazardVersion != run.HazardVersion;
+ bool portal = false, map = false, doors = false, blocked = false;
+ if (now >= run.NextCheckAt)
+ {
+ run.NextCheckAt = now + DunExploreCheckMs;
+ portal = ExplorePortalAppeared(run);
+ map = !run.Plan.ByRoom && ExploreMapReady(run.Landblock);
+ var opened = new List();
+ doors = ScanShutDoorsInto(run, run.Landblock, opened);
+ if (opened.Count > 0)
+ {
+ run.PreferCells.Clear();
+ foreach (var d in opened) run.PreferCells.UnionWith(d.CellsBehind);
+ }
+ blocked = ScanBlockersInto(run, run.Landblock);
+ }
+ if (!hazards && !portal && !map && !doors && !blocked) return;
+
+ string why = hazards ? "new hazard" : doors ? "shut door" : blocked ? "something in a doorway" : portal ? "portal came into view" : "dungeon map loaded";
+ int before = run.Entered;
+ if (BuildDunExplore(run, isRebuild: true, why) && hazards)
+ ChatLine($"[RynthAi] DunNav-Explore: new hazard sighted → rerouted around it ({before} of {run.Rooms} rooms entered).");
+ }
+
+ /// The explore's side of a way it can't get through: closed for its walk, said in chat.
+ private bool CloseStuckOpening(DunExploreRun run, LegacyUiSettings settings, uint cell, float lx, float ly, float z)
+ {
+ var closed = run.BlockedEdges.Count == 0 ? run.StuckEdges : new HashSet(run.StuckEdges.Concat(run.BlockedEdges));
+ if (!TryFindStuckOpening(run.Route, run.Landblock, closed, run.StuckNotes.Count, settings.ActiveNavIndex, cell, lx, ly, z,
+ "DunNav-Explore", out var keys, out string note, out var inIt, out var spot))
+ return false;
+ if (spot != null)
+ {
+ run.StuckSpots.Add(spot);
+ run.StuckNotes.Add(note);
+ ChatLine($"[RynthAi] DunNav-Explore: couldn't get past something at {note} (not on the dungeon map) → walking round that spot.");
+ return true;
+ }
+ run.StuckEdges.UnionWith(keys);
+ run.StuckNotes.Add(note);
+ // What stands in that doorway (named in the log): any other one of its name in a doorway is walked round.
+ foreach (string n in inIt)
+ if (run.BlockerNames.Add(n))
+ Host.Log($"[RynthAi] DunNav-Explore: '{n}' stood in the doorway it couldn't get through: each other '{n}' in a doorway is walked round");
+ ChatLine($"[RynthAi] DunNav-Explore: couldn't get past something between {note} (not on the dungeon map) → going round it; rooms only that way are left out.");
+ return true;
+ }
+
+ ///
+ /// The opening the character was heading through when it got stuck for good (the explore and the patrol):
+ /// the first step from its cell towards the next waypoint in another cell (within StuckLookAheadPoints of
+ /// ), not one of . False when there is none (the next
+ /// points are all in this cell, no map, no way). : the opening's cell pairs not closed
+ /// yet; : the openings closed before it (for the log).
+ ///
+ private bool TryFindStuckOpening(NavRouteParser? route, uint landblock, IReadOnlySet closed, int stuckCount, int activeIdx,
+ uint cell, float lx, float ly, float z, string label, out HashSet keys, out string note,
+ out List inDoorway, out PatrolPortal? spot)
+ {
+ keys = new HashSet();
+ note = "";
+ inDoorway = new List();
+ spot = null;
+ if (route == null || route.Points.Count == 0) return false;
+ var map = DungeonMapOverride?.Invoke(landblock);
+ var cellDat = DungeonMapOverride == null ? _raycast?.GeometryLoader.CellDat : null;
+ var graph = map?.Graph ?? (cellDat is { IsLoaded: true } ? DungeonPathfinder.GetGraph(landblock, cellDat) : null);
+ if (graph == null || graph.Count == 0) return false;
+ var geo = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(landblock, cellDat!, _raycast?.GeometryLoader?.DungeonLOS);
+ double wx = ((cell >> 24) & 0xFF) * 192.0 + lx, wy = ((cell >> 16) & 0xFF) * 192.0 + ly;
+ uint from = graph.ContainsKey(cell) ? cell : DungeonPathfinder.NearestCell(graph, DungeonGeometry.WorldToNav(wy), DungeonGeometry.WorldToNav(wx), z);
+ if (from == 0) return false;
+
+ uint toward = 0;
+ // A Circular route (the patrol) goes on past its end; a Once route (the explore) stops there.
+ int n = route.Points.Count;
+ int at = Math.Clamp(activeIdx, 0, n - 1);
+ bool loop = route.RouteType == NavRouteType.Circular;
+ for (int k = 0; k < StuckLookAheadPoints && (loop ? k < n : at + k < n); k++)
+ {
+ uint c = DungeonPathfinder.CellAt(graph, geo, route.Points[(at + k) % n]);
+ if (c != 0 && c != from) { toward = c; break; }
+ }
+ if (toward == 0)
+ {
+ if (geo != null && StuckSpot(route, at, from, wx, wy, z, label, lx, ly, "with the next points in its cell too", out spot, out note)) return true;
+ Host.Log($"[RynthAi] {label}: stuck in cell {from:X8} with the next {StuckLookAheadPoints} points in it too: nothing to close");
+ return false;
+ }
+ var open = closed.Count > 0 ? DungeonPathfinder.WithoutOpenings(graph, new HashSet(closed), from) : graph;
+ var path = DungeonPathfinder.FindPath(from, toward, open, null);
+ if (path.Count < 2) return false;
+ uint a = path[0], b = path[1];
+ // Stuck in a room, away from the doorway on its way (2026-11-16, a DreamWeave hall 0x01F5: 5 and 11 m from it;
+ // three openings were closed one after another and it was stuck as before): the thing in the way is where it
+ // stands, not in that doorway. A spot just ahead of it is walked round instead.
+ if (geo != null && geo.TryGetDoorway(a, b, out var onWay))
+ {
+ double doorDist = Math.Sqrt((onWay.X - wx) * (onWay.X - wx) + (onWay.Y - wy) * (onWay.Y - wy));
+ if (doorDist > StuckAtDoorwayMeters
+ && StuckSpot(route, at, from, wx, wy, z, label, lx, ly, $"{doorDist:F0} m from the doorway on its way", out spot, out note))
+ return true;
+ }
+ // Every cell pair through that opening (a cell stacked on another at a room's edge gives it two:
+ // DungeonPathfinder.OpeningPairs), or the walk laid again goes through the same gap.
+ keys = DungeonPathfinder.OpeningPairs(graph, geo, a, b);
+ keys.ExceptWith(closed);
+ if (keys.Count == 0) return false;
+ note = $"cells {a:X8} and {b:X8}";
+ string twins = keys.Count > 1 ? $" and {keys.Count - 1} more cell pair(s) through the same opening" : "";
+ string seen = geo != null && geo.TryGetDoorway(a, b, out var dw) ? ThingsInDoorway(landblock, dw, inDoorway) : "";
+ Host.Log($"[RynthAi] {label}: stuck for good at ({lx:F1},{ly:F1},{z:F1}) heading for waypoint {at} (cell {toward:X8}): "
+ + $"closing the opening between {note}{twins} ({stuckCount + 1} closed){seen}");
+ return true;
+ }
+
+ /// The spot just ahead of the character (StuckSpotAhead towards the waypoint it heads for, StuckSpotRadius
+ /// across) it got stuck at, to walk round (a PatrolPortal: the walk keeps out of its circle). False with the waypoint
+ /// on top of it.
+ private bool StuckSpot(NavRouteParser route, int at, uint cell, double wx, double wy, double z, string label, float lx, float ly,
+ string where, out PatrolPortal? spot, out string note)
+ {
+ spot = null;
+ note = "";
+ var p = route.Points[at];
+ double tx = DungeonGeometry.NavToWorld(p.EW) - wx, ty = DungeonGeometry.NavToWorld(p.NS) - wy, tl = Math.Sqrt(tx * tx + ty * ty);
+ if (tl < 0.5) return false;
+ double ahead = Math.Min(StuckSpotAhead, tl);
+ spot = new PatrolPortal
+ {
+ Name = "a spot it got stuck at", Cell = cell,
+ X = wx + tx / tl * ahead, Y = wy + ty / tl * ahead, Z = z, Radius = StuckSpotRadius,
+ };
+ note = $"a spot in cell {cell:X8}";
+ Host.Log($"[RynthAi] {label}: stuck for good at ({lx:F1},{ly:F1},{z:F1}) heading for waypoint {at}, {where}: "
+ + $"walking round the spot ({spot.X:F1},{spot.Y:F1}) {StuckSpotRadius:F1} m round it");
+ return true;
+ }
+
+ // ── Things in doorways ───────────────────────────────────────────────────
+ // Things a server puts in a doorway are on no map: the walk goes through and the character runs into one until
+ // the stuck fallback gives the doorway up a minute later (TryFindStuckOpening). (Thread 0x5456's spider webs,
+ // 2026-11-14 and 11-16, turned out to be the cells' own placed objects: the map closes those itself,
+ // DungeonPathfinder.Blocked.cs.) A thing named like a web standing in a doorway, and in this run anything of a
+ // name it got stuck on in a doorway, closes that doorway before it is walked. The rooms only that way are left
+ // out, as behind a doorway it couldn't get through.
+
+ /// A doorway's middle is this close to a thing (horizontally) for it to stand in the doorway.
+ private const double BlockerInDoorwayMeters = 1.5;
+
+ private static bool NamedLikeWeb(string name) => name.IndexOf("web", StringComparison.OrdinalIgnoreCase) >= 0;
+
+ /// Not a thing left standing in a doorway: a creature, a person, a door (the shut-door scan has those),
+ /// a portal, a corpse, a lifestone, a pet.
+ private static bool CanBlockDoorway(WorldObject wo) => wo.ObjectClass is not (AcObjectClass.Monster or AcObjectClass.Player
+ or AcObjectClass.Npc or AcObjectClass.Vendor or AcObjectClass.Door or AcObjectClass.Portal or AcObjectClass.Corpse
+ or AcObjectClass.Lifestone or AcObjectClass.CombatPet);
+
+ ///
+ /// The things in that stand in a doorway the walk would go through: named like a web,
+ /// or a name in run.BlockerNames. New ones close their doorway (every cell pair of it) for the walk. True when
+ /// anything was added.
+ ///
+ private bool ScanBlockersInto(DunExploreRun run, uint landblock)
+ {
+ if (_objectCache == null || landblock == 0 || !Host.HasGetObjectPosition) return false;
+ bool changed = false;
+ Dictionary? graph = null;
+ DungeonGeometry? geo = null;
+ bool mapRead = false;
+ foreach (var wo in _objectCache.GetLandscapeObjects())
+ {
+ uint uid = unchecked((uint)wo.Id);
+ if (run.Blockers.ContainsKey(uid) || run.BlockersNowhere.Contains(uid)) continue;
+ string name = wo.Name ?? "";
+ if (name.Length == 0 || !CanBlockDoorway(wo) || !(NamedLikeWeb(name) || run.BlockerNames.Contains(name))) continue;
+ if (!Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float z) || cell == 0) continue;
+ if ((cell >> 16) != landblock || (cell & 0xFFFF) < 0x0100) continue;
+ if (!mapRead)
+ {
+ mapRead = true;
+ var map = DungeonMapOverride?.Invoke(landblock);
+ var cellDat = DungeonMapOverride == null ? _raycast?.GeometryLoader.CellDat : null;
+ graph = map?.Graph ?? (cellDat is { IsLoaded: true } ? DungeonPathfinder.GetGraph(landblock, cellDat) : null);
+ geo = map != null ? map.Value.Geo : cellDat is { IsLoaded: true } ? DungeonPathfinder.GetGeometry(landblock, cellDat, _raycast?.GeometryLoader?.DungeonLOS) : null;
+ }
+ if (graph == null || geo == null) return changed;
+ double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
+ var edges = DungeonPathfinder.DoorwayAt(graph, geo, wx, wy, z, BlockerInDoorwayMeters, out var dw);
+ if (edges.Count == 0 || dw == null)
+ {
+ run.BlockersNowhere.Add(uid);
+ Host.Log($"[RynthAi] DunNav-Explore: 0x{uid:X8} '{name}' at ({x:F1},{y:F1},{z:F1}) cell {cell:X8} stands in no doorway: left alone");
+ continue;
+ }
+ run.Blockers[uid] = name;
+ run.BlockedEdges.UnionWith(edges);
+ changed = true;
+ Host.Log($"[RynthAi] DunNav-Explore: 0x{uid:X8} '{name}' ({wo.ObjectClass}) at ({x:F1},{y:F1},{z:F1}) cell {cell:X8} stands in the doorway "
+ + $"between cells {dw.CellA:X8} and {dw.CellB:X8} ({edges.Count} cell pair(s)): closed for the walk");
+ ChatLine($"[RynthAi] DunNav-Explore: {name} in the doorway between cells {dw.CellA:X8} and {dw.CellB:X8} → going round it; rooms only that way are left out.");
+ }
+ return changed;
+ }
+
+ /// For the stuck log: the things (not creatures, people, doors...) standing in ;
+ /// the names of those within BlockerInDoorwayMeters of its middle go to .
+ private string ThingsInDoorway(uint landblock, DungeonDoorway dw, List names)
+ {
+ if (_objectCache == null || !Host.HasGetObjectPosition) return "";
+ var parts = new List();
+ foreach (var wo in _objectCache.GetLandscapeObjects())
+ {
+ uint uid = unchecked((uint)wo.Id);
+ if (!CanBlockDoorway(wo) || !Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float z) || (cell >> 16) != landblock) continue;
+ double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
+ double h = Math.Sqrt((wx - dw.X) * (wx - dw.X) + (wy - dw.Y) * (wy - dw.Y));
+ if (h > 3.0 || Math.Abs(z - dw.Z) > 3.0) continue;
+ string name = wo.Name ?? "";
+ parts.Add($"0x{uid:X8} '{name}' ({wo.ObjectClass}) {h:F1} m from its middle");
+ if (h <= BlockerInDoorwayMeters && name.Length > 0 && !names.Contains(name)) names.Add(name);
+ }
+ return parts.Count == 0 ? "; nothing the client knows stands in it" : "; in it: " + string.Join(", ", parts.Take(6));
+ }
+
+ private bool ExplorePortalAppeared(DunExploreRun run)
+ {
+ foreach (var p in PatrolPortalsIn(run.Landblock))
+ {
+ if (run.PortalIds.Contains(p.Id)) continue;
+ Host.Log($"[RynthAi] DunNav-Explore: portal 0x{p.Id:X8} '{p.Name}' came into view at ({p.X:F1},{p.Y:F1},{p.Z:F1}) cell {p.Cell:X8}: laying the rest round it");
+ return true;
+ }
+ return false;
+ }
+
+ private bool ExploreMapReady(uint landblock)
+ {
+ if (DungeonMapOverride != null) return DungeonMapOverride(landblock)?.Geo is { DoorwayCount: > 0 };
+ var cellDat = _raycast?.GeometryLoader?.CellDat;
+ if (cellDat == null || !cellDat.IsLoaded) return false;
+ return DungeonPathfinder.GetGeometry(landblock, cellDat, _raycast?.GeometryLoader?.DungeonLOS) is { DoorwayCount: > 0 };
+ }
+
+ // ── radunexploreinfo[] ───────────────────────────────────────────────────
+
+ /// The explore as JSON for radunexploreinfo[] (landblock-local metres for positions).
+ private string DunExploreInfoJson()
+ {
+ var run = _dunExplore;
+ if (run == null) return "{}";
+ var inv = CultureInfo.InvariantCulture;
+ uint lb = run.Landblock;
+ double ox = ((lb >> 8) & 0xFF) * 192.0, oy = (lb & 0xFF) * 192.0;
+ var sb = new StringBuilder(256);
+ sb.Append("{\"state\":").Append((int)run.State)
+ .Append(",\"rooms\":").Append(run.Rooms)
+ .Append(",\"entered\":").Append(run.Entered)
+ .Append(",\"landblock\":\"").Append(lb.ToString("X4", inv)).Append('"')
+ .Append(",\"doors\":[");
+ bool first = true;
+ foreach (var d in run.Doors.Values.OrderByDescending(d => d.RoomsBehind).ThenBy(d => d.Id))
+ {
+ if (!first) sb.Append(',');
+ first = false;
+ sb.Append("{\"id\":\"").Append(d.Id.ToString("X8", inv)).Append("\",\"name\":").Append(JsonText(d.Name))
+ .Append(",\"why\":").Append(JsonText(d.Why))
+ .Append(",\"rooms\":").Append(d.RoomsBehind)
+ .Append(",\"cell\":\"").Append(d.Cell.ToString("X8", inv)).Append('"')
+ .Append(",\"x\":").Append((d.X - ox).ToString("0.###", inv))
+ .Append(",\"y\":").Append((d.Y - oy).ToString("0.###", inv))
+ .Append(",\"z\":").Append(d.Z.ToString("0.###", inv)).Append('}');
+ }
+ sb.Append(']');
+ var e = run.Errand;
+ if (e != null)
+ sb.Append(",\"errand\":{\"lever\":\"").Append(e.Lever.ToString("X8", inv)).Append("\",\"door\":\"").Append(e.Door.ToString("X8", inv))
+ .Append("\",\"plate\":").Append(e.Plate ? "true" : "false").Append(",\"phase\":\"").Append(e.Phase).Append("\"}");
+ sb.Append(",\"last\":").Append(JsonText(run.LastLever)).Append('}');
+ return sb.ToString();
+ }
+
+ private static string JsonText(string s)
+ {
+ var sb = new StringBuilder(s.Length + 2).Append('"');
+ foreach (char c in s)
+ {
+ if (c == '"' || c == '\\') sb.Append('\\').Append(c);
+ else if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("X4", CultureInfo.InvariantCulture));
+ else sb.Append(c);
+ }
+ return sb.Append('"').ToString();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs
new file mode 100644
index 0000000..5437ef9
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs
@@ -0,0 +1,300 @@
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.Shared;
+
+namespace RynthCore.Plugin.RynthAi;
+
+// Loot Nearby Chests (2026-11-14), the host side. NearbyChestLooter.cs is the state machine and has
+// the rules; this file feeds it the game.
+//
+// Setting: Settings > Looting > Loot Nearby Chests (LootNearbyChests, off by default; the meta option
+// lootnearbychests). Status: /ra chests (always answers).
+//
+// How it sits in the loot tick (CorpseOpenController.cs):
+// * HasLootWork: a chest it is working on keeps Looting; a chest to start on is loot work only
+// after corpses, and never while combat has targets (so the arbiter never gives a fight's tick
+// to a chest).
+// * TickCorpseOpeningCore: TickNearbyChests reads answers every tick; a new chest is started
+// only where no corpse is in range (the corpse claim found none), and while one is being worked
+// on no corpse is claimed (opening a corpse would close the chest).
+// * Each step is one use the server answers (ACE walks the character to the chest first, as for a
+// far corpse open); the open chest is taken by the chest looter (RynthAiPlugin.ChestLoot.cs)
+// and looted by the loot profile like any opened chest.
+public sealed partial class RynthAiPlugin
+{
+ private NearbyChestLooter? _nearbyChests;
+ private int _nearbyOpenedId;
+ private long _nearbyOpenedAt;
+ private long _nearbyBusySince;
+
+ private const uint StypeSkillLockpick = 23; // AC Skill.Lockpick
+ private const uint StypeIntResistLockpick = 38; // ACE PropertyInt.ResistLockpick
+ private const uint StypeIntLockpickSuccessPct = 173; // ACE PropertyInt.AppraisalLockpickSuccessPercent
+
+ private NearbyChestLooter NearbyChests => _nearbyChests ??= new NearbyChestLooter(new NearbyChestEnv(this));
+
+ /// OnViewObjectContents for a non-corpse container: the proof a chest opened.
+ private void NoteNearbyChestOpened(int id)
+ {
+ _nearbyOpenedId = id;
+ _nearbyOpenedAt = CorpseNowMs;
+ }
+
+ /// OnChatWindowText: the lockpick's and the key's answers.
+ private void NearbyChestsChat(string text) => _nearbyChests?.OnChat(text);
+
+ /// The setting is on and nothing else owns chests now.
+ private bool NearbyChestsEnabled(LegacyUiSettings? s)
+ => s != null && s.LootNearbyChests && s.IsMacroRunning && s.EnableLooting
+ && !BoostNavHoldsLoot(s) && _chestKey?.Running != true && _forcedLootContainerId == 0
+ && !IsLootingBlockedByPack(s);
+
+ private bool NearbyChestsFighting(LegacyUiSettings? s)
+ => s != null && s.EnableCombat && _combatManager?.HasTargets == true;
+
+ ///
+ /// TickCorpseOpeningCore, every tick past the macro/Looting gate: the looter reads its answers.
+ /// Off (or something else owns chests): whatever it was doing is dropped, nothing marked.
+ ///
+ private void TickNearbyChests(LegacyUiSettings settings)
+ {
+ if (_nearbyChests == null && !settings.LootNearbyChests) return;
+ var looter = NearbyChests;
+ looter.RelockWaitSec = settings.ChestRelockWaitSec;
+ if (!NearbyChestsEnabled(settings))
+ {
+ looter.StandDown(!settings.LootNearbyChests ? "Loot Nearby Chests was turned off" : "something else has the chests (the Item Tool, /ra lootthis, a full pack or Boost Nav)");
+ return;
+ }
+ looter.Tick(mayStart: false);
+ }
+
+ /// The macro or Looting went off: drop the chest being worked on.
+ private void StandDownNearbyChests(string why) => _nearbyChests?.StandDown(why);
+
+ ///
+ /// TickCorpseOpeningCore, nothing claimed or open: a chest being worked on holds the tick (no corpse
+ /// is claimed meanwhile); in its Looting step the chest looter has it and this lets go.
+ ///
+ private bool NearbyChestHoldsTick()
+ => _nearbyChests is { Busy: true } n && n.State != NearbyChestLooter.Phase.Looting;
+
+ /// TickCorpseOpeningCore, no corpse in range: start on a nearby chest. True when this tick is spent on it.
+ private bool TryStartNearbyChest(LegacyUiSettings settings)
+ {
+ if (!settings.LootNearbyChests || !NearbyChestsEnabled(settings)) return false;
+ var looter = NearbyChests;
+ looter.Tick(mayStart: true);
+ return looter.Busy;
+ }
+
+ /// HasLootWork: the looter is on a chest (no state changed but the scan).
+ private bool NearbyChestBusy(LegacyUiSettings settings)
+ => settings.LootNearbyChests && _nearbyChests is { Busy: true } && NearbyChestsEnabled(settings);
+
+ /// HasLootWork, after corpses: a chest in loot range to start on (never while fighting).
+ private bool HasNearbyChestWork(LegacyUiSettings settings)
+ => settings.LootNearbyChests && NearbyChestsEnabled(settings) && NearbyChests.Candidate() != 0;
+
+ // ── /ra chests ──────────────────────────────────────────────────────────
+
+ private void HandleNearbyChestsCommand()
+ {
+ var s = _dashboard?.Settings;
+ if (s == null) { ChatLine("[RynthAi] Loot Nearby Chests: settings not ready."); return; }
+ string on = s.LootNearbyChests ? "on" : "off (Settings > Looting > Loot Nearby Chests)";
+ string why = !s.LootNearbyChests ? "" : !s.IsMacroRunning ? " - waits for the macro"
+ : !s.EnableLooting ? " - waits for Looting" : !NearbyChestsEnabled(s) ? " - something else has the chests now"
+ : NearbyChestsFighting(s) ? " - waits for the fight" : "";
+ var looter = _nearbyChests;
+ ChatLine($"[RynthAi] Loot Nearby Chests: {on}{why}. {(looter == null ? "Nothing done yet." : looter.Status)}");
+ if (looter == null) return;
+ int n = 0;
+ foreach (var (id, name, done, leftMs, reason) in looter.LeftAlone())
+ {
+ if (++n > 8) { ChatLine("[RynthAi] ... and more."); break; }
+ ChatLine($"[RynthAi] 0x{(uint)id:X8} '{name}': {(done ? "looted" : "skipped")} ({reason}); again in {Math.Max(1, leftMs / 1000)} s.");
+ }
+ }
+
+ // ── The looter's view of the game ───────────────────────────────────────
+
+ private sealed class NearbyChestEnv : INearbyChestEnv
+ {
+ private readonly RynthAiPlugin _p;
+ public NearbyChestEnv(RynthAiPlugin p) => _p = p;
+ private RynthCore.PluginSdk.RynthCoreHost Host => _p.Host;
+ private LegacyUiSettings? S => _p._dashboard?.Settings;
+
+ public long Now => CorpseNowMs;
+ public bool Enabled => _p.NearbyChestsEnabled(S);
+ public bool Fighting => _p.NearbyChestsFighting(S);
+
+ public IReadOnlyList ScanChests()
+ {
+ var list = new List();
+ var cache = _p._objectCache;
+ var s = S;
+ if (cache == null || s == null || _p._playerId == 0) return list;
+ double range = GetCorpseApproachRangeMaxMeters(s);
+ foreach (var wo in cache.GetLandscapeObjects())
+ {
+ if (wo.ObjectClass != AcObjectClass.Container) continue; // the cheap test first
+ if (wo.Id == _p._lootChestId || wo.Id == _p._chestCandidateId || wo.Id == _p._chestReopenId) continue; // open already
+ double d = cache.Distance(unchecked((int)_p._playerId), wo.Id);
+ if (double.IsNaN(d) || d > range) continue;
+ if (_p.NearbyChestRefusal(wo.Id) != null) continue;
+ list.Add(new NearbyChest(wo.Id, wo.Name, d));
+ }
+ return list;
+ }
+
+ public bool InWorld(int id) => _p._objectCache?[id] != null;
+
+ public bool StillEligible(int id, out string why)
+ {
+ why = "";
+ var cache = _p._objectCache;
+ var s = S;
+ if (cache == null || s == null) { why = "not ready"; return false; }
+ string? refusal = _p.NearbyChestRefusal(id);
+ if (refusal != null) { why = refusal; return false; }
+ double range = GetCorpseApproachRangeMaxMeters(s);
+ double d = cache.Distance(unchecked((int)_p._playerId), id);
+ if (double.IsNaN(d) || d > Math.Max(range * 1.5, range + 2.0))
+ {
+ why = $"it is {d:0.0} m away, past the loot range ({range:0.0} m)";
+ return false;
+ }
+ return true;
+ }
+
+ public string? HoldReason()
+ {
+ if (ActionPacer.IsPortaling(Host)) return "portal space";
+ if (_p._activity != BotActivity.Looting) return "Looting doesn't have the tick";
+ if (_p._targetCorpseId != 0 || _p._openedContainerId != 0) return "the corpse looter is busy";
+ if (_p.GroundPickupInFlight) return "a ground pickup is in flight";
+ if (_p._salvageManager?.PanelPending == true) return "the salvage panel is opening";
+ if (!ActionPacer.MayStart(Host, "Loot", HealNeed.None, out string why))
+ return why.Length > 0 ? why : "the server owes an answer";
+ long now = CorpseNowMs;
+ if (_p._busyCount > 0)
+ {
+ if (_p._nearbyBusySince == 0) _p._nearbyBusySince = now;
+ if (now - _p._nearbyBusySince < OpenBusyWaitMaxMs) return $"the client is busy ({_p._busyCount})";
+ }
+ else _p._nearbyBusySince = 0;
+ return null;
+ }
+
+ public bool CanAppraise => Host.HasRequestId && (Host.HasGetLastIdTime || Host.HasHasAppraisalData);
+ public bool RequestAppraisal(int chestId) => Host.RequestId(unchecked((uint)chestId));
+ public long AppraisalStamp(int chestId)
+ {
+ uint id = unchecked((uint)chestId);
+ if (Host.HasGetLastIdTime) return Host.GetLastIdTime(id);
+ return Host.HasHasAppraisalData && Host.HasAppraisalData(id) ? 1 : 0;
+ }
+
+ public bool? Locked(int chestId)
+ => Host.HasGetObjectBoolProperty && Host.TryGetObjectBoolProperty(unchecked((uint)chestId), StypeBoolLocked, out bool v) ? v : null;
+ public int? LockResistance(int chestId)
+ => Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(unchecked((uint)chestId), StypeIntResistLockpick, out int v) ? v : null;
+ public int? PickSuccessPercent(int chestId)
+ => Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(unchecked((uint)chestId), StypeIntLockpickSuccessPct, out int v) ? v : null;
+
+ public bool LockpickSkill(out int buffed, out bool trained)
+ {
+ buffed = 0; trained = false;
+ if (_p._playerId == 0 || !Host.HasGetObjectSkill
+ || !Host.TryGetObjectSkill(_p._playerId, StypeSkillLockpick, out buffed, out int training))
+ return false;
+ trained = training >= 2; // 2 trained, 3 specialized
+ return true;
+ }
+
+ public IReadOnlyList Keys()
+ {
+ var keys = new List();
+ var names = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var wo in _p.NearbyCarried())
+ if (wo.ObjectClass == AcObjectClass.Key && names.Add(wo.Name))
+ keys.Add(new ChestTool(wo.Id, wo.Name));
+ return keys;
+ }
+
+ public ChestTool? Lockpick()
+ {
+ // The Consumable Items list first (as the door logic), then any lockpick carried.
+ if (_p.FindLockpickInConsumables() is WorldObject listed && _p.IsCarriedByPlayer(listed.Id))
+ return new ChestTool(listed.Id, listed.Name);
+ foreach (var wo in _p.NearbyCarried())
+ if (wo.ObjectClass == AcObjectClass.Lockpick)
+ return new ChestTool(wo.Id, wo.Name);
+ return null;
+ }
+
+ public bool HasUseDone => Host.HasUseDoneSeq;
+ public int UseDoneSeq() => Host.HasUseDoneSeq ? Host.GetUseDoneSeq() : 0;
+ public bool LastUseDone(out int seq, out uint error)
+ {
+ seq = 0; error = 0;
+ return Host.HasGetLastUseDone && Host.TryGetLastUseDone(out seq, out error);
+ }
+
+ public bool SendUseWith(int toolId, int chestId, string why)
+ {
+ _p.PauseNavigationForCorpse();
+ _p.StopCorpseMovement();
+ return Host.UseOnFor(unchecked((uint)toolId), unchecked((uint)chestId), "NearbyChests", why);
+ }
+
+ public bool SendOpen(int chestId)
+ {
+ _p.PauseNavigationForCorpse();
+ _p.StopCorpseMovement();
+ return Host.UseFor(unchecked((uint)chestId), "NearbyChests", "Loot Nearby Chests: open the chest");
+ }
+
+ public long OpenedAt(int chestId) => _p._nearbyOpenedId == chestId ? _p._nearbyOpenedAt : 0;
+
+ public bool Looting(int chestId)
+ => _p._chestCandidateId == chestId || _p._chestReopenId == chestId
+ || (_p.IsChestLoot(chestId) && (_p._openedContainerId == chestId || _p._targetCorpseId == chestId));
+
+ public void Log(string text) => _p.LootDiag(text);
+ }
+
+ /// Why the world object is not a chest to loot (null = it is one).
+ private string? NearbyChestRefusal(int id)
+ {
+ var wo = _objectCache?[id];
+ if (wo == null) return "it is gone";
+ if (unchecked((uint)id) == _playerId) return "your main pack";
+ uint uid = unchecked((uint)id);
+ uint bf = 0;
+ bool bfKnown = Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(uid, out bf);
+ uint houseOwner = 0;
+ if (Host.HasGetObjectInstanceIdProperty && Host.TryGetObjectInstanceIdProperty(uid, ChestIidHouseOwner, out uint ho)) houseOwner = ho;
+ string name = wo.Name;
+ if (string.IsNullOrWhiteSpace(name) && Host.TryGetObjectName(uid, out string hostName)) name = hostName;
+ uint container = 0, wielder = 0;
+ bool ownKnown = Host.HasGetObjectOwnershipInfo && Host.TryGetObjectOwnershipInfo(uid, out container, out wielder, out _);
+ AcObjectClass cls = IsCorpseLikeObject(id) ? AcObjectClass.Corpse : wo.ObjectClass;
+ return NearbyChestLooter.ChestRefusal(cls, bfKnown, bf, houseOwner, name, ownKnown, container, wielder);
+ }
+
+ /// What the character carries (the pack walk, else the cache's inventory).
+ private IEnumerable NearbyCarried()
+ {
+ var cache = _objectCache;
+ if (cache == null) yield break;
+ IReadOnlyList direct = cache.GetDirectInventory();
+ IEnumerable items = direct.Count > 0 ? direct : cache.GetInventory();
+ foreach (var wo in items)
+ if (wo != null && IsCarriedByPlayer(wo.Id) && !WorldObjectCache.IsWieldedByPlayer(Host, wo))
+ yield return wo;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs
index 6079017..d450189 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs
@@ -405,6 +405,16 @@ public sealed partial class RynthAiPlugin
StopHunt("another route was loaded", say: true);
return;
}
+ // A walk that ran out: the nav engine turned nav off, as for any finished Once route (so the
+ // arbiter doesn't hold "Navigating" for nothing). The hunt owns nav while it runs: on again at once
+ // with no walk left (an empty route: nothing to hold the tick for), not off until the next walk.
+ // Off in between, the Nav switch kept flicking off, and stayed off while the hunt waited
+ // ("nav keeps shutting off", Tom 2026-11-16).
+ if (s.NavRouteFinished())
+ {
+ InstallHuntRoute(s, Array.Empty());
+ s.EnableNavigation = true;
+ }
if (!TryHuntPosition(out uint cell, out var me)) return;
if (InDungeon(cell)) { StopHunt("went into a dungeon", say: true); return; }
// A building's rooms (InDungeon said it isn't a dungeon): off RynthNav's landscape map. The way in
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs
index df89309..150ff9d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs
@@ -63,6 +63,33 @@ public sealed partial class RynthAiPlugin
return list;
}
+ ///
+ /// The portals within NavigationEngine.EscapePortalRangeMeters of the character, indoors or out
+ /// (world x east, y north, z), for the navigation engine's stuck escapes: a burst must not run into
+ /// one (2026-11-15, DreamWeave Thread 0x00B5: out through the Thread Exit, twice). Asked only when
+ /// an escape is about to run.
+ ///
+ private IReadOnlyList<(double X, double Y, double Z)> EscapePortalsNear()
+ {
+ var list = new List<(double X, double Y, double Z)>();
+ if (_objectCache == null || !Host.HasGetObjectPosition || !Host.HasGetPlayerPose) return list;
+ if (!Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out _, out _, out _, out _) || pc == 0) return list;
+ double wx = ((pc >> 24) & 0xFF) * 192.0 + px, wy = ((pc >> 16) & 0xFF) * 192.0 + py;
+ double range = NavigationEngine.EscapePortalRangeMeters;
+ foreach (var wo in _objectCache.GetLandscapeObjects())
+ {
+ uint uid = unchecked((uint)wo.Id);
+ bool portal = wo.ObjectClass == AcObjectClass.Portal
+ || (wo.ObjectClass == AcObjectClass.Unknown && Host.TryGetItemType(uid, out uint type) && (type & PatrolItemTypePortal) != 0);
+ if (!portal) continue;
+ if (!Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float z) || cell == 0) continue;
+ double ox = ((cell >> 24) & 0xFF) * 192.0 + x, oy = ((cell >> 16) & 0xFF) * 192.0 + y;
+ if (Math.Abs(ox - wx) > range || Math.Abs(oy - wy) > range) continue;
+ list.Add((ox, oy, z));
+ }
+ return list;
+ }
+
///
/// The running patrol's dungeon has a portal it wasn't built round (one that arrived after the
/// build: a dungeon's objects stream in after portal space, a summoned portal). Checked every
@@ -99,7 +126,8 @@ public sealed partial class RynthAiPlugin
///
private int LeadPatrolPastPortals(NavRouteParser route, Dictionary graph, DungeonGeometry? geometry,
List portals, List? report, NavPoint? walkOut,
- double playerWX, double playerWY, double playerWZ, int startIdx, double wall)
+ double playerWX, double playerWY, double playerWZ, int startIdx, double wall,
+ bool loop = true)
{
if (portals.Count == 0 || route.Points.Count == 0) return startIdx;
if (report != null)
@@ -138,7 +166,7 @@ public sealed partial class RynthAiPlugin
lead.AddRange(corners);
if (lead.Count == 0) return startIdx;
route.Points.InsertRange(startIdx, lead);
- DungeonPathfinder.KeepOutOfPortals(route.Points, closed: true, graph, geometry, portals, report, wall);
+ DungeonPathfinder.KeepOutOfPortals(route.Points, closed: loop, graph, geometry, portals, report, wall);
for (int i = 0; i < route.Points.Count; i++)
if (ReferenceEquals(route.Points[i], lead[0])) return i;
return Math.Min(startIdx, route.Points.Count - 1);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
index 01a91e7..e81057b 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
@@ -120,6 +120,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// portalled to a different dungeon.
private bool _dunPatrolActive;
private uint _dunPatrolLandblock;
+ // Openings the patrol couldn't get through (something not on the dungeon map in them, 2026-11-14: a spider
+ // web spawned in a doorway), closed for its laps in that dungeon until it is in another one.
+ private readonly HashSet _dunPatrolStuckEdges = new();
+ private int _dunPatrolStuckOpenings; // the openings _dunPatrolStuckEdges closes (one can be two cell pairs)
+ private readonly List _dunPatrolStuckSpots = new(); // spots in a room it got stuck at for good: walked round
+ private uint _dunPatrolStuckLb;
// The patrol's own route object: the patrol is the mode for as long as it is the loaded route
// (a macro stop or start leaves it; another route loaded in its place ends it, said in chat).
private NavRouteParser? _dunPatrolRoute;
@@ -620,6 +626,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// The dungeon patrol keeps its order after a fight (Go To Closest Waypoint is for
// routes; on a patrol loop the closest point can be near the end).
KeepWaypointAfterPause = () => _dunPatrolActive,
+ // Stuck escapes keep out of portals (RynthAiPlugin.PatrolPortals.cs).
+ EscapePortals = EscapePortalsNear,
};
// Plans the detours: the dungeon cell graph indoors, RynthNav's navmesh outdoors.
// Reads the raycast geometry and hazards through the fields, so it follows their
@@ -677,6 +685,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// never checked, and "raycast warming up" held off the no-progress
// blacklist, for the whole session. The setup wires it too (below).
WireRaycastIntoCombat();
+ // The dungeon map closes doorways the cells' placed objects stand across (a spider web:
+ // DungeonPathfinder.Blocked.cs). No map is built before this (it needs the raycast's DungeonLOS).
+ var loaderRef = raycastRef.GeometryLoader;
+ DungeonPathfinder.StaticMeshSource = lb => loaderRef.GetDungeonStaticMeshes(lb);
_dashboard?.SetRaycast(raycastRef);
_terrainOverlay?.SetRaycast(raycastRef);
_radarWallRenderer?.SetRaycast(raycastRef);
@@ -785,7 +797,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.BuffingWantsTick = () => _buffManager != null
&& (_buffManager.PendingSpellId != 0 || _buffManager.WantsVitalRecharge
|| (_dashboard?.Settings?.EnableBuffing == true && _buffManager.NeedsAnyBuff()));
- _combatManager.HoldNewTarget = LootHoldsNewTarget; // Boost Loot Priority: one kill, one loot; the death wait (2026-11-08)
+ _combatManager.HoldNewTarget = LootHoldsNewTarget; // Boost Loot Priority: one kill, one loot (the death wait holds no target since 2026-11-15)
_combatManager.HoldNewTargetWhy = LootHoldWhy;
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells
@@ -844,6 +856,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id));
_metaManager.SetCombatTargetCount(() => _combatManager?.LastScanPossible ?? -1);
_metaManager.SetLastChestLooted(() => _lastChestLootedId);
+ _metaManager.SetDunExploreStatus(DunExploreStatus, DunExploreInfoJson);
if (_dashboard != null)
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();
// A hot reload: the meta carries on where it was (Resume Meta After Reload).
@@ -1850,6 +1863,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// looping through it — or with the Dungeon Patrol settings changed since.
// Cheap no-op unless a new hazard cell was registered or a setting changed.
TickDunPatrolHazardReroute();
+ // The dungeon explore: rooms entered, reroutes, its end (no-op unless one runs).
+ TickDunExplore();
// Outdoor hunting's next walk (no-op unless /ra hunt is on).
TickOutdoorHunt();
});
@@ -2517,6 +2532,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { NoteServerPolicyChat(text); } catch { } // DreamWeave's Thread lines (ServerPolicy)
try { NoteDoorServerText(text); } catch { } // "The door is locked!" (the door logic)
try { ItemToolChat(text); } catch { } // the key's answers (chest looter)
+ try { NearbyChestsChat(text); } catch { } // the lockpick's and key's answers (Loot Nearby Chests)
try { _sessionStats?.OnChatWindowText(text); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats chat"); }
try { NoteMonsterStatsChat(text, chatType); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats chat"); }
// The Meta Manager eats the reply to its own /myquests poll (only that).
@@ -4106,6 +4122,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "groundloot": HandleGroundLootCommand(parts); break;
case "addnavpt": HandleAddNavPointCommand(); break;
case "lootname": HandleLootNameCommand(parts); break;
+ case "chests": HandleNearbyChestsCommand(); break;
case "navheading": HandleNavHeadingCommand(parts); break;
case "dfheight": HandleDfHeightCommand(parts); break;
case "nav": HandleNavCommand(parts); break;
@@ -4127,7 +4144,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "refreshquests": _questTracker?.Refresh(); ReplyOk("[RynthAi] Quest flag refresh requested."); break;
case "metamgr": QueueMetaMgrCommand(parts); Reply.Answered(); break; // Meta Manager: applied (and answered) on the next tick
case "dunnav": HandleDungeonNavCommand(parts); break;
+ case "dunnav-to": HandleDunNavToCommand(parts); break; // walk to an object in this dungeon (RynthAiCommands.cs)
case "dunnav-patrol": HandleDungeonNavPatrolCommand(parts); break;
+ case "dunnav-explore": HandleDunExploreCommand(parts); break; // RynthAiPlugin.DunExplore.cs
case "dunroute": HandleDunRouteCommand(parts); break; // RynthAiPlugin.DunRoutes.cs
case "dunpatrol-save": HandleDunPatrolSaveCommand(parts); break;
case "hunt": HandleHuntCommand(parts); break;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs b/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs
index c73c3fb..44c00b9 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs
@@ -49,6 +49,7 @@ internal static class ServerPolicy
private const string ThreadVar = "RYNTHAI_THREAD_RUN";
public const string PatrolOffMessage = "[RynthAi] The dungeon patrol is turned off in Threads on DreamWeave (its owners asked for that).";
+ public const string DunNavToOffMessage = "[RynthAi] DunNav-To is turned off in Threads on DreamWeave (its owners asked for that).";
/// A Thread run: the dungeon landblock it is in (0 = not known yet) and the landblock the gem was
/// used in (0 = none: the run was learned from a [REALM] line).
diff --git a/Plugins/RynthCore.Plugin.RynthLua/GameCharacter.cs b/Plugins/RynthCore.Plugin.RynthLua/GameCharacter.cs
index 176b2d7..cc7edb7 100644
--- a/Plugins/RynthCore.Plugin.RynthLua/GameCharacter.cs
+++ b/Plugins/RynthCore.Plugin.RynthLua/GameCharacter.cs
@@ -100,6 +100,11 @@ public sealed partial class RynthLuaPlugin
ch["IsBusy"] = DynValue.NewCallback((c, a) => DynValue.NewBoolean(ChBusy()));
ch["SpellBook"] = MakeSpellBook(s);
+ // The server's yes/no prompts (engine API v85, ConfirmationResponder): the next one of a type
+ // answered for the script, without the client showing its dialog. 2026-11-15, for example:
+ // DreamWeave's Fragment Press asks "Destroy this gem at the press?" before it grinds a gem.
+ ch["AnswerNextPrompt"] = DynValue.NewCallback((c, a) => DynValue.NewBoolean(ChAnswerNextPrompt(LuaArgs.Of(a, ch))));
+
ch["Trade"] = CreateTradeTable(s, ctx);
var mt = new Table(s);
@@ -121,6 +126,60 @@ public sealed partial class RynthLuaPlugin
game["Character"] = DynValue.NewTable(ch);
}
+ /// The longest AnswerNextPrompt arms for (ms): an arm answers whatever prompt of its type comes next.
+ internal const int PromptArmMaxMs = 30000;
+ internal const int PromptArmDefaultMs = 5000;
+
+ ///
+ /// game.Character.AnswerNextPrompt([type [, timeoutMs [, minPercent]]]): the next server prompt of
+ /// type (a ClientConfirmationType, default YESNO) that arrives within timeoutMs (default
+ /// PromptArmDefaultMs, at most PromptArmMaxMs; 0 or less disarms) is answered for the script:
+ /// Yes when the server's "N percent chance" is at least minPercent (default 0: always), else No.
+ /// One-shot, one slot per client. False when the engine can't (before API v85) or the arguments
+ /// are bad; true when armed (or disarmed).
+ ///
+ private bool ChAnswerNextPrompt(DynValue[] args)
+ {
+ if (!Host.HasConfirmationAnswers) return false;
+ DynValue t = LuaArgs.At(args, 0), ms = LuaArgs.At(args, 1), min = LuaArgs.At(args, 2);
+ uint type = t.IsNil() ? RynthCore.PluginSdk.RynthCoreHost.ConfirmationKind.YesNo : (uint)LuaArgs.Num(t, -1);
+ if (type < 1 || type > 7) return false;
+ int timeout = ms.IsNil() ? PromptArmDefaultMs : (int)Math.Min(PromptArmMaxMs, LuaArgs.Num(ms, PromptArmDefaultMs));
+ int minPercent = min.IsNil() ? 0 : (int)Math.Clamp(LuaArgs.Num(min, 0), 0, 100);
+ int r = Host.ArmConfirmation(type, minPercent, Math.Max(0, timeout));
+ if (r == 1) Host.Log($"[RynthLua] a script armed the answer to the next prompt of type {type} for {timeout} ms (Yes from {minPercent}%)");
+ return r == 1;
+ }
+
+ ///
+ /// game.Character.LastPrompt: the last server prompt this session, or nil: { Seq, Type, ContextId,
+ /// Percent (-1: none in its text), Outcome ("Shown": the client's dialog, "Accepted", "Declined",
+ /// "SendFailed", "AcceptedSticky"), AgeMs }.
+ ///
+ private DynValue ChLastPrompt(Script s)
+ {
+ if (!Host.HasConfirmationAnswers
+ || !Host.TryGetLastConfirmation(out int seq, out uint type, out uint context, out int percent, out int outcome, out int ageMs)
+ || outcome == RynthCore.PluginSdk.RynthCoreHost.ConfirmationOutcome.None)
+ return DynValue.Nil;
+ var t = new Table(s);
+ t.Set("Seq", DynValue.NewNumber(seq));
+ t.Set("Type", DynValue.NewNumber(type));
+ t.Set("ContextId", DynValue.NewNumber(context));
+ t.Set("Percent", DynValue.NewNumber(percent));
+ t.Set("Outcome", DynValue.NewString(outcome switch
+ {
+ RynthCore.PluginSdk.RynthCoreHost.ConfirmationOutcome.Shown => "Shown",
+ RynthCore.PluginSdk.RynthCoreHost.ConfirmationOutcome.Accepted => "Accepted",
+ RynthCore.PluginSdk.RynthCoreHost.ConfirmationOutcome.Declined => "Declined",
+ RynthCore.PluginSdk.RynthCoreHost.ConfirmationOutcome.SendFailed => "SendFailed",
+ RynthCore.PluginSdk.RynthCoreHost.ConfirmationOutcome.AcceptedSticky => "AcceptedSticky",
+ _ => outcome.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ }));
+ t.Set("AgeMs", DynValue.NewNumber(ageMs));
+ return DynValue.NewTable(t);
+ }
+
/// game.Character.<key> for everything that isn't a raw field.
private DynValue ChProperty(Script s, ScriptContext ctx, string key)
{
@@ -136,6 +195,7 @@ public sealed partial class RynthLuaPlugin
case "InPortalSpace": return DynValue.NewBoolean(Host.HasIsPortaling && Host.IsPortaling());
case "Vitae": return DynValue.NewNumber(pid != 0 && Host.HasGetVitae ? Host.GetVitae(pid) : 1.0);
case "Busy": return DynValue.NewBoolean(ChBusy());
+ case "LastPrompt": return ChLastPrompt(s);
case "Health": return DynValue.NewNumber(ChVitalCurrent(1));
case "Stamina": return DynValue.NewNumber(ChVitalCurrent(3));
case "Mana": return DynValue.NewNumber(ChVitalCurrent(5));
diff --git a/Plugins/RynthCore.Plugin.RynthLua/GameCharacterEvents.cs b/Plugins/RynthCore.Plugin.RynthLua/GameCharacterEvents.cs
index c4effbb..2a326f6 100644
--- a/Plugins/RynthCore.Plugin.RynthLua/GameCharacterEvents.cs
+++ b/Plugins/RynthCore.Plugin.RynthLua/GameCharacterEvents.cs
@@ -358,6 +358,12 @@ public sealed partial class RynthLuaPlugin
if (!death && (line.EndsWith("killed you!", StringComparison.OrdinalIgnoreCase)
|| line.EndsWith("killed you.", StringComparison.OrdinalIgnoreCase)))
death = true;
+ // DreamWeave's own: "You are fatally punctured by X! (Killing blow: 130 damage. You had 21/346 health.)"
+ // (any of AC's death verbs, then the blow). 2026-11-15: a script missed one, the health read
+ // having skipped the 0 too.
+ if (!death && line.IndexOf("(Killing blow:", StringComparison.Ordinal) >= 0
+ && line.IndexOf(" You had ", StringComparison.Ordinal) >= 0)
+ death = true;
if (!death) return;
long now = Environment.TickCount64;
diff --git a/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua b/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua
index 3269328..edf4adc 100644
--- a/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua
+++ b/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua
@@ -847,6 +847,15 @@ function SpellBook.KnownSpellIds() end
---@return string?
function SpellBook.Name(spellId) end
+---The last server yes/no prompt (game.Character.LastPrompt).
+---@class RynthLua.Prompt
+---@field Seq integer
+---@field Type ClientConfirmationType|integer
+---@field ContextId integer
+---@field Percent integer -1 when its text has no "N percent chance".
+---@field Outcome "Shown"|"Accepted"|"Declined"|"SendFailed"|"AcceptedSticky"
+---@field AgeMs integer
+
---@class RynthLua.Character
---@field Id integer
---@field Name string
@@ -857,6 +866,7 @@ function SpellBook.Name(spellId) end
---@field InPortalSpace boolean
---@field Vitae number 1.0 = no penalty, 0.95 = 5% vitae.
---@field Busy boolean Busy with a use or cast.
+---@field LastPrompt? RynthLua.Prompt The last server yes/no prompt this session (nil: none).
---@field Health integer
---@field Stamina integer
---@field Mana integer
@@ -959,6 +969,17 @@ function Character.KnowsSpell(spellId) end
---@return boolean
function Character.IsBusy() end
+---The server's next yes/no prompt of `type` (default ClientConfirmationType.YESNO) that comes
+---within `timeoutMs` (default 5000, at most 30000; 0 disarms) is answered for the script without
+---the client's dialog: Yes when its "N percent chance" is at least `minPercent` (default 0:
+---always), else No. One-shot, one slot per client: arm it right before the action that brings the
+---prompt. False on an engine before API v85 or an unknown type.
+---@param type? ClientConfirmationType|integer
+---@param timeoutMs? integer
+---@param minPercent? integer
+---@return boolean armed
+function Character.AnswerNextPrompt(type, timeoutMs, minPercent) end
+
---How many you have, counting stack sizes.
---@param filter RynthLua.Filter
---@return integer
diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs
index 98634f8..d26cb85 100644
--- a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs
+++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs
@@ -32,8 +32,11 @@ internal sealed class QuestFlag
}
}
-/// What one chat line is, as far as /myquests goes.
-internal enum MyQuestsLine { None, Quest, Empty, Disabled, Throttled }
+///
+/// What one chat line is, as far as /myquests goes. TooRecent: the server turned a quest down
+/// ("You have solved this quest too recently!" and its "You may complete this quest again in ...").
+///
+internal enum MyQuestsLine { None, Quest, Empty, Disabled, Throttled, TooRecent }
///
/// The character's quest flags, read from the server's /myquests reply (ACE: one Broadcast line
@@ -57,6 +60,23 @@ internal sealed class QuestFlagStore
public const string DisabledText = "The command \"myquests\" is not currently enabled on this server.";
/// ACECustom's per-session throttle reply ("... may only be run once every 60 seconds.").
public const string ThrottledText = "[MyQuests] This command may only be run once every";
+ /// ACE's QuestManager when a quest is turned down on its timer; the next line says how long.
+ public const string TooRecentText = "You have solved this quest too recently!";
+ public const string AgainInText = "You may complete this quest again in ";
+
+ // A chat timestamp the client may put first (as LineRegex allows), then the server's line.
+ private static readonly Regex AgainInRegex = new(
+ @"^\s*(?:\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?\s+)?You may complete this quest again in (?[^.]+)\.?\s*$",
+ RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ private static readonly Regex WaitPartRegex = new(@"(?\d+)\s*(?d|h|m|s)[a-z]*",
+ RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+
+ ///
+ /// How old the flags may get while a page or alert uses their timers before they are read again
+ /// (2026-11-13, R-20261110-155059-e947). /myquests was read once at login, so a quest done after
+ /// that kept the stamp from before it and showed "ready" for the rest of a long session.
+ ///
+ public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(10);
private const int QuietMs = 1500; // a reply is complete once no line came for this long
private const int RequestTimeoutMs = 10_000;
@@ -89,6 +109,17 @@ internal sealed class QuestFlagStore
/// Bumps whenever the flags change (views rebuild their caches on it).
public int Revision { get; private set; }
+ ///
+ /// The flags held are known to be out of date (the server turned a quest down on its timer, or a
+ /// timer alert wants the fresh reading first): read again as soon as the server allows. Cleared
+ /// when a reply lands. 2026-11-13, R-20261110-155059-e947.
+ ///
+ public bool RereadWanted { get; private set; }
+ /// The server's last "You may complete this quest again in ..." (the wait, and when it was said).
+ public (TimeSpan Left, DateTime AtUtc)? LastServerWait { get; private set; }
+
+ public void WantReread() => RereadWanted = true;
+
// Our own request: its reply may be hidden from chat.
public bool AwaitingOurs { get; private set; }
private long _requestedMs = long.MinValue / 2;
@@ -127,7 +158,9 @@ internal sealed class QuestFlagStore
}
/// Classifies a chat line and takes in its flag.
- public MyQuestsLine OnChatLine(string? text, long nowMs)
+ public MyQuestsLine OnChatLine(string? text, long nowMs) => OnChatLine(text, nowMs, DateTime.UtcNow);
+
+ public MyQuestsLine OnChatLine(string? text, long nowMs, DateTime utcNow)
{
if (string.IsNullOrEmpty(text)) return MyQuestsLine.None;
string line = text.Trim();
@@ -156,6 +189,22 @@ internal sealed class QuestFlagStore
Revision++;
return MyQuestsLine.Throttled;
}
+ // The server turned a quest down on its timer: what is held for it is out of date (the
+ // report above: Oracle said "ready", the server said 2h 50m). The lines don't name the quest,
+ // so the fix is a fresh /myquests; the wait is kept so the plugin can log which flag it was.
+ // Only a whole line counts: a player quoting it in a tell gets at most one extra read.
+ if (line.EndsWith(TooRecentText, StringComparison.Ordinal) && line.Length - TooRecentText.Length <= 12)
+ {
+ RereadWanted = true;
+ return MyQuestsLine.TooRecent;
+ }
+ if (line.Contains(AgainInText, StringComparison.Ordinal))
+ {
+ if (!TryParseAgainIn(line, out TimeSpan left)) return MyQuestsLine.None;
+ LastServerWait = (left, utcNow);
+ RereadWanted = true;
+ return MyQuestsLine.TooRecent;
+ }
if (line.IndexOf(" solves (", StringComparison.Ordinal) < 0) return MyQuestsLine.None;
QuestFlag? flag = Parse(line);
@@ -193,6 +242,7 @@ internal sealed class QuestFlagStore
Flags = reply;
}
LastReadUtc = DateTime.UtcNow;
+ RereadWanted = false;
// On a throttling server any reply (ours, the player's, RynthAi's poll) starts its minute.
if (_serverThrottles)
ThrottledUntilMs = nowMs + ServerThrottleMs - QuietMs;
@@ -215,9 +265,64 @@ internal sealed class QuestFlagStore
ThrottledUntilMs = long.MinValue / 2;
_serverThrottles = false;
LastPartialReply = null;
+ RereadWanted = false;
+ LastServerWait = null;
Revision++;
}
+ ///
+ /// Whether the held flags should be read again now (the plugin also checks its own settings and
+ /// spacing): the server said they are out of date, or something uses their timers
+ /// (: a quest page or the Quest Timers window showing, timer alerts
+ /// on) and they are older than . Never before the first read (the login
+ /// read does that), while a reply is coming in, or on a server without /myquests.
+ /// 2026-11-13, R-20261110-155059-e947.
+ ///
+ public bool NeedsReread(DateTime utcNow, bool timersInUse)
+ {
+ if (LastReadUtc == DateTime.MinValue || Loading || ServerDisabled) return false;
+ return RereadWanted || timersInUse && utcNow - LastReadUtc >= StaleAfter;
+ }
+
+ /// "You may complete this quest again in 2h 50m 42s." -> 2:50:42 (ACE's friendly time: d, h, m, s parts).
+ internal static bool TryParseAgainIn(string line, out TimeSpan left)
+ {
+ left = TimeSpan.Zero;
+ Match m = AgainInRegex.Match(line);
+ if (!m.Success) return false;
+ bool any = false;
+ foreach (Match p in WaitPartRegex.Matches(m.Groups["left"].Value))
+ {
+ if (!long.TryParse(p.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out long n) || n > 100_000) return false;
+ left += char.ToLowerInvariant(p.Groups["u"].Value[0]) switch
+ {
+ 'd' => TimeSpan.FromDays(n),
+ 'h' => TimeSpan.FromHours(n),
+ 'm' => TimeSpan.FromMinutes(n),
+ _ => TimeSpan.FromSeconds(n),
+ };
+ any = true;
+ }
+ return any;
+ }
+
+ ///
+ /// The held flags whose timers have about to go at
+ /// (the server's "again in" wait), closest first: which quest the server turned down, for the log.
+ ///
+ public List<(QuestFlag Flag, TimeSpan Off)> WaitingAbout(TimeSpan left, DateTime atUtc, TimeSpan tolerance)
+ {
+ var found = new List<(QuestFlag, TimeSpan)>();
+ foreach (QuestFlag f in Flags.Values)
+ {
+ if (f.RepeatTime <= TimeSpan.Zero) continue;
+ TimeSpan off = f.NextAvailableTime(atUtc) - left;
+ if (off.Duration() <= tolerance) found.Add((f, off));
+ }
+ found.Sort((a, b) => a.Item2.Duration().CompareTo(b.Item2.Duration()));
+ return found;
+ }
+
public bool TryGet(string flag, out QuestFlag q) => Flags.TryGetValue(flag, out q!);
internal static QuestFlag? Parse(string line)
diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs
index 124f7c4..a201789 100644
--- a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs
@@ -27,6 +27,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase
// The Character tab's session (RynthAi): read only while that tab is on screen.
private const long CharacterExtrasReadMs = 2000;
private const long BookWorldWaitMs = 15_000; // how long the quest book waits for the world name
+ // Re-reading /myquests during a session (2026-11-13, R-20261110-155059-e947): at most one of
+ // RynthOracle's own re-reads a minute (the throttling servers' limit, and a long list is a big
+ // chat burst), and a timer alert holds this long for the fresh reading before printing anyway.
+ private const long AutoReadGapMs = 60_000;
+ private const long AlertConfirmWaitMs = 120_000;
+ // A timer alert from flags read longer ago than this is checked against a fresh read first.
+ private static readonly TimeSpan AlertConfirmAge = TimeSpan.FromMinutes(2);
+ // How far the server's "again in" wait may sit from a held flag's timer and still be that quest.
+ private static readonly TimeSpan ServerWaitTolerance = TimeSpan.FromMinutes(2);
private readonly OracleContext _c = new();
private readonly UiHost _ui = new();
@@ -51,6 +60,14 @@ public sealed class RynthOraclePlugin : RynthPluginBase
private int _seenPackRevision = -1; // the active server plugin's quest pack (ServerQuestPackClient.Revision)
private int _titleCount = -2;
private uint _titleCurrent;
+ private long _nextAutoReadMs;
+ private DateTime _seenReadUtc = DateTime.MinValue;
+ // The server's "again in" wait not yet checked against a read made after it (the log line).
+ private (TimeSpan Left, DateTime AtUtc)? _uncheckedServerWait;
+ // Timer alerts held for a fresh read (flags read too long ago to trust a "ready").
+ private readonly System.Collections.Generic.List _heldAlerts = new();
+ private long _heldAlertsSinceMs;
+ private DateTime _heldAlertsReadUtc;
public override int Initialize()
{
@@ -146,9 +163,18 @@ public sealed class RynthOraclePlugin : RynthPluginBase
// The quest book loads once the character's name (and world) are known (TickData).
_c.Book.Clear();
_c.Timers.Reset();
+ ResetRereads();
if (_timers != null) { _timers.Visible = _c.Settings.QuestTimersOpen; _timers.NeedsPass = true; }
}
+ private void ResetRereads()
+ {
+ _nextAutoReadMs = 0;
+ _seenReadUtc = DateTime.MinValue;
+ _uncheckedServerWait = null;
+ _heldAlerts.Clear();
+ }
+
public override void OnLogout()
{
_c.InWorld = false;
@@ -161,6 +187,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
_ui.SubmitEmpty(Host);
_c.Book.Clear(); // saved as it changed
_c.Timers.Reset();
+ ResetRereads();
_c.Flags.Clear();
_c.Void.Clear();
_c.Server.Reset();
@@ -253,7 +280,17 @@ public sealed class RynthOraclePlugin : RynthPluginBase
long now = Environment.TickCount64;
string line = text.TrimEnd('\r', '\n');
- MyQuestsLine kind = _c.Flags.OnChatLine(line, now);
+ MyQuestsLine kind = _c.Flags.OnChatLine(line, now, DateTime.UtcNow);
+ if (kind == MyQuestsLine.TooRecent)
+ {
+ // Shown as the server sent it; the store now wants a fresh read (TickData sends it).
+ if (_c.Flags.LastServerWait is { } wait && wait.AtUtc != _uncheckedServerWait?.AtUtc)
+ {
+ _uncheckedServerWait = wait;
+ Host.Log("[RynthOracle] The server turned a quest down: " + DescribeServerWait(wait, "the flags held"));
+ }
+ return;
+ }
if (kind != MyQuestsLine.None)
{
// Only the reply to RynthOracle's own request, and only when the setting says so.
@@ -382,6 +419,81 @@ public sealed class RynthOraclePlugin : RynthPluginBase
return sent;
}
+ // ── Keeping the flags current (2026-11-13, R-20261110-155059-e947) ──────
+ // The report: every daily quest showed "ready" hours early, and the server turned one down with
+ // "again in 2h 50m 42s". /myquests was read once at login (34 hours before, in that log), so a
+ // quest done since kept the stamp from before it and its old timer had long run out. Nothing in
+ // the log said when the flags were read, so reads, re-reads and the server's turn-downs log now.
+
+ ///
+ /// RynthOracle may send /myquests on its own during a session: only with the login read on and
+ /// its replies hidden (a re-read must never print the whole list into chat).
+ ///
+ private bool AutoRereads() => _c.Settings.ReadQuestsAtLogin && _c.Settings.HideOwnQuestReplies;
+
+ /// Something on screen shows quest timers: a quest page of the Oracle window, or the Quest Timers window.
+ private bool TimersOnScreen()
+ {
+ if (_timers?.Visible == true) return true;
+ if (_main?.Visible != true || _mainView == null) return false;
+ string tab = _mainView.Tab;
+ return tab == OracleView.TabQuests || tab == OracleView.TabAugs || tab == OracleView.TabSociety;
+ }
+
+ /// Re-reads /myquests when the flags are known stale, or old and on screen; at most once a minute.
+ private void RereadIfStale(long now)
+ {
+ if (now < _nextAutoReadMs || !AutoRereads()) return;
+ bool wanted = _c.Flags.RereadWanted;
+ if (!_c.Flags.NeedsReread(_c.UtcNow, TimersOnScreen())) return;
+ _nextAutoReadMs = now + AutoReadGapMs;
+ string why = wanted
+ ? "the server turned a quest down, or a timer alert wants a fresh reading"
+ : $"the quest timers are on screen and the flags were read {TimeText.Friendly(_c.UtcNow - _c.Flags.LastReadUtc)} ago";
+ if (RequestQuests()) Host.Log($"[RynthOracle] Re-reading /myquests: {why}.");
+ }
+
+ /// Logs each /myquests reply that landed (whoever asked) and checks the server's last "again in" against it.
+ private void NoteRead()
+ {
+ DateTime read = _c.Flags.LastReadUtc;
+ if (read == _seenReadUtc || read == DateTime.MinValue) return;
+ DateTime previous = _seenReadUtc;
+ _seenReadUtc = read;
+ Host.Log($"[RynthOracle] Read {_c.Flags.Flags.Count} quest flags"
+ + (previous == DateTime.MinValue ? " (the first read since login)." : $" (the read before was {TimeText.Friendly(read - previous)} earlier)."));
+ if (_uncheckedServerWait is { } w && read > w.AtUtc)
+ {
+ _uncheckedServerWait = null;
+ Host.Log("[RynthOracle] After the server turned a quest down: " + DescribeServerWait(w, "the flags just read"));
+ }
+ }
+
+ ///
+ /// "again in 2h 50m 42s; the flags held (read 07:12:05 UTC, 2h 33m before it) have aaaflag at 2h 50m",
+ /// or that none has about that long to go: which quest it was, and whether Oracle's timer agrees.
+ ///
+ private string DescribeServerWait((TimeSpan Left, DateTime AtUtc) w, string which)
+ {
+ var sb = new System.Text.StringBuilder();
+ sb.Append("again in ").Append(TimeText.Friendly(w.Left)).Append("; ").Append(which);
+ if (_c.Flags.LastReadUtc == DateTime.MinValue) return sb.Append(" (none read yet)").ToString();
+ TimeSpan gap = w.AtUtc - _c.Flags.LastReadUtc;
+ sb.Append($" (read {_c.Flags.LastReadUtc:HH:mm:ss} UTC, ")
+ .Append(gap >= TimeSpan.Zero ? TimeText.Friendly(gap) + " before it)" : TimeText.Friendly(-gap) + " after it)");
+ var near = _c.Flags.WaitingAbout(w.Left, w.AtUtc, ServerWaitTolerance);
+ if (near.Count == 0)
+ return sb.Append(" have no quest with about that long to go: out of date, or the server's timer isn't the one /myquests gives.").ToString();
+ sb.Append(" have ");
+ for (int i = 0; i < near.Count && i < 3; i++)
+ {
+ if (i > 0) sb.Append(", ");
+ TimeSpan held = near[i].Flag.NextAvailableTime(w.AtUtc);
+ sb.Append(near[i].Flag.Key).Append(" at ").Append(TimeText.Friendly(held));
+ }
+ return sb.Append('.').ToString();
+ }
+
// ── The Oracle window's Refresh buttons (the data side; Views\RefreshBar.cs has the rest) ──
/// Reads the character's stats, buffs and (on the Character tab) RynthAi's session now, not at the next timer.
@@ -469,6 +581,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
_c.Flags.LastPartialReply = null;
Host.Log($"[RynthOracle] /myquests reply looked cut short ({partial.Got} lines, {partial.Had} flags held): merged it instead of replacing the list.");
}
+ NoteRead();
if (_c.Flags.Revision != _seenFlagRevision)
{
_seenFlagRevision = _c.Flags.Revision;
@@ -530,6 +643,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
// Another plugin (RynthAi's meta manager) or the player may already have asked.
if (_c.Flags.LastReadUtc == DateTime.MinValue && !_c.Flags.Loading) RequestQuests();
}
+ RereadIfStale(now);
if (!_dailyCheckStarted && _c.Settings.CheckQuestListDaily
&& _c.UtcNow - _c.Settings.LastQuestListCheckUtc >= QuestCatalogUpdater.Interval)
@@ -572,10 +686,41 @@ public sealed class RynthOraclePlugin : RynthPluginBase
/// Says in chat which watched quest timers came up: tracked quests, or every held quest if so set.
private void AnnounceTimers()
{
- if (!_c.Settings.AlertTimers || !_c.Book.Loaded) { _c.Timers.Reset(); return; }
+ if (!_c.Settings.AlertTimers || !_c.Book.Loaded) { _c.Timers.Reset(); _heldAlerts.Clear(); return; }
+ long now = _c.NowMs;
var ready = _c.Timers.Check(_c.Flags, _c.Catalog, _c.Settings.AlertAllTimers ? null : _c.Book.Tracked, _c.UtcNow);
+ // A timer that ran out on flags read a while ago may be a quest done again since (R-20261110-155059-e947):
+ // hold the alert for a fresh read rather than call it ready (2026-11-13).
+ bool confirm = ready.Count > 0 && AutoRereads() && !_c.Flags.ServerDisabled
+ && _c.UtcNow - _c.Flags.LastReadUtc > AlertConfirmAge;
foreach (Quest q in ready)
- _c.Print($"Quest ready again: {q.Label}");
+ {
+ if (!confirm) { _c.Print($"Quest ready again: {q.Label}"); continue; }
+ if (_heldAlerts.Count == 0) { _heldAlertsSinceMs = now; _heldAlertsReadUtc = _c.Flags.LastReadUtc; }
+ if (!_heldAlerts.Exists(h => string.Equals(h.Flag, q.Flag, StringComparison.OrdinalIgnoreCase))) _heldAlerts.Add(q);
+ }
+ if (confirm) _c.Flags.WantReread();
+ ReleaseHeldAlerts(now);
+ }
+
+ ///
+ /// Held timer alerts once a fresh read is in: still ready, they print; on a timer again (the quest
+ /// was done since the old read) they're dropped and the watcher alerts when that timer ends. With
+ /// no read in (throttled, no reply) they print as before.
+ ///
+ private void ReleaseHeldAlerts(long now)
+ {
+ if (_heldAlerts.Count == 0) return;
+ bool fresh = _c.Flags.LastReadUtc > _heldAlertsReadUtc;
+ if (!fresh && now - _heldAlertsSinceMs < AlertConfirmWaitMs) return;
+ foreach (Quest q in _heldAlerts)
+ {
+ if (!fresh || QuestTimer.State(q, _c.Flags, _c.UtcNow, out _) == QuestTimerState.Ready)
+ _c.Print($"Quest ready again: {q.Label}");
+ else
+ Host.Log($"[RynthOracle] No \"ready again\" for {q.Flag}: the fresh read has it on a timer (done again since the last read).");
+ }
+ _heldAlerts.Clear();
}
///
diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs
index b874feb..b492b88 100644
--- a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs
+++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs
@@ -17,7 +17,10 @@ internal sealed partial class OracleView
OracleSettings s = _c.Settings;
w.SeparatorText("Settings");
w.Checkbox("Read quest flags when you log in", "o.readlogin", s.ReadQuestsAtLogin, v => { s.ReadQuestsAtLogin = v; s.Save(); });
- w.Tooltip("Sends /myquests once after login so the quest pages have data.");
+ // 2026-11-13 (R-20261110-155059-e947): the login read alone went stale over a long session.
+ w.Tooltip("Sends /myquests after login so the quest pages have data, and again while quest timers are on screen "
+ + "and the flags are over 10 minutes old, or when the server turns a quest down as solved too recently "
+ + "(only with the replies hidden).");
w.Checkbox("Hide the replies to RynthOracle's own requests", "o.hide", s.HideOwnQuestReplies, v => { s.HideOwnQuestReplies = v; s.Save(); });
w.Tooltip("/myquests. A command you type yourself always shows its reply.");
w.Checkbox("Show the Void window for characters with Void Magic", "o.void", s.AutoShowVoidWindow, v => { s.AutoShowVoidWindow = v; s.Save(); });
diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs
index b50b064..b894edd 100644
--- a/Plugins/Shared/ActionPacer.cs
+++ b/Plugins/Shared/ActionPacer.cs
@@ -271,6 +271,7 @@ internal static class ActionPacer
OnSelf = onSelf && kind == PacedKind.ItemUse,
};
if (kind == PacedKind.ItemUse) a.WieldedAtSend = IsWieldedByPlayer(host, id);
+ SpendTryAfterBusy(host, who); // the try after a 'too busy' answer, if one is open
string? over = null;
lock (Gate)
{
@@ -497,15 +498,38 @@ internal static class ActionPacer
// above left it for the next asker. A Conquest report (10-25): after a corpse pickup and a cast went
// out together, the buff step took all three tries and sent nothing (still animating), combat never
// got one, and the fight stood for the latch's 15 s.
- if (tryAfterBusy) SpendTryAfterBusy(host, who);
+ // And only by a send (Begin), not by passing here (2026-11-15, R-20261115-172110-9e6a): the buff
+ // step passed MayStart, found nothing to cast and sent nothing, three times (05.4, 08.4, 14.4 s
+ // into the latch), while combat, asking after it every tick, was held, with eleven monsters in
+ // range, until the latch ran out. The try stays open for the next asker until a send spends it,
+ // or TryOpenMs passes (then it counts as spent, so passes that send nothing can't keep it open).
+ if (tryAfterBusy) GrantTryAfterBusy(who);
return true;
}
+ /// A try after 'too busy' let through but not used by a send is taken as spent after this.
+ public const long TryOpenMs = 1000;
+ private static long _tryGrantedAt; // when the open try was first let through (0 = none open)
+ private static string _tryGrantedTo = ""; // the first start it was let through for (the lapse line)
+
+ private static void GrantTryAfterBusy(string who)
+ {
+ lock (Gate)
+ {
+ if (_tryGrantedAt != 0) return;
+ _tryGrantedAt = NowMs();
+ _tryGrantedTo = who;
+ }
+ }
+
+ /// Begin: a send while a try is open spends it (logged).
private static void SpendTryAfterBusy(RynthCoreHost host, string who)
{
int n;
lock (Gate)
{
+ if (_tryGrantedAt == 0 || _busySince == 0) { _tryGrantedAt = 0; return; }
+ _tryGrantedAt = 0;
_probes++;
_lastProbeAt = NowMs();
n = _probes;
@@ -819,6 +843,7 @@ internal static class ActionPacer
_busyRefusals = 0;
_probes = 0;
_lastProbeAt = 0;
+ _tryGrantedAt = 0;
_stage = BreakStage.None;
_stageAt = 0;
_stageFor = null;
@@ -904,7 +929,7 @@ internal static class ActionPacer
PacedAction? stuck;
bool probe = false;
long age = 0;
- string? staleLine = null;
+ string? staleLine = null, lapseLine = null;
lock (Gate)
{
if (_shadow != null && _hung == null && now - _shadow.SentMs >= CastMaxMs) { _hung = _shadow; _shadow = null; }
@@ -938,6 +963,15 @@ internal static class ActionPacer
// use would send first every time and the heal would see the next slot, up to BusyProbeMaxMs later).
if (heal == HealNeed.Heal && _busySince != 0) _healWaitAt = now;
bool healWaiting = heal != HealNeed.Heal && _healWaitAt != 0 && now - _healWaitAt < HealWaitFreshMs;
+ // A try let through TryOpenMs ago that no send used: spent now, from when it opened.
+ if (_tryGrantedAt != 0 && now - _tryGrantedAt >= TryOpenMs)
+ {
+ _probes++;
+ _lastProbeAt = _tryGrantedAt;
+ lapseLine = $"[Pace] the try after the server's 'too busy' answer (#{_probes}) went unused for {now - _tryGrantedAt} ms " +
+ $"(first let through for {_tryGrantedTo}, nothing was sent)";
+ _tryGrantedAt = 0;
+ }
// A waiting heal's probe comes at least every HealGraceMs (the doubling would reach BusyProbeMaxMs).
long probeWait = Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs);
if (heal == HealNeed.Heal) probeWait = Math.Min(probeWait, HealGraceMs);
@@ -949,6 +983,7 @@ internal static class ActionPacer
}
if (staleLine != null) Log(host, staleLine);
+ if (lapseLine != null) Log(host, lapseLine);
if (stuck != null && !IsPortaling(host)) StepBreaker(host, stuck, age, now);
if (AirborneHolds(host, now, out why)) return true;
diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs
index a5b7123..7a7f20d 100644
--- a/Tools/RynthCore.RynthAiHostTests/Program.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Program.cs
@@ -87,7 +87,15 @@ internal static class Program
PatrolSettingsTests.Register(runner);
PatrolPocketTests.Register(runner);
PatrolPortalTests.Register(runner);
+ LedgeTests.Register(runner);
+ DunNavToTests.Register(runner);
+ StraightenTests.Register(runner);
+ HoleTests.Register(runner);
+ StuckOpeningTests.Register(runner);
+ BlockedDoorwayTests.Register(runner);
+ StackedStepTests.Register(runner);
DunRouteTests.Register(runner);
+ DunExploreTests.Register(runner);
BuffTests.Register(runner);
BuffItemsTests.Register(runner);
SpellCatalogTests.Register(runner);
@@ -159,6 +167,7 @@ internal static class Program
WorldCacheTypedTests.Register(runner);
VendorFlagTests.Register(runner);
LootByNameTests.Register(runner);
+ NearbyChestTests.Register(runner);
NavOverlayTests.Register(runner);
ActionPacingTests.Register(runner);
HazardEscapeTests.Register(runner);
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs
index 69f543a..dc5730e 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/AttackLatencyTests.cs
@@ -26,6 +26,7 @@ internal static class AttackLatencyTests
r.Add("attack latency: the first cast at a new target skips the Attack Spell Delay only with the server gates", NewTargetInterval);
r.Add("attack latency: a killed monster isn't locked again from the old scan list", NoRelockOfTheDead);
r.Add("attack latency: [CombatLatency] charges each wait, one line per engagement, throttled", LatencyLine);
+ r.Add("attack latency (R-20261115-165857-1de7): time the arbiter gave another activity is 'held ... by', not 'other'", LatencyHeld);
}
// ── Busy leftovers ────────────────────────────────────────────────────────
@@ -165,6 +166,27 @@ internal static class AttackLatencyTests
Check.True(t.OnAttack(6, 6100, "Melee", null) == null, "dropped before attacking: nothing");
}
+ // 2026-11-15, R-20261115-165857-1de7: "lock->attack 3687 ms (... other 3281)" was a healing kit the
+ // arbiter ran in the Buffing slot while combat didn't tick; the line said "other".
+ private static void LatencyHeld()
+ {
+ var t = new CombatLatencyTracker();
+ t.OnLock(1, 1000);
+ t.OnTick(1, 1033, CombatLatencyTracker.Wait.Busy);
+ t.OnHeld(1, 2033, "Buffing");
+ t.OnHeld(1, 4033, "Buffing");
+ t.OnTick(1, 4066, CombatLatencyTracker.Wait.Busy);
+ Check.Eq(t.Held, 3000.0, "the held ticks' time is the hold's");
+ Check.Eq(t.Waited(CombatLatencyTracker.Wait.Other), 0.0, "not other's");
+ string? line = t.OnAttack(1, 4100, "Magic", "Kirit");
+ Check.Eq(line, "[CombatLatency] lock->attack 3100 ms (stance 0, face 0, busy 66, cast 0, interval 0, other 34, held 3000 ms by Buffing) Magic 'Kirit'",
+ "the line names the holder");
+
+ t.OnLock(2, 9000);
+ string? plain = t.OnAttack(2, 9100, "Magic", null);
+ Check.False((plain ?? "").Contains("held"), "a lock nobody held: the line as before");
+ }
+
// ── Helpers ───────────────────────────────────────────────────────────────
private static CombatManager MakeCombat(LegacyUiSettings s)
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BlockedDoorwayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BlockedDoorwayTests.cs
new file mode 100644
index 0000000..9467c96
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/BlockedDoorwayTests.cs
@@ -0,0 +1,96 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using RynthCore.Plugin.RynthAi;
+using RynthCore.Plugin.RynthAi.Raycasting;
+using RynthCore.RynthAiTests.Harness;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// Doorways a dungeon's placed objects stand across (DungeonPathfinder.Blocked.cs, 2026-11-16). DreamWeave
+// Thread 0x5456 places twelve spider webs (model 0x02000D34) in its doorways; the map had them open and the
+// explore walked into one after another. The map now closes them; dungeons without such things lose nothing.
+internal static class BlockedDoorwayTests
+{
+ public static void Register(Runner r)
+ {
+ r.Add("blocked doorways: Thread 0x5456's spider webs close their doorways (every cell pair) on the real dats; the explore keeps out of them; other dungeons lose none, 0x039B its round room's floor-level way (if the dats are here)", RealDats);
+ }
+
+ private static void RealDats()
+ {
+ string acDir = DunRouteTests.AcDir;
+ if (!Directory.Exists(acDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
+ var loader = new GeometryLoader();
+ if (!loader.Initialize(acDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
+ var before = DungeonPathfinder.StaticMeshSource;
+ try
+ {
+ DungeonPathfinder.StaticMeshSource = lb => loader.GetDungeonStaticMeshes(lb);
+ ulong K(uint a, uint b) => DungeonPathfinder.OpeningKey(a, b);
+
+ // 0x5456: the three doorways the character was stuck in (both cell pairs of each) are among them, all webs.
+ DungeonPathfinder.InvalidateCache();
+ var raw = DungeonPathfinder.GetGraph(0x5456, loader.CellDat);
+ var copy = raw.ToDictionary(kv => kv.Key, kv => new DungeonNavNode { CellId = kv.Value.CellId, NS = kv.Value.NS, EW = kv.Value.EW, Z = kv.Value.Z, Neighbors = { } });
+ foreach (var (id, n) in raw) copy[id].Neighbors.AddRange(n.Neighbors);
+ var geo = DungeonPathfinder.GetGeometry(0x5456, loader.CellDat, loader.DungeonLOS)!;
+ var blocked = DungeonPathfinder.FindBlockedDoorways(copy, geo, loader.GetDungeonStaticMeshes(0x5456));
+ var keys = blocked.Select(x => K(x.A, x.B)).ToHashSet();
+ Console.WriteLine($" 0x5456: {blocked.Count} pair(s): {string.Join(" ", blocked.Select(x => $"{x.A & 0xFFFF:X4}>{x.B & 0xFFFF:X4}"))}; {DungeonPathfinder.BlockedNote}");
+ foreach (var (a, b) in new[] { (0x5456014Fu, 0x54560148u), (0x54560150u, 0x54560148u), (0x54560158u, 0x54560157u),
+ (0x54560159u, 0x54560157u), (0x54560173u, 0x54560177u), (0x54560174u, 0x54560177u) })
+ Check.True(keys.Contains(K(a, b)), $"{a:X8}>{b:X8} (a doorway it was stuck in) is closed");
+ Check.True(blocked.All(x => x.Setups.All(m => m is 0x02000D34 or 0x02000CCE)),
+ "by the web model 0x02000D34, or 0x02000CCE (five 3.8 m blocks filling the way down to the one-cell room 0100)");
+ int all = DungeonPathfinder.ReachableCells(copy, 0x545602A0, null).Count, left = DungeonPathfinder.ReachableCells(raw, 0x545602A0, null).Count;
+ Console.WriteLine($" 0x5456 from 02A0: {all} cells reachable as the map was, {left} with the webs closed");
+ Check.True(DungeonPathfinder.BlockedNote is { } note && note.Contains("0x02000D34"), "the build log names the model");
+ Check.False(raw[0x5456014F].Neighbors.Contains(0x54560148) || raw[0x54560150].Neighbors.Contains(0x54560148), "the cached graph has the web doorway closed");
+
+ // The explore laid from where the run started: no step through a closed doorway.
+ var route = DungeonPathfinder.BuildExploreRoute(raw, 0x545602A0, null, geo, null, null, (16239.0, 16492.0, 0.0), null, out _);
+ int through = 0;
+ for (int i = 0; i + 1 < route.Points.Count; i++)
+ {
+ uint c0 = DungeonPathfinder.CellAt(raw, geo, route.Points[i]), c1 = DungeonPathfinder.CellAt(raw, geo, route.Points[i + 1]);
+ if (c0 != 0 && c1 != 0 && keys.Contains(K(c0, c1))) through++;
+ }
+ Console.WriteLine($" explore from 02A0: {route.Points.Count} points, {through} step(s) through a web");
+ DungeonPathfinder.MainRouteNote = null;
+ Check.Eq(through, 0, "the explore walk takes no step through a web's doorway");
+
+ // Dungeons the explore has walked: nothing closed. 0x039B aside: a 9.2 m model 6.2 m tall fills its round
+ // room from the floor (-12) to the corridor (-6), and the one doorway into it at floor level meets its side.
+ foreach (uint lb in new uint[] { 0x0289, 0x0192, 0x6346, 0x0199, 0x01F5, 0x039B })
+ {
+ DungeonPathfinder.InvalidateCache();
+ var g = DungeonPathfinder.GetGraph(lb, loader.CellDat);
+ var before39 = lb == 0x039B ? DungeonPathfinder.ReachableCells(g, 0x039B0177, null) : new HashSet();
+ int reachBefore = before39.Count;
+ var gg = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
+ if (gg == null) continue;
+ Console.WriteLine($" 0x{lb:X4}: {(DungeonPathfinder.BlockedNote ?? "nothing closed")}");
+ if (lb == 0x039B)
+ {
+ Check.True(DungeonPathfinder.BlockedNote is { } n39 && n39.Contains("0x010000EE") && !n39.Contains(", 0x"), "0x039B: only by the round room's 9 m model");
+ var full = DungeonPathfinder.GetGraph(lb, loader.CellDat);
+ var after39 = DungeonPathfinder.ReachableCells(full, 0x039B0177, null);
+ int reach = after39.Count;
+ Console.WriteLine($" 0x039B from 0177: {reachBefore} cells reachable as the map was, {reach} with it closed");
+ // The cells under the 9 m model's floor-level side (012C-012F at -12, 010A-010F at -18 past them).
+ Check.True(after39.Contains(0x039B0141) && !after39.Contains(0x039B012E) && reachBefore - reach == 11,
+ $"0x039B: the round room stays, the 11 cells only past the model's side are left out ({reachBefore - reach})");
+ }
+ else Check.Eq(DungeonPathfinder.BlockedNote, null, $"0x{lb:X4}: nothing closed");
+ }
+ }
+ finally
+ {
+ DungeonPathfinder.StaticMeshSource = before;
+ loader.Dispose();
+ DungeonPathfinder.InvalidateCache();
+ }
+ }
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs
index 3832162..500f704 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs
@@ -53,6 +53,8 @@ internal static class CombatHookTests
r.Add("combat hook: a script answer at an ignored monster is rejected, even one hitting us (RynthAi casts its own)", HookRejectsIgnoredTarget);
r.Add("combat hook: a script heal (a drain) at a fight target whose rule turned to Priority 0 is rejected", HookHealRejectsIgnoredTarget);
r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged);
+ r.Add("ghost (R-20261115-172110-9e6a): two casts answered 'target not acquired' (UseDone 0x42C) mark the target a ghost and stop the casting", NotAcquiredMarksGhost);
+ r.Add("blacklist (2026-11-15): melee landing nothing across a building's wall (one inside, one out) keeps the target off 5 min; elsewhere the usual timeout", AcrossWallBlacklistLonger);
r.Add("loot jump: Think sends no cast while in the air after a loot jump; it casts on the landing, or at the cap", LootJumpHoldsAttack);
r.Add("loot jump: a swing refused in the air (WeenieError 0x4EB) is not a no-damage attack (without it: a miss)", MeleeInAirNotJudged);
r.Add("combat hook: ctx.pending is the cast in flight; ctx.last the last resolved one, err its first UseDone (final; -1 when missed or after 7 s)", LastErrIsTheCastsAnswer);
@@ -1082,6 +1084,79 @@ internal static class CombatHookTests
}
});
+ // 2026-11-15, R-20261115-172110-9e6a: every Blade Arc at a target the server didn't have came back
+ // UseDone 0x42C about 70 ms after the send, and combat cast again at once (13 casts in 0.85 s, the
+ // hourglass going round), never dropping it.
+ private static void NotAcquiredMarksGhost() => Guard(() =>
+ {
+ var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
+ rig.S.EnableRaycasting = false;
+ rig.Attack();
+ Check.Eq(FakeHost.Casts.Count, 1, "the first cast goes out");
+ FakeHost.UseDone(CombatManager.TargetNotAcquiredErr);
+ rig.Attack();
+ Check.Eq(FakeHost.Casts.Count, 2, "one 'target not acquired' could be a death on the way: one more cast");
+ Check.False(rig.C.Ghosts.IsGhost(Target), "not a ghost yet");
+ FakeHost.UseDone(CombatManager.TargetNotAcquiredErr);
+ rig.Attack();
+ Check.Eq(FakeHost.Casts.Count, 2, "the second answer: no third cast at it");
+ Check.True(rig.C.Ghosts.IsGhost(Target), "it is a ghost");
+ Check.Eq(rig.C.activeTargetId, 0, "and dropped");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("[Ghost]") && l.Contains("'target not acquired' (UseDone 0x42C)") && !l.Contains("it hasn't moved")),
+ "logged with the server's answer as the evidence: " + FakeHost.Logs.LastOrDefault(l => l.Contains("[Ghost]")));
+ SetField(rig.C, "_lastScanTime", DateTime.MinValue); // the scan's own throttle
+ rig.C.ScanNearbyTargets();
+ Check.False(rig.C.ScannedTargets.Any(t => t.Id == Target), "the scan skips it");
+
+ // An answer in between that isn't 0x42C (the server has it after all): the count starts over.
+ var real = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
+ real.S.EnableRaycasting = false;
+ real.Attack();
+ FakeHost.UseDone(CombatManager.TargetNotAcquiredErr);
+ real.Attack();
+ FakeHost.UseDone(0);
+ real.Attack();
+ FakeHost.UseDone(CombatManager.TargetNotAcquiredErr);
+ real.Attack();
+ Check.Eq(FakeHost.Casts.Count, 4, "not two in a row: every cast goes");
+ Check.False(real.C.Ghosts.IsGhost(Target), "and it is no ghost");
+ Check.Eq(real.C.activeTargetId, Target, "the target stays");
+ });
+
+ // A Thread, 2026-11-15: the character in a building, a mage 2.5 m off outside it, no raycast blocking
+ // it: three swings for nothing, blacklisted 30 s, locked again, round and round.
+ private static void AcrossWallBlacklistLonger() => Guard(() =>
+ {
+ foreach (bool across in new[] { true, false })
+ {
+ string what = across ? "inside a building, the target outside" : "both outside";
+ var rig = new AttackRig(setup: () => { FakeHost.WeaponCalls = true; FakeHost.CombatModeValue = CombatMode.Melee; });
+ rig.S.BlacklistAttempts = 3;
+ rig.S.EnableRaycasting = false;
+ var bm = Field(rig.C, "_blacklistManager");
+ bm.TimeoutSeconds = 30;
+ FakeHost.PlayerPose = (across ? 0x01010105u : 0x0101001Bu, 0f, 0f, 0f);
+ FakeHost.Positions[Player] = FakeHost.PlayerPose;
+ var tp = FakeHost.Positions[Target];
+ FakeHost.Positions[Target] = (0x0101001Cu, tp.Item2, tp.Item3, tp.Item4);
+ SetField(rig.C, "_pendingJudgeTargetId", (int)Target);
+ SetField(rig.C, "_damageSincePendingCast", false);
+ SetField(rig.C, "_consecutiveCastMisses", 2);
+ SetField(rig.C, "_pendingJudgeCastAt", DateTime.Now.AddSeconds(-30));
+ CallPrivate(rig.C, "JudgePendingCast");
+ var exp = Field>(bm, "_blacklistExpirations");
+ Check.True(exp.TryGetValue((int)Target, out DateTime until), what + ": blacklisted after the third swing for nothing");
+ double secs = (until - DateTime.Now).TotalSeconds;
+ if (across)
+ {
+ Check.True(secs > CombatManager.AcrossWallBlacklistSec - 10, $"{what}: off {secs:0} s (5 min)");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("across a building's wall")), what + ": logged");
+ }
+ else
+ Check.True(secs < 40, $"{what}: off {secs:0} s (the usual 30)");
+ }
+ });
+
// A jump-loot pickup's jump (ActionPacer.NoteLootJump) holds the attack until the landing.
// ACE refuses a cast, swing or shot in the air (Player_Magic/Melee/Missile: IsJumping).
private static void LootJumpHoldsAttack() => Guard(() =>
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DunExploreTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DunExploreTests.cs
new file mode 100644
index 0000000..33c4f95
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/DunExploreTests.cs
@@ -0,0 +1,854 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using RynthCore.Plugin.RynthAi;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Meta;
+using RynthCore.Plugin.RynthAi.Raycasting;
+using RynthCore.RynthAiHostTests.Fakes;
+using RynthCore.RynthAiTests.Harness;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// The dungeon explore (2026-11-13): /ra dunnav-explore walks through every room of the dungeon once,
+// then stops (DungeonPathfinder.Explore.cs, RynthAiPlugin.DunExplore.cs). On DunRouteTests' hand-built
+// dungeon (a 3x3 hall, a corridor north to a nook with the Surface Portal, east to a side room with the
+// Portal to the Depths, west to a room):
+// - the walk is a Once route that enters every room it can walk to, once, and ends in the last one
+// (no walk back), keeping out of both portals (the nook behind the Surface Portal is left out);
+// - rooms already entered are left out when it is laid again; without the map it goes cell by cell;
+// - a closet next door is entered before moving on;
+// - the plugin: the command starts it with the macro on, rooms count as the character walks in, a
+// portal coming into view lays the rest again, rooms passed by are gone back for, the end is done
+// with navigation off and the macro left on; stop, another route and leaving the dungeon end it;
+// - radunexplore[] and the counts;
+// - Tiny Hive on the real dats, when they are on this PC.
+internal static class DunExploreTests
+{
+ public static void Register(Runner r)
+ {
+ r.Add("dun explore: a Once walk into every room once, ending in the last (no walk back), out of both portals", EveryRoomOnce);
+ r.Add("dun explore: rooms already entered are left out when the walk is laid again", EnteredLeftOut);
+ r.Add("dun explore: without the dungeon map the walk goes cell by cell, every cell once", CellWalk);
+ r.Add("dun explore: a closet next door is entered before moving on", ClosetFirst);
+ r.Add("dun explore: plugin: started with the macro on, rooms counted, relaid round a new portal, missed rooms gone back for, done", PluginRun);
+ r.Add("dun explore: plugin: stop, another route, leaving the dungeon and the server's word end it", PluginEnds);
+ r.Add("dun explore: plugin: stuck for good in an opening (something not on the map in it): the opening is closed, the rest laid round it", PluginStuckOpening);
+ r.Add("dun patrol: stuck for good in an opening: the opening is closed and the patrol laid round it; kept in that dungeon", PatrolStuckOpening);
+ r.Add("dun explore (2026-11-16, a hall 0x01F5): stuck for good in a room, away from the doorway on its way: no opening closed, the spot ahead of it walked round", PluginStuckSpot);
+ r.Add("dun explore: plugin: a spider web in a doorway closes it before the walk; one in the open is left alone; one seen mid-walk relays it", PluginWebInDoorway);
+ r.Add("dun explore: plugin: stuck in a doorway, what stands in it is named and learned: another of that name in a doorway is walked round", PluginStuckLearnsName);
+ r.Add("dun explore: plugin: enter and scan - waits at room middles; when the walk is over a monster still in the dungeon is walked to, then done", PluginLeftoverMonster);
+ r.Add("dun explore: Thread 0x00B5 on the real dats - the walk goes into the boss's 6-cell dead end and waits at its middle (if the dats are here)", Real00B5BossRoom);
+ r.Add("dun explore: a door you can't use is shut: walked round, the rooms behind it counted; the walk ends waiting at it", PluginShutDoor);
+ r.Add("dun explore: lever errands: one behind the door can't be walked to, a button that opens nothing, a lever that opens it (through it first)", PluginLeverErrands);
+ r.Add("dun explore: a Thread puzzle gate is a shut door to the walk; its puzzle lever is never pulled", PluginPuzzleGate);
+ r.Add("dun explore: done at the doors, a door that opens by itself, the door opener giving up on a door, resume", PluginDoorsMore);
+ r.Add("dun explore: radunexplore[], radunexplorerooms[], radunexplorevisited[]", Expressions);
+ r.Add("dun explore: Tiny Hive 0x0289 on the real dats: every room, out of the Surface Portal (if the dats are here)", TinyHiveRealDats);
+ }
+
+ private const double Ox = DunRouteTests.Ox, Oy = DunRouteTests.Oy;
+
+ private static (double X, double Y, double Z) Mid(DunRouteTests.Sample d, uint cell)
+ {
+ var n = d.Graph[cell];
+ return (DungeonGeometry.NavToWorld(n.EW), DungeonGeometry.NavToWorld(n.NS), n.Z);
+ }
+
+ /// The rooms the walk's legs pass through (each leg looked at every half metre).
+ private static HashSet RoomsWalked(List pts, Dictionary graph, DungeonGeometry? geo, ExplorePlan plan)
+ {
+ var rooms = new HashSet();
+ for (int i = 0; i < pts.Count; i++)
+ {
+ var a = pts[i];
+ var b = i + 1 < pts.Count ? pts[i + 1] : a;
+ double len = Math.Sqrt(Math.Pow(DungeonGeometry.NavToWorld(b.EW) - DungeonGeometry.NavToWorld(a.EW), 2)
+ + Math.Pow(DungeonGeometry.NavToWorld(b.NS) - DungeonGeometry.NavToWorld(a.NS), 2));
+ int n = Math.Max(1, (int)Math.Ceiling(len / 0.5));
+ for (int k = 0; k <= n; k++)
+ {
+ double t = (double)k / n;
+ var q = new NavPoint { NS = a.NS + (b.NS - a.NS) * t, EW = a.EW + (b.EW - a.EW) * t, Z = a.Z + (b.Z - a.Z) * t };
+ int r = plan.RoomOf(DungeonPathfinder.CellAt(graph, geo, q));
+ if (r >= 0) rooms.Add(r);
+ }
+ }
+ return rooms;
+ }
+
+ private static void EveryRoomOnce()
+ {
+ var d = new DunRouteTests.Sample();
+ var geo = d.Geo();
+ var portals = new List { d.Surface(), d.Depths() };
+ var route = DungeonPathfinder.BuildExploreRoute(d.Graph, d.Start, null, geo, null, portals, Mid(d, d.Start), null, out var plan);
+
+ Check.Eq(route.RouteType, NavRouteType.Once, "a Once route");
+ Check.True(plan.ByRoom, "laid on the map's rooms");
+ Check.True(route.Points.Count >= 6, $"points laid ({route.Points.Count})");
+ int hall = plan.RoomOf(d.Start);
+ Check.True(Enumerable.Range(0, 3).All(i => Enumerable.Range(0, 3).All(j => plan.RoomOf(d.Hall[i, j]) == hall)), "the 3x3 hall is one room");
+ Check.False(plan.PlanRooms.Contains(plan.RoomOf(d.Nook)), "the nook behind the Surface Portal is left out");
+ foreach (uint c in new[] { d.C1, d.E1, d.Side, d.W1, d.West })
+ Check.True(plan.PlanRooms.Contains(plan.RoomOf(c)), $"room of cell {c:X8} is in the plan");
+
+ var walked = RoomsWalked(route.Points, d.Graph, geo, plan);
+ Check.True(plan.PlanRooms.IsSubsetOf(walked), $"every room is walked into: plan {string.Join(",", plan.PlanRooms)}, walked {string.Join(",", walked)}");
+ Check.Eq(plan.Order.Count, plan.PlanRooms.Count - 1, "each room but the start once in the order");
+ Check.Eq(plan.Order.Distinct().Count(), plan.Order.Count, "none twice");
+ int lastRoom = plan.RoomOf(DungeonPathfinder.CellAt(d.Graph, geo, route.Points[^1]));
+ Check.Eq(lastRoom, plan.Order[^1], "it ends in the last new room, not back at the start");
+ foreach (var p in portals)
+ {
+ double near = DungeonPathfinder.NearestApproach(route.Points, closed: false, p);
+ Check.True(near >= p.Radius - 0.05, $"keeps out of {p.Name} ({near:F1} m, radius {p.Radius:F1})");
+ }
+ }
+
+ private static void EnteredLeftOut()
+ {
+ var d = new DunRouteTests.Sample();
+ var geo = d.Geo();
+ var portals = new List { d.Surface(), d.Depths() };
+ var visited = new HashSet { d.Start, d.W1, d.West };
+ var route = DungeonPathfinder.BuildExploreRoute(d.Graph, d.Start, null, geo, null, portals, Mid(d, d.Start), visited, out var plan);
+ int west = plan.RoomOf(d.West), w1 = plan.RoomOf(d.W1);
+ Check.True(plan.DoneRooms.Contains(west) && plan.DoneRooms.Contains(w1), "the west rooms count as done");
+ Check.False(plan.Order.Contains(west) || plan.Order.Contains(w1), "and aren't in the order: " + string.Join(",", plan.Order));
+ Check.False(RoomsWalked(route.Points, d.Graph, geo, plan).Contains(west), "the walk doesn't go into the west room");
+ Check.True(plan.Order.Contains(plan.RoomOf(d.Side)) && plan.Order.Contains(plan.RoomOf(d.C1)), "the rest still is");
+
+ var all = new HashSet(d.Graph.Keys);
+ var none = DungeonPathfinder.BuildExploreRoute(d.Graph, d.Start, null, geo, null, portals, Mid(d, d.Start), all, out var p2);
+ Check.Eq(none.Points.Count, 0, "everything entered: nothing to walk");
+ Check.Eq(p2.Order.Count, 0, "and no rooms in the order");
+ }
+
+ private static void CellWalk()
+ {
+ var d = new DunRouteTests.Sample();
+ var route = DungeonPathfinder.BuildExploreRoute(d.Graph, d.Start, null, null, null, null, null, null, out var plan);
+ Check.False(plan.ByRoom, "no map: cells");
+ Check.Eq(route.RouteType, NavRouteType.Once, "a Once route");
+ Check.Eq(plan.PlanRooms.Count, d.Graph.Count, "every cell (no portals given: the nook too)");
+ Check.Eq(plan.Order.Count, d.Graph.Count - 1, "every cell but the start once");
+ Check.True(route.Points.Count > 0, "points laid");
+ }
+
+ private static void ClosetFirst()
+ {
+ // A hub H with a closet K, and a branch B1-B2-B3 off it; start in H.
+ var g = new Dictionary();
+ void Link(uint a, uint b)
+ {
+ foreach (uint c in new[] { a, b })
+ if (!g.ContainsKey(c)) g[c] = new DungeonNavNode { CellId = c, NS = (c & 0xFF) * 0.01, EW = (c >> 8 & 0xFF) * 0.01 };
+ g[a].Neighbors.Add(b); g[b].Neighbors.Add(a);
+ }
+ const uint H = 0x7E7E0101, K = 0x7E7E0202, B1 = 0x7E7E0303, B2 = 0x7E7E0404, B3 = 0x7E7E0505;
+ Link(H, B1); Link(B1, B2); Link(B2, B3); Link(H, K);
+ DungeonPathfinder.BuildExploreRoute(g, H, null, null, null, null, null, null, out var plan);
+ var order = plan.Order.Select(r => plan.Rooms.Cells[r][0]).ToList();
+ Check.Eq(string.Join(",", order.Select(c => c.ToString("X8"))), string.Join(",", new[] { K, B1, B2, B3 }.Select(c => c.ToString("X8"))),
+ "closet first, then the branch to its end (no walk back for the closet)");
+ }
+
+ // ── The plugin ───────────────────────────────────────────────────────────
+
+ private static object Status(DunRouteTests.Rig rig) => rig.Call("DunExploreStatus")!;
+ private static (int State, int Rooms, int Visited) St(DunRouteTests.Rig rig) => ((int State, int Rooms, int Visited))Status(rig);
+ private static void Tick(DunRouteTests.Rig rig) => rig.Call("TickDunExplore");
+ private static string Show(List lines) => lines.Count == 0 ? "(nothing)" : string.Join(" | ", lines);
+
+ private static List Said(Action a)
+ {
+ int before = FakeHost.Chat.Count;
+ a();
+ return FakeHost.Chat.Skip(before).ToList();
+ }
+
+ private static void StandIn(DunRouteTests.Rig rig, uint cell)
+ {
+ var (x, y, _) = Mid(rig.D, cell);
+ rig.At(x - Ox, y - Oy, cell);
+ }
+
+ /// In cell , a metre short of its doorway into (stuck in that opening).
+ private static void StandAtDoorway(DunRouteTests.Rig rig, uint a, uint b)
+ {
+ var geo = rig.D.Geo()!;
+ Check.True(geo.TryGetDoorway(a, b, out var d), $"a doorway {a:X8}>{b:X8}");
+ var (nx, ny) = d.NormalFrom(a);
+ rig.At(d.X - nx * 1.0 - Ox, d.Y - ny * 1.0 - Oy, a);
+ }
+
+ private static void Finish(DunRouteTests.Rig rig)
+ {
+ // What NavigationEngine.CompleteOnceRoute does at the end of a Once route.
+ rig.S.ActiveNavIndex = rig.S.CurrentRoute.Points.Count;
+ rig.S.EnableNavigation = false;
+ }
+
+ private static void PluginRun()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore");
+ // Only the Depths portal known at the start: the Surface Portal comes into view later.
+ rig.Cache.OnDeleteObject(DunRouteTests.SurfaceId);
+ rig.Cache.Tick();
+ var said = rig.Typed("/ra dunnav-explore");
+ Check.True(said.Count == 1 && said[0].StartsWith("[RynthAi] DunNav-Explore: ") && said[0].Contains("room(s) to walk through") && said[0].Contains("exploring"),
+ "it answers: " + Show(said));
+ Check.True(said[0].Contains("kept out of 1 portal(s)"), "with the one portal known: " + said[0]);
+ var first = rig.S.CurrentRoute;
+ Check.Eq(first.RouteType, NavRouteType.Once, "a Once route installed");
+ Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation, "macro and navigation on");
+ var s = St(rig);
+ Check.Eq(s.State, 1, "exploring");
+ Check.Eq(s.Visited, 1, "the start room counts as entered");
+ int rooms = s.Rooms;
+ Check.True(rooms >= 5, $"rooms to walk through ({rooms})");
+
+ said = rig.Typed("/ra dunnav-explore");
+ Check.True(said.Count == 1 && said[0].Contains("already exploring, 1 of"), "again: already exploring: " + Show(said));
+ Check.True(ReferenceEquals(rig.S.CurrentRoute, first), "and the walk is the same");
+
+ StandIn(rig, rig.D.W1);
+ Tick(rig);
+ StandIn(rig, rig.D.West);
+ Tick(rig);
+ Check.Eq(St(rig).Visited, 3, "w1 and the west room entered");
+
+ // The Surface Portal comes into view: the rest is laid again round it (the west rooms left out).
+ rig.Cache.OnCreateObject(DunRouteTests.SurfaceId);
+ rig.Cache.Tick();
+ var run = rig.Get("_dunExplore")!;
+ run.GetType().GetField("NextCheckAt")!.SetValue(run, 0L);
+ Tick(rig);
+ Check.False(ReferenceEquals(rig.S.CurrentRoute, first), "relaid when the portal came into view");
+ Check.Eq(rig.S.CurrentRoute.RouteType, NavRouteType.Once, "still a Once route");
+ Check.Eq(St(rig).Visited, 3, "the rooms entered are kept");
+ Check.True(St(rig).Rooms <= rooms, $"the nook is out now ({St(rig).Rooms} rooms)");
+ var surface = rig.D.Surface();
+ surface.Radius = 3.5;
+ Check.True(DungeonPathfinder.NearestApproach(rig.S.CurrentRoute.Points, closed: false, surface) >= surface.Radius - 0.1, "kept out of the Surface Portal");
+
+ // The walk ends with rooms not entered (the character was carried past them): it goes back once.
+ Finish(rig);
+ said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("passed by without going in → going back for them")), "missed rooms gone back for: " + Show(said));
+ Check.True(rig.S.EnableNavigation && rig.S.CurrentRoute.Points.Count > 0, "a walk for them");
+ Check.Eq(St(rig).State, 1, "still exploring");
+
+ // Walk into every room, then the walk ends: done.
+ foreach (uint c in rig.D.Graph.Keys.Where(c => c != rig.D.Nook)) { StandIn(rig, c); Tick(rig); }
+ s = St(rig);
+ Check.Eq(s.Visited, s.Rooms, $"every room entered ({s.Visited} of {s.Rooms})");
+ Finish(rig);
+ said = Said(() => Tick(rig));
+ Check.True(said.Count == 1 && said[0].Contains($"DunNav-Explore: done, {s.Rooms} of {s.Rooms} rooms") && said[0].Contains("the macro is still on"),
+ "done: " + Show(said));
+ Check.Eq(St(rig).State, 3, "done");
+ Check.True(!rig.S.EnableNavigation && rig.S.CurrentRoute.Points.Count == 0, "navigation off, the walk taken off");
+ Check.True(rig.S.IsMacroRunning, "the macro left on");
+ said = rig.Typed("/ra dunnav-explore status");
+ Check.True(said[0].Contains("done in dungeon 0x7E7E") && said[0].Contains($"{s.Rooms} of {s.Rooms} rooms"), "status: " + Show(said));
+ }
+
+ private static void PluginEnds()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-ends");
+ var said = rig.Typed("/ra dunnav-explore stop");
+ Check.True(said.Count == 1 && said[0].Contains("nothing to stop"), "stop with none running: " + Show(said));
+ said = rig.Typed("/ra dunnav-explore sideways");
+ Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunnav-explore"), "a wrong word: the usage: " + Show(said));
+
+ rig.Typed("/ra dunnav-explore");
+ said = rig.Typed("/ra dunnav-explore stop");
+ Check.True(said.Count == 1 && said[0].Contains("DunNav-Explore stopped (you stopped it): 1 of"), "stopped: " + Show(said));
+ Check.True(!rig.S.EnableNavigation && rig.S.CurrentRoute.Points.Count == 0, "navigation off, the walk taken off");
+ Check.Eq(St(rig).State, 4, "stopped");
+
+ rig.Typed("/ra dunnav-explore");
+ var other = new NavRouteParser { RouteType = NavRouteType.Circular };
+ other.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 1 });
+ rig.S.CurrentRoute = other;
+ said = Said(() => Tick(rig));
+ Check.True(said.Count == 1 && said[0].Contains("stopped (another route is the route now)"), "another route: " + Show(said));
+ Check.True(ReferenceEquals(rig.S.CurrentRoute, other), "that route stays");
+
+ rig.Typed("/ra dunnav-explore");
+ rig.At(42.1, 33.6, 0xA9B4002Fu);
+ said = Said(() => Tick(rig));
+ Check.True(said.Count == 1 && said[0].Contains("stopped (you left the dungeon)"), "left the dungeon: " + Show(said));
+ Check.True(!rig.S.EnableNavigation, "navigation off");
+ said = rig.Typed("/ra dunnav-explore");
+ Check.True(said.Count == 1 && said[0].Contains("dunnav-explore requires you to be inside a dungeon"), "outdoors: refused: " + Show(said));
+
+ var thread = new DunRouteTests.Rig("NavProfiles-explore-thread", world: "DreamWeave");
+ ServerPolicy.NoteChat("[REALM] id=0 inst=7841 eph=1 name=Base World", thread.D.Start);
+ said = thread.Typed("/ra dunnav-explore");
+ Check.True(said.Count == 1 && said[0].Contains("turned off in Threads"), "in a Thread on DreamWeave: refused with the policy's line: " + Show(said));
+ Check.False(thread.S.IsMacroRunning || thread.S.EnableNavigation, "nothing started");
+ ServerPolicy.Forget();
+ }
+
+ // 2026-11-14 on DreamWeave, 0x5456: a spider web in a doorway (then not on the map); the engine's detours
+ // went back through it and then it only tried its escapes. Here: heading down the east corridor for the
+ // side room when every detour is used up and it is still stuck.
+ private static void PluginStuckOpening()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-stuck");
+ rig.Typed("/ra dunnav-explore");
+ int rooms = St(rig).Rooms;
+ StandAtDoorway(rig, rig.D.E1, rig.D.Side);
+ Tick(rig);
+ var before = rig.S.CurrentRoute;
+ var geo = rig.D.Geo();
+ int toSide = before.Points.FindIndex(p => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side);
+ Check.True(toSide >= 0, "the walk goes into the side room");
+ rig.S.ActiveNavIndex = toSide;
+
+ Check.True(Said(() => Tick(rig)).Count == 0 && ReferenceEquals(rig.S.CurrentRoute, before), "not stuck: nothing happens");
+ bool stuck = true;
+ rig.P.ExploreStuckProbe = () => stuck;
+ var said = Said(() => Tick(rig));
+ stuck = false;
+ Check.True(said.Any(l => l.Contains($"couldn't get past something between cells {rig.D.E1:X8} and {rig.D.Side:X8}") && l.Contains("going round it")),
+ "it says which opening it gives up: " + Show(said));
+ Check.False(ReferenceEquals(rig.S.CurrentRoute, before), "the rest laid again");
+ Check.Eq(St(rig).State, 1, "still exploring");
+ Check.Eq(St(rig).Rooms, rooms - 1, "the side room (only that way) is left out");
+ var run = rig.Get("_dunExplore")!;
+ Check.Eq(((HashSet)run.GetType().GetField("StuckEdges")!.GetValue(run)!).Count, 1, "one opening closed");
+ Check.False(rig.S.CurrentRoute.Points.Any(p => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side), "and the new walk doesn't go in there");
+ Check.True(Said(() => Tick(rig)).Count == 0, "unstuck: nothing more");
+ }
+
+ // 2026-11-16, a DreamWeave hall (0x01F5): stuck for good 5 and 11 m from the doorway on its way, three openings
+ // were closed one after another and it stood stuck as before. Now the spot just ahead of it is walked round.
+ private static void PluginStuckSpot()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-stuckspot");
+ rig.Typed("/ra dunnav-explore");
+ int rooms = St(rig).Rooms;
+ StandIn(rig, rig.D.E1);
+ Tick(rig);
+ var before = rig.S.CurrentRoute;
+ var geo = rig.D.Geo();
+ int toSide = before.Points.FindIndex(p => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side);
+ Check.True(toSide >= 0, "the walk goes into the side room");
+ rig.S.ActiveNavIndex = toSide;
+ var (mx, my, _) = Mid(rig.D, rig.D.E1);
+ Check.True(geo!.TryGetDoorway(rig.D.E1, rig.D.Side, out var d) && Math.Sqrt((d.X - mx) * (d.X - mx) + (d.Y - my) * (d.Y - my)) > RynthAiPlugin.StuckAtDoorwayMeters,
+ "it stands in the middle of its cell, away from the doorway");
+
+ bool stuck = true;
+ rig.P.ExploreStuckProbe = () => stuck;
+ int logs = FakeHost.Logs.Count;
+ var said = Said(() => Tick(rig));
+ stuck = false;
+ Check.True(said.Any(l => l.Contains($"couldn't get past something at a spot in cell {rig.D.E1:X8}") && l.Contains("walking round that spot")),
+ "it says it walks round the spot: " + Show(said));
+ Check.True(Logged(logs, "from the doorway on its way: walking round the spot"), "and logs where");
+ var run = rig.Get("_dunExplore")!;
+ Check.Eq(((HashSet)run.GetType().GetField("StuckEdges")!.GetValue(run)!).Count, 0, "no opening closed");
+ var spots = (List)run.GetType().GetField("StuckSpots")!.GetValue(run)!;
+ Check.Eq(spots.Count, 1, "one spot");
+ Check.Eq(St(rig).Rooms, rooms, "no room left out");
+ Check.False(ReferenceEquals(rig.S.CurrentRoute, before), "the rest laid again");
+ var sp = spots[0];
+ var pts = rig.S.CurrentRoute.Points;
+ double Dist(double x, double y) => Math.Sqrt((x - sp.X) * (x - sp.X) + (y - sp.Y) * (y - sp.Y));
+ bool inside = false;
+ for (int i = 0; i + 1 < pts.Count; i++)
+ {
+ double ax = DungeonGeometry.NavToWorld(pts[i].EW), ay = DungeonGeometry.NavToWorld(pts[i].NS);
+ double bx = DungeonGeometry.NavToWorld(pts[i + 1].EW), by = DungeonGeometry.NavToWorld(pts[i + 1].NS);
+ for (int k = 0; k <= 20; k++)
+ {
+ double t = k / 20.0;
+ if (Dist(ax + (bx - ax) * t, ay + (by - ay) * t) < sp.Radius - 0.05) inside = true;
+ }
+ }
+ Check.False(inside, "the new walk keeps out of the spot's circle");
+ Check.True(pts.Any(p => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side), "and still goes into the side room");
+ }
+
+ // The same web, for the dungeon patrol (Tom: "This same change needs to be made in patrol").
+ private static void PatrolStuckOpening()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-patrol-stuck");
+ var said = rig.Typed("/ra dunnav-patrol");
+ Check.True(said.Any(l => l.Contains("circular patrol started")), "the patrol starts: " + Show(said));
+ var before = rig.S.CurrentRoute;
+ var geo = rig.D.Geo();
+ bool InSide(NavPoint p) => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side;
+ Check.Eq(before.RouteType, NavRouteType.Circular, "a circular patrol");
+ int toSide = before.Points.FindIndex(InSide);
+ Check.True(toSide >= 0, "its lap goes into the side room (coverage Everything)");
+ StandAtDoorway(rig, rig.D.E1, rig.D.Side);
+ rig.S.ActiveNavIndex = toSide;
+
+ Check.True(Said(() => rig.Call("TickDunPatrolHazardReroute")).Count == 0 && ReferenceEquals(rig.S.CurrentRoute, before), "not stuck: nothing happens");
+ bool stuck = true;
+ rig.P.ExploreStuckProbe = () => stuck;
+ said = Said(() => rig.Call("TickDunPatrolHazardReroute"));
+ stuck = false;
+ Check.True(said.Any(l => l.Contains($"DunNav-Patrol: couldn't get past something between cells {rig.D.E1:X8} and {rig.D.Side:X8}") && l.Contains("patrolling round it")),
+ "it says which opening it gives up: " + Show(said));
+ Check.False(ReferenceEquals(rig.S.CurrentRoute, before), "the patrol laid again");
+ Check.Eq(rig.S.CurrentRoute.RouteType, NavRouteType.Circular, "still a circular patrol");
+ Check.False(rig.S.CurrentRoute.Points.Any(InSide), "and its lap keeps out of the side room");
+ Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation, "still running");
+ Check.True(Said(() => rig.Call("TickDunPatrolHazardReroute")).Count == 0, "unstuck: nothing more");
+
+ rig.At(15, 15, rig.D.Start);
+ rig.Typed("/ra dunnav-patrol");
+ Check.False(rig.S.CurrentRoute.Points.Any(InSide), "started again in this dungeon: the opening stays closed");
+ }
+
+ // ── Things in doorways (2026-11-16) ──────────────────────────────────────
+ // A web a server puts in a doorway is on no map (Thread 0x5456's are the cells' own: BlockedDoorwayTests). One named so
+ // closes its doorway before the walk is laid; one in the open is left alone; one that comes into view
+ // mid-walk gets the walk laid again; and the name of a thing in a doorway it got stuck in is learned.
+
+ private const uint WebId = 0x80E0E001, OpenWebId = 0x80E0E002, LateWebId = 0x80E0E003, StrandsId = 0x80E0E004, Strands2Id = 0x80E0E005;
+
+ private static void Place(DunRouteTests.Rig rig, uint id, string name, uint cell, float lx, float ly)
+ {
+ FakeHost.Names[id] = name;
+ FakeHost.ItemTypes[id] = 0x80; // TYPE_MISC
+ FakeHost.Positions[id] = (cell, lx, ly, 0f);
+ rig.Cache.OnCreateObject(id);
+ for (int i = 0; i < 3; i++) rig.Cache.Tick();
+ }
+
+ private static bool Logged(int from, string text) => FakeHost.Logs.Skip(from).Any(l => l.Contains(text));
+
+ private static void PluginWebInDoorway()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-web");
+ var geo = rig.D.Geo();
+ bool InSide(NavPoint p) => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side;
+ Place(rig, WebId, "Spider Web", rig.D.E1, 39.6f, 5.2f); // in the doorway e1 > side room (x 40)
+ Place(rig, OpenWebId, "Spider Web", rig.D.Start, 15f, 15f); // the hall's middle: no doorway there
+ int logs = FakeHost.Logs.Count;
+ var said = rig.Typed("/ra dunnav-explore");
+ Check.True(said.Any(l => l.Contains($"Spider Web in the doorway between cells") && l.Contains("going round it")),
+ "it says which doorway the web closes: " + Show(said));
+ Check.True(said.Any(l => l.Contains("exploring")), "and explores: " + Show(said));
+ Check.False(rig.S.CurrentRoute.Points.Any(InSide), "the walk keeps out of the side room (only through the web's doorway)");
+ Check.True(Logged(logs, $"0x{OpenWebId:X8} 'Spider Web'") && Logged(logs, "stands in no doorway: left alone"), "the web in the open is left alone");
+ var run = Run(rig);
+ Check.Eq(((Dictionary)run.GetType().GetField("Blockers")!.GetValue(run)!).Count, 1, "one web in a doorway");
+
+ // A web that comes into view mid-walk, in the doorway hall > w1 (x 0): the walk is laid again round it.
+ var first = rig.S.CurrentRoute;
+ bool InWest(NavPoint p) { uint c = DungeonPathfinder.CellAt(rig.D.Graph, geo, p); return c == rig.D.W1 || c == rig.D.West; }
+ Check.True(first.Points.Any(InWest), "the walk goes into the west rooms");
+ Place(rig, LateWebId, "Spider Web", rig.D.Hall[0, 2], 0.4f, 25f);
+ run.GetType().GetField("NextCheckAt")!.SetValue(run, 0L);
+ said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("Spider Web in the doorway")), "the new web is said: " + Show(said));
+ Check.False(ReferenceEquals(rig.S.CurrentRoute, first), "the walk laid again");
+ Check.False(rig.S.CurrentRoute.Points.Any(InWest), "round the new web (the west rooms are only that way)");
+ Check.Eq(St(rig).State, 1, "still exploring");
+ Check.True(Said(() => { run.GetType().GetField("NextCheckAt")!.SetValue(run, 0L); Tick(rig); }).Count == 0, "the same webs again: nothing new");
+ }
+
+ private static void PluginStuckLearnsName()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-strands");
+ var geo = rig.D.Geo();
+ // Not named like a web: not known to block until it got stuck on one.
+ Place(rig, StrandsId, "Thick Strands", rig.D.E1, 39.6f, 5.2f);
+ Place(rig, Strands2Id, "Thick Strands", rig.D.Hall[0, 2], 0.4f, 25f);
+ rig.Typed("/ra dunnav-explore");
+ StandAtDoorway(rig, rig.D.E1, rig.D.Side);
+ Tick(rig);
+ var before = rig.S.CurrentRoute;
+ bool InWest(NavPoint p) { uint c = DungeonPathfinder.CellAt(rig.D.Graph, geo, p); return c == rig.D.W1 || c == rig.D.West; }
+ Check.True(before.Points.Any(InWest), "at first the walk goes through both (no web by name)");
+ int toSide = before.Points.FindIndex(p => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side);
+ Check.True(toSide >= 0, "the walk goes into the side room");
+ rig.S.ActiveNavIndex = toSide;
+
+ bool stuck = true;
+ rig.P.ExploreStuckProbe = () => stuck;
+ int logs = FakeHost.Logs.Count;
+ Tick(rig);
+ stuck = false;
+ Check.True(Logged(logs, $"in it: 0x{StrandsId:X8} 'Thick Strands'"), "the stuck line names what stands in the doorway");
+ Check.True(Logged(logs, "'Thick Strands' stood in the doorway it couldn't get through"), "and learns its name");
+
+ var run = Run(rig);
+ run.GetType().GetField("NextCheckAt")!.SetValue(run, 0L);
+ var said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("Thick Strands in the doorway between cells")), "the other one of that name closes its doorway: " + Show(said));
+ Check.False(rig.S.CurrentRoute.Points.Any(InWest), "and the walk keeps out of the west rooms");
+ }
+
+ // ── Enter and scan (2026-11-16) ─────────────────────────────────────────
+ // DreamWeave Thread 0x00B5: the boss stood in a 6-cell dead end; the walk touched its doorway and turned back, the
+ // client had no position for the boss yet, and the explore went on without it. The walk now goes into every dead
+ // end and waits at the middles it walks to; when the walk is over, a monster still known in the dungeon is walked to.
+
+ private const uint LeftMobId = 0x80E0E101;
+
+ private static void PluginLeftoverMonster()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-leftover");
+ rig.Typed("/ra dunnav-explore");
+ Check.True(rig.S.CurrentRoute.Points.Any(p => p.Type == NavPointType.Pause && p.PauseTimeMs == DungeonPathfinder.ExploreScanMs),
+ "the walk waits at the room middles it walks to");
+ foreach (uint c in rig.D.Graph.Keys.Where(c => c != rig.D.Nook)) { StandIn(rig, c); Tick(rig); }
+
+ // A monster the walk went past, still in the west room when the walk is over.
+ FakeHost.Names[LeftMobId] = "Dread Test Commander";
+ FakeHost.ItemTypes[LeftMobId] = 0x10;
+ FakeHost.Wcids[LeftMobId] = 99001;
+ FakeHost.Positions[LeftMobId] = (rig.D.West, -18f, 25f, 0f);
+ rig.Cache.OnCreateObject(LeftMobId);
+ for (int i = 0; i < 3; i++) rig.Cache.Tick();
+ StandIn(rig, rig.D.Start);
+ FakeHost.Positions[DunRouteTests.Player] = FakeHost.PlayerPose; // combat's hunt list reads the player's own position
+ // Combat's hunt list (alive, attackable, on the monster list; the rig has no combat manager): the monster, while alive.
+ bool alive = true;
+ rig.P.LeftoverMonstersProbe = () => alive
+ ? new List { new(unchecked((int)LeftMobId), "Dread Test Commander", new OutdoorHunt.Vec(Ox - 18, Oy + 25, 0), 30, 1, rig.D.West) }
+ : new List();
+ Finish(rig);
+ var said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("Dread Test Commander is still in the dungeon") && l.Contains("going after it")),
+ "the walk over, it goes after the monster still here: " + Show(said));
+ Check.Eq(St(rig).State, 1, "still exploring");
+ var geo = rig.D.Geo();
+ var pts = rig.S.CurrentRoute.Points;
+ Check.True(rig.S.EnableNavigation && pts.Count > 0 && DungeonPathfinder.CellAt(rig.D.Graph, geo, pts[^1]) == rig.D.West,
+ "a walk to it, ending in the west room");
+
+ // Walked there, the monster dead: nothing left, done.
+ alive = false;
+ StandIn(rig, rig.D.West);
+ FakeHost.Positions[DunRouteTests.Player] = FakeHost.PlayerPose;
+ Finish(rig);
+ said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("DunNav-Explore: done,")), "then done: " + Show(said));
+ Check.Eq(St(rig).State, 3, "done");
+ }
+
+ // On the real dats: the walk from where that run started goes to the middle of the boss's dead end and waits there.
+ private static void Real00B5BossRoom()
+ {
+ string acDir = DunRouteTests.AcDir;
+ if (!Directory.Exists(acDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
+ var loader = new GeometryLoader();
+ if (!loader.Initialize(acDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
+ try
+ {
+ const uint lb = 0x00B5;
+ DungeonPathfinder.InvalidateCache();
+ var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
+ var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!;
+ var route = DungeonPathfinder.BuildExploreRoute(graph, 0x00B501FF, null, geo, null, null, null, null, out var plan);
+ int bossRoom = plan.RoomOf(0x00B5012A);
+ var cells = plan.Rooms.Cells[bossRoom];
+ var mid = DungeonPathfinder.RoomMiddle(graph, geo, cells, DungeonPathfinder.WallClearance, out _)!;
+ var pts = route.Points;
+ int at = pts.FindIndex(p => p.Type == NavPointType.Point && Math.Abs(p.NS - mid.NS) * 240 < 0.3 && Math.Abs(p.EW - mid.EW) * 240 < 0.3);
+ Console.WriteLine($" 0x00B5: {pts.Count} points, {pts.Count(p => p.Type == NavPointType.Pause)} waits; the boss room ({cells.Count} cells) middle at [{at}]; {DungeonPathfinder.MainRouteNote}");
+ DungeonPathfinder.MainRouteNote = null;
+ Check.True(at >= 0, "the walk goes to the middle of the boss's dead end");
+ Check.True(at >= 0 && at + 1 < pts.Count && pts[at + 1].Type == NavPointType.Pause, "and waits there");
+ }
+ finally
+ {
+ loader.Dispose();
+ DungeonPathfinder.InvalidateCache();
+ }
+ }
+
+ // ── Shut doors and levers (2026-11-14) ───────────────────────────────────
+ // A door in the opening between the hall and the west corridor (x 0, y 25) that can't be used (ItemUseable
+ // No, as every lever door in ACE's data), a lever in the hall that opens it, a button in the hall that
+ // opens nothing.
+
+ private const uint DoorId = 0x7E7E9003, LeverId = 0x7E7E9004, ButtonId = 0x7E7E9005, FarLeverId = 0x7E7E9006;
+ private const uint BfDoor = 0x1000, DoorClosed = 0x00010018, DoorEthereal = 0x4;
+
+ // A Thread puzzle gate (DreamWeave wcid 1006850: a spawned door, locked until its levers' puzzle is solved) in the
+ // doorway e1 > side room: a shut door to the walk. Its lever (wcid 1006851) is never pulled: three wrong pulls in an
+ // hour ban the connection from Threads.
+ private const uint PuzzleGateId = 0x80E0E201, PuzzleLeverId = 0x80E0E202;
+
+ private static void PluginPuzzleGate()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-explore-puzzle", beforeCreate: () =>
+ {
+ FakeHost.Wcids[PuzzleGateId] = 1006850;
+ FakeHost.Wcids[PuzzleLeverId] = 1006851;
+ FakeHost.ObjectStates[PuzzleGateId] = DoorClosed;
+ });
+ FakeHost.Names[PuzzleGateId] = "Warded Gate";
+ FakeHost.ItemTypes[PuzzleGateId] = 0x80;
+ FakeHost.Positions[PuzzleGateId] = (rig.D.E1, 39.7f, 5f, 0f);
+ FakeHost.Names[PuzzleLeverId] = "Puzzle Lever";
+ FakeHost.ItemTypes[PuzzleLeverId] = 0x80;
+ FakeHost.Positions[PuzzleLeverId] = (rig.D.E1, 35f, 5f, 0f);
+ foreach (uint id in new[] { PuzzleGateId, PuzzleLeverId }) rig.Cache.OnCreateObject(id);
+ for (int i = 0; i < 3; i++) rig.Cache.Tick();
+
+ int logs = FakeHost.Logs.Count;
+ rig.Typed("/ra dunnav-explore");
+ Check.True(Logged(logs, $"shut door 0x{PuzzleGateId:X8} 'Warded Gate' (a Thread puzzle gate)"), "the puzzle gate is a shut door to the walk");
+ var geo = rig.D.Geo();
+ Check.False(rig.S.CurrentRoute.Points.Any(p => DungeonPathfinder.CellAt(rig.D.Graph, geo, p) == rig.D.Side), "the walk keeps out of the room behind it");
+
+ int uses = FakeHost.Uses.Count;
+ var said = rig.Typed($"/ra dunnav-explore lever {PuzzleLeverId:X8} door {PuzzleGateId:X8}");
+ Check.True(said.Any(l => l.Contains("is a Thread puzzle lever: the explore never pulls one")), "a puzzle lever is refused: " + Show(said));
+ Check.False(FakeHost.Uses.Skip(uses).Contains(PuzzleLeverId), "and never used");
+ Check.True(Info(rig).GetProperty("last").GetString()!.StartsWith($"puzzle {PuzzleLeverId:X8}"), "puzzle, in radunexploreinfo[]");
+ }
+
+ private static DunRouteTests.Rig LeverRig(string folder, int doorUsable = 1)
+ {
+ // UseObject, the object bitfields and the physics states are the host's only when asked for at Create().
+ var rig = new DunRouteTests.Rig(folder, beforeCreate: () =>
+ {
+ FakeHost.WeaponCalls = true;
+ FakeHost.Bitfields[DoorId] = BfDoor;
+ FakeHost.ObjectStates[DoorId] = DoorClosed;
+ });
+ FakeHost.Names[DoorId] = "Door";
+ FakeHost.Positions[DoorId] = (rig.D.Hall[0, 2], 0.3f, 25f, 0f);
+ FakeHost.Ints[(DoorId, 16u)] = doorUsable;
+ FakeHost.Names[LeverId] = "Lever";
+ FakeHost.Positions[LeverId] = (rig.D.Hall[0, 2], 5f, 25f, 0f);
+ FakeHost.Names[ButtonId] = "Button";
+ FakeHost.Positions[ButtonId] = (rig.D.Hall[2, 2], 25f, 25f, 0f);
+ foreach (uint id in new[] { DoorId, LeverId, ButtonId }) rig.Cache.OnCreateObject(id);
+ for (int i = 0; i < 3; i++) rig.Cache.Tick();
+ return rig;
+ }
+
+ private static System.Text.Json.JsonElement Info(DunRouteTests.Rig rig)
+ => System.Text.Json.JsonDocument.Parse((string)rig.Call("DunExploreInfoJson")!).RootElement.Clone();
+
+ private static object Run(DunRouteTests.Rig rig) => rig.Get("_dunExplore")!;
+ private static string Pts(IEnumerable pts) => string.Join(" ", pts.Select(p => $"({DungeonGeometry.NavToWorld(p.EW) - Ox:F1},{DungeonGeometry.NavToWorld(p.NS) - Oy:F1})"));
+
+ /// Stands in every cell but those given (and the nook), a tick in each.
+ private static void WalkAllBut(DunRouteTests.Rig rig, params uint[] skip)
+ {
+ foreach (uint c in rig.D.Graph.Keys.Where(c => c != rig.D.Nook && !skip.Contains(c))) { StandIn(rig, c); Tick(rig); }
+ }
+
+ private static void PluginShutDoor()
+ {
+ var rig = LeverRig("NavProfiles-explore-door");
+ var said = rig.Typed("/ra dunnav-explore");
+ Check.True(said.Count == 1 && said[0].Contains("round 1 shut door(s)"), "it starts round the shut door: " + Show(said));
+ var geo = rig.D.Geo();
+ bool Behind(NavPoint p) { uint c = DungeonPathfinder.CellAt(rig.D.Graph, geo, p); return c == rig.D.W1 || c == rig.D.West; }
+ Check.False(rig.S.CurrentRoute.Points.Any(Behind), "the walk doesn't go through it");
+ var info = Info(rig);
+ Check.Eq(info.GetProperty("state").GetInt32(), 1, "exploring");
+ var door = info.GetProperty("doors")[0];
+ Check.Eq(door.GetProperty("id").GetString(), "7E7E9003", "the door in radunexploreinfo[]");
+ Check.Eq(door.GetProperty("why").GetString(), "can't be used", "why it's shut");
+ Check.Eq(door.GetProperty("rooms").GetInt32(), 2, "two rooms behind it (the west corridor and room)");
+ Check.Near(door.GetProperty("x").GetDouble(), 0.3, 0.01, "landblock-local x");
+
+ WalkAllBut(rig, rig.D.W1, rig.D.West);
+ Finish(rig);
+ said = Said(() => Tick(rig));
+ Check.True(said.Count == 1 && said[0].Contains("every room it can walk to is done") && said[0].Contains("behind 1 shut door(s): Door 0x7E7E9003 (2)"),
+ "the walk over: it waits at the door: " + Show(said));
+ Check.Eq(St(rig).State, 5, "waiting at the doors");
+ Check.True(!rig.S.EnableNavigation && rig.S.CurrentRoute.Points.Count == 0, "navigation off, an empty route of its own");
+ Check.True(rig.S.IsMacroRunning, "the macro left on");
+ Check.True(Said(() => Tick(rig)).Count == 0, "it waits quietly");
+ said = rig.Typed("/ra dunnav-explore status");
+ Check.True(said[0].Contains("waiting at shut doors") && said[0].Contains("2 room(s) behind 1 shut door(s)"), "status: " + Show(said));
+ }
+
+ private static void PluginLeverErrands()
+ {
+ var rig = LeverRig("NavProfiles-explore-lever");
+ rig.Typed("/ra dunnav-explore");
+ WalkAllBut(rig, rig.D.W1, rig.D.West);
+ Finish(rig);
+ Tick(rig);
+ Check.Eq(St(rig).State, 5, "at the door");
+
+ // A lever on the far side: no way there through the shut door.
+ var said = rig.Typed("/ra dunnav-explore lever 7E7E9006 door 7E7E9003 at -17 25 0");
+ Check.True(said.Any(l => l.Contains("can't be walked to from here")), "a lever behind the door: " + Show(said));
+ Check.True(Info(rig).GetProperty("last").GetString()!.StartsWith("unreachable 7E7E9006 7E7E9003"), "unreachable, in radunexploreinfo[]");
+ Check.Eq(St(rig).State, 5, "still at the door");
+
+ // The button: walked to, used, nothing opens.
+ int usesBefore = FakeHost.Uses.Count;
+ said = rig.Typed("/ra dunnav-explore lever 7E7E9005 door 7E7E9003");
+ Check.True(said.Count == 1 && said[0].Contains("going to pull Button 0x7E7E9005 for Door 0x7E7E9003 (2 room(s) behind it)"), "the errand starts: " + Show(said));
+ Check.Eq(St(rig).State, 6, "at a lever");
+ Check.True(rig.S.EnableNavigation && rig.S.CurrentRoute.RouteType == NavRouteType.Once && rig.S.CurrentRoute.Points.Count > 0, "walking to it");
+ Check.Eq(Info(rig).GetProperty("errand").GetProperty("phase").GetString(), "walking", "walking, in radunexploreinfo[]");
+ rig.At(24.5, 25, rig.D.Hall[2, 2]);
+ Tick(rig);
+ Check.True(FakeHost.Uses.Skip(usesBefore).Contains(ButtonId), "used when there");
+ Check.False(rig.S.EnableNavigation, "navigation off while it watches");
+ Check.Eq(Info(rig).GetProperty("errand").GetProperty("phase").GetString(), "waiting", "watching the door");
+ var errand = Run(rig).GetType().GetField("Errand")!.GetValue(Run(rig))!;
+ // One pull, then the door watched: a door shows open ~4.5 s after (Thread 0x5873, 2026-11-16), and a second
+ // pull before then flips it shut. Not again at 3 s; again after 8 s; given up after 12 s.
+ int pulls() => FakeHost.Uses.Skip(usesBefore).Count(u => u == ButtonId);
+ errand.GetType().GetField("PhaseAt")!.SetValue(errand, Environment.TickCount64 - 3000);
+ Tick(rig);
+ Check.Eq(pulls(), 1, "not pulled again 3 s on (the door may still be opening)");
+ errand.GetType().GetField("PhaseAt")!.SetValue(errand, Environment.TickCount64 - 9000);
+ Tick(rig);
+ Check.Eq(pulls(), 2, "pulled again 9 s on, the door still shut");
+ errand.GetType().GetField("PhaseAt")!.SetValue(errand, Environment.TickCount64 - 13000);
+ said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("Button 0x7E7E9005 didn't open door 0x7E7E9003")), "nothing opened: " + Show(said));
+ Check.Eq(Info(rig).GetProperty("last").GetString(), "notopened 7E7E9005 7E7E9003", "notopened, in radunexploreinfo[]");
+ Check.Eq(St(rig).State, 5, "back at the door");
+
+ // The lever: used, the door opens, the walk goes through it first.
+ said = rig.Typed("/ra dunnav-explore lever 7E7E9004 door 7E7E9003");
+ Check.True(said[0].Contains("going to pull Lever 0x7E7E9004"), "the lever: " + Show(said));
+ rig.At(5.5, 25, rig.D.Hall[0, 2]);
+ Tick(rig);
+ Check.True(FakeHost.Uses.Contains(LeverId), "pulled");
+ FakeHost.ObjectStates[DoorId] = DoorClosed | DoorEthereal;
+ said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("Lever 0x7E7E9004 opened Door 0x7E7E9003 → through it first (2 room(s) behind it)")), "opened: " + Show(said));
+ Check.Eq(St(rig).State, 1, "exploring again");
+ Check.Eq(Info(rig).GetProperty("last").GetString(), "opened 7E7E9003 7E7E9004", "opened, in radunexploreinfo[]");
+ Check.Eq(Info(rig).GetProperty("doors").GetArrayLength(), 0, "no shut door left");
+ var geo = rig.D.Geo();
+ // Along its legs (the west corridor is one run between two openings in line: no point in it).
+ var pts = rig.S.CurrentRoute.Points;
+ var cells = new HashSet();
+ for (int i = 0; i + 1 < pts.Count; i++)
+ for (int k = 0; k <= 20; k++)
+ {
+ double f = k / 20.0;
+ cells.Add(DungeonPathfinder.CellAt(rig.D.Graph, geo, new NavPoint { NS = pts[i].NS + (pts[i + 1].NS - pts[i].NS) * f, EW = pts[i].EW + (pts[i + 1].EW - pts[i].EW) * f }));
+ }
+ Check.True(cells.Contains(rig.D.W1) && cells.Contains(rig.D.West), "the walk goes through the door, the corridor and into the west room: " + Pts(pts));
+ Check.True(rig.S.EnableNavigation && rig.S.IsMacroRunning, "walking");
+ StandIn(rig, rig.D.W1); Tick(rig);
+ StandIn(rig, rig.D.West); Tick(rig);
+ Finish(rig);
+ said = Said(() => Tick(rig));
+ var s = St(rig);
+ Check.True(said.Count == 1 && said[0].Contains($"done, {s.Rooms} of {s.Rooms} rooms") && !said[0].Contains("shut door"), "done, every room: " + Show(said));
+ }
+
+ private static void PluginDoorsMore()
+ {
+ // Done at the doors: the rooms behind them said.
+ var rig = LeverRig("NavProfiles-explore-doors-done");
+ rig.Typed("/ra dunnav-explore");
+ WalkAllBut(rig, rig.D.W1, rig.D.West);
+ Finish(rig);
+ Tick(rig);
+ var said = rig.Typed("/ra dunnav-explore done");
+ Check.True(said.Count == 1 && said[0].Contains("2 more behind 1 shut door(s)"), "done at the doors: " + Show(said));
+ Check.Eq(St(rig).State, 3, "done");
+ said = rig.Typed("/ra dunnav-explore done");
+ Check.True(said[0].Contains("none is"), "done again: nothing waits: " + Show(said));
+
+ // A shut door that opens by itself while it waits: through it.
+ rig = LeverRig("NavProfiles-explore-doors-self");
+ rig.Typed("/ra dunnav-explore");
+ WalkAllBut(rig, rig.D.W1, rig.D.West);
+ Finish(rig);
+ Tick(rig);
+ FakeHost.ObjectStates[DoorId] = DoorClosed | DoorEthereal;
+ Run(rig).GetType().GetField("NextCheckAt")!.SetValue(Run(rig), 0L);
+ said = Said(() => Tick(rig));
+ Check.True(said.Any(l => l.Contains("Door 0x7E7E9003 is open → through it first")), "an open door: " + Show(said));
+ Check.Eq(St(rig).State, 1, "exploring again");
+
+ // A door it could use, that the door opener gave up on (locked, no picks): shut from then on.
+ rig = LeverRig("NavProfiles-explore-doors-locked", doorUsable: 0x20);
+ said = rig.Typed("/ra dunnav-explore");
+ Check.False(said[0].Contains("shut door"), "a door you can use isn't shut: " + Show(said));
+ rig.Call("NoteExploreDoorRefused", DoorId, "locked");
+ Tick(rig);
+ var info = Info(rig);
+ Check.True(info.GetProperty("doors").GetArrayLength() == 1 && info.GetProperty("doors")[0].GetProperty("why").GetString() == "locked",
+ "the door opener gave up on it: shut (locked): " + info.GetRawText());
+
+ // Resume: stopped, then carried on with the rooms entered kept.
+ int entered = St(rig).Visited;
+ StandIn(rig, rig.D.E1); Tick(rig);
+ rig.Typed("/ra dunnav-explore stop");
+ Check.Eq(St(rig).State, 4, "stopped");
+ said = rig.Typed("/ra dunnav-explore resume");
+ Check.True(said.Count == 1 && said[0].Contains("exploring again"), "resumed: " + Show(said));
+ Check.True(St(rig).State == 1 && St(rig).Visited >= entered + 1, "the rooms entered kept");
+ said = rig.Typed("/ra dunnav-explore resume");
+ Check.True(said[0].Contains("already exploring"), "resume while exploring: " + Show(said));
+ }
+
+ private static void Expressions()
+ {
+ FakeHost.Reset();
+ var host = FakeHost.Create();
+ var m = new MetaManager(new LegacyUiSettings(), host, new PlayerVitalsCache());
+ Check.Eq(m.Expressions.Evaluate("radunexplore[]"), "0", "not wired: 0");
+ Check.Eq(m.Expressions.Evaluate("radunexplorerooms[]"), "0", "rooms 0");
+ m.SetDunExploreStatus(() => (1, 12, 5));
+ Check.Eq(m.Expressions.Evaluate("radunexplore[]"), "1", "exploring");
+ Check.Eq(m.Expressions.Evaluate("radunexplorerooms[]"), "12", "rooms");
+ Check.Eq(m.Expressions.Evaluate("radunexplorevisited[]"), "5", "entered");
+ }
+
+ private static void TinyHiveRealDats()
+ {
+ if (!Directory.Exists(DunRouteTests.AcDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
+ var loader = new GeometryLoader();
+ if (!loader.Initialize(DunRouteTests.AcDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
+ try
+ {
+ const uint lb = 0x0289, start = 0x028902A5, nook = 0x028902BA;
+ var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
+ var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
+ Check.True(graph.Count > 400 && geo != null, $"Tiny Hive loaded ({graph.Count} cells)");
+ var s = graph[start];
+ var p = new PatrolPortal { Id = 0x7028905D, Name = "Surface Portal", Cell = nook, X = 2 * 192 + 110, Y = 0x89 * 192 - 3.77927, Z = -23.995 };
+ var at = (DungeonGeometry.NavToWorld(s.EW), DungeonGeometry.NavToWorld(s.NS), (double)s.Z);
+ var clock = System.Diagnostics.Stopwatch.StartNew();
+ var route = DungeonPathfinder.BuildExploreRoute(graph, start, null, geo, null, new List { p }, at, null, out var plan);
+ double ms = clock.Elapsed.TotalMilliseconds;
+ var walked = RoomsWalked(route.Points, graph, geo, plan);
+ var missed = plan.PlanRooms.Where(r => !walked.Contains(r)).ToList();
+ double yards = 0;
+ for (int i = 0; i + 1 < route.Points.Count; i++)
+ yards += Math.Sqrt(Math.Pow(route.Points[i + 1].NS - route.Points[i].NS, 2) + Math.Pow(route.Points[i + 1].EW - route.Points[i].EW, 2)) * 240.0;
+ var lap = DungeonPathfinder.BuildPatrolRoute(graph, start, null, geo, new DungeonPatrolOptions { Coverage = PatrolCoverage.Everything }, new List { p }, at);
+ double lapYards = 0;
+ for (int i = 0; i < lap.Points.Count; i++)
+ {
+ var a = lap.Points[i]; var b = lap.Points[(i + 1) % lap.Points.Count];
+ lapYards += Math.Sqrt(Math.Pow(b.NS - a.NS, 2) + Math.Pow(b.EW - a.EW, 2)) * 240.0;
+ }
+ Console.WriteLine($" explore: {plan.PlanRooms.Count} rooms, {route.Points.Count} points, {yards:F0} yd, laid in {ms:F0} ms; "
+ + $"the patrol's Everything lap: {lap.Points.Count} points, {lapYards:F0} yd; rooms the legs miss: {missed.Count}");
+ Check.True(plan.ByRoom && plan.PlanRooms.Count > 10, $"rooms ({plan.PlanRooms.Count})");
+ Check.Eq(plan.Order.Count, plan.PlanRooms.Count - 1, "each room but the start in the order");
+ Check.True(missed.Count == 0, "every room walked into; missed: " + string.Join(",", missed.Select(r => plan.Rooms.Cells[r][0].ToString("X8"))));
+ double near = DungeonPathfinder.NearestApproach(route.Points, closed: false, p);
+ Check.True(near >= p.Radius - 0.05, $"keeps out of the Surface Portal ({near:F1} m)");
+ }
+ finally { DungeonPathfinder.InvalidateCache(); }
+ }
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs
new file mode 100644
index 0000000..52a76af
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/DunNavToTests.cs
@@ -0,0 +1,77 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Plugin.RynthAi;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.RynthAiHostTests.Fakes;
+using RynthCore.RynthAiTests.Harness;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// /ra dunnav-to (2026-11-15): a walk on the dungeon map to an object's own cell (any
+// floor), for a script's walks to the monsters still to be killed after an explore.
+// On DunRouteTests' sample dungeon (the start in the hall's middle, the west room two rooms away).
+internal static class DunNavToTests
+{
+ public static void Register(Runner r)
+ {
+ r.Add("dunnav-to: walks to an object's cell on the dungeon map, the macro on; refuses an unknown one or one outside the dungeon", WalksToObject);
+ }
+
+ private const uint Rat = 0x7E7E9101, Outside = 0x7E7E9102, Unknown = 0x7E7E9103;
+
+ private static void WalksToObject()
+ {
+ var rig = new DunRouteTests.Rig("NavProfiles-dunnav-to");
+ FakeHost.Names[Rat] = "Threadbound Rat";
+ FakeHost.Positions[Rat] = (rig.D.West, -17f, 25f, 0f);
+ rig.S.IsMacroRunning = false;
+
+ var said = rig.Typed("/ra dunnav-to 0x7E7E9101");
+ Check.True(said.Count == 1 && said[0].StartsWith("[RynthAi] DunNav-To: 'Threadbound Rat' 0x7E7E9101") && said[0].Contains("walking there"),
+ "it answers: " + string.Join(" | ", said));
+ var pts = rig.S.CurrentRoute.Points;
+ Check.True(pts.Count >= 2, $"a walk ({pts.Count} points)");
+ Check.Eq(rig.S.CurrentRoute.RouteType, NavRouteType.Once, "a Once walk");
+ Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation && rig.S.ActiveNavIndex == 0, "macro and navigation on, from its start");
+ var last = pts[^1];
+ double lx = DungeonGeometry.NavToWorld(last.EW) - DunRouteTests.Ox, ly = DungeonGeometry.NavToWorld(last.NS) - DunRouteTests.Oy;
+ Check.True(Math.Abs(lx - -17) < 3 && Math.Abs(ly - 25) < 3, $"it ends at the rat ({lx:F1}, {ly:F1})");
+ // Through w1 (x -10..0, y 22.35..27.65), the one way into the west room: a leg crosses x = -5 inside it.
+ bool throughW1 = false;
+ double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW) - DunRouteTests.Ox;
+ double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS) - DunRouteTests.Oy;
+ for (int i = 0; i + 1 < pts.Count; i++)
+ {
+ double ax = X(pts[i]), bx = X(pts[i + 1]);
+ if ((ax - -5) * (bx - -5) > 0 || Math.Abs(bx - ax) < 1e-6) continue;
+ double y = Y(pts[i]) + (Y(pts[i + 1]) - Y(pts[i])) * ((-5 - ax) / (bx - ax));
+ throughW1 |= y > 22.35 && y < 27.65;
+ }
+ Check.True(throughW1, "through w1, the way to the west room");
+
+ // Decimal ids work too; an unknown object, or one outside the dungeon, is refused (nothing changed).
+ var before = rig.S.CurrentRoute;
+ said = rig.Typed("/ra dunnav-to " + Unknown.ToString());
+ Check.True(said.Count == 1 && said[0].Contains("has no position the client knows"), "unknown: " + string.Join(" | ", said));
+ FakeHost.Positions[Outside] = (0xA9B40020, 10f, 10f, 0f);
+ said = rig.Typed("/ra dunnav-to 0x7E7E9102");
+ Check.True(said.Count == 1 && said[0].Contains("isn't in this dungeon"), "outside: " + string.Join(" | ", said));
+ said = rig.Typed("/ra dunnav-to");
+ Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunnav-to "), "no id: the usage");
+ Check.True(ReferenceEquals(rig.S.CurrentRoute, before), "the walk in hand is left alone");
+
+ // In a Thread on DreamWeave it is off, as the patrol and the explore are.
+ var thread = new DunRouteTests.Rig("NavProfiles-dunnav-to-thread", world: "DreamWeave");
+ FakeHost.Names[Rat] = "Threadbound Rat";
+ FakeHost.Positions[Rat] = (thread.D.West, -17f, 25f, 0f);
+ thread.S.IsMacroRunning = false;
+ ServerPolicy.NoteChat("[REALM] id=0 inst=7841 eph=1 name=Base World", thread.D.Start);
+ var routeBefore = thread.S.CurrentRoute;
+ said = thread.Typed("/ra dunnav-to 0x7E7E9101");
+ Check.True(said.Count == 1 && said[0].Contains("turned off in Threads"), "in a Thread on DreamWeave: refused: " + string.Join(" | ", said));
+ Check.False(thread.S.IsMacroRunning || thread.S.EnableNavigation, "nothing started");
+ Check.True(ReferenceEquals(thread.S.CurrentRoute, routeBefore), "no walk laid");
+ ServerPolicy.Forget();
+ }
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs
index c543735..fe53b8f 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs
@@ -62,12 +62,12 @@ internal static class DunRouteTests
// ── The sample dungeon ───────────────────────────────────────────────────
- private const uint Lb = 0x7E7E;
- private const double Ox = 0x7E * 192.0, Oy = 0x7E * 192.0;
- private const uint SurfaceId = 0x7E7E9001, DepthsId = 0x7E7E9002;
+ internal const uint Lb = 0x7E7E;
+ internal const double Ox = 0x7E * 192.0, Oy = 0x7E * 192.0;
+ internal const uint SurfaceId = 0x7E7E9001, DepthsId = 0x7E7E9002;
/// A hand-built dungeon in landblock 0x7E7E; positions are landblock-local metres.
- private sealed class Sample
+ internal sealed class Sample
{
public readonly Dictionary Graph = new();
public readonly List<(uint, V3[])> Portals = new(), Floors = new(), Walls = new();
@@ -409,7 +409,7 @@ internal static class DunRouteTests
// ── Files ────────────────────────────────────────────────────────────────
- private static string Fresh(string sub)
+ internal static string Fresh(string sub)
{
string dir = Path.Combine(Program.TempRoot, sub);
if (Directory.Exists(dir)) Directory.Delete(dir, true);
@@ -769,9 +769,9 @@ internal static class DunRouteTests
// ── The plugin ───────────────────────────────────────────────────────────
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
- private const uint Player = 0x50000E01;
+ internal const uint Player = 0x50000E01;
- private sealed class Rig
+ internal sealed class Rig
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
@@ -779,7 +779,7 @@ internal static class DunRouteTests
public readonly DungeonGeometry Geo;
public readonly WorldObjectCache Cache;
- public Rig(string folder, string world = "", double lx = 15, double ly = 15, bool namedExit = true)
+ public Rig(string folder, string world = "", double lx = 15, double ly = 15, bool namedExit = true, Action? beforeCreate = null)
{
FakeHost.Reset();
ServerPolicy.Forget();
@@ -794,6 +794,7 @@ internal static class DunRouteTests
FakeHost.Names[DepthsId] = "Portal to the Depths";
FakeHost.ItemTypes[DepthsId] = 0x00010000;
FakeHost.Positions[DepthsId] = (D.Side, 45f, 5f, 0f);
+ beforeCreate?.Invoke(); // FakeHost options read when the host is made (WeaponCalls: UseObject)
var host = FakeHost.Create(Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
@@ -1301,7 +1302,7 @@ internal static class DunRouteTests
// ── Tiny Hive on the real dats ───────────────────────────────────────────
- private const string AcDir = @"C:\Turbine\Asheron's Call";
+ internal const string AcDir = @"C:\Turbine\Asheron's Call";
private static void TinyHiveRealDats()
{
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HazardFloorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HazardFloorTests.cs
index 9078800..7f88113 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/HazardFloorTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/HazardFloorTests.cs
@@ -26,6 +26,7 @@ internal static class HazardFloorTests
public static void Register(Runner r)
{
r.Add("hazard floors: a polygon facing up at FloorZ or more is floor; walls, ceilings, steep slopes are not", WalkableFloor);
+ r.Add("hazard floors (2026-11-16): kept out of where that shuts the walk in (stands on one, or most of the dungeon behind them); a side pool isn't", ShutIn);
r.Add("hazard floors: a cell's floor surfaces are its floor polygons', not its walls', ceiling's or portals'", FloorSurfaces);
r.Add("hazard floors: a hazard texture on a cell's wall doesn't make it a hazard; on its floor it does", WallVersusFloor);
r.Add("hazard floors: learnhere takes a rare floor texture, never a wall texture", LearnIgnoresWalls);
@@ -223,4 +224,27 @@ internal static class HazardFloorTests
}
finally { ResetSet(); }
}
+
+ // A Thread arrived on lava: 14 of its cells reachable round 9 lava cells, the explore "done" with 8 of 75 rooms.
+ private static void ShutIn()
+ {
+ // A corridor 1-2-3-4-5-6, and a side room 7 off 2.
+ var g = new Dictionary();
+ void Link(uint a, uint b)
+ {
+ if (!g.TryGetValue(a, out var na)) g[a] = na = new DungeonNavNode { CellId = a };
+ if (!g.TryGetValue(b, out var nb)) g[b] = nb = new DungeonNavNode { CellId = b };
+ na.Neighbors.Add(b); nb.Neighbors.Add(a);
+ }
+ Link(1, 2); Link(2, 3); Link(3, 4); Link(4, 5); Link(5, 6); Link(2, 7);
+ var lava = new HashSet { 3 };
+ Check.True(DungeonPathfinder.HazardFloorsShutIn(g, 1, lava, lava, out int r, out int j), $"lava across the corridor: shut in ({r} of {j})");
+ Check.Eq(r, 3, "1, 2 and the side room reachable");
+ Check.Eq(j, 7, "of the 7 the openings join");
+ var under = new HashSet { 1 };
+ Check.True(DungeonPathfinder.HazardFloorsShutIn(g, 1, under, under, out _, out _), "standing on lava: shut in");
+ var side = new HashSet { 7 };
+ Check.False(DungeonPathfinder.HazardFloorsShutIn(g, 1, side, side, out r, out j), $"a pool in the side room: kept out of ({r} of {j})");
+ Check.False(DungeonPathfinder.HazardFloorsShutIn(g, 1, lava, null, out _, out _), "no floor cells: nothing to walk");
+ }
}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HoleTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HoleTests.cs
new file mode 100644
index 0000000..f692eac
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/HoleTests.cs
@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using RynthCore.Plugin.RynthAi;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Raycasting;
+using RynthCore.RynthAiTests.Harness;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// The explore walked over a hole (DungeonPathfinder.Holes.cs, 2026-11-15). DreamWeave Thread 0x039B:
+// a walkway at z 6 through two square rooms, each with a 5 x 5 m pit in the middle (down to the z -6
+// rooms) and a 2 m rim; the walk went doorway to doorway over both pits. And a corridor at -6 that
+// opens into a round room whose floor (-12) is its other cells' (a floorless cell at the opening):
+// a 6 m ledge the ledge finder didn't see.
+internal static class HoleTests
+{
+ public static void Register(Runner r)
+ {
+ r.Add("holes: Thread 0x039B on the real dats - the explore walks round the walkway's two pits, not over them; its 6 m ledge is seen (if the dats are here)", Real039B);
+ }
+
+ private static void Real039B()
+ {
+ string acDir = DunRouteTests.AcDir;
+ if (!Directory.Exists(acDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
+ var loader = new GeometryLoader();
+ if (!loader.Initialize(acDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
+ try
+ {
+ const uint lb = 0x039B;
+ DungeonPathfinder.InvalidateCache();
+ var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
+ var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!;
+ Check.NotNull(geo, "geometry");
+ var ledges = DungeonPathfinder.FindLedges(graph, geo);
+ Check.True(ledges.Exists(l => (l.High & 0xFFFF) == 0x014F && (l.Low & 0xFFFF) == 0x0143),
+ $"the corridor's 6 m ledge into the round room is seen ({ledges.Count} ledge(s))");
+
+ var exit = new PatrolPortal { Id = 0x7039B3EB, Name = "Thread Exit", Cell = 0x039B015E, X = 665.9, Y = 29689.7, Z = -6.1 };
+ foreach (bool holes in new[] { false, true })
+ {
+ DungeonPathfinder.HolesEnabled = holes;
+ var route = DungeonPathfinder.BuildExploreRoute(graph, 0x039B0177, null, geo, null, new[] { exit }, (606.0, 29720.0, 6.0), null, out _);
+ int over = 0;
+ var pts = route.Points;
+ for (int i = 0; i + 1 < pts.Count; i++)
+ {
+ double x0 = DungeonGeometry.NavToWorld(pts[i].EW), y0 = DungeonGeometry.NavToWorld(pts[i].NS), z0 = pts[i].Z * 240.0;
+ double x1 = DungeonGeometry.NavToWorld(pts[i + 1].EW), y1 = DungeonGeometry.NavToWorld(pts[i + 1].NS);
+ if (z0 < 4 || pts[i + 1].Z * 240.0 < 4) continue; // legs along the walkway (z 6), not down its ramp
+ double len = Math.Sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
+ int n = Math.Max(1, (int)Math.Ceiling(len / 0.5));
+ for (int s = 1; s < n; s++)
+ {
+ double t = (double)s / n, x = x0 + (x1 - x0) * t, y = y0 + (y1 - y0) * t;
+ if (!geo.TryFloorHeight(x, y, 6.0, 1.0, out _)) { over++; break; }
+ }
+ }
+ Console.WriteLine($" holes {(holes ? "on" : "off")}: {pts.Count} points, {over} walkway leg(s) over missing floor; {DungeonPathfinder.MainRouteNote}");
+ DungeonPathfinder.MainRouteNote = null;
+ if (holes) Check.Eq(over, 0, "no walkway leg over a pit");
+ else Check.True(over >= 2, $"as laid, the walk went over both pits ({over})");
+ }
+ }
+ finally
+ {
+ DungeonPathfinder.HolesEnabled = true;
+ loader.Dispose();
+ DungeonPathfinder.InvalidateCache();
+ }
+ }
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs
index 6210219..bf9c2c1 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs
@@ -27,6 +27,7 @@ internal static class HuntBuildingTests
r.Add("hunt buildings: of a building's two doors, the one giving the shorter walk (the other's way round never asked for)", NearerDoor);
r.Add("hunt buildings: from inside, a monster outdoors is walked to out through the nearer door, then on RynthNav's map", OutOfBuilding);
r.Add("hunt buildings: inside a building with no door known (or none known at all): back out the way in", NoDoorFallsBack);
+ r.Add("hunt buildings (2026-11-16): inside, no door it can walk to from here, or no way on from any: back out the way in, no monster left out", NoDoorFromHere);
r.Add("hunt buildings: one in the same building through its rooms; one in another building out of one door and in by another", SameAndOtherBuilding);
r.Add("hunt buildings: a door whose step out isn't on the ground is never used; a building it doesn't know is left alone", DoorOffTheGround);
r.Add("building map: a hand-built house: its door faces out, a window and a slit are no doors, a shared opening joins two buildings", HandBuiltHouse);
@@ -202,6 +203,44 @@ internal static class HuntBuildingTests
Check.True(d.Act == OutdoorHunt.Act.Walk && h2.WalkingOut, "no building map at all: the same");
}
+ // A Thread: after a kill in a building every monster outside was "left out for 120 s: no door of
+ // building 1747#1 it can walk to" and the hunt stood 2 min. Where it stands is the trouble, not them.
+ private static void NoDoorFromHere()
+ {
+ // The house's only door is in the east room, and the west room (where it stands) doesn't join it.
+ var house = House(East(RoomE, 1030, 1000));
+ house.Apart.Add((RoomW, RoomE));
+ var h = new OutdoorHunt();
+ h.Start(T0, V(990, 1000));
+ h.Track(V(1018, 1000), indoors: false);
+ h.Track(V(1020, 1000), indoors: true);
+ h.Track(V(1022, 1000), indoors: true);
+ var me = V(1022, 1000);
+ var d = h.Tick(T0, me, RoomW, true, Sorted(C(1, V(990, 1000), me), C(2, V(1000, 1030), me)), new Nav().Path, house);
+ Check.True(d.Act == OutdoorHunt.Act.Walk && h.WalkingOut && h.Note.Contains("back out the way in"), $"no door from here: back out the way in ({d.Act}, {h.Note})");
+ Check.False(h.IsSkipped(1, T0.AddSeconds(5)) || h.IsSkipped(2, T0.AddSeconds(5)), "no monster left out for it");
+
+ // A door it can walk to, but RynthNav finds no way on from its step to either monster.
+ var house2 = House(West(RoomW, 1020, 1000));
+ var nav = new Nav();
+ nav.Overrides[(990, 1000)] = new(OutdoorHunt.PathStatus.NoPath, Array.Empty(), 0, 0);
+ nav.Overrides[(1000, 1030)] = new(OutdoorHunt.PathStatus.NoPath, Array.Empty(), 0, 0);
+ var h2 = new OutdoorHunt();
+ h2.Start(T0, V(990, 1000));
+ h2.Track(V(1018, 1000), indoors: false);
+ h2.Track(V(1022, 1000), indoors: true);
+ d = h2.Tick(T0, me, RoomW, true, Sorted(C(1, V(990, 1000), me), C(2, V(1000, 1030), me)), nav.Path, house2);
+ Check.True(d.Act == OutdoorHunt.Act.Walk && h2.WalkingOut, $"no way on from its door: back out the way in ({d.Act}, {h2.Note})");
+ Check.False(h2.IsSkipped(1, T0.AddSeconds(5)) || h2.IsSkipped(2, T0.AddSeconds(5)), "none left out for that either");
+
+ // Outdoors again, one RynthNav can't reach is left out as before.
+ var h3 = new OutdoorHunt();
+ h3.Start(T0, V(990, 1000));
+ var out1 = V(1000, 1000);
+ d = h3.Tick(T0, out1, Outdoors, true, Sorted(C(1, V(990, 1000), out1)), nav.Path, house2);
+ Check.True(h3.IsSkipped(1, T0.AddSeconds(5)), "outdoors, an unreachable one is still left out");
+ }
+
private static void SameAndOtherBuilding()
{
var me = V(1022, 1000);
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs
index 44fd7c5..6d542f0 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs
@@ -22,6 +22,7 @@ internal static class KeepHuntingAfterDeathTests
r.Add("keep hunting (11-13): a meta's route loaded after the death, or the macro stopped: not started again, said in chat", Dropped);
r.Add("keep hunting (11-13): /ra hunt death answers, sets it, says why not with the usage", Command);
r.Add("keep hunting (11-13): KeepHuntingAfterDeath is off by default and round-trips (saved, copied)", Setting);
+ r.Add("hunt (2026-11-16): a walk that ran out leaves nav on with no walk left, not off until the next walk", NavStaysOn);
}
private static void Decide()
@@ -87,6 +88,33 @@ internal static class KeepHuntingAfterDeathTests
public string All => string.Join(" | ", FakeHost.Chat);
}
+ private static void NavStaysOn()
+ {
+ var g = new Rig();
+ g.Hunting();
+ var walk = (NavRouteParser)g.Get("_huntRoute")!;
+ walk.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 1 });
+ g.S.ActiveNavIndex = 1; // walked off its end
+ g.S.EnableNavigation = false; // what the nav engine does then (CompleteOnceRoute)
+ Check.True(g.S.NavRouteFinished(), "the walk is a finished Once route");
+ g.Call("TickOutdoorHunt");
+ Check.True(g.S.EnableNavigation, "nav on again at once");
+ Check.True(ReferenceEquals(g.S.CurrentRoute, g.Get("_huntRoute")) && g.S.CurrentRoute.Points.Count == 0,
+ "with an empty walk: nothing for the arbiter to hold Navigating for");
+ Check.True(g.P.HuntActive, "and the hunt still on");
+
+ // The player turning nav off mid-walk is left alone (a walk still to go: not finished).
+ var h = new Rig();
+ h.Hunting();
+ var w2 = (NavRouteParser)h.Get("_huntRoute")!;
+ w2.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 1 });
+ w2.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 2, EW = 2 });
+ h.S.ActiveNavIndex = 1;
+ h.S.EnableNavigation = false;
+ h.Call("TickOutdoorHunt");
+ Check.False(h.S.EnableNavigation, "nav off mid-walk: left off");
+ }
+
private static void PauseAndRestart()
{
var g = new Rig();
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LedgeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LedgeTests.cs
new file mode 100644
index 0000000..1a53ec5
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/LedgeTests.cs
@@ -0,0 +1,182 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using RynthCore.Plugin.RynthAi;
+using RynthCore.Plugin.RynthAi.Raycasting;
+using RynthCore.RynthAiTests.Harness;
+using V3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// Ledges (DungeonPathfinder.Ledges.cs, 2026-11-15). DreamWeave Thread 0x0192: the explore walked over
+// a 6 m ledge (019201C4, floor 0 -> 019201C6, floor -6), which AC won't walk a character off (it slides
+// along the edge) and nobody walks up; it snagged there every time. Now an opening whose floors are more
+// than LedgeMeters apart is closed in the dungeon graph (walked round), unless it is the only way on.
+// - a high room and a low room joined by a ledge and by stairs round: the ledge is found (the stairs
+// aren't one) and closed, and the way from one to the other goes by the stairs;
+// - the same with no stairs: the ledge is the only way and stays open;
+// - 0x0192 on the real dats: its twelve ledges are closed, every cell still reached, and the explore's
+// walk never steps across one.
+internal static class LedgeTests
+{
+ public static void Register(Runner r)
+ {
+ r.Add("ledges: a ledge with stairs round is found (the stairs aren't one) and closed; the way goes by the stairs", LedgeWithStairs);
+ r.Add("ledges: a ledge that is the only way on stays open", LedgeOnlyWay);
+ r.Add("ledges: Thread 0x0192 on the real dats: 12 ledges closed, every cell reached, the explore never steps over one (if the dats are here)", Real0192);
+ }
+
+ private sealed class Dungeon
+ {
+ public readonly Dictionary Graph = new();
+ public readonly List<(uint, V3[])> Portals = new();
+ public readonly List<(uint, V3[])> Floors = new();
+ public readonly List<(uint, V3[])> Walls = new();
+ private uint _next = 0x7E7E0100;
+
+ public uint Cell(double x0, double y0, double x1, double y1, double z = 0)
+ {
+ uint id = _next++;
+ Graph[id] = new DungeonNavNode { CellId = id, EW = DungeonGeometry.WorldToNav((x0 + x1) / 2), NS = DungeonGeometry.WorldToNav((y0 + y1) / 2), Z = (float)z };
+ Floors.Add((id, new[] { new V3((float)x0, (float)y0, (float)z), new V3((float)x1, (float)y0, (float)z), new V3((float)x1, (float)y1, (float)z), new V3((float)x0, (float)y1, (float)z) }));
+ return id;
+ }
+
+ // An opening from floor z up 3 m (the high side's floor for a ledge).
+ public void OpenX(uint a, uint b, double x, double y0, double y1, double z = 0) => Open(a, b, Quad(x, y0, x, y1, z));
+ public void OpenY(uint a, uint b, double y, double x0, double x1, double z = 0) => Open(a, b, Quad(x0, y, x1, y, z));
+
+ private void Open(uint a, uint b, V3[] quad)
+ {
+ Graph[a].Neighbors.Add(b);
+ Graph[b].Neighbors.Add(a);
+ Portals.Add((a, quad));
+ Portals.Add((b, quad.Reverse().ToArray()));
+ }
+
+ private static V3[] Quad(double x0, double y0, double x1, double y1, double z) => new[]
+ {
+ new V3((float)x0, (float)y0, (float)z), new V3((float)x1, (float)y1, (float)z),
+ new V3((float)x1, (float)y1, (float)z + 3f), new V3((float)x0, (float)y0, (float)z + 3f),
+ };
+
+ public DungeonGeometry Geo() => DungeonGeometry.Build(Graph, Portals, Floors, Walls);
+ }
+
+ // A high room (floor 0) south of a low room (floor -6), a ledge between them; with stairs, a way
+ // round east: six 1 m steps down, then a corridor back west into the low room.
+ private static (Dungeon D, uint High, uint Low) Build(bool stairs)
+ {
+ var d = new Dungeon();
+ uint high = d.Cell(0, 0, 10, 10, 0);
+ uint low = d.Cell(0, 10, 10, 20, -6);
+ d.OpenY(high, low, 10, 3, 7, 0);
+ if (stairs)
+ {
+ uint prev = high;
+ double x = 10;
+ for (int i = 1; i <= 6; i++)
+ {
+ uint step = d.Cell(x, 2, x + 3, 8, -i);
+ d.OpenX(prev, step, x, 2, 8, -i + 1);
+ prev = step;
+ x += 3;
+ }
+ uint up = d.Cell(x - 3, 8, x, 20, -6);
+ d.OpenY(prev, up, 8, x - 3, x, -6);
+ uint corr = d.Cell(10, 12, x - 3, 18, -6);
+ d.OpenX(corr, up, x - 3, 12, 18, -6);
+ d.OpenX(low, corr, 10, 12, 18, -6);
+ }
+ return (d, high, low);
+ }
+
+ private static void LedgeWithStairs()
+ {
+ var (d, high, low) = Build(stairs: true);
+ var geo = d.Geo();
+ var ledges = DungeonPathfinder.FindLedges(d.Graph, geo);
+ Check.Eq(ledges.Count, 1, "one ledge (the 1 m stairs are not ledges)");
+ Check.True(ledges[0].High == high && ledges[0].Low == low, $"high {ledges[0].High:X8} -> low {ledges[0].Low:X8}");
+ Check.Near(ledges[0].Step, 6.0, 0.01, "6 m");
+ Check.True(DungeonPathfinder.FindPath(high, low, d.Graph).Count == 2, "before: straight over the ledge");
+
+ var kept = DungeonPathfinder.CloseLedges(d.Graph, ledges, out int closed);
+ Check.Eq(closed, 1, "closed");
+ Check.Eq(kept.Count, 0, "none kept open");
+ Check.False(d.Graph[high].Neighbors.Contains(low) || d.Graph[low].Neighbors.Contains(high), "the ledge is gone both ways");
+ var path = DungeonPathfinder.FindPath(high, low, d.Graph);
+ Check.True(path.Count > 8, $"after: down the stairs and round ({path.Count} cells)");
+ }
+
+ private static void LedgeOnlyWay()
+ {
+ var (d, high, low) = Build(stairs: false);
+ var geo = d.Geo();
+ var ledges = DungeonPathfinder.FindLedges(d.Graph, geo);
+ Check.Eq(ledges.Count, 1, "the ledge");
+ var kept = DungeonPathfinder.CloseLedges(d.Graph, ledges, out int closed);
+ Check.Eq(closed, 0, "not closed");
+ Check.Eq(kept.Count, 1, "kept: the only way on");
+ Check.True(d.Graph[high].Neighbors.Contains(low) && d.Graph[low].Neighbors.Contains(high), "still linked both ways");
+ }
+
+ private static void Real0192()
+ {
+ string acDir = DunRouteTests.AcDir;
+ if (!Directory.Exists(acDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
+ var loader = new GeometryLoader();
+ if (!loader.Initialize(acDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
+ try
+ {
+ const uint lb = 0x0192, start = 0x019201A8;
+ DungeonPathfinder.InvalidateCache();
+ var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
+ int linksBefore = graph.Values.Sum(n => n.Neighbors.Count);
+ var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
+ Check.NotNull(geo, "geometry");
+ Console.WriteLine(" " + DungeonPathfinder.LedgeNote);
+ Check.True(DungeonPathfinder.LedgeNoteLandblock == lb && DungeonPathfinder.LedgeNote != null
+ && DungeonPathfinder.LedgeNote.StartsWith("12 ledge(s)") && DungeonPathfinder.LedgeNote.Contains("12 closed"), "12 ledges, 12 closed");
+ Check.False(graph[0x019201C4].Neighbors.Contains(0x019201C6), "019201C4 -> 019201C6 (the report's) closed");
+ Check.True(graph.Values.Sum(n => n.Neighbors.Count) < linksBefore, "links gone from the cached graph");
+ Check.True(ReferenceEquals(graph, DungeonPathfinder.GetGraph(lb, loader.CellDat)), "the cached graph itself");
+
+ // Every cell walkable before is still reached.
+ var seen = new HashSet { start };
+ var q = new Queue(); q.Enqueue(start);
+ while (q.Count > 0)
+ {
+ var c = q.Dequeue();
+ foreach (var nb in graph[c].Neighbors)
+ if (graph.TryGetValue(nb, out var o) && !DungeonPathfinder.IsDropEdge(graph[c], o) && seen.Add(nb)) q.Enqueue(nb);
+ }
+ Check.Eq(seen.Count, 194, "all 194 cells still reached from the start");
+
+ // The explore's walk never steps from one side of a ledge to the other.
+ var ledgeCells = new HashSet<(uint, uint)>
+ {
+ (0x01920133, 0x01920135), (0x01920133, 0x01920136), (0x0192013B, 0x0192013D), (0x0192013B, 0x0192013E),
+ (0x01920143, 0x01920145), (0x01920143, 0x01920146), (0x019201C4, 0x019201C6), (0x019201C4, 0x019201C7),
+ (0x019201CA, 0x019201CC), (0x019201CA, 0x019201CD), (0x019201D0, 0x019201D2), (0x019201D0, 0x019201D3),
+ };
+ var n0 = graph[start];
+ var route = DungeonPathfinder.BuildExploreRoute(graph, start, null, geo, null, Array.Empty(),
+ (DungeonGeometry.NavToWorld(n0.EW), DungeonGeometry.NavToWorld(n0.NS), n0.Z), null, out var plan);
+ Check.True(route.Points.Count > 50, $"an explore ({route.Points.Count} points)");
+ int over = 0;
+ for (int i = 0; i + 1 < route.Points.Count; i++)
+ {
+ uint a = DungeonPathfinder.CellAt(graph, geo, route.Points[i]), b = DungeonPathfinder.CellAt(graph, geo, route.Points[i + 1]);
+ if (ledgeCells.Contains((a, b)) || ledgeCells.Contains((b, a))) over++;
+ }
+ Check.Eq(over, 0, "no leg steps over a ledge");
+ }
+ finally
+ {
+ loader.Dispose();
+ DungeonPathfinder.InvalidateCache();
+ }
+ }
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs
index d9a098e..2648d18 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs
@@ -48,11 +48,12 @@ internal static class LootCorpseTests
r.Add("loot chain: an item the cache never saw created is found in the corpse's contents and looted", UnseenItemRescued);
r.Add("loot chain: without GetContainerContents an unseen item stays unseen (no crash)", UnseenItemOldEngine);
r.Add("loot starvation: a corpse waiting behind far-off combat gets a turn, a close monster keeps combat", LootStarvation);
+ r.Add("loot starvation (R-20261115-165857-1de7): a starved open waits for combat's first attack at a fresh lock, at most 3 s", StarvedOpenWaitsForFirstAttack);
r.Add("loot logging: a corpse held by combat is logged once, with the reason", HeldByCombatLoggedOnce);
r.Add("boost loot: our kill holds the next target until its corpse is looted (one kill, one loot)", BoostLootOneKillOneLoot);
r.Add("boost loot: the wait ends after BoostLootKillWaitMs, for a close monster, and with Boost Loot off", BoostLootHoldLimits);
r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse);
- r.Add("death wait (11-08): Looting on, our kill holds the next target for the learned death + 1 s; Looting gets the tick", DeathWaitUsesLearnedTime);
+ r.Add("death wait (11-08, R-20261115-165857-1de7): the learned death + 1 s keeps nav off; a monster in range is locked at once", DeathWaitUsesLearnedTime);
r.Add("death wait (11-08): not learned yet: 2.5 s + 1 s; the corpse's coming is timed and learned", DeathWaitDefaultAndLearns);
r.Add("death wait (11-08): looting the kill's corpse ends it at once; a corpse the rules don't take ends it soon after it came", DeathWaitEndsOnLoot);
r.Add("death wait (11-08): no corpse in the time: it carries on; a close attacker is fought; Looting off changes nothing", DeathWaitLimits);
@@ -389,6 +390,53 @@ internal static class LootCorpseTests
Check.Eq(ActivityArbiter.Decide(in buffing), BotActivity.Buffing, "buffing still outranks a starved corpse");
}
+ // 2026-11-15, R-20261115-165857-1de7: a corpse claimed with nothing about, then a monster locked at
+ // 15.5 m. The starved turn kept Looting and the open went out 0.3 s after the lock, ahead of the
+ // first cast; the server didn't answer it for 5 s and combat stood behind it ("Combat" showing).
+ private static void StarvedOpenWaitsForFirstAttack()
+ {
+ DateTime now = new(2026, 11, 15, 11, 57, 33);
+ RynthClock.TestNow = () => now;
+ try
+ {
+ var bot = StarvationWorld(15f, out var combat);
+ AgeCorpse(bot, RynthAiPlugin.LootStarveMs + 1000);
+ Check.True(bot.HasLootWork(), "the corpse is lootable");
+ Check.True((bool)bot.Call("IsLootStarvedTurn", true, true)!, "starved, nothing within 5 yd: a loot turn");
+ combat.HandleCombatTrigger();
+ Check.Eq(combat.activeTargetId, unchecked((int)Monster), "combat locks the monster (15 m)");
+ Check.True(combat.FirstAttackPendingMs >= 0, "its first attack hasn't gone out");
+
+ bot.Set("_lootStarveTurn", true);
+ bot.Tick(BotActivity.Looting);
+ Check.Eq(bot.Get("_targetCorpseId"), unchecked((int)Corpse), "the starved corpse is claimed");
+ Check.False(FakeHost.Uses.Contains(Corpse), "but not opened ahead of the fight's first attack");
+ Check.True(FakeHost.Logs.Any(l => l.Contains($"open of 0x{Corpse:X8} waits for combat's first attack")), "and says so");
+
+ // The first cast goes out ([CombatLatency]'s engagement): the open follows.
+ object latency = typeof(CombatManager).GetField("_latency", Any)!.GetValue(combat)!;
+ latency.GetType().GetMethod("OnAttack")!.Invoke(latency, new object?[] { combat.activeTargetId, (double)Environment.TickCount64, "Magic", null });
+ Check.Eq(combat.FirstAttackPendingMs, -1.0, "attacked: nothing pending");
+ bot.Tick(BotActivity.Looting);
+ Check.True(FakeHost.Uses.Contains(Corpse), "now the corpse is opened");
+ Check.True(FakeHost.Logs.Any(l => l.Contains($"attempting open for 0x{Corpse:X8} (d=") && l.Contains("combat locked on")),
+ "the open line gives the distance and the fight: " + FakeHost.Logs.LastOrDefault(l => l.Contains("attempting open")));
+
+ // A lock that can't attack doesn't stop the starved turn for good.
+ var stuck = StarvationWorld(15f, out var combat2);
+ AgeCorpse(stuck, RynthAiPlugin.LootStarveMs + 1000);
+ stuck.HasLootWork();
+ combat2.HandleCombatTrigger();
+ stuck.Set("_lootStarveTurn", true);
+ stuck.Tick(BotActivity.Looting);
+ Check.False(FakeHost.Uses.Contains(Corpse), "held while the lock is fresh");
+ now = now.AddMilliseconds(RynthAiPlugin.StarvedOpenYieldsMs + 1);
+ stuck.Tick(BotActivity.Looting);
+ Check.True(FakeHost.Uses.Contains(Corpse), "past StarvedOpenYieldsMs the open goes");
+ }
+ finally { RynthClock.TestNow = null; }
+ }
+
private static void IgnoredMonsterDoesNotHoldLoot()
{
// The same close (2 m) Water Elemental that keeps combat in charge above, with its rule at Priority 0.
@@ -647,16 +695,28 @@ internal static class LootCorpseTests
Check.Eq(bot.Get("_deathWaitMs"), 2500L, "the learned 1.5 s and 1 s more");
Check.True(FakeHost.Logs.Any(l => l.Contains("waiting up to 2.5 s for the corpse of 'Ancient Water Elemental'") && l.Contains("learned over 1 kill")),
"said once, plainly: " + FakeHost.Logs.LastOrDefault());
- combat.HandleCombatTrigger();
- Check.Eq(combat.activeTargetId, 0, "the next monster (15 m) is not locked while the corpse comes");
- Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] next target waits: the kill's corpse comes first")), "combat says why");
Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "Looting has the tick (no nav, no hunt walk)");
- now += 2400;
- Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "still at 2.4 s");
- now += 200;
- Check.Eq(Arbiter(bot, combat), BotActivity.Combat, "at 2.6 s, no corpse: it carries on");
+ // 2026-11-15, R-20261115-165857-1de7: the next monster was held for the death + 1 s while the
+ // looter, which claims no corpse with combat targets in range, waited for the fight: 3.6 s
+ // standing until the monster walked within 5 yd. Combat locks it at once now.
combat.HandleCombatTrigger();
- Check.Eq(combat.activeTargetId, unchecked((int)Monster), "and the next monster is locked");
+ Check.Eq(combat.activeTargetId, unchecked((int)Monster), "the next monster (15 m) is locked at once");
+ Check.False(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] next target waits")), "nothing holds it");
+ Check.Eq(Arbiter(bot, combat), BotActivity.Combat, "and fought");
+ Check.True(bot.Get("_deathWaitAt") != 0, "the wait itself goes on (for when the fight is over)");
+
+ // No fight left (the owner's case: the last kill): the wait keeps nav off for the death + 1 s.
+ BotActivity Calm()
+ {
+ bool wantLoot = bot.HasLootWork();
+ var inputs = new ArbiterInputs(true, false, false, wantLoot, false, true, deathWait: wantLoot && bot.Get("_deathWaitHeld"));
+ return ActivityArbiter.Decide(in inputs);
+ }
+ Check.Eq(Calm(), BotActivity.Looting, "nothing to fight: Looting holds the tick, nav waits");
+ now += 2400;
+ Check.Eq(Calm(), BotActivity.Looting, "still at 2.4 s");
+ now += 200;
+ Check.Eq(Calm(), BotActivity.Navigating, "at 2.6 s, no corpse: nav carries on");
}
finally { RestoreCorpseClock(); }
}
@@ -750,9 +810,11 @@ internal static class LootCorpseTests
// No corpse ever: the wait ends at its time, once.
var bot = DeathWorld(15f, out var combat, () => now);
bot.Call("StartDeathWait", Elemental);
- Check.True((bool)bot.Call("LootHoldsNewTarget")!, "holding");
+ Check.True(bot.HasLootWork() && bot.Get("_deathWaitHeld"), "holding (nav)");
+ Check.False((bool)bot.Call("LootHoldsNewTarget")!, "but not combat's next target (2026-11-15)");
now += RynthAiPlugin.DeathWaitDefaultMs + RynthAiPlugin.DeathWaitExtraMs;
- Check.False((bool)bot.Call("LootHoldsNewTarget")!, "past the time: no hold");
+ bot.HasLootWork();
+ Check.False(bot.Get("_deathWaitHeld"), "past the time: no hold");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no corpse came in 3.5 s")), 1, "said once");
combat.HandleCombatTrigger();
Check.Eq(combat.activeTargetId, unchecked((int)Monster), "the next monster is locked");
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NearbyChestTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NearbyChestTests.cs
new file mode 100644
index 0000000..716bcf2
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/NearbyChestTests.cs
@@ -0,0 +1,665 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Text.Json;
+using System.Threading;
+using RynthCore.Loot;
+using RynthCore.Plugin.RynthAi;
+
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Loot;
+using RynthCore.Plugin.RynthAi.Meta;
+using RynthCore.PluginCore;
+using RynthCore.PluginSdk;
+using RynthCore.RynthAiHostTests.Fakes;
+using RynthCore.RynthAiTests.Harness;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// Loot Nearby Chests (2026-11-14): with the setting on, the macro running, Looting on and no fight, a
+// chest in loot range is walked to (the server walks: every step is a use), opened and looted by the
+// loot profile, then left alone until it resets. Locked: a carried key that fits, else a lockpick when
+// the Lockpick skill gives 50% or better, else skipped for 10 minutes. The state machine
+// (NearbyChestLooter.cs) runs on a fake environment with a clock the test moves; the plugin glue
+// (which objects are chests, the loot hand-over, the setting) runs on the fake host.
+internal static class NearbyChestTests
+{
+ private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
+
+ public static void Register(Runner r)
+ {
+ r.Add("nearby chests: an unlocked chest is appraised, opened and looted, then left alone until the re-lock wait passes", UnlockedHappyPath);
+ r.Add("nearby chests: the nearest chest not left alone; nothing while fighting; a fight drops a chest nothing was sent to", CandidateSelection);
+ r.Add("nearby chests: locked, a carried key fits -> the key, then the open", LockedKeyFits);
+ r.Add("nearby chests: locked, a key that doesn't fit (0x4B2) -> the next key; a key that didn't fit is never tried on that chest again", LockedKeyDoesntFit);
+ r.Add("nearby chests: locked, no key fits, skill good enough -> the lockpick (a failed pick is tried again, up to 3)", LockpickEnoughSkill);
+ r.Add("nearby chests: locked, skill too low, untrained or an unpickable lock -> skipped, no lockpick spent", LockpickNotEnoughSkill);
+ r.Add("nearby chests: locked, no key fits and no lockpick -> skipped 10 minutes, then tried again", NoLockpickSkipThenRetry);
+ r.Add("nearby chests: a looted locked chest is ready when it reads locked again; still unlocked after the wait = another wait; gone = forgotten", RespawnTimer);
+ r.Add("nearby chests: a chest that won't open is taken as locked; unknown resistance picks at most twice", WontOpenTakenAsLocked);
+ r.Add("nearby chests: off -> nothing is scanned or sent", OffNothing);
+ r.Add("nearby chests: 'skill good enough' is ACE's GetSkillChance at 50% or better (the server's own percent first)", PickRuleMath);
+ r.Add("nearby chests: what is a chest (stuck container in the world; not a corpse, vendor, player, door, house storage, pack or held)", ChestRule);
+ r.Add("nearby chests plugin: off by default; off -> no loot work, no appraisal, no use", PluginOffNothing);
+ r.Add("nearby chests plugin: in range and eligible only (house storage, a vendor, a dropped pack, a far chest are passed by)", PluginCandidates);
+ r.Add("nearby chests plugin: a closed chest in range is appraised, opened and looted by the loot profile, then left alone", PluginLootsChest);
+ r.Add("nearby chests plugin: no chest work while combat has a target", PluginSkippedWhileFighting);
+ r.Add("nearby chests plugin: the setting reaches the engine, an engine save without it leaves it, the meta option sets it; /ra chests answers", PluginSettingPlumbing);
+ }
+
+ // ── The fake environment ────────────────────────────────────────────────
+
+ private sealed class Env : INearbyChestEnv
+ {
+ public long T = 1_000_000;
+ public long Now => T;
+ public bool Enabled { get; set; } = true;
+ public bool Fighting { get; set; }
+ public readonly List Chests = new() { new NearbyChest(1, "Chest", 4) };
+ public readonly HashSet Gone = new();
+ public string? Hold;
+ public bool CanAppraise { get; set; } = true;
+ public bool AppraisalAnswers = true;
+ public readonly Dictionary Stamps = new();
+ public readonly Dictionary LockedMap = new();
+ public readonly Dictionary Resist = new();
+ public readonly Dictionary Pct = new();
+ public bool SkillKnown = true, Trained = true;
+ public int Skill = 300;
+ public readonly List KeyList = new();
+ public ChestTool? Pick;
+ public bool HasUseDone { get; set; } = true;
+ public int Seq;
+ public uint LastErr;
+ public readonly List Sent = new(), Logs = new();
+ public readonly Dictionary Opened = new();
+ public int LootingId;
+ public long LootEnd;
+ /// The server's script for a use with a tool: (error, chat line, unlocks). Null = no answer.
+ public Func? OnUseWith;
+ /// The chest opens on the open (default: when it isn't locked).
+ public Func? OnOpen;
+ public NearbyChestLooter L = null!;
+ private int _pendingAppraisal;
+
+ public IReadOnlyList ScanChests() => Chests.Where(c => !Gone.Contains(c.Id)).ToList();
+ public bool InWorld(int id) => !Gone.Contains(id);
+ public bool StillEligible(int id, out string why) { why = ""; return true; }
+ public string? HoldReason() => Hold;
+ public bool RequestAppraisal(int chestId) { Sent.Add("id " + chestId); if (AppraisalAnswers) _pendingAppraisal = chestId; return true; }
+ public long AppraisalStamp(int chestId) => Stamps.TryGetValue(chestId, out long s) ? s : 0;
+ public bool? Locked(int chestId) => LockedMap.TryGetValue(chestId, out bool b) ? b : null;
+ public int? LockResistance(int chestId) => Resist.TryGetValue(chestId, out int v) ? v : null;
+ public int? PickSuccessPercent(int chestId) => Pct.TryGetValue(chestId, out int v) ? v : null;
+ public bool LockpickSkill(out int buffed, out bool trained) { buffed = Skill; trained = Trained; return SkillKnown; }
+ public IReadOnlyList Keys() => KeyList;
+ public ChestTool? Lockpick() => Pick;
+ public int UseDoneSeq() => Seq;
+ public bool LastUseDone(out int seq, out uint error) { seq = Seq; error = LastErr; return true; }
+ public bool SendUseWith(int toolId, int chestId, string why)
+ {
+ var tool = KeyList.Concat(Pick is { } p ? new[] { p } : Array.Empty()).First(t => t.Id == toolId);
+ Sent.Add("use " + tool.Name);
+ var ans = OnUseWith?.Invoke(tool);
+ if (ans is { } a)
+ {
+ if (a.Chat != null) L.OnChat(a.Chat);
+ if (a.Unlocks) LockedMap[chestId] = false;
+ LastErr = a.Err; Seq++;
+ }
+ return true;
+ }
+ public bool SendOpen(int chestId)
+ {
+ Sent.Add("open " + chestId);
+ bool opens = OnOpen?.Invoke(chestId) ?? Locked(chestId) != true;
+ if (opens) { Opened[chestId] = T + 1; LootingId = chestId; LootEnd = T + 2000; }
+ LastErr = 0; Seq++;
+ return true;
+ }
+ public long OpenedAt(int chestId) => Opened.TryGetValue(chestId, out long t) ? t : 0;
+ public bool Looting(int chestId) => LootingId == chestId;
+ public void Log(string text) => Logs.Add(text);
+
+ /// Moves the clock in 100 ms steps, ticking as the loot tick does (may start: no corpse waits).
+ public void Run(long ms, Func? until = null)
+ {
+ long end = T + ms;
+ while (T < end && (until == null || !until()))
+ {
+ T += 100;
+ if (_pendingAppraisal != 0) { Stamps[_pendingAppraisal] = T; _pendingAppraisal = 0; }
+ if (LootingId != 0 && T >= LootEnd) LootingId = 0; // the corpse looter finishes and closes it
+ L.Tick(mayStart: true);
+ }
+ }
+
+ public int Count(string prefix) => Sent.Count(s => s.StartsWith(prefix, StringComparison.Ordinal));
+ }
+
+ private static Env NewEnv()
+ {
+ var e = new Env();
+ e.L = new NearbyChestLooter(e);
+ return e;
+ }
+
+ private static string Sent(Env e) => string.Join(" | ", e.Sent);
+
+ // ── State machine ───────────────────────────────────────────────────────
+
+ private static void UnlockedHappyPath()
+ {
+ var e = NewEnv();
+ e.Run(5000, () => e.L.Looted == 1 && !e.L.Busy);
+ Check.Eq(Sent(e), "id 1 | open 1", "one appraisal, one open, nothing else");
+ Check.Eq(e.L.Looted, 1, "looted");
+ Check.False(e.L.Busy, "done");
+ Check.True(e.L.IsLeftAlone(1, e.T), "left alone after the loot");
+ Check.True(e.Logs.Any(l => l.Contains("Nearby chests: done with chest") && l.Contains("left alone until it resets")), "the finish says why it is left: " + string.Join(" / ", e.Logs));
+
+ // Nothing more until the re-lock wait (125 s) passes, then it is looted again.
+ e.Run(100_000);
+ Check.Eq(e.Count("open"), 1, "no second open before the wait");
+ e.Run(40_000, () => e.L.Looted == 2);
+ Check.Eq(e.L.Looted, 2, "looted again after the re-lock wait (the chest regenerated)");
+ Check.Eq(e.Count("id"), 2, "appraised again first");
+ }
+
+ private static void CandidateSelection()
+ {
+ var e = NewEnv();
+ e.Chests.Clear();
+ e.Chests.Add(new NearbyChest(1, "Far Chest", 8));
+ e.Chests.Add(new NearbyChest(2, "Near Chest", 3));
+ Check.Eq(e.L.Candidate(), 2, "the nearest first");
+
+ e.Fighting = true;
+ Check.Eq(e.L.Candidate(), 0, "nothing while fighting");
+ e.Run(2000);
+ Check.Eq(e.Sent.Count, 0, "nothing sent while fighting");
+
+ // The fight ends; the appraisal goes out, a fight starts before the next step: the chest is dropped.
+ e.Fighting = false;
+ e.AppraisalAnswers = false; // the answer is slow
+ e.Run(150, () => e.Sent.Count > 0);
+ Check.Eq(Sent(e), "id 2", "the near chest is appraised");
+ e.Fighting = true;
+ e.Run(AppraiseWait());
+ Check.False(e.L.Busy, "a fight drops the chest once nothing is owed");
+ Check.Eq(e.Count("open"), 0, "no open in the fight");
+ Check.True(e.Logs.Any(l => l.Contains("for the fight")), "says it left the chest for the fight");
+ Check.False(e.L.IsLeftAlone(2, e.T), "nothing marked: tried again after the fight");
+
+ // The hold: nothing starts while the client/arbiter holds the send.
+ e.Fighting = false;
+ e.AppraisalAnswers = true;
+ e.Hold = "Looting doesn't have the tick";
+ int before = e.Sent.Count;
+ e.Run(2000);
+ Check.Eq(e.Sent.Count, before, "nothing while held");
+ e.Hold = null;
+ e.Run(5000, () => e.L.Looted == 1);
+ Check.Eq(e.L.Looted, 1, "looted once free");
+ Check.Eq(e.L.Candidate(), 1, "then the far chest (the near one is left alone)");
+ }
+
+ private static long AppraiseWait() => NearbyChestLooter.AppraiseMaxMs + 300;
+
+ private static Env LockedEnv(int resist = 100, int? pct = null)
+ {
+ var e = NewEnv();
+ e.LockedMap[1] = true;
+ e.Resist[1] = resist;
+ if (pct != null) e.Pct[1] = pct.Value;
+ return e;
+ }
+
+ private static void LockedKeyFits()
+ {
+ var e = LockedEnv();
+ e.KeyList.Add(new ChestTool(50, "Aged Key"));
+ e.Pick = new ChestTool(60, "Plain Lockpick");
+ e.OnUseWith = t => t.Name == "Aged Key" ? (0u, "The Chest has been unlocked.\nYour key has 4 uses left.", true) : (NearbyChestLooter.ErrKeyDoesntFit, null, false);
+ e.Run(10_000, () => e.L.Looted == 1 && !e.L.Busy);
+ Check.Eq(Sent(e), "id 1 | use Aged Key | open 1", "the key, then the open; no lockpick");
+ Check.Eq(e.L.Looted, 1, "looted");
+ }
+
+ private static void LockedKeyDoesntFit()
+ {
+ var e = LockedEnv();
+ e.KeyList.Add(new ChestTool(50, "Black Key"));
+ e.KeyList.Add(new ChestTool(51, "Aged Key"));
+ e.OnUseWith = t => t.Name == "Aged Key" ? (0u, "The Chest has been unlocked.", true) : (NearbyChestLooter.ErrKeyDoesntFit, null, false);
+ e.Run(10_000, () => e.L.Looted == 1 && !e.L.Busy);
+ Check.Eq(Sent(e), "id 1 | use Black Key | use Aged Key | open 1", "the wrong key, then the next, then the open");
+ Check.True(e.Logs.Any(l => l.Contains("Black Key doesn't fit")), "says the key doesn't fit");
+
+ // None fits, no lockpick: skipped. A retry (10 min later) never tries the keys that didn't fit.
+ var f = LockedEnv();
+ f.KeyList.Add(new ChestTool(50, "Black Key"));
+ f.OnUseWith = _ => (NearbyChestLooter.ErrKeyDoesntFit, null, false);
+ f.Run(10_000, () => f.L.IsLeftAlone(1, f.T));
+ Check.Eq(Sent(f), "id 1 | use Black Key", "one key tried, nothing else (no lockpick)");
+ Check.True(f.L.IsLeftAlone(1, f.T), "skipped");
+ f.Run(NearbyChestLooter.SkipMs + 2000, () => f.Count("id") == 2);
+ f.Run(2000);
+ Check.Eq(f.Count("use Black Key"), 1, "the key that didn't fit is not tried again on that chest");
+ f.KeyList.Add(new ChestTool(52, "Gold Key"));
+ f.Run(NearbyChestLooter.SkipMs + 5000, () => f.Count("use Gold Key") == 1);
+ Check.Eq(f.Count("use Gold Key"), 1, "a new key is tried on the next attempt");
+ }
+
+ private static void LockpickEnoughSkill()
+ {
+ // Resistance 250 against skill 300: ACE's chance 81% (as its appraisal truncates it). The first pick fails, the second works.
+ var e = LockedEnv(resist: 250);
+ e.Pick = new ChestTool(60, "Plain Lockpick");
+ int picks = 0;
+ e.OnUseWith = t => ++picks == 1
+ ? (0u, "You have failed to pick the lock. It is still locked. Your lockpicks have 4 uses left.", false)
+ : (0u, "You have successfully picked the lock! It is now unlocked.\n Your lockpicks have 3 uses left.", true);
+ e.Run(15_000, () => e.L.Looted == 1 && !e.L.Busy);
+ Check.Eq(Sent(e), "id 1 | use Plain Lockpick | use Plain Lockpick | open 1", "two picks (the first failed), then the open");
+ Check.True(e.Logs.Any(l => l.Contains("picking chest") && l.Contains("81%")), "says the chance it picks at: " + string.Join(" / ", e.Logs));
+
+ // Every pick fails: three, then skipped.
+ var f = LockedEnv(resist: 250);
+ f.Pick = new ChestTool(60, "Plain Lockpick");
+ f.OnUseWith = _ => (0u, "You have failed to pick the lock. It is still locked.", false);
+ f.Run(20_000, () => f.L.IsLeftAlone(1, f.T));
+ Check.Eq(f.Count("use Plain Lockpick"), NearbyChestLooter.MaxPicks, "at most 3 picks");
+ Check.True(f.L.IsLeftAlone(1, f.T), "then skipped");
+ Check.True(f.Logs.Any(l => l.Contains("the lock held after 3 lockpick tries") && l.Contains("10 minutes")), "says why and when again");
+
+ // The server's own percent wins over the estimate.
+ var g = LockedEnv(resist: 250, pct: 40);
+ g.Pick = new ChestTool(60, "Plain Lockpick");
+ g.Run(10_000, () => g.L.IsLeftAlone(1, g.T));
+ Check.Eq(g.Count("use"), 0, "the server says 40%: not picked");
+ }
+
+ private static void LockpickNotEnoughSkill()
+ {
+ var e = LockedEnv(resist: 400); // skill 300: ~5%
+ e.Pick = new ChestTool(60, "Plain Lockpick");
+ e.Run(10_000, () => e.L.IsLeftAlone(1, e.T));
+ Check.Eq(Sent(e), "id 1", "appraised; no lockpick spent");
+ Check.True(e.L.IsLeftAlone(1, e.T), "skipped");
+ Check.True(e.Logs.Any(l => l.Contains("too low") && l.Contains("10 minutes")), "says the skill is too low: " + string.Join(" / ", e.Logs));
+
+ var u = LockedEnv(resist: 10);
+ u.Pick = new ChestTool(60, "Plain Lockpick");
+ u.Trained = false;
+ u.Run(10_000, () => u.L.IsLeftAlone(1, u.T));
+ Check.Eq(u.Count("use"), 0, "untrained: never picks");
+ Check.True(u.Logs.Any(l => l.Contains("isn't trained")), "says so");
+
+ var n = NewEnv();
+ n.LockedMap[1] = true; // locked, appraised, and no resistance: ACE can't pick it
+ n.Pick = new ChestTool(60, "Plain Lockpick");
+ n.Run(10_000, () => n.L.IsLeftAlone(1, n.T));
+ Check.Eq(n.Count("use"), 0, "an unpickable lock: no pick");
+ Check.True(n.Logs.Any(l => l.Contains("can't be picked")), "says so");
+ }
+
+ private static void NoLockpickSkipThenRetry()
+ {
+ var e = LockedEnv(resist: 50);
+ e.Run(10_000, () => e.L.IsLeftAlone(1, e.T));
+ Check.Eq(Sent(e), "id 1", "appraised, nothing to use");
+ Check.True(e.Logs.Any(l => l.Contains("carry no lockpick") && l.Contains("10 minutes")), "says why");
+ e.Run(NearbyChestLooter.SkipMs - 15_000);
+ Check.Eq(e.Count("id"), 1, "left alone for 10 minutes");
+ e.Pick = new ChestTool(60, "Plain Lockpick");
+ e.OnUseWith = _ => (0u, "You have successfully picked the lock! It is now unlocked.", true);
+ e.Run(30_000, () => e.L.Looted == 1);
+ Check.Eq(e.L.Looted, 1, "tried again after 10 minutes (with a lockpick now) and looted");
+ }
+
+ private static void RespawnTimer()
+ {
+ var e = LockedEnv(resist: 50);
+ e.Pick = new ChestTool(60, "Plain Lockpick");
+ e.OnUseWith = _ => (0u, "You have successfully picked the lock!", true);
+ e.Run(10_000, () => e.L.Looted == 1 && !e.L.Busy);
+ Check.Eq(e.L.Looted, 1, "looted");
+ Check.True(e.L.IsLeftAlone(1, e.T), "left alone");
+ e.Run(20_000);
+ e.LockedMap[1] = true; // ACE's Chest.Reset: locked again (and regenerated)
+ Check.False(e.L.IsLeftAlone(1, e.T), "reads locked again: ready at once");
+ e.Run(10_000, () => e.L.Looted == 2);
+ Check.Eq(e.L.Looted, 2, "picked and looted again");
+
+ // Not re-locked when the wait is over: appraised, and another wait without a use.
+ int uses = e.Count("use");
+ e.Run(126_000, () => e.Count("id") == 3);
+ e.Run(1000);
+ Check.Eq(e.Count("use"), uses, "no use on a chest that hasn't reset");
+ Check.Eq(e.Count("open"), 2, "no open either");
+ Check.True(e.L.IsLeftAlone(1, e.T), "another wait");
+ Check.True(e.Logs.Any(l => l.Contains("hasn't reset yet")), "says so");
+
+ // Gone from the world: forgotten (a new one comes in fresh).
+ e.Gone.Add(1);
+ e.Run(1000);
+ Check.True(e.Logs.Any(l => l.Contains("left the world; forgotten")), "forgotten");
+ e.Gone.Remove(1);
+ Check.False(e.L.IsLeftAlone(1, e.T), "back: not left alone");
+ }
+
+ private static void WontOpenTakenAsLocked()
+ {
+ var e = NewEnv();
+ e.CanAppraise = false; // an engine without the ID: the lock is unknown
+ e.Pick = new ChestTool(60, "Plain Lockpick");
+ bool unlocked = false;
+ e.OnOpen = _ => unlocked;
+ e.OnUseWith = _ => (0u, "You have failed to pick the lock. It is still locked.", false);
+ e.Run(30_000, () => e.L.IsLeftAlone(1, e.T));
+ Check.Eq(Sent(e), "open 1 | use Plain Lockpick | use Plain Lockpick", "the open failed: taken as locked, two picks at an unknown resistance, then skipped");
+ Check.True(e.Logs.Any(l => l.Contains("taking it as locked")), "says so");
+ }
+
+ private static void OffNothing()
+ {
+ var e = NewEnv();
+ e.Enabled = false;
+ Check.Eq(e.L.Candidate(), 0, "no candidate");
+ e.Run(5000);
+ Check.Eq(e.Sent.Count, 0, "nothing sent");
+ // Turned off mid-chest: dropped, nothing marked.
+ e.Enabled = true;
+ e.AppraisalAnswers = false;
+ e.Run(200, () => e.Sent.Count > 0);
+ e.L.StandDown("Loot Nearby Chests was turned off");
+ Check.False(e.L.Busy, "dropped");
+ Check.False(e.L.IsLeftAlone(1, e.T), "nothing marked");
+ }
+
+ private static void PickRuleMath()
+ {
+ Check.True(Math.Abs(NearbyChestLooter.PickChance(300, 300) - 0.5) < 1e-9, "skill = resistance: 50%");
+ Check.True(Math.Abs(NearbyChestLooter.PickChance(300, 250) - (1 - 1 / (1 + Math.Exp(1.5)))) < 1e-9, "ACE's logistic, factor 0.03");
+ Check.Eq(NearbyChestLooter.PickTries(true, 300, true, true, true, 300, null, out _), NearbyChestLooter.MaxPicks, "50%: picks");
+ Check.Eq(NearbyChestLooter.PickTries(true, 299, true, true, true, 300, null, out _), null, "just under 50%: no");
+ Check.Eq(NearbyChestLooter.PickTries(true, 100, true, true, true, 300, 60, out _), NearbyChestLooter.MaxPicks, "the server's 60% wins over the estimate");
+ Check.Eq(NearbyChestLooter.PickTries(true, 300, false, true, true, 10, null, out _), null, "untrained: no");
+ Check.Eq(NearbyChestLooter.PickTries(true, 900, true, true, true, 9999, null, out _), null, "9999: unpickable");
+ Check.Eq(NearbyChestLooter.PickTries(true, 300, true, true, true, null, null, out _), null, "locked with no resistance after an appraisal: unpickable");
+ Check.Eq(NearbyChestLooter.PickTries(true, 300, true, false, null, null, null, out _), NearbyChestLooter.MaxPicksUnknown, "never appraised: a couple of tries");
+ }
+
+ private static void ChestRule()
+ {
+ const uint stuck = NearbyChestLooter.BfStuck;
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck, 0, "Chest", true, 0, 0), null, "a stuck container in the world: a chest");
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Corpse, true, stuck, 0, "Corpse of X", true, 0, 0), "a corpse", "corpse class");
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck | NearbyChestLooter.BfCorpse, 0, "x", true, 0, 0), "a corpse", "corpse bit");
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck | NearbyChestLooter.BfVendor, 0, "x", true, 0, 0), "a vendor", "vendor");
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck | NearbyChestLooter.BfPlayer, 0, "x", true, 0, 0), "a player", "player");
+ Check.True(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck, 0x50000001, "Chest", true, 0, 0)!.StartsWith("house storage"), "house owner");
+ Check.True(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck, 0, "Storage", true, 0, 0)!.StartsWith("house storage"), "named storage");
+ Check.True(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, 0, 0, "Pack", true, 0, 0)!.Contains("picked up"), "a dropped pack (not stuck)");
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, true, stuck, 0, "Chest", true, 0x50000001, 0), "someone holds it", "held");
+ Check.Eq(NearbyChestLooter.ChestRefusal(AcObjectClass.Door, true, stuck | NearbyChestLooter.BfDoor, 0, "Door", true, 0, 0), "not a container", "a door");
+ Check.True(NearbyChestLooter.ChestRefusal(AcObjectClass.Container, false, 0, 0, "Chest", true, 0, 0) != null, "no bitfield read: not trusted");
+ }
+
+ // ── Plugin glue ─────────────────────────────────────────────────────────
+
+ private const uint Player = 0x50000D01;
+ private const uint Chest = 0x7A9B4011;
+ private const uint Storage = 0x7A9B4012;
+ private const uint VendorBox = 0x7A9B4013;
+ private const uint DroppedPack = 0x80263400;
+ private const uint FarChest = 0x7A9B4015;
+ private const uint Gem = 0x80263401;
+ private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
+ private const uint Stuck = 0x4;
+
+ private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
+
+ private static void Place(uint id, string name, float dx, uint bitfield, uint type = ItemTypeContainer)
+ {
+ FakeHost.Names[id] = name;
+ FakeHost.ItemTypes[id] = type;
+ FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
+ FakeHost.NotAttackable.Add(id);
+ FakeHost.Containers[id] = 0;
+ FakeHost.Bitfields[id] = bitfield;
+ }
+
+ private static void World()
+ {
+ FakeHost.Reset();
+ FakeHost.SalvageCalls = true;
+ FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData, UseObject
+ FakeHost.CloseContainerCalls = true;
+ FakeHost.UseOnCalls = true;
+ FakeHost.Names[Player] = "Dargoth Hera";
+ FakeHost.Positions[Player] = Me0;
+ FakeHost.PlayerPose = Me0;
+ FakeHost.Bitfields[Player] = 0x8;
+ Place(Storage, "Storage", 1.0f, Stuck);
+ FakeHost.InstanceIds[(Storage, 32)] = 0x50000AAA; // HouseOwner
+ Place(VendorBox, "Vendor Chest", 1.2f, Stuck | 0x200);
+ Place(DroppedPack, "Pack", 1.6f, 0);
+ Place(Chest, "Chest", 3.0f, Stuck);
+ Place(FarChest, "Far Chest", 60.0f, Stuck);
+ FakeHost.Names[Gem] = "Black Opal";
+ FakeHost.ItemTypes[Gem] = ItemTypeGem;
+ FakeHost.Containers[Gem] = Chest;
+ FakeHost.Appraised.Add(Gem);
+ }
+
+ private sealed class Bot
+ {
+ public readonly RynthAiPlugin P = new();
+ public readonly LegacyUiSettings S = new()
+ {
+ IsMacroRunning = true,
+ EnableLooting = true,
+ EnableCombat = false,
+ LootOwnership = 0,
+ LootContentSettleMs = 0,
+ LootEmptyCorpseMs = 0,
+ StopLootingWhenPackFull = false,
+ LootNearbyChests = true,
+ };
+ public readonly WorldObjectCache Cache;
+
+ public Bot(RynthCoreHost host)
+ {
+ typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
+ var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
+ typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
+ typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
+ Set("_dashboard", dash);
+ Cache = new WorldObjectCache(host);
+ Cache.SetPlayerId(Player);
+ Set("_objectCache", Cache);
+ Set("_playerId", Player);
+ string profile = Path.Combine(Program.TempRoot, "loot-nearby-chest.json");
+ var p = new LootProfile { Name = "chest" };
+ var gems = new LootRule { Name = "Gems", Action = LootAction.Keep };
+ gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
+ p.Rules.Add(gems);
+ p.Save(profile);
+ S.CurrentLootPath = profile;
+ }
+
+ public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
+ public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
+ public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
+ public bool HasLootWork() => (bool)Call("HasLootWork", S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!;
+ public void Tick(BotActivity act = BotActivity.Looting)
+ {
+ Set("_activity", act);
+ Call("TickCorpseOpening");
+ }
+ public void Create(params uint[] ids)
+ {
+ foreach (uint id in ids) Cache.OnCreateObject(id);
+ Cache.Tick();
+ }
+ public void TickUntil(Func