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 — walk to an object in this dungeon, any floor (a monster, say)"); ChatLine("[RynthAi] /ra dunnav-patrol — circular hunt patrol through the whole dungeon (no nav file needed)"); + ChatLine("[RynthAi] /ra dunnav-explore [stop|status|resume|done] — walk through every room of this dungeon once, then stop (fights, loots, buffs as set)"); + ChatLine("[RynthAi] /ra dunnav-explore lever [door ] [at ] [plate] — pull a lever (or step on a plate) for a shut door, then carry on"); ChatLine("[RynthAi] /ra dunroute to exit|far|portal | |room [overwrite] — save a Once nav from here to there in this dungeon"); ChatLine("[RynthAi] /ra dunpatrol-save [overwrite] — save the patrol dunnav-patrol would walk from here as a circular nav"); ChatLine("[RynthAi] /ra dunroute info | where — describe a saved nav (points, length, cells, this dungeon's?) | where you are, the portals known"); @@ -135,6 +138,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra lootcheckinv — test the loot profile against inventory"); ChatLine("[RynthAi] /ra lootcheck — classify selected item (on|off = auto on click)"); ChatLine("[RynthAi] /ra lootname add|remove|list|radius|clear — loot anything in the world with that name while botting (a chest is opened, an item picked up; *part* matches part of a name)"); + ChatLine("[RynthAi] /ra chests — Loot Nearby Chests: on or off, what it is doing, and the chests it is leaving alone and why"); ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); ChatLine("[RynthAi] /ra loot mode [profile|rares] — loot by the loot profile, or rares and needed mana stones only"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item"); @@ -3168,6 +3172,75 @@ public sealed partial class RynthAiPlugin : $"[RynthAi] No items in inventory matched profile '{System.IO.Path.GetFileName(profilePath)}'"); } + internal const string DunNavToUsage ="[RynthAi] Usage: /ra dunnav-to — walk to an object in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456"; + + /// + /// /ra dunnav-to <object id> (2026-11-15): walks to an object in the dungeon the character is in, + /// by the dungeon map (ledges closed: DungeonPathfinder.Ledges.cs), from the player's cell to the + /// object's own cell, so another floor works too (/ra dunnav aims at the player's floor). For + /// a script: after an explore, the monsters still to be killed are walked to one by + /// one; the fight is RynthAi's, as on any route. The macro goes on; the route is a Once walk. + /// + private void HandleDunNavToCommand(string[] parts) + { + var settings = _dashboard?.Settings; + if (settings == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + // Off in a Thread on DreamWeave, as the patrol and the explore are (its owners asked for that: ServerPolicy). + if (ServerPolicy.PatrolOff(Host)) { ReplyFail(ServerPolicy.DunNavToOffMessage); return; } + string arg = parts.Length > 2 ? parts[2].Trim() : ""; + bool hex = arg.StartsWith("0x", StringComparison.OrdinalIgnoreCase); + if (!uint.TryParse(hex ? arg[2..] : arg, hex ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer, + System.Globalization.CultureInfo.InvariantCulture, out uint target) || target == 0) + { + ReplyFail(DunNavToUsage); + return; + } + if (!Host.TryGetPlayerPose(out uint playerCell, out float plx, out float ply, out float playerZ, out _, out _, out _, out _) || (playerCell & 0xFFFF) < 0x0100) + { + ReplyFail("[RynthAi] DunNav-To: you're not in a dungeon."); + return; + } + if (!Host.HasGetObjectPosition || !Host.TryGetObjectPosition(target, out uint objCell, out float ox, out float oy, out float oz) || objCell == 0) + { + ReplyFail($"[RynthAi] DunNav-To: 0x{target:X8} has no position the client knows."); + return; + } + uint landblockKey = playerCell >> 16; + if ((objCell >> 16) != landblockKey || (objCell & 0xFFFF) < 0x0100) + { + ReplyFail($"[RynthAi] DunNav-To: 0x{target:X8} isn't in this dungeon (cell {objCell:X8})."); + return; + } + var map = DungeonMapOverride?.Invoke(landblockKey); + var cellDat = _raycast?.GeometryLoader.CellDat; + if (map == null && (cellDat == null || !cellDat.IsLoaded)) { ReplyFail("[RynthAi] Cell dat not loaded — raycast system must be initialized first."); return; } + + var graph = map?.Graph ?? DungeonPathfinder.GetGraph(landblockKey, cellDat!); + var geo = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(landblockKey, cellDat!, _raycast?.GeometryLoader?.DungeonLOS); // closes the ledges first + double lbX = ((playerCell >> 24) & 0xFF) * 192.0, lbY = ((playerCell >> 16) & 0xFF) * 192.0; + double playerEW = DungeonGeometry.WorldToNav(lbX + plx), playerNS = DungeonGeometry.WorldToNav(lbY + ply); + double destEW = DungeonGeometry.WorldToNav(lbX + ox), destNS = DungeonGeometry.WorldToNav(lbY + oy); + uint startCell = graph.ContainsKey(playerCell) ? playerCell : DungeonPathfinder.NearestCell(graph, playerNS, playerEW, playerZ); + uint goalCell = graph.ContainsKey(objCell) ? objCell : DungeonPathfinder.NearestCell(graph, destNS, destEW, oz); + var hazards = _objectCache?.GetHazardCells(); + var path = startCell != 0 && goalCell != 0 ? DungeonPathfinder.FindPath(startCell, goalCell, graph, hazards) : new List(); + Host.TryGetObjectName(target, out string name); + if (path.Count == 0) + { + ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to '{name}' 0x{target:X8} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?)."); + return; + } + var route = DungeonPathfinder.BuildNavRoute(path, graph, destNS, destEW, geo, hazards, playerNS, playerEW, playerZ, oz); + if (route.Points.Count == 0) { ReplyFail($"[RynthAi] DunNav-To: no walk laid to '{name}' 0x{target:X8}."); return; } + + if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) + settings.IsMacroRunning = true; + settings.CurrentRoute = route; + settings.ActiveNavIndex = 0; + settings.EnableNavigation = true; + ReplyOk($"[RynthAi] DunNav-To: '{name}' 0x{target:X8} in {goalCell:X8}: {path.Count} cells, {route.Points.Count} points → walking there"); + } + /// /// /ra dunnav <NS> <EW> /// Builds a dungeon cell graph for the player's current landblock, runs A* to @@ -3339,6 +3412,8 @@ public sealed partial class RynthAiPlugin public bool Evacuated; public NavPoint? WalkOut; public List? PortalReport; + /// An explore (): the rooms its walk was laid over (null for the patrol). + public ExplorePlan? Plan; } /// Tests: a landblock's cell graph and map geometry without the dats (null: the dats, as live). @@ -3430,10 +3505,25 @@ public sealed partial class RynthAiPlugin // (DungeonHazardStore) are avoided either way. var hazards = DungeonPathfinder.PatrolHazards(_objectCache?.GetHazardCells(), surfaceHazards, patrolOptions.AvoidHazardFloors ? null : DungeonHazardStore.Load(landblockKey), patrolOptions); + // Kept out of the lava/acid floors where that shuts it in (it stands on one, or most of the + // dungeon is behind them: DungeonPathfinder.HazardFloorsShutIn): they are walked this time. + if (patrolOptions.AvoidHazardFloors && surfaceHazards != null + && DungeonPathfinder.HazardFloorsShutIn(graph, startCell, hazards, surfaceHazards, out int reachable, out int joined)) + { + hazards = DungeonPathfinder.PatrolHazards(_objectCache?.GetHazardCells(), surfaceHazards, + DungeonHazardStore.Load(landblockKey), patrolOptions with { AvoidHazardFloors = false }); + Host.Log($"[RynthAi] {label}: dungeon {landblockKey:X4}: keeping out of its {surfaceHazards.Count} lava/acid floor cell(s) " + + (surfaceHazards.Contains(startCell) ? "can't start (it stands on one)" : $"leaves {reachable} of {joined} cells reachable") + + ": walked this time (pools sighted or marked by hand still avoided)."); + } // The dungeon map geometry (doorways, floors, walls): doorways taken straight on and // big rooms crossed directly. Null (old cell walk) until DungeonLOS is up. var geometry = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(landblockKey, cellDat!, _raycast?.GeometryLoader?.DungeonLOS); + if (map == null && DungeonPathfinder.LedgeNote is { } ledgeNote && DungeonPathfinder.LedgeNoteLandblock == landblockKey) + Host.Log($"[RynthAi] {label}: dungeon {landblockKey:X4}: {ledgeNote}"); + if (map == null && DungeonPathfinder.BlockedNote is { } blockedNote && DungeonPathfinder.BlockedNoteLandblock == landblockKey) + Host.Log($"[RynthAi] {label}: dungeon {landblockKey:X4}: {blockedNote}"); refusal = DunBuildRefusal.None; return new DunRouteWorld @@ -3459,8 +3549,12 @@ public sealed partial class RynthAiPlugin /// patrol is built (/ra dunnav-patrol installs it, /ra dunpatrol-save writes it). /// names the command in the "inside a dungeon" line. Null with the /// line to show ( says why). + /// With (/ra dunnav-explore, RynthAiPlugin.DunExplore.cs) the same start + /// (out of lava/acid, out of a portal's circle, the first point in sight, round the portals) but the + /// explore's Once walk through the rooms it hasn't entered (DungeonPathfinder.Explore.cs); an empty + /// walk (nothing left) is returned, not refused. /// - private DunPatrolBuild? TryBuildDunPatrol(string who, out string error, out DunBuildRefusal refusal) + private DunPatrolBuild? TryBuildDunPatrol(string who, out string error, out DunBuildRefusal refusal, DunExploreRun? explore = null) { // The one way into the dungeon patrol (the command, the dashboard button, a meta's "Patrol", the hazard // reroute, /ra dunpatrol-save): where a server's owners asked for it to be off (a Thread on DreamWeave) @@ -3471,12 +3565,29 @@ public sealed partial class RynthAiPlugin error = ServerPolicy.PatrolOffMessage; return null; } - var w = TryGetDunWorld(who, "DunNav-Patrol", out var patrolOptions, out error, out refusal); + string label = explore != null ? "DunNav-Explore" : "DunNav-Patrol"; + var w = TryGetDunWorld(who, label, out var patrolOptions, out error, out refusal); if (w == null) return null; var graph = w.Graph; + // Openings it couldn't get through (something not on the map in the way): closed for the explore's walk, + // and for the patrol's laps in the dungeon where it got stuck (forgotten in another dungeon). + if (explore is { StuckEdges.Count: > 0 }) graph = DungeonPathfinder.WithoutOpenings(graph, explore.StuckEdges, w.StartCell); + // Things standing in a doorway that the map doesn't have (a spider web: RynthAiPlugin.DunExplore.cs, ScanBlockersInto). + if (explore is { BlockedEdges.Count: > 0 }) graph = DungeonPathfinder.WithoutOpenings(graph, explore.BlockedEdges, w.StartCell); + if (explore == null) + { + if (_dunPatrolStuckLb != w.Landblock) { _dunPatrolStuckEdges.Clear(); _dunPatrolStuckSpots.Clear(); _dunPatrolStuckOpenings = 0; _dunPatrolStuckLb = w.Landblock; } + if (_dunPatrolStuckEdges.Count > 0) graph = DungeonPathfinder.WithoutOpenings(graph, _dunPatrolStuckEdges, w.StartCell); + } + // The explore's shut doors (a lever opens them): their openings are closed for its walk and the start. + if (explore is { DoorEdges.Count: > 0 }) graph = DungeonPathfinder.WithoutOpenings(graph, explore.DoorEdges, w.StartCell); var hazards = w.Hazards; var geometry = w.Geo; var portals = w.Portals; + // Spots in a room it got stuck at for good, away from any doorway (something not on the map in the way): + // walked round like a portal's circle (RynthAiPlugin.DunExplore.cs, StuckSpot). + var stuckSpots = explore != null ? explore.StuckSpots : _dunPatrolStuckLb == w.Landblock ? _dunPatrolStuckSpots : null; + if (stuckSpots is { Count: > 0 }) portals = new List(portals.Concat(stuckSpots)); uint playerCell = w.PlayerCell, startCell = w.StartCell; float playerLocalX = (float)(w.X - w.OriginX), playerLocalY = (float)(w.Y - w.OriginY), patrolWZ = (float)w.Z; @@ -3513,10 +3624,12 @@ public sealed partial class RynthAiPlugin DungeonPathfinder.MainRouteNote = null; NavRouteParser route; List loop; + ExplorePlan? plan = null; try { if (portals.Count > 0) - walkOut = DungeonPathfinder.PortalWalkOut(geometry, portals, playerWX, playerWY, patrolWZ, patrolOptions.WallClearance); + walkOut = DungeonPathfinder.PortalWalkOut(geometry, portals, playerWX, playerWY, patrolWZ, patrolOptions.WallClearance, + graph: graph, startCell: startCell); if (walkOut != null) { startAt = (DungeonGeometry.NavToWorld(walkOut.EW), DungeonGeometry.NavToWorld(walkOut.NS), walkOut.Z * 240.0); @@ -3530,7 +3643,9 @@ public sealed partial class RynthAiPlugin losZ = (float)startAt.Z; } } - route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry, patrolOptions, portals, startAt); + route = explore != null + ? DungeonPathfinder.BuildExploreRoute(graph, startCell, hazards, geometry, patrolOptions, portals, startAt, explore.VisitedCells, out plan, explore.PreferCells) + : DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry, patrolOptions, portals, startAt); portalReport = DungeonPathfinder.LastPortalAvoidance; loop = new List(route.Points); // the lap, before any lead-in goes in front of it } @@ -3551,12 +3666,13 @@ public sealed partial class RynthAiPlugin // waypoint 0. Walking the list forward to the first LOS-clear point sidesteps the // "patrol immediately runs into a wall on login" failure mode. (From where the character // walks out of a portal's circle to, when it stands in one.) - int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ); + // (The explore only looks a few points ahead: past those it would skip rooms, a loop comes round again.) + int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ, explore != null ? ExploreSightLookahead : int.MaxValue); // The way to that waypoint: out of a portal's circle first, round any portal in between. if (portals.Count > 0 && route.Points.Count > 0) { DungeonPathfinder.PointLog = pointLog; - try { startIdx = LeadPatrolPastPortals(route, graph, geometry, portals, portalReport, walkOut, playerWX, playerWY, patrolWZ, startIdx, patrolOptions.WallClearance); } + try { startIdx = LeadPatrolPastPortals(route, graph, geometry, portals, portalReport, walkOut, playerWX, playerWY, patrolWZ, startIdx, patrolOptions.WallClearance, loop: explore == null); } finally { DungeonPathfinder.PointLog = null; } } LogPatrolWaypoints(route, graph, geometry, hazards, pointLog, playerCell, startCell); @@ -3564,7 +3680,8 @@ public sealed partial class RynthAiPlugin // Empty-route guard: a single-cell / hazard-locked start yields no waypoints. Do NOT claim the // patrol started or enable nav — the bot would just stand in place (in the hazard) taking damage. - if (route.Points.Count == 0) + // (An explore with nothing left to walk to is its caller's to say.) + if (route.Points.Count == 0 && explore == null) { refusal = DunBuildRefusal.EmptyRoute; error = "[RynthAi] DunNav-Patrol: no walkable route from here — you're standing in or surrounded by a hazard. Move to safe ground and retry."; @@ -3587,11 +3704,11 @@ public sealed partial class RynthAiPlugin return new DunPatrolBuild { World = w, Options = patrolOptions, Route = route, Loop = loop, StartIdx = startIdx, StartCell = startCell, - Evacuated = evacuate, WalkOut = walkOut, PortalReport = portalReport, + Evacuated = evacuate, WalkOut = walkOut, PortalReport = portalReport, Plan = plan, }; } - private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false) + private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false, bool stuckOpening = false) { var b = TryBuildDunPatrol("dunnav-patrol", out string error, out var refusal); if (b == null) @@ -3659,6 +3776,10 @@ public sealed partial class RynthAiPlugin { ChatLine($"[RynthAi] DunNav-Patrol: a portal came into view → rerouted to keep out of it ({portals.Count} portal(s) kept out of)."); } + else if (isRebuild && stuckOpening) + { + Host.Log($"[RynthAi] DunNav-Patrol: laid again round {_dunPatrolStuckOpenings} opening(s) it couldn't get through, {route.Points.Count} waypoints"); + } else if (isRebuild) { ChatLine($"[RynthAi] DunNav-Patrol: new hazard sighted → rerouted around it ({hazardCount} hazard cell(s) avoided)."); @@ -3723,6 +3844,27 @@ public sealed partial class RynthAiPlugin if (TickPatrolFollow(settings)) return; if (_objectCache == null) return; + // Stuck for good where the map says the way is open (every detour used up): close that opening and lay + // the patrol round it (RynthAiPlugin.DunExplore.cs, TryFindStuckOpening; the explore does the same). + if (StuckForGood() && _dunPatrolStuckOpenings < DunExploreMaxStuckOpenings + && Host.TryGetPlayerPose(out uint stuckCell, out float sx, out float sy, out float sz, out _, out _, out _, out _) + && (stuckCell >> 16) == _dunPatrolLandblock && (stuckCell & 0xFFFF) >= 0x0100) + { + if (_dunPatrolStuckLb != _dunPatrolLandblock) { _dunPatrolStuckEdges.Clear(); _dunPatrolStuckSpots.Clear(); _dunPatrolStuckOpenings = 0; _dunPatrolStuckLb = _dunPatrolLandblock; } + if (TryFindStuckOpening(settings.CurrentRoute, _dunPatrolLandblock, _dunPatrolStuckEdges, _dunPatrolStuckOpenings, settings.ActiveNavIndex, + stuckCell, sx, sy, sz, "DunNav-Patrol", out var stuckKeys, out string stuckNote, out _, out var stuckSpot)) + { + if (stuckSpot != null) _dunPatrolStuckSpots.Add(stuckSpot); + else _dunPatrolStuckEdges.UnionWith(stuckKeys); + _dunPatrolStuckOpenings++; + ChatLine(stuckSpot != null + ? $"[RynthAi] DunNav-Patrol: couldn't get past something at {stuckNote} (not on the dungeon map) → patrolling round that spot." + : $"[RynthAi] DunNav-Patrol: couldn't get past something between {stuckNote} (not on the dungeon map) → patrolling round it."); + BuildDunPatrol(isRebuild: true, stuckOpening: true); + return; + } + } + var patrolOptions = PatrolOptionsFrom(settings); bool settingsChanged = _dunPatrolSettings.ShouldRebuild(patrolOptions, Environment.TickCount64); bool hazardsChanged = _objectCache.HazardVersion != _dunPatrolHazardVersion; @@ -4158,7 +4300,8 @@ public sealed partial class RynthAiPlugin /// worst we behave like the old "always start at 0" code, so this is a strict win. /// 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 done, int max = 300) + { + for (int i = 0; i < max && !done(); i++) { Tick(); Thread.Sleep(10); } + } + public void TickFor(int ms, BotActivity act = BotActivity.Looting) + { + long end = Environment.TickCount64 + ms; + while (Environment.TickCount64 < end) { Tick(act); Thread.Sleep(10); } + } + } + + private static Bot NewBot(bool on = true) + { + World(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.LootNearbyChests = on; + bot.Create(Storage, VendorBox, DroppedPack, Chest, FarChest, Gem); + return bot; + } + + private static readonly uint[] NotChests = { Storage, VendorBox, DroppedPack, FarChest }; + + private static void PluginOffNothing() + { + Check.False(new LegacyUiSettings().LootNearbyChests, "off by default"); + var bot = NewBot(on: false); + Check.False(bot.HasLootWork(), "off: a chest in range is no loot work"); + bot.TickFor(300); + Check.Eq(FakeHost.IdRequests.Count, 0, "off: nothing appraised"); + Check.Eq(FakeHost.Uses.Count, 0, "off: nothing used"); + Check.Eq(FakeHost.UsesOn.Count, 0, "off: no key or lockpick used"); + + // The macro off with the setting on: nothing either. + var b2 = NewBot(); + b2.S.IsMacroRunning = false; + Check.False(b2.HasLootWork(), "macro off: no loot work"); + b2.TickFor(200); + Check.Eq(FakeHost.IdRequests.Count + FakeHost.Uses.Count, 0, "macro off: nothing sent"); + // Looting off: nothing. + var b3 = NewBot(); + b3.S.EnableLooting = false; + Check.False(b3.HasLootWork(), "Looting off: no loot work"); + b3.TickFor(200); + Check.Eq(FakeHost.IdRequests.Count + FakeHost.Uses.Count, 0, "Looting off: nothing sent"); + } + + private static void PluginCandidates() + { + var bot = NewBot(); + Check.True(bot.HasLootWork(), "a chest in loot range is loot work"); + bot.TickUntil(() => FakeHost.IdRequests.Count > 0, 50); + Check.Eq(string.Join(",", FakeHost.IdRequests.Select(i => $"{i:X8}")), $"{Chest:X8}", "only the real chest is appraised (the nearer storage, vendor chest and dropped pack, and the far chest, are passed by; corpses: ChestRule)"); + bot.TickFor(300); + foreach (uint id in NotChests) + { + Check.False(FakeHost.IdRequests.Contains(id) || FakeHost.Uses.Contains(id), $"0x{id:X8} '{FakeHost.Names[id]}' is never touched"); + } + } + + private static void PluginLootsChest() + { + var bot = NewBot(); + bot.TickUntil(() => FakeHost.IdRequests.Count > 0, 50); + FakeHost.Appraised.Add(Chest); // the ID arrives: no Locked property, so it isn't locked + bot.TickUntil(() => FakeHost.Uses.Contains(Chest), 100); + Check.True(FakeHost.Uses.Contains(Chest), "the chest is used (the server walks there and opens it)"); + Check.Eq(FakeHost.AutoRunCalls.Count(on => on), 0, "no walking of our own"); + + // The server opens it: the chest looter takes it and loots the gem by the profile. + FakeHost.GroundContainer = Chest; + bot.P.OnViewObjectContents(Chest); + bot.P.OnUpdateObjectInventory(Chest); + bot.TickUntil(() => FakeHost.ExternalMoves.Any(m => m.Id == Gem)); + Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the gem is picked up"); + FakeHost.Containers[Gem] = Player; + int closes = FakeHost.Closes.Count; + bot.TickUntil(() => FakeHost.Closes.Count > closes); + if (FakeHost.GroundContainer == Chest) FakeHost.GroundContainer = 0; + bot.P.OnStopViewingObjectContents(Chest); + bot.TickFor(300); + var looter = bot.Get("_nearbyChests"); + Check.Eq(looter.Looted, 1, "counted as looted"); + Check.True(looter.IsLeftAlone(unchecked((int)Chest), RynthAiPlugin.CorpseClock()), "left alone until it resets"); + Check.False(bot.HasLootWork(), "no loot work left"); + int uses = FakeHost.Uses.Count(u => u == Chest); + bot.TickFor(300); + Check.Eq(FakeHost.Uses.Count(u => u == Chest), uses, "not opened again"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Nearby chests: done with chest")), "the finish is logged"); + } + + private const uint Monster = 0x80263501; + + private static void PluginSkippedWhileFighting() + { + World(); + FakeHost.Names[Monster] = "Drudge Skulker"; + FakeHost.ItemTypes[Monster] = 0x10; + FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 20f, Me0.Y + 0.5f, Me0.Z); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.EnableCombat = true; + bot.S.MonsterRange = 50; + bot.Create(Storage, VendorBox, DroppedPack, Chest, FarChest, Gem); + _ = bot.Cache[unchecked((int)Monster)]; + bot.Cache.OnUpdateHealth(Monster, 1f); + bot.Cache.Tick(); + var combat = new CombatManager(host, bot.S, bot.Cache); + combat.SetPlayerId(Player); + typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue); + combat.ScanNearbyTargets(); + bot.Set("_combatManager", combat); + Check.True(combat.HasTargets, "a monster in range"); + Check.False(bot.HasLootWork(), "fighting: the chest is no loot work"); + bot.TickFor(300); + bot.TickFor(300, BotActivity.Combat); + Check.Eq(FakeHost.IdRequests.Count + FakeHost.Uses.Count + FakeHost.UsesOn.Count, 0, "nothing sent to the chest while fighting"); + } + + private static void PluginSettingPlumbing() + { + var s = new LegacyUiSettings { LootNearbyChests = true }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.LootNearbyChests == true, "sent to the engine's Settings row"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.True(s.LootNearbyChests, "an engine save without the field leaves it"); + dash.ApplySettingsJson("{\"LootNearbyChests\":false}"); + Check.False(s.LootNearbyChests, "an engine save with it sets it"); + + FakeHost.Reset(); + var host = FakeHost.Create(); + var ms = new LegacyUiSettings(); + var meta = new MetaManager(ms, host, new PlayerVitalsCache()); + meta.TryHandleVtCommand("/vt opt set lootnearbychests true"); + Check.True(ms.LootNearbyChests, "/vt opt set lootnearbychests turns it on"); + meta.TryHandleVtCommand("/vt opt set lootnearbychests false"); + Check.False(ms.LootNearbyChests, "and off"); + var e = ExpressionTests.Engine(settings: ms); + Check.Eq(e.Evaluate("vtsetsetting[LootNearbyChests, 1]"), "1", "metas: vtsetsetting knows it"); + Check.True(ms.LootNearbyChests, "and turns it on"); + + // /ra chests always answers. + var bot = NewBot(on: false); + int before = FakeHost.Chat.Count; + bot.Call("HandleNearbyChestsCommand"); + Check.True(FakeHost.Chat.Skip(before).Any(l => l.Contains("Loot Nearby Chests: off")), "/ra chests says it is off: " + string.Join(" / ", FakeHost.Chat.Skip(before))); + bot.S.LootNearbyChests = true; + before = FakeHost.Chat.Count; + bot.Call("HandleNearbyChestsCommand"); + Check.True(FakeHost.Chat.Skip(before).Any(l => l.Contains("Loot Nearby Chests: on")), "/ra chests says it is on"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs index 26263b8..57d8f3b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs @@ -26,6 +26,8 @@ internal static class OutdoorHuntTests r.Add("hunt: the settings round-trip with the rest (saved, copied, engine payload)", Settings); r.Add("hunt (test 10-23): a monster 12 yd away but a 143 yd walk is too far round; the one being walked to is kept past Hunt Range", FarRound); r.Add("hunt (test 10-23): at a wall with the monster on its far side: no 1 yd walks every half second; left out after NoFightSec", WallBetween); + r.Add("hunt (2026-11-16): a walk ending where it stands, its corners round it, is no walk: it stands, then the monster is left out", EndsHereNoWalk); + r.Add("hunt (2026-11-16 17:11): the walk over, under a monster on the floor above: left out, not walked again every half second", FloorApartLeftOut); r.Add("hunt: a monster right beside it that combat doesn't take: stands, then leaves it out", RightHere); r.Add("hunt (test 10-23): in a building it walks back out the way it went in (the loops it made cut out)", WayBackOut); r.Add("hunt: in a building with no way in known, or the walks out ending still inside: it waits", IndoorsWaits); @@ -287,6 +289,56 @@ internal static class OutdoorHuntTests Check.True(h.IsSkipped(1, T0.AddSeconds(h.NoFightSec + 1)), "combat never took it: left out"); } + // 2026-11-16, a Thread: under a monster on the floor above, the walk to it was two corners a yard or + // so either side of the character, planned again every half second: it turned in circles. + private static void EndsHereNoWalk() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + nav.Overrides[(1000.5, 1000)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(1001.2, 1000.8), V(1000.6, 1000.1) }, 2.6, 0); + var d = h.Tick(T0, me, true, Sorted(C(1, 1000.5, 1000, me)), nav.Path); + Check.True(d.Act != OutdoorHunt.Act.Walk && d.TargetId == 1, $"a 2.6 yd walk ending where it stands: no walk, it stands ({d.Act} {d.TargetId})"); + h.Tick(T0.AddSeconds(h.NoFightSec + 0.6), me, true, Sorted(C(1, 1000.5, 1000, me)), nav.Path); + Check.True(h.IsSkipped(1, T0.AddSeconds(h.NoFightSec + 1)), "combat never took it: left out, no circling"); + } + + // 2026-11-16 17:11, a Thread: the walk "through its rooms" to a monster on the floor above (3 m up) ended + // under it (nav's points count as reached by the flat distance), and the same walk was planned and walked + // again every half second for 20 s. + private static void FloorApartLeftOut() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + var up = new OutdoorHunt.Vec(1006, 1000, 3.3); + nav.Overrides[(1006, 1000)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(1003, 1002), up }, 7.5, 0); // a doorway, then the monster + var list = Sorted(new OutdoorHunt.Candidate(1, "Elite Olthoi Ravener", up, up.DistanceTo(me), 1)); + var d = h.Tick(T0, me, true, list, nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, "walks to it"); + + // Walked: under where it was. It moved 2.5 yd up there, so the walk planned again would end 2 yd off. + var under = V(1006.4, 1000.3); + var moved = new OutdoorHunt.Vec(1008.5, 1000, 3.3); + nav.Overrides[(1008.5, 1000)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(1003, 1002), moved }, 9.5, 0); + list = Sorted(new OutdoorHunt.Candidate(1, "Elite Olthoi Ravener", moved, moved.DistanceTo(under), 1)); + d = h.Tick(T0.AddSeconds(3), under, true, list, nav.Path); + Check.True(d.Act != OutdoorHunt.Act.Walk, $"the walk over, under it: no walk again ({d.Act})"); + Check.True(h.IsSkipped(1, T0.AddSeconds(4)), "left out"); + var notes = string.Join(" | ", h.PendingNotes); + Check.True(notes.Contains("the walk to it ended 3 yd below it"), "says so: " + notes); + + // Up there with it (the walk took it up the stairs): not left out. + var h2 = new OutdoorHunt(); + h2.Start(T0, me); + h2.Tick(T0, me, true, list, nav.Path); + var level = new OutdoorHunt.Vec(1006.4, 1000.3, 3.3); + h2.Tick(T0.AddSeconds(3), level, true, Sorted(new OutdoorHunt.Candidate(1, "Elite Olthoi Ravener", up, up.DistanceTo(level), 1)), nav.Path); + Check.False(h2.IsSkipped(1, T0.AddSeconds(4)), "level with it: combat's turn, not left out"); + } + private static void WayBackOut() { var h = new OutdoorHunt(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolPortalTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolPortalTests.cs index e799f82..c0a8729 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolPortalTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolPortalTests.cs @@ -39,6 +39,9 @@ internal static class PatrolPortalTests r.Add("patrol portals: a portal in a dead end (Tiny Hive's nook) is turned round before; it used to get a point on it", DeadEndTurnedRoundBefore); r.Add("patrol portals: without the map geometry (cell walk) the patrol keeps out too", CellWalkKeepsOut); r.Add("patrol portals: a start next to a portal walks straight away from it first, then round it", StartNextToPortalWalksAway); + r.Add("patrol portals: a start ON a portal walks out towards the room's doorway, never to a spot in the wall (Thread 0x00B5)", StartOnPortalWalksToDoorway); + r.Add("patrol portals: a start in a portal with no checked spot round it walks nowhere (no unchecked spot)", StartOnPortalNoSpot); + r.Add("nav escapes: a stuck escape burst turns away from a portal it would run into; boxed in: none", EscapeBurstKeepsOutOfPortals); r.Add("patrol portals: a portal across the start's corridor leaves the patrol the side the character is on", PortalSplitsStartCorridor); r.Add("patrol portals: a portal on another level changes nothing", OtherLevelIgnored); r.Add("patrol portals: Tiny Hive 0x0289 on the real dats keeps out of the Surface Portal (if the dats are here)", TinyHiveRealDats); @@ -331,6 +334,80 @@ internal static class PatrolPortalTests Check.True(DungeonPathfinder.PortalLeadIn(d.Graph, geo, portals, At(3, 3), At(3, 17), 1.0).Count == 0, "a clear walk needs no corners"); } + private static void StartOnPortalWalksToDoorway() + { + // DreamWeave Thread 0x00B5 (2026-11-15): the character arrives ON the Thread Exit, in a one-cell + // room whose one way out is a doorway north. Here: a room x 0..4, y 0..8, the portal at (2, 2), + // a doorway north (y 8, x 0.5..3.5) into a corridor. The character stands 0.07 m from the + // portal's centre, so "away from it" is a random heading (south-east here). The old search + // (that heading +-90 degrees) found no spot and fell back to one off the floor, by the wall. + var d = new Dungeon(); + uint room = d.Cell(0, 0, 4, 8); + uint corr = d.Cell(0.5, 8, 3.5, 20); + d.OpenY(room, corr, 8, 0.5, 3.5); + var geo = d.Geo(); + var p = Portal(2, 2); + var portals = new[] { p }; + double px = 2.05, py = 1.95; + var report = new List { new() { Portal = p } }; + + var walk = DungeonPathfinder.PortalWalkOut(geo, portals, px, py, 0, 1.0, report, d.Graph, room); + Check.NotNull(walk, "a spot to walk out to"); + double wx = X(walk!), wy = Y(walk); + Check.True(geo.OnWalkableFloor(wx, wy, 0), $"on walkable floor: ({wx:F2}, {wy:F2})"); + Check.True(wy > p.Y + 3.0, $"north, the doorway's side: ({wx:F2}, {wy:F2})"); + Check.True(Math.Sqrt((wx - p.X) * (wx - p.X) + (wy - p.Y) * (wy - p.Y)) >= p.Radius, "outside the circle"); + Check.True(geo.LegClearance(px, py, 0, wx, wy, 0, 1.0, 0.3, out _, out _, out _) >= 0.1, "walked to in a straight line through no wall"); + Check.True(report[0].StartInside && !report[0].NoWalkOut, "the report: started inside, walked out"); + Check.True(report[0].Describe().Contains("walked out first"), report[0].Describe()); + + // The patrol from there starts on the doorway's side too. + var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, room, null, geo, null, portals, (wx, wy, 0)); + KeptOut(route, p, "start on a portal"); + } + + private static void StartOnPortalNoSpot() + { + // A sealed 3 m room with the portal in its middle: no spot 3.9 m out is on any floor. + var d = new Dungeon(); + uint room = d.Cell(0, 0, 3, 3); + var geo = d.Geo(); + var p = Portal(1.5, 1.5); + var report = new List { new() { Portal = p } }; + var walk = DungeonPathfinder.PortalWalkOut(geo, new[] { p }, 1.5, 1.6, 0, 1.0, report, d.Graph, room); + Check.Null(walk, "no checked spot: nowhere to walk (it used to be a spot off the floor)"); + Check.True(report[0].StartInside && report[0].NoWalkOut, "the report says so"); + Check.True(report[0].Describe().Contains("no clear spot to walk out to"), report[0].Describe()); + } + + private static void EscapeBurstKeepsOutOfPortals() + { + // Facing north at (0, 0); a portal 5 m east-north-east: the +75 degree side-step runs at it. + double off = 75; + var east = new[] { (5.0, 1.5, 0.0) }; + Check.True(NavigationEngine.EscapeOffsetClear(0, 0, 0, 0, east, ref off, out string? note), "a clear way is found"); + Check.Near(off, -75, 1e-9, "the other side-step instead"); + Check.True(note != null && note.Contains("instead"), "said: " + note); + + // Nothing near, or only on another level: the rung's own heading, nothing said. + off = 75; + Check.True(NavigationEngine.EscapeOffsetClear(0, 0, 0, 0, Array.Empty<(double, double, double)>(), ref off, out note) && off == 75 && note == null, "no portal: as it was"); + off = 75; + Check.True(NavigationEngine.EscapeOffsetClear(0, 0, 0, 0, new[] { (5.0, 1.5, 10.0) }, ref off, out note) && off == 75 && note == null, "a portal 10 m up: as it was"); + + // Standing 1 m west of a portal: anything eastwards gets nearer it; the burst goes the other way. + off = 75; + Check.True(NavigationEngine.EscapeOffsetClear(0, 0, 0, 0, new[] { (1.0, 0.0, 0.0) }, ref off, out note), "a way away from it"); + double h = off * Math.PI / 180.0; + Check.True(Math.Sin(h) < 0, $"westwards ({off:+0;-0} degrees)"); + + // Boxed in by portals all round: no burst (the jump instead). + var ring = Enumerable.Range(0, 12).Select(i => (4.0 * Math.Sin(i * Math.PI / 6), 4.0 * Math.Cos(i * Math.PI / 6), 0.0)).ToArray(); + off = 75; + Check.False(NavigationEngine.EscapeOffsetClear(0, 0, 0, 0, ring, ref off, out note), "every heading runs at one"); + Check.True(note != null && note.Contains("portal"), "names the portal: " + note); + } + private static void PortalSplitsStartCorridor() { // A corridor (x 0..5.3, y 0..20) between a room south (y -10..0) and a room north (y 20..30), diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs index 735eed0..35f6f7e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs @@ -39,7 +39,7 @@ internal static class PetRefillTests r.Add("pets: 'not enough charges' after a confirmed refill ends the trust; refill again", TrustEndsOnEmptySummon); r.Add("pets: refilled twice in 2 min and still empty (no reply) -> parked 5 min", SilentRefillsParked); r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires); - r.Add("pets: a landed summon whose pet is not in the cache yet holds a second essence back for the 10 s window", LandedSummonHoldsWindow); + r.Add("pets: a landed summon whose pet is not in the cache yet holds a second essence back for the 10 s window, then the shared 45 s cooldown", LandedSummonHoldsWindow); r.Add("pets: failed summon (no charge drop) does not assume a pet; waits the 45 s essence cooldown", FailedSummonRespectsCooldown); r.Add("pets: Boost Nav Priority along a route (RynthAi only follows it): no summon with a monster near; route unloaded: it summons", BoostNavNoSummon); r.Add("pets: Boost Nav Priority with no route: it summons as with the flag off (R-20261103-000159-a65e)", BoostNavNoRouteSummons); @@ -280,7 +280,12 @@ internal static class PetRefillTests FakeHost.Ints[(Essence2, StructureKey)] = 49; // whichever essence it was, its charge dropped rig.Run(8_000); Check.Eq(rig.AllSummons, 1, "inside the 10 s window the other essence is not used"); + // Window over and still no pet: the other essence used to be summoned now. Every ACE combat + // essence shares one 45 s cooldown (SharedCooldown 213), so the server refused it; the next + // summon waits for that cooldown (2026-11-13, R-20261113-130755-35ae). rig.Run(5_000); - Check.Eq(rig.AllSummons, 2, "window over and still no pet: the other essence is used"); + Check.Eq(rig.AllSummons, 1, "window over and still no pet: the shared 45 s cooldown still runs, no other essence"); + rig.Run(32_000); + Check.Eq(rig.AllSummons, 2, "the cooldown over: the next summon goes"); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PetSelectionTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PetSelectionTests.cs index 2616deb..18978c6 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PetSelectionTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PetSelectionTests.cs @@ -42,6 +42,54 @@ internal static class PetSelectionTests r.Add("pet choice: an essence used before its appraisal that turns out passive is learned, and its pet holds nothing (before: held for good)", PassiveLearnedAfterSummon); r.Add("pet choice: the Pets tab shows a listed passive essence under Cosmetic, unticked, and the combat pick skips it", PetsTabShowsPassiveAsCosmetic); r.Add("pet choice: pack fill does not list an appraised passive essence as a Pet; a combat essence and an unappraised one still are", FillSkipsPassiveEssence); + // R-20261113-130755-35ae (Conquest, 2026.11.12.1): "Cold chosen -> Frost ..." on every line, yet + // when the pet died before 45 s the next listed essences (other elements) were used: refused + // "used this item too recently" for most of the window, summoned for real at its edge. + r.Add("pet choice: the pet dies inside the shared 45 s cooldown: the chosen element waits for it; no other essence is used (before: the next listed)", ChosenWaitsSharedCooldown); + r.Add("pet choice: 'used this item too recently' does not park the chosen essence 45 s; it is tried again in 5 s, no other essence (before: the next listed)", TooRecentlyRetriesChosen); + } + + /// The report's fight: Cold chosen for the monster, a Fire essence listed after the Frost one. + private static Rig ColdChosenRig() + { + var rig = new Rig(frostFirst: true); + rig.Store.SetManualPet(MobWcid, "E:Cold"); + return rig; + } + + private static void ChosenWaitsSharedCooldown() + { + using var rig = ColdChosenRig(); + rig.Run(1_500); + Check.Eq(Rig.UsesOf(Frost), 1, "Cold chosen: the Frost essence is summoned"); + Check.True(Logged("Cold chosen -> Frost Moar Essence"), "the choice line names it"); + FakeHost.Ints[(Frost, StructureKey)] = 49; // the summon landed: a charge spent + rig.ShowPet(Ours, "Pet Tester's Frost Moar"); + rig.Run(18_000); + Check.Eq(Rig.UsesOf(Frost) + Rig.UsesOf(Essence), 1, "the pet is out: no second summon"); + FakeHost.Names.Remove(Ours); // the pet dies about 20 s in + FakeHost.Positions.Remove(Ours); + rig.Run(20_000); + Check.Eq(Rig.UsesOf(Essence), 0, "inside the 45 s cooldown every essence shares, the Fire essence is not used (before: it was, at once)"); + Check.True(Logged("every essence shares the 45s summon cooldown"), "the wait is logged"); + rig.Run(8_000); + Check.Eq(Rig.UsesOf(Frost), 2, "the cooldown over: the chosen Frost essence is summoned again"); + Check.Eq(Rig.UsesOf(Essence), 0, "and never the Fire one"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("every essence shares the 45s")), 1, "the wait logged once"); + } + + private static void TooRecentlyRetriesChosen() + { + using var rig = ColdChosenRig(); + rig.Run(1_500); + Check.Eq(Rig.UsesOf(Frost), 1, "Cold chosen: the Frost essence is tried"); + rig.Pets.OnChatWindowText("You have used this item too recently"); // a pet summoned by hand started the cooldown + Check.True(Logged("used too recently"), "the refusal is logged"); + rig.Run(3_000); + Check.Eq(Rig.UsesOf(Frost) + Rig.UsesOf(Essence), 1, "no Use for a moment"); + rig.Run(3_000); + Check.Eq(Rig.UsesOf(Frost), 2, "the chosen Frost essence is tried again (before: parked 45 s, so the Fire one went)"); + Check.Eq(Rig.UsesOf(Essence), 0, "never the Fire one"); } private const uint Golem = 0x80320030; // Common Golem Essence: a passive pet's essence diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StackedStepTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StackedStepTests.cs new file mode 100644 index 0000000..70d5953 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StackedStepTests.cs @@ -0,0 +1,79 @@ +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.Raycasting; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Steps nav can't walk (DungeonPathfinder.Explore.cs, 2026-11-16). DreamWeave Thread 0x0278: the explore crossed a +// two-level room straight, from the doorway at its foot (z -42) to the opening on the level above (z -36), 1 m off +// on the map; nav took the upper point as reached and ran from the lower floor into the wall under the next one. +internal static class StackedStepTests +{ + public static void Register(Runner r) + { + r.Add("stacked steps: Thread 0x0278's walk from where that run started has no step 6 m up in 1 m (its doorway closed, the walk laid again, the rooms still walked); the stairs of 0x00B5 and 0x0185 are left as they are (if the dats are here)", RealDats); + } + + private static int Stacked(List pts, Dictionary graph, DungeonGeometry geo) + { + DungeonPathfinder.StackedStepOpenings(pts, graph, geo, out int steps); + return steps; + } + + 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); + DungeonPathfinder.InvalidateCache(); + var graph = DungeonPathfinder.GetGraph(0x0278, loader.CellDat); + var geo = DungeonPathfinder.GetGeometry(0x0278, loader.CellDat, loader.DungeonLOS)!; + + DungeonPathfinder.CloseStackedSteps = false; + DungeonPathfinder.MainRouteNote = null; + var old = DungeonPathfinder.BuildExploreRoute(graph, 0x02780369, null, geo, null, null, null, null, out var oldPlan); + int oldStacked = Stacked(old.Points, graph, geo); + DungeonPathfinder.CloseStackedSteps = true; + DungeonPathfinder.MainRouteNote = null; + var route = DungeonPathfinder.BuildExploreRoute(graph, 0x02780369, null, geo, null, null, null, null, out var plan); + string note = DungeonPathfinder.MainRouteNote ?? ""; + Console.WriteLine($" 0x0278: as laid {old.Points.Count} points, {oldStacked} stacked, {oldPlan.Order.Count} rooms; now {route.Points.Count} points, {plan.Order.Count} rooms; {note}"); + Check.True(oldStacked >= 1, "as laid, the walk has the step 6 m up in 1 m"); + Check.Eq(Stacked(route.Points, graph, geo), 0, "now it has none"); + Check.True(note.Contains("stacked steps:"), "and says so: " + note); + Check.True(plan.Order.Count >= oldPlan.Order.Count * 0.9, $"the rooms still walked ({plan.Order.Count} of {oldPlan.Order.Count})"); + var keys = DungeonPathfinder.StackedStepOpenings(old.Points, graph, geo, out _); + Check.True(keys.Contains(DungeonPathfinder.OpeningKey(0x0278012C, 0x02780155)) && keys.Contains(DungeonPathfinder.OpeningKey(0x0278012C, 0x02780156)), + "the doorway closed is the one at its foot, both cell pairs (012C>0155, 012C>0156)"); + + foreach (uint lb in new uint[] { 0x00B5, 0x0185 }) + { + DungeonPathfinder.InvalidateCache(); + var g = DungeonPathfinder.GetGraph(lb, loader.CellDat); + var gg = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!; + DungeonPathfinder.MainRouteNote = null; + var r = DungeonPathfinder.BuildExploreRoute(g, g.Keys.Min(), null, gg, null, null, null, null, out _); + string n = DungeonPathfinder.MainRouteNote ?? ""; + Check.False(n.Contains("stacked steps:"), $"0x{lb:X4}: its stairs (3 m up over 2 m) are walkable steps: " + n); + } + } + finally + { + DungeonPathfinder.CloseStackedSteps = true; + DungeonPathfinder.MainRouteNote = null; + DungeonPathfinder.StaticMeshSource = before; + loader.Dispose(); + DungeonPathfinder.InvalidateCache(); + } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StraightenTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StraightenTests.cs new file mode 100644 index 0000000..402a90c --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StraightenTests.cs @@ -0,0 +1,92 @@ +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.Raycasting; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The explore's walk straightened (DungeonPathfinder.Straighten.cs, 2026-11-15). DreamWeave Thread +// 0x00ED: its zig-zag corridors are cut into many 3-5 cell rooms, the walk had a point at every room +// boundary (334 points, 182 of them at openings) and the character turned every 2.5-5 m. On the real +// dats: far fewer points, every leg walkable, and every room the walk was laid into still crossed. +internal static class StraightenTests +{ + public static void Register(Runner r) + { + r.Add("straighten: Thread 0x00ED's explore on the real dats has far fewer turns, every leg walkable, every room still crossed (if the dats are here)", Real00ED); + } + + private static void Real00ED() + { + 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 = 0x00ED, start = 0x00ED0350; + DungeonPathfinder.InvalidateCache(); + var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat); + var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!; + Check.NotNull(geo, "geometry"); + // Where the character arrives (local 180, -330), and the Thread Exit beside it (as logged 2026-11-15). + double sx = 180.0, sy = 0xED * 192.0 - 330.0; + var exit = new PatrolPortal { Id = 0x700ED032, Name = "Thread Exit", Cell = 0x00ED0351, X = 180.0, Y = 45160.0, Z = -0.1 }; + // As laid, for comparison: the rooms that walk crosses. + DungeonPathfinder.StraightenEnabled = false; + var laid = DungeonPathfinder.BuildExploreRoute(graph, start, null, geo, null, new[] { exit }, (sx, sy, 0), null, out var laidPlan); + DungeonPathfinder.StraightenEnabled = true; + DungeonPathfinder.MainRouteNote = null; + var route = DungeonPathfinder.BuildExploreRoute(graph, start, null, geo, null, new[] { exit }, (sx, sy, 0), null, out var plan); + var pts = route.Points; + Console.WriteLine($" {pts.Count} points (laid in game before: 334), {plan.Order.Count} rooms in order; {DungeonPathfinder.MainRouteNote}"); + // Against the same walk laid unstraightened, waits left out. (2026-11-16: the explore walks into every dead + // end and keeps those middles, so it has more points than the 334 of 2026-11-15.) + int moves = pts.Count(p => p.Type == NavPointType.Point), laidMoves = laid.Points.Count(p => p.Type == NavPointType.Point); + Console.WriteLine($" {moves} moving points straightened, {laidMoves} as laid"); + Check.True(moves > 50 && moves < laidMoves * 0.85, $"far fewer points ({moves}, {laidMoves} as laid)"); + + double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW); + double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS); + int bad = 0; + for (int i = 0; i + 1 < pts.Count; i++) + if (geo.LegClearance(X(pts[i]), Y(pts[i]), pts[i].Z * 240.0, X(pts[i + 1]), Y(pts[i + 1]), pts[i + 1].Z * 240.0, 1.0, 0.5, out _, out _, out _) < 0.2) bad++; + Check.Eq(bad, 0, "every leg on walkable floor, off the walls"); + + // Every room the walk was laid into is crossed by it (sampled every 0.5 m) - as the walk as laid did. + HashSet Crossed(List pts) + { + var crossed = new HashSet(); + for (int i = 0; i + 1 < pts.Count; i++) + { + double x0 = X(pts[i]), y0 = Y(pts[i]), z0 = pts[i].Z * 240.0, x1 = X(pts[i + 1]), y1 = Y(pts[i + 1]), z1 = pts[i + 1].Z * 240.0; + int steps = Math.Max(1, (int)Math.Ceiling(Math.Sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)) / 0.5)); + 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; + if (geo.TryFloorHeight(x, y, zf, 0.6, out double h)) zf = h; + foreach (var n in graph.Values) + if (geo.OnCellFloor(n.CellId, x, y, zf)) { int r = plan.RoomOf(n.CellId); if (r >= 0) crossed.Add(r); break; } + } + } + return crossed; + } + var before = Crossed(laid.Points); + var after = Crossed(pts); + var laidMissed = plan.Order.Where(r => !before.Contains(r)).ToList(); + var missed = plan.Order.Where(r => !after.Contains(r) && before.Contains(r)).ToList(); + Console.WriteLine($" as laid: {laid.Points.Count} points, rooms not crossed {laidMissed.Count} ({string.Join(",", laidMissed.Take(10))})"); + Check.Eq(missed.Count, 0, $"no room the laid walk crossed is left out ({missed.Count}: {string.Join(",", missed.Take(10))})"); + } + finally + { + loader.Dispose(); + DungeonPathfinder.InvalidateCache(); + } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs index 631ae30..00993d3 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs @@ -24,6 +24,7 @@ internal static class StuckCastTests r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy); r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen); r.Add("too busy (Conquest 10-25): a try held by another check (animating) is not spent; the next asker (combat) gets it", TryNotSpentWhenHeld); + r.Add("too busy (R-20261115-172110-9e6a): a try let through but sent nothing with is not spent; combat, asking next, gets it", TrySpentOnlyBySend); r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump TurnGraceMs after the turn; a normal 4 s cast trips neither", TurnThenJump); r.Add("stuck cast: already facing the target (no turn), the jump is at cycle + 2 s", JumpWithoutTurn); r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump); @@ -346,6 +347,38 @@ internal static class StuckCastTests // Conquest report R-20261025-183343 (Dargoth Hera): a corpse pickup and a cast went out together, the // cast was refused 'too busy', and the buff step took all three tries after it while the character was // still animating, so it sent nothing; combat never got a try and the fight stood for the latch's 15 s. + // 2026-11-15, R-20261115-172110-9e6a: the buff step passed MayStart three times in a 15 s latch, found + // nothing to cast and sent nothing; combat, asking after it, never got a try with eleven monsters in range. + private static void TrySpentOnlyBySend() + { + var host = Setup(); + try + { + Check.True(MayAs(host, "Combat", HealNeed.None), "free"); + Cast(host, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); + Check.False(MayAs(host, "Combat", HealNeed.None), "held right after the 0x1D"); + _t += ActionPacer.BusyProbeMs; + Check.True(MayAs(host, "Buff", HealNeed.None), "the buff step is let through with the try"); + // ...and sends nothing (nothing to cast). + Check.True(MayAs(host, "Combat", HealNeed.None), "unused, the try is still there for combat"); + Check.False(FakeHost.Logs.Any(l => l.Contains("one try (#")), "nothing spent it yet"); + Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Combat", "Heart Rend"), "combat casts"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Combat: one try (#1)")), "the send spent it, and it was combat's"); + FakeHost.UseDone(ActionPacer.TooBusyErr); + Check.False(MayAs(host, "Buff", HealNeed.None), "spent: the next asker waits for the next try"); + + // Let through and never used: after TryOpenMs it counts as spent (no endless passes). + _t += ActionPacer.BusyProbeMs * 2; + Check.True(MayAs(host, "Buff", HealNeed.None), "the second try is let through"); + _t += ActionPacer.TryOpenMs; + Check.False(MayAs(host, "Combat", HealNeed.None), "unused for TryOpenMs: spent, the next one waits"); + Check.True(FakeHost.Logs.Any(l => l.Contains("went unused for") && l.Contains("first let through for Buff")), "and said so"); + } + finally { Done(); } + } + private static void TryNotSpentWhenHeld() { var host = Setup(); @@ -361,9 +394,11 @@ internal static class StuckCastTests Check.False(MayAs(host, "Buff", HealNeed.None), "the buff step's try is held by the animation"); FakeHost.CastBusy = 0; Check.True(MayAs(host, "Combat", HealNeed.None), "combat gets the try the buff step couldn't use"); + Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Combat", "Heart Rend"), "and casts with it"); Check.False(MayAs(host, "Buff", HealNeed.None), "and only one start has it"); Check.Eq(FakeHost.Logs.Count(l => l.Contains("one try (#1)")), 1, "one try logged"); Check.True(FakeHost.Logs.Any(l => l.Contains("Combat: one try (#1)")), "and it was combat's"); + FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again: the latch goes on // The next try is counted from the one that went (doubling as before). _t += ActionPacer.BusyProbeMs * 2 - 1; Check.False(MayAs(host, "Combat", HealNeed.None), "the next try waits twice as long"); @@ -389,8 +424,8 @@ internal static class StuckCastTests Check.False(Start(host), "held until BusyProbeMs"); _t += 1; Check.True(Start(host), "one probe at BusyProbeMs"); - Check.False(Start(host), "only one"); Cast(host, "Heart Rend"); + Check.False(Start(host), "only one (the send spent it; 2026-11-15 a pass that sends nothing doesn't)"); _t += 100; FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again _t += ActionPacer.BusyProbeMs * 2 - 101; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StuckOpeningTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StuckOpeningTests.cs new file mode 100644 index 0000000..ed21b75 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StuckOpeningTests.cs @@ -0,0 +1,78 @@ +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; + +// Stuck for good in an opening the map says is open (DungeonPathfinder.OpeningPairs, 2026-11-16). DreamWeave +// Thread 0x5456: cells 014F and 0150 have one centre at the big room's west edge, and both join 0148 through +// the one doorway at (16133, 16492). The explore, stuck in it (something in the doorway no dat has), closed +// 014F>0148, laid the walk again through 0150>0148, and was stuck in the same doorway again (three closings, +// the last an opening inside the big room). The same at 0177 (0173>0177 and 0174>0177) and 0157 (0158>0157 +// and 0159>0157): each one doorway. +internal static class StuckOpeningTests +{ + public static void Register(Runner r) + { + r.Add("stuck opening: Thread 0x5456 on the real dats - a doorway two stacked cells open into is closed whole; the walk laid again keeps out (if the dats are here)", Real5456); + } + + private const uint C014F = 0x5456014F, C0150 = 0x54560150, C0148 = 0x54560148, C0147 = 0x54560147, + C0173 = 0x54560173, C0174 = 0x54560174, C0177 = 0x54560177; + + private static void Real5456() + { + 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 = 0x5456; + DungeonPathfinder.InvalidateCache(); + var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat); + var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!; + Check.NotNull(geo, "geometry"); + ulong K(uint a, uint b) => DungeonPathfinder.OpeningKey(a, b); + + var west = DungeonPathfinder.OpeningPairs(graph, geo, C014F, C0148); + Check.True(west.SetEquals(new[] { K(C014F, C0148), K(C0150, C0148) }), + $"the west doorway is 014F>0148 and 0150>0148 ({west.Count} pair(s))"); + var south = DungeonPathfinder.OpeningPairs(graph, geo, C0173, C0177); + Check.True(south.SetEquals(new[] { K(C0173, C0177), K(C0174, C0177) }), + $"the doorway into 0177 is 0173>0177 and 0174>0177, 3 m over it ({south.Count} pair(s))"); + Check.Eq(DungeonPathfinder.OpeningPairs(graph, geo, C0148, C0147).Count, 1, "the next doorway (0148>0147, 2 m on) is one pair"); + var east = DungeonPathfinder.OpeningPairs(graph, geo, 0x54560158, 0x54560157); + Check.True(east.SetEquals(new[] { K(0x54560158, 0x54560157), K(0x54560159, 0x54560157) }), + $"the doorway into 0157 is 0158>0157 and 0159>0157 (the third doorway it was stuck in: {east.Count} pair(s))"); + + // A web where the character stood stuck (16148.0, 16506.4): that doorway, both pairs; the big room's middle: none. + var web = DungeonPathfinder.DoorwayAt(graph, geo, 16148.0, 16506.6, -24.0, 1.5, out var webDoor); + Check.True(web.SetEquals(east), $"a web at (16148, 16506.6) stands in the doorway into 0157 ({web.Count} pair(s), {webDoor?.CellA:X8}>{webDoor?.CellB:X8})"); + Check.Eq(DungeonPathfinder.DoorwayAt(graph, geo, 16150.0, 16470.0, -24.0, 1.5, out _).Count, 0, "one in the big room's middle stands in no doorway"); + + // Laid again from 014F as it was (014F>0148 closed) and as it is now (the doorway's pairs closed). + var (x, y) = (16137.0, 16492.0); + foreach (bool whole in new[] { false, true }) + { + var closed = whole ? west : new HashSet { K(C014F, C0148) }; + var g = DungeonPathfinder.WithoutOpenings(graph, closed, C014F); + var route = DungeonPathfinder.BuildExploreRoute(g, C014F, null, geo, null, null, (x, y, -24.0), null, out _); + int behind = route.Points.Count(p => DungeonPathfinder.CellAt(graph, geo, p) is C0148 or C0147); + Console.WriteLine($" {(whole ? "whole doorway" : "014F>0148 only")} closed: {route.Points.Count} points, {behind} behind the doorway"); + DungeonPathfinder.MainRouteNote = null; + if (whole) Check.Eq(behind, 0, "the doorway closed whole: the walk keeps out of the rooms behind it"); + else Check.True(behind > 0, $"as it was, the walk went back through the same doorway ({behind})"); + } + } + finally + { + loader.Dispose(); + DungeonPathfinder.InvalidateCache(); + } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs index 0f5669d..4107426 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs @@ -239,6 +239,53 @@ internal static class TargetingTests FakeHost.WeaponCalls = true; FakeHost.CombatModeValue = CombatMode.Magic; Check.Eq(magic.Tick(), A, "magic: one on a balcony in sight is still a target"); + + // 2026-11-16, a Thread: in a building, an Armoredillo 5.5 m up and 8 m off in another of its cells + // (h 8.1, dz +5.5: a gentle slope by the rule above). It was locked and chased round under it. + Check.False(CombatManager.OutOfMeleeReachUpOrDown(9.8, 5.5), "by the slope alone it would be walked to"); + var balcony = new ScanPick(20); + balcony.Place(A, "Mob A", north: 8, up: 5.5); + FakeHost.Positions[Player] = (Lb | 0x0107, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0107, 96f, 96f, 0f); + FakeHost.Positions[A] = (Lb | 0x0100, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(balcony.Tick(), 0u, "melee, both inside, another cell 5.5 m up: not the target (the stairs first)"); + + // 2026-11-16 17:11, a Thread: the building's floor above 3.0 m up, the monsters in the next cell 2.5 m + // off; "more than 3 m" let them through and they were swung at from the floor below. + var floorAbove = new ScanPick(20); + floorAbove.Place(A, "Mob A", north: 2.5, up: 3.0); + FakeHost.Positions[Player] = (Lb | 0x0125, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0125, 96f, 96f, 0f); + FakeHost.Positions[A] = (Lb | 0x0126, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(floorAbove.Tick(), 0u, "melee, both inside, the next cell 3.0 m up: not the target"); + + var stair = new ScanPick(20); + stair.Place(A, "Mob A", north: 2.5, up: 2.0); + FakeHost.Positions[Player] = (Lb | 0x0125, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0125, 96f, 96f, 0f); + FakeHost.Positions[A] = (Lb | 0x0126, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(stair.Tick(), A, "the next cell 2.0 m up (a stair): still the target"); + + var hill = new ScanPick(20); + hill.Place(A, "Mob A", north: 8, up: 5.5); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(hill.Tick(), A, "outdoors, the same up a hillside: still the target"); + + var sameCell = new ScanPick(20); + sameCell.Place(A, "Mob A", north: 8, up: 5.5); + FakeHost.Positions[Player] = (Lb | 0x0107, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0107, 96f, 96f, 0f); + FakeHost.Positions[A] = (Lb | 0x0107, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(sameCell.Tick(), A, "inside, up a ramp in the same cell: still the target"); } public static void Register(Runner r) diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs index ac045f0..e76857c 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; using RynthCore.Plugin.RynthAi; @@ -25,6 +26,9 @@ internal static class VitalWandGateTests public static void Register(Runner r) { + r.Add("heal before stamina: health falling to Emergency Heal At within a stamina kit's 3 s: the healing kit goes, no stamina kit", HealBeforeStaminaWhenFalling); + r.Add("heal before stamina: health steady or falling slowly: the stamina kit goes as before", StaminaWhenHealthSteady); + r.Add("heal before stamina: the projection (latest high, at least 1 s of rate, 4 s window)", HealthProjection); r.Add("vital wand gate: out of Magic with a healing kit carried, Heal Self starts no wand swap (not handled)", HealRefusedWithKit); r.Add("vital wand gate: the refused Heal Self falls through to the kit despite Kit Min Success", KitDespiteMinSuccessAfterRefusal); r.Add("vital wand gate: a caster already wielded in melee stance: the Magic stance change only, no weapon move", StanceOnlyWithCasterWielded); @@ -32,20 +36,21 @@ internal static class VitalWandGateTests r.Add("vital wand gate: Revitalize with a stamina kit, Stamina to Mana in a fight, the script heal with a health potion: no swap", OtherVitalsRefused); r.Add("vital wand gate: a pure caster in Magic mode with a kit carried still casts Heal Self", PureCasterUnaffected); r.Add("vital wand gate: buffing still swaps to the wand with a kit carried", BuffsStillSwap); - r.Add("vital wand gate: Revitalize refused, no stamina potion: the stamina kit is used despite Kit Min Success", StaminaKitDespiteMinSuccess); + r.Add("vital wand gate: a stamina kit under Stamina Kit Min Success % is never used, with a weapon out too; Revitalize goes instead", StaminaKitDespiteMinSuccess); r.Add("vital wand gate: Stamina to Mana never swaps in a fight; out of one with no mana potion it may", ManaInFightNoSwap); r.Add("vital wand gate: in Magic stance with no wand in hand and a kit carried, Heal Self is not gated", MagicNoWandNotGated); r.Add("vital wand gate: a kit its line called used up, or gone from the client's pack, is no kit: Heal Self is handled and the swap is allowed", GoneKitAllowsSwap); r.Add("vital wand gate: a swap already under way finishes when a kit reappears (no abandoned swap, no kit mid-wield)", SwapInFlightFinishes); r.Add("vital wand gate: a kit the server refused 3 times within 10 s is no kit for the gate; a kit landing counts it again", RefusedKitAllowsSwap); - r.Add("vital wand gate: the mana step's stamina refill also uses the stamina kit despite Kit Min Success", ManaRefillStaminaLastResort); + r.Add("vital wand gate: the mana step's stamina refill respects Stamina Kit Min Success % too", ManaRefillStaminaLastResort); r.Add("vital wand gate: out of a fight Stamina to Mana may swap with a mana potion carried; in a fight it may not", ManaPotionOutOfFightSwaps); r.Add("vital wand gate: a refusal streak ages out: 11 s after the last refusal the kit counts again", RefusedStreakAgesOut); r.Add("vital wand gate: no wand found: Heal Self takes the bare-handed Magic stance, not gated", NoWandNotGated); r.Add("vital wand gate: one line when it starts refusing, one when the swap may go again or nothing asks for 5 s, one for a refused kit", GateLogLines); r.Add("vital wand gate: under Emergency Heal At the kit despite Kit Min Success still goes; the HP failsafe's recall still swaps to the wand", EmergencyFloorKept); - r.Add("vital wand gate: the between-fights top-off (no Revitalize) uses a stamina kit under Stamina Kit Min Success as the last resort", TopOffStaminaLastResort); + r.Add("vital wand gate: the between-fights top-off (no Revitalize) uses no stamina kit under Stamina Kit Min Success %", TopOffStaminaLastResort); r.Add("vital wand gate: at or under Emergency Heal At a health spell may swap to the wand with a kit carried (the surest heal goes)", EmergencySpellMaySwap); + r.Add("emergency heal: under Stamina To Health At but over Emergency Heal At, a melee character casts Stamina to Health, no kit first", StamToHealthLineFirst); r.Add("buffs wait: under Heal At in a fight no buff is cast and the arbiter isn't asked for buffs; over it or out of a fight they go on", BuffsWaitWhileHurt); } @@ -65,6 +70,42 @@ internal static class VitalWandGateTests Check.True(Why(a).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "with its reason: " + Why(a)); } + // 2026-11-13: Stamina To Health At over Emergency Heal At = the spell is the emergency heal. + private static void StamToHealthLineFirst() + { + var b = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 0); + S.HealAt = 0; S.TopOffHP = 0; S.EmergencyHealAt = 15; S.StaminaToHealthAt = 40; + b.InCombatOverride = () => true; + SetVitals(b, 35, 74, 100); + Check.True(b.CheckVitals(), "35% under Stamina To Health At 40%: the vitals act: " + Why(b)); + Check.Eq(FakeHost.UsesOn.Count, 0, "no kit ahead of the spell"); + Check.True(SwapActive(b), "Stamina to Health's wand swap is under way"); + + // Under Emergency Heal At too: the kit-first order is unchanged. + var k = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 0); + S.HealAt = 0; S.TopOffHP = 0; S.EmergencyHealAt = 15; S.StaminaToHealthAt = 40; + k.InCombatOverride = () => true; + SetVitals(k, 10, 74, 100); + Check.True(k.CheckVitals(), "10%: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "under Emergency Heal At the kit goes first, as before"); + + // Stamina at or under the floor: no spell, the normal chain (the kit) heals. + var f = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 0); + S.HealAt = 50; S.TopOffHP = 50; S.EmergencyHealAt = 15; S.StaminaToHealthAt = 40; + f.InCombatOverride = () => true; + SetVitals(f, 35, 10, 100); + Check.True(f.CheckVitals(), "35%, stamina 10%: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "no Stamina to Health under its stamina floor: the kit under Heal At"); + + // Defaults (30 / 30): both lines together, kit first as before. + var d = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 0); + S.HealAt = 0; S.TopOffHP = 0; S.EmergencyHealAt = 30; S.StaminaToHealthAt = 30; + d.InCombatOverride = () => true; + SetVitals(d, 25, 74, 100); + Check.True(d.CheckVitals(), "25% on the 30 / 30 defaults: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "defaults unchanged: the kit first"); + } + // 2026-11-07: four weapon auras in a row with a golem hitting him under Heal At; the emergency heal waited for the last cast. private static void BuffsWaitWhileHurt() { @@ -142,19 +183,25 @@ internal static class VitalWandGateTests Check.True(SwapActivity() > before, "the recall's wand swap starts with a kit and a potion carried"); } - // b2e1ade4: between fights out of Magic no Revitalize is cast for Top Off Stamina; kits still top off, - // and with this port a stamina kit under Stamina Kit Min Success % is that last resort. + // b2e1ade4: between fights out of Magic no Revitalize is cast for Top Off Stamina; kits still top off. + // 2026-11-13: a stamina kit under Stamina Kit Min Success % is not used (no last resort); the wand + // comes out for Revitalize instead (Tom), between fights too. private static void TopOffStaminaLastResort() { var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 95); b.InCombatOverride = () => false; S.TopOffStam = 60; S.RestamAt = 10; SetVitals(b, 100, 40, 100); - Check.True(b.CheckVitals(), "stamina 40% under Top Off Stamina 60%, no fight: acts"); - Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use"); - Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit"); - Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize"); - Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic stance"); + Check.True(b.CheckVitals(), "stamina 40% under Top Off Stamina 60%, no fight, kit under its %: acts: " + Why(b)); + Check.Eq(FakeHost.UsesOn.Count, 0, "no kit use under Stamina Kit Min Success %"); + Check.True(SwapActive(b), "the wand swap for Revitalize is under way"); + + var ok = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 0); + ok.InCombatOverride = () => false; + S.TopOffStam = 60; S.RestamAt = 10; + SetVitals(ok, 100, 40, 100); + Check.True(ok.CheckVitals(), "control, min 0: the top-off acts"); + Check.Eq(FakeHost.UsesOn.Count, 1, "control: the kit tops off"); } // Out of a fight buffing is about to swap to the wand anyway, so a @@ -183,10 +230,8 @@ internal static class VitalWandGateTests bool acted = (bool)typeof(BuffManager).GetMethod("AttemptManaRefill", Np)!.Invoke(b, args)!; Check.True(acted, "the mana step acts"); Check.True((bool)args[1], "by refilling stamina"); - Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use"); - Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit Kit Min Success skipped"); - Check.True(FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal)), "logged"); - Check.Eq(SwapActivity(), 0, "no swap"); + Check.Eq(FakeHost.UsesOn.Count, 0, "no kit under Stamina Kit Min Success %"); + Check.True(SwapActive(b), "Revitalize's wand swap goes instead (the kit under its % refuses nothing)"); } /// The kit sent and refused by the server (a UseDone with an error code). @@ -329,6 +374,71 @@ internal static class VitalWandGateTests Check.Eq(FakeHost.Wields.Count, 0, "no wield"); } + // 2026-11-11 16:24: Drakkon (Heal At 1, Emergency Heal At 30, Re-stam To 90) took three stamina kits in a + // row while a monster hit him, each started over 30%, and died. 2026-11-17: the heal goes first. + private static void HealBeforeStaminaWhenFalling() + { + var b = Rig(CombatMode.Melee, new[] { Kit, StamKit }, kitMinSuccess: 0); + S.HealAt = 1; S.TopOffHP = 95; S.EmergencyHealAt = 30; S.RestamAt = 50; S.RestamTo = 90; + DateTime now = new DateTime(2026, 1, 1, 18, 0, 0); + b.Clock = () => now; + SetVitals(b, 100, 100, 100); + b.CheckVitals(); // a reading at full health + Check.Eq(FakeHost.UsesOn.Count, 0, "full health, full stamina: nothing used"); + now = now.AddMilliseconds(1500); + SetVitals(b, 70, 30, 100); // 30% lost in 1.5 s: 60% more in a kit's 3 s + Check.True(b.CheckVitals(), "70% and falling 20%/s, stamina 30% under Re-stam At: the vitals act: " + Why(b)); + Check.Eq(FakeHost.UsesOn.Count, 1, "one use"); + Check.Eq(FakeHost.UsesOn[0].Source, Kit, "the healing kit, not the stamina kit"); + Check.True(FakeHost.Logs.Any(l => l.Contains("a heal first, the stamina after it", StringComparison.Ordinal)), "the line says why"); + } + + private static void StaminaWhenHealthSteady() + { + // Steady: the same health 1.5 s ago. + var b = Rig(CombatMode.Melee, new[] { Kit, StamKit }, kitMinSuccess: 0); + S.HealAt = 1; S.TopOffHP = 95; S.EmergencyHealAt = 30; S.RestamAt = 50; S.RestamTo = 90; + DateTime now = new DateTime(2026, 1, 1, 18, 0, 0); + b.Clock = () => now; + SetVitals(b, 70, 100, 100); + b.CheckVitals(); + now = now.AddMilliseconds(1500); + SetVitals(b, 70, 30, 100); + Check.True(b.CheckVitals(), "70% steady, stamina 30%: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one use"); + Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit, as before"); + + // Falling slowly: 100% to 90% over 3 s (10% more in a kit's 3 s, well over 30%). + var s = Rig(CombatMode.Melee, new[] { Kit, StamKit }, kitMinSuccess: 0); + S.HealAt = 1; S.TopOffHP = 95; S.EmergencyHealAt = 30; S.RestamAt = 50; S.RestamTo = 90; + DateTime t = new DateTime(2026, 1, 1, 18, 0, 0); + s.Clock = () => t; + SetVitals(s, 100, 100, 100); + s.CheckVitals(); + t = t.AddSeconds(3); + SetVitals(s, 90, 30, 100); + Check.True(s.CheckVitals(), "90% falling slowly, stamina 30%: the vitals act"); + Check.Eq(FakeHost.UsesOn.Count, 1, "one use"); + Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "slow fall: the stamina kit"); + } + + private static void HealthProjection() + { + DateTime t0 = new DateTime(2026, 1, 1, 18, 0, 0); + var none = new List<(DateTime, int)>(); + Check.Eq(BuffManager.ProjectedHealthPct(none, t0, 60, 3000), 60, "no samples: health as it is"); + var fall = new List<(DateTime, int)> { (t0, 100), (t0.AddMilliseconds(500), 100), (t0.AddMilliseconds(1500), 80) }; + // Latest high at +0.5 s, 20% lost in 1 s: 60% more over 3 s. + Check.Eq(BuffManager.ProjectedHealthPct(fall, t0.AddMilliseconds(1500), 80, 3000), 20, "20%/s from the latest high: 80 -> 20"); + var hit = new List<(DateTime, int)> { (t0, 100) }; + // One hit 0.2 s after the reading: the rate is taken over 1 s, not 0.2 s. + Check.Eq(BuffManager.ProjectedHealthPct(hit, t0.AddMilliseconds(200), 90, 3000), 60, "one hit: over at least 1 s (10%/s -> 60)"); + var rising = new List<(DateTime, int)> { (t0, 40), (t0.AddMilliseconds(1000), 70) }; + Check.Eq(BuffManager.ProjectedHealthPct(rising, t0.AddMilliseconds(1000), 70, 3000), 70, "rising: health as it is"); + var stale = new List<(DateTime, int)> { (t0, 100) }; + Check.Eq(BuffManager.ProjectedHealthPct(stale, t0.AddMilliseconds(5000), 50, 3000), 50, "a high older than the 4 s window is no trend"); + } + private static void SetVitals(BuffManager b, uint health, uint stamina, uint mana) { var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", Np)!.GetValue(b)!; @@ -343,13 +453,18 @@ internal static class VitalWandGateTests S.RestamAt = 50; SetVitals(b, 100, 20, 100); Check.True(b.CheckVitals(), $"min {minSuccess}: stamina 20% under Re-stam At 50%: the chain acts"); - Check.Eq(FakeHost.UsesOn.Count, 1, $"min {minSuccess}: one kit use"); - Check.Eq(FakeHost.UsesOn[0].Source, StamKit, $"min {minSuccess}: the stamina kit"); - bool lastResort = FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal)); - if (minSuccess == 95) Check.True(lastResort, "under Kit Min Success: used as the last resort, logged"); - else Check.False(lastResort, "control, chance fine: the normal kit use, no last-resort line"); - Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, $"min {minSuccess}: no Magic stance"); - Check.Eq(FakeHost.Casts.Count, 0, $"min {minSuccess}: no Revitalize"); + if (minSuccess == 95) + { + Check.Eq(FakeHost.UsesOn.Count, 0, "under Stamina Kit Min Success % (weapon out, no 30% bar): no kit"); + Check.True(SwapActive(b), "Revitalize's wand swap goes instead"); + } + else + { + Check.Eq(FakeHost.UsesOn.Count, 1, "control, min 0: one kit use"); + Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "control: the stamina kit"); + Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "control: no Magic stance"); + Check.Eq(FakeHost.Casts.Count, 0, "control: no Revitalize"); + } } } diff --git a/Tools/RynthLua.CompatTests/FakeHost.cs b/Tools/RynthLua.CompatTests/FakeHost.cs index f580ecb..346b455 100644 --- a/Tools/RynthLua.CompatTests/FakeHost.cs +++ b/Tools/RynthLua.CompatTests/FakeHost.cs @@ -27,7 +27,7 @@ internal static unsafe class FakeHost public static RynthCoreApiNative Build() { - var a = new RynthCoreApiNative { Version = 73 }; + var a = new RynthCoreApiNative { Version = 85 }; // 85: the server prompt answers (AnswerNextPrompt) a.LogFn = (IntPtr)(delegate* unmanaged[Cdecl])&LogImpl; a.WriteToChatFn = (IntPtr)(delegate* unmanaged[Cdecl])&WriteToChat; a.InvokeChatParserFn = (IntPtr)(delegate* unmanaged[Cdecl])&InvokeChatParser; @@ -109,6 +109,8 @@ internal static unsafe class FakeHost a.TradeDeclineFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeDecline; a.TradeResetFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeReset; a.TradeCloseFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeClose; + a.ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl])&ArmConfirmation; + a.GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLastConfirmation; return a; } @@ -127,6 +129,27 @@ internal static unsafe class FakeHost // ── Identity ──────────────────────────────────────────────────────────── + // ── The server's yes/no prompts (API v85) ── + // The last arm a script made, and the last prompt the "server" sent (the harness sets it). + public static uint ArmType; + public static int ArmMinPercent, ArmTimeoutMs, ArmCalls; + public static int PromptSeq, PromptPercent = -1, PromptOutcome, PromptAgeMs; + public static uint PromptType, PromptContext; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int ArmConfirmation(uint type, int minPercent, int timeoutMs) + { + ArmType = type; ArmMinPercent = minPercent; ArmTimeoutMs = timeoutMs; ArmCalls++; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetLastConfirmation(uint* type, uint* context, int* percent, int* outcome, int* ageMs) + { + *type = PromptType; *context = PromptContext; *percent = PromptPercent; *outcome = PromptOutcome; *ageMs = PromptAgeMs; + return PromptSeq; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetPlayerId() => FakeWorld.Player; diff --git a/Tools/RynthLua.CompatTests/Harness.cs b/Tools/RynthLua.CompatTests/Harness.cs index 9d8c781..61595a8 100644 --- a/Tools/RynthLua.CompatTests/Harness.cs +++ b/Tools/RynthLua.CompatTests/Harness.cs @@ -84,6 +84,20 @@ internal static class Harness } Fn("chat", a => { W.IncomingChat(Str(a, 0), (int)Num(a, 1, 0)); return DynValue.Nil; }); + // The server prompt answers: what the script armed, and the last prompt the "server" sent. + Fn("promptArm", a => + { + var t = new Table(s); + t["Type"] = (double)FakeHost.ArmType; t["MinPercent"] = (double)FakeHost.ArmMinPercent; + t["TimeoutMs"] = (double)FakeHost.ArmTimeoutMs; t["Calls"] = (double)FakeHost.ArmCalls; + return DynValue.NewTable(t); + }); + Fn("setLastPrompt", a => + { + FakeHost.PromptSeq = (int)Num(a, 0); FakeHost.PromptType = (uint)Num(a, 1); FakeHost.PromptContext = (uint)Num(a, 2); + FakeHost.PromptPercent = (int)Num(a, 3, -1); FakeHost.PromptOutcome = (int)Num(a, 4); FakeHost.PromptAgeMs = (int)Num(a, 5); + return DynValue.Nil; + }); Fn("chatInput", a => { int eat = 0; diff --git a/Tools/RynthLua.CompatTests/Scripts/character.lua b/Tools/RynthLua.CompatTests/Scripts/character.lua index 3ac3353..a6e7d7d 100644 --- a/Tools/RynthLua.CompatTests/Scripts/character.lua +++ b/Tools/RynthLua.CompatTests/Scripts/character.lua @@ -23,6 +23,34 @@ eq(Character.BurdenUnits, 1500, "BurdenUnits") eq(Character.MaxBurdenUnits, 200 * 150, "MaxBurdenUnits") eq(Character.IsBusy(), false, "IsBusy()") +-- the server's yes/no prompts (AnswerNextPrompt / LastPrompt) +eq(Character.LastPrompt, nil, "LastPrompt: none this session") +eq(Character.AnswerNextPrompt(), true, "AnswerNextPrompt() arms") +local arm = harness.promptArm() +eq(arm.Type, 7, "default type YESNO") +eq(arm.TimeoutMs, 5000, "default 5 s") +eq(arm.MinPercent, 0, "default: Yes whatever the percent") +eq(Character.AnswerNextPrompt(ClientConfirmationType.CRAFT_INTERACTION, 90000, 70), true, "a craft prompt") +arm = harness.promptArm() +eq(arm.Type, 5, "CRAFT_INTERACTION") +eq(arm.TimeoutMs, 30000, "the timeout is capped at 30 s") +eq(arm.MinPercent, 70, "Yes from 70%") +eq(Character.AnswerNextPrompt(9), false, "an unknown type is refused") +eq(harness.promptArm().Calls, 2, "and not armed") +eq(Character.AnswerNextPrompt(7, 0), true, "0 ms disarms") +eq(harness.promptArm().TimeoutMs, 0, "disarm sent") +harness.setLastPrompt(4, 7, 0x1234, -1, 2, 150) +local lp = Character.LastPrompt +check(lp ~= nil, "LastPrompt after one") +eq(lp.Seq, 4, "LastPrompt.Seq") +eq(lp.Type, 7, "LastPrompt.Type") +eq(lp.ContextId, 0x1234, "LastPrompt.ContextId") +eq(lp.Percent, -1, "LastPrompt.Percent: none in its text") +eq(lp.Outcome, "Accepted", "LastPrompt.Outcome") +eq(lp.AgeMs, 150, "LastPrompt.AgeMs") +harness.setLastPrompt(5, 7, 0, -1, 1, 10) +eq(Character.LastPrompt.Outcome, "Shown", "not armed: the client's dialog") + -- stats the UB way (on the weenie) and with the vital numbering UB uses local vitals = Character.Weenie.Vitals eq(vitals[VitalId.Health].Current, 300, "Health.Current") diff --git a/Tools/RynthLua.CompatTests/Scripts/deathline.lua b/Tools/RynthLua.CompatTests/Scripts/deathline.lua new file mode 100644 index 0000000..9bc2c78 --- /dev/null +++ b/Tools/RynthLua.CompatTests/Scripts/deathline.lua @@ -0,0 +1,15 @@ +-- DreamWeave's death line ("... (Killing blow: N damage. You had H/M health.)") fires OnDeath +-- (2026-11-15: a script missed one, the health read having skipped the 0 too). +local death +game.Character.OnDeath.Add(function(e) death = e end) +sleep(700) + +harness.chat("You are fatally punctured by Zefir Knotbinder! (Killing blow: 130 damage. You had 21/346 health.)", ChatMessageType.System) +local t = 0 +while not death and t < 3000 do sleep(20); t = t + 20 end +check(death ~= nil, "OnDeath on DreamWeave's killing-blow line") +if death then + check(death.Text:find("Killing blow", 1, true) ~= nil, "OnDeath.Text is the line") +end + +done() diff --git a/Tools/RynthOracle.Tests/Program.cs b/Tools/RynthOracle.Tests/Program.cs index abfd5e7..c64b034 100644 --- a/Tools/RynthOracle.Tests/Program.cs +++ b/Tools/RynthOracle.Tests/Program.cs @@ -66,6 +66,7 @@ namespace RynthOracle.Tests SkillsTabs(); ServerMove(); Replies(); + ReadyEarly(); Console.WriteLine($"{_pass} passed, {_fail} failed"); return _fail == 0 ? 0 : 1; } diff --git a/Tools/RynthOracle.Tests/ReadyEarlyTests.cs b/Tools/RynthOracle.Tests/ReadyEarlyTests.cs new file mode 100644 index 0000000..6912a1e --- /dev/null +++ b/Tools/RynthOracle.Tests/ReadyEarlyTests.cs @@ -0,0 +1,77 @@ +using System; +using RynthCore.Plugin.RynthOracle.Data; + +namespace RynthOracle.Tests +{ + // R-20261110-155059-e947 (2026-11-13): every daily quest showed "ready" hours early; the server + // turned one down with "You may complete this quest again in 2h 50m 42s." /myquests had been read + // once, at a login 34 hours before, so a quest done since kept its older stamp. The store now asks + // for a fresh read when the server turns a quest down or the flags on screen are old. + internal static partial class Program + { + private static void ReadyEarly() + { + DateTime now = DateTime.UtcNow; // the store stamps its reads with the real clock + long ms = 1_000_000; + long Unix(DateTime t) => new DateTimeOffset(t).ToUnixTimeSeconds(); + + // The login read: the daily (20 h timer) was last done 30 h before. Ready, rightly, then. + var store = new QuestFlagStore(); + Check(!store.NeedsReread(now, timersInUse: true), "ready-early: no re-read before the first read (the login read does that)"); + store.OnChatLine($"dailyquesttimer - 5 solves ({Unix(now.AddHours(-30))})\"Daily\" -1 72000", ms); + store.Tick(ms + 2_000); + Check(store.TryGet("dailyquesttimer", out QuestFlag before) && before.Ready(now), "ready-early: the login read has the daily ready"); + Check(!store.NeedsReread(now.AddMinutes(5), timersInUse: true), "ready-early: fresh flags on screen aren't re-read"); + Check(!store.NeedsReread(now.AddHours(5), timersInUse: false), "ready-early: old flags nobody looks at aren't re-read"); + Check(store.NeedsReread(now.AddMinutes(11), timersInUse: true), "ready-early: flags over 10 min old on screen are re-read"); + + // Hours later the player turns it in and the server says no (they did it again after the + // login read). The pasted lines, with the chat timestamp. + DateTime said = now.AddMinutes(5); + ms += 300_000; + Check(store.OnChatLine("9:45:47 You have solved this quest too recently!", ms, said) == MyQuestsLine.TooRecent, + "ready-early: 'solved this quest too recently' is recognised"); + Check(store.OnChatLine("9:45:47 You may complete this quest again in 2h 50m 42s.", ms + 1, said) == MyQuestsLine.TooRecent, + "ready-early: 'again in' is recognised"); + TimeSpan wait = new(2, 50, 42); + Check(store.LastServerWait is { } w && w.Left == wait && w.AtUtc == said, "ready-early: the server's wait is kept: " + store.LastServerWait); + Check(store.RereadWanted && store.NeedsReread(said, timersInUse: false), "ready-early: the turn-down asks for a fresh read, on screen or not"); + Check(store.WaitingAbout(wait, said, TimeSpan.FromMinutes(2)).Count == 0, "ready-early: the stale flags have no quest that long from ready"); + + // The fresh read: completed 20 h - 2:50:42 before the server's line. + int sent = 0; + Check(store.Request(_ => { sent++; return true; }, ms + 10_000) && sent == 1, "ready-early: the re-read sends /myquests"); + DateTime redone = said - (TimeSpan.FromSeconds(72000) - wait); + store.OnChatLine($"dailyquesttimer - 6 solves ({Unix(redone)})\"Daily\" -1 72000", ms + 10_200); + store.Tick(ms + 12_000); + Check(!store.RereadWanted && !store.NeedsReread(said, timersInUse: true), "ready-early: the reply ends the re-read"); + Check(store.TryGet("dailyquesttimer", out QuestFlag after) && !after.Ready(said) + && QuestTimer.State(after, true, said, out string text) == QuestTimerState.Waiting && text == "2h 50m", + "ready-early: after the re-read the daily waits 2h 50m, as the server said"); + var near = store.WaitingAbout(wait, said, TimeSpan.FromMinutes(2)); + Check(near.Count == 1 && near[0].Flag.Key == "dailyquesttimer" && near[0].Off.Duration() < TimeSpan.FromSeconds(2), + "ready-early: the server's wait points at the daily in the fresh read"); + + // The lines only count whole: quoted in a tell, they're chat. + var s2 = new QuestFlagStore(); + Check(s2.OnChatLine("Someone tells you, \"You may complete this quest again in 1h 0m 0s.\"", 1) == MyQuestsLine.None + && s2.OnChatLine("Someone tells you, \"You have solved this quest too recently!\"", 2) == MyQuestsLine.None + && !s2.RereadWanted, "ready-early: a quoted turn-down is ordinary chat"); + Check(QuestFlagStore.TryParseAgainIn("You may complete this quest again in 1d 3h 0m 5s.", out TimeSpan d) + && d == new TimeSpan(1, 3, 0, 5), "ready-early: days in the wait"); + Check(QuestFlagStore.TryParseAgainIn("You may complete this quest again in 12m 4s.", out TimeSpan m) && m == new TimeSpan(0, 12, 4), + "ready-early: a short wait"); + Check(!QuestFlagStore.TryParseAgainIn("You may complete this quest again in a while.", out _), "ready-early: no number, no wait"); + + // A server without /myquests is never re-read; a logout forgets the wish. + var s3 = new QuestFlagStore(); + s3.OnChatLine("alpha - 1 solves (1719432000)\"A\" -1 72000", 10); + s3.Tick(5_000); + s3.OnChatLine(QuestFlagStore.DisabledText, 6_000); + s3.WantReread(); + Check(!s3.NeedsReread(DateTime.UtcNow.AddHours(1), timersInUse: true), "ready-early: no re-read where /myquests is off"); + s3.Clear(); + Check(!s3.RereadWanted && s3.LastServerWait == null, "ready-early: Clear forgets the re-read"); + } + } +}