From 95282c83fa982792e18aea4e7119f1c7e057b74f Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 29 Nov 2026 22:28:29 -0500 Subject: [PATCH] RynthSuite as of 2026-11-29 (internal 3c6745b): release 2026.11.29.1 --- .../CorpseOpenController.cs | 104 +++++++++-- .../DungeonPathfinder.Portals.cs | 2 +- .../DungeonPathfinder.cs | 26 ++- .../Loot/LootModes.cs | 3 + .../NavigationEngine.VendorVisit.cs | 128 +++++++++++++ .../NavigationEngine.cs | 57 ++++-- .../RynthAiCommands.cs | 51 +++++- .../RynthAiPlugin.PatrolPortals.cs | 85 ++++++++- .../RynthAiPlugin.RareCorpses.cs | 117 ++++++++++++ .../Tests/ActionPacingTests.cs | 47 +++++ .../Tests/DunRouteTests.cs | 52 ++++++ .../Tests/LootRaresModeTests.cs | 111 +++++++++++- .../Tests/NavEngineTests.cs | 169 ++++++++++++++++++ 13 files changed, 916 insertions(+), 36 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.VendorVisit.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 1cfc613..1f8ad17 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -699,6 +699,7 @@ public sealed partial class RynthAiPlugin { CancelManualChestReopen(unchecked((int)vendorId), "a vendor was opened"); _metaManager?.OnVendorOpen(vendorId); + _navigationEngine?.NoteVendorOpened(vendorId); // a nav Vendor point waits for this (NavigationEngine.VendorVisit.cs) // AutoVendor prints the open line itself (UB's merchant-info line when it can read the // vendor, once per open rather than on every list re-send) and may start a session. @@ -933,7 +934,7 @@ public sealed partial class RynthAiPlugin // Same gate as HasLootWork: this claim runs every tick whatever the arbiter // decided, so without it a full pack still claimed the next corpse. Your own // corpse is let through unless no pack has a slot at all. - if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) + if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters) && !RareCorpseBypassesPackGate(settings, maxMeters)) { _lootSkipWhy = "the pack is full (Stop Looting When Pack Full)"; return; @@ -1263,6 +1264,8 @@ public sealed partial class RynthAiPlugin int playerId = unchecked((int)_playerId); WorldObject? ownCorpse = null; double ownDistance = double.MaxValue; + WorldObject? rareCorpse = null; + double rareDistance = double.MaxValue; foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) { if (candidate.ObjectClass != AcObjectClass.Corpse) @@ -1302,6 +1305,14 @@ public sealed partial class RynthAiPlugin continue; } + // Then a corpse that generated a rare beats the others (2026-11-29): it goes before a full + // pack can stop looting (RynthAiPlugin.RareCorpses.cs). + if (IsRareCorpse(decision.LongDesc)) + { + if (rareCorpse == null || dist < rareDistance) { rareCorpse = candidate; rareDistance = dist; } + continue; + } + if (dist >= distanceMeters) continue; @@ -1314,6 +1325,11 @@ public sealed partial class RynthAiPlugin corpse = ownCorpse; distanceMeters = ownDistance; } + else if (rareCorpse != null) + { + corpse = rareCorpse; + distanceMeters = rareDistance; + } return corpse != null; } @@ -1333,6 +1349,11 @@ public sealed partial class RynthAiPlugin /// it) but never a stream of them; Recover My Corpse keeps its own 5 s ask (RequestOwnCorpseId). At most /// CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with many uncached /// corpses in range does not burst. + /// Loot Only Rare Corpses is the other re-asker (RareCorpseIdWaitInRange): its corpses wait unclaimed for + /// the description, so none of them is ever the target, and one whose only accepted request was dropped + /// stayed closed for good, a rare on it or not (found 2026-11-29 checking a Discord question about whether + /// rare-only looting opens corpses with higher-tier rares: tier never mattered, a lost ID did). Each one in + /// loot range is asked again on the same clock and cap. /// private void TryRequestCorpseId(WorldObject corpse, string longDesc) { @@ -1342,8 +1363,9 @@ public sealed partial class RynthAiPlugin bool candidate = corpse.Id == _targetCorpseId || (_openedContainerId != 0 && corpse.Id == _openedContainerId); int asks = _corpseIdAskCount.TryGetValue(corpse.Id, out int askCount) ? askCount : 0; bool due = !_corpseIdRequested.Contains(corpse.Id) - || (candidate && asks <= CorpseIdMaxReasks && CorpseNameNeeded() - && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs); + || (asks <= CorpseIdMaxReasks + && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs + && (candidate ? CorpseNameNeeded() : RareCorpseIdWaitInRange(corpse))); if (!due || _corpseIdAcceptedThisTick >= CorpseIdPerTick) return; if (_corpseIdRefusedAt.TryGetValue(corpse.Id, out long refusedAt) && idNow - refusedAt < CorpseIdRefusedRetryMs) return; if (Host.RequestId(unchecked((uint)corpse.Id))) @@ -1363,6 +1385,16 @@ public sealed partial class RynthAiPlugin /// The loot mode reads the killer name (My Kills Only, Fellowship Kills); All Corpses does not. private bool CorpseNameNeeded() => (_dashboard?.Settings?.LootOwnership ?? 0) < 2; + /// Loot Only Rare Corpses is on and this unidentified corpse is within the corpse approach range: + /// it opens only once its description says it generated a rare, so its ID is worth asking for again. A + /// corpse farther out gets its one request; it is asked again once the bot comes within range of it. + private bool RareCorpseIdWaitInRange(WorldObject corpse) + { + var settings = _dashboard?.Settings; + if (settings?.LootOnlyRareCorpses != true || _objectCache == null || _playerId == 0) return false; + return _objectCache.Distance(unchecked((int)_playerId), corpse.Id) <= GetCorpseApproachRangeMaxMeters(settings); + } + private CorpseLootDecision EvaluateCorpseLootDecision(WorldObject? corpse) { var settings = _dashboard?.Settings; @@ -1870,6 +1902,7 @@ public sealed partial class RynthAiPlugin string matchActionLabel = string.Empty; string matchRuleLabel = string.Empty; bool matchIsSalvage = false; + bool matchIsRare = false; foreach (WorldObject item in containedItems) { @@ -1949,7 +1982,9 @@ public sealed partial class RynthAiPlugin // A keeper already judged on this open is judged again only when its turn comes (it // is the first match): that fresh pass is what Keep # and the mana stone cap count // against. Re-running the profile on every waiting keeper each pass did nothing else. - if (firstMatchId != 0 && _lootEvalLogged.TryGetValue(item.Id, out string? judged) && judged.StartsWith("KEEP", StringComparison.Ordinal)) + // A rare is the exception: it goes first (below), so it is judged every pass. + bool isRareItem = RareItems.IsRare(Host, item, out _); + if (firstMatchId != 0 && !isRareItem && _lootEvalLogged.TryGetValue(item.Id, out string? judged) && judged.StartsWith("KEEP", StringComparison.Ordinal)) continue; // Evaluate against loot profile — pure classification, no UseObject. @@ -1985,14 +2020,16 @@ public sealed partial class RynthAiPlugin if (classified) { - // First match wins — save it for pickup below - if (firstMatchId == 0) + // First match wins — save it for pickup below. A rare beats any other match: it is + // taken before a full pack or a corpse timeout can end the corpse (2026-11-29). + if (firstMatchId == 0 || (isRareItem && !matchIsRare)) { firstMatchId = item.Id; matchItemName = item.Name ?? string.Empty; matchActionLabel = actionLabel; matchRuleLabel = ruleLabel; matchIsSalvage = isSalvage; + matchIsRare = isRareItem; } // Don't break — keep evaluating to mark non-matches processed } @@ -2037,8 +2074,9 @@ public sealed partial class RynthAiPlugin // Keep room for weapon swaps: with a full pack the bow can't be put away to // switch to the wand, so buffs and spell heals stop (2026-09-28 death). Leave // the corpse rather than filling the last slots; -1 = side-pack capacity unknown. + // A rare may take a reserved slot: it is never left for the swap room (2026-11-29). int freeSlots = WorldObjectCache.CountFreeItemSlots(Host, _objectCache); - if (freeSlots >= 0 && freeSlots < WorldObjectCache.LootReserveFreeSlots) + if (freeSlots >= 0 && freeSlots < WorldObjectCache.LootReserveFreeSlots && !(matchIsRare && freeSlots > 0)) { if (LastPickupSettling(now)) return; // the last item lands first, then the corpse closes @@ -3539,7 +3577,8 @@ public sealed partial class RynthAiPlugin // No room anywhere: don't start on another corpse (IsPackFull says so once in chat). // Your own corpse is let through unless no pack has a slot at all. - if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, GetCorpseApproachRangeMaxMeters(settings))) + if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, GetCorpseApproachRangeMaxMeters(settings)) + && !RareCorpseBypassesPackGate(settings, GetCorpseApproachRangeMaxMeters(settings))) return false; // An open chest the player or a meta opened, eligible to loot (RynthAiPlugin.ChestLoot.cs). @@ -3882,6 +3921,18 @@ public sealed partial class RynthAiPlugin if (LootModes.IsRares(settings.LootMode)) return ClassifyRaresMode(item, settings, preview, out actionLabel, out ruleLabel, out builtIn); + // A rare is always kept, ahead of the loot profile and every other built-in keep (2026-11-29: no + // rare may be left on a corpse). A profile with no rule for rares left it on the corpse, a + // Salvage rule that matched it salvaged it, and Mana Tap drained one no rule wanted. + if (RareItems.IsRare(Host, item, out string rareHow)) + { + if (!preview) { _corpseItemsEvaluated++; _corpseMatchedIds.Add(item.Id); } + actionLabel = "Keep"; + ruleLabel = RareItems.AlwaysKeptRule; + builtIn = $"a rare ({rareHow}): rares are always kept, whatever the loot profile says"; + return true; + } + // Learn unknown spells (VTank ReadUnknownScrolls): a built-in rule ahead of the loot // profile, as in VTank. A scroll of a spell we don't know and can learn is looted to read. if (_scrollLearner != null && _scrollLearner.ShouldLootFromCorpse(item, out string learnRule, out string learnWhy, preview)) @@ -4325,6 +4376,10 @@ public sealed partial class RynthAiPlugin // counts for an item that has one.) if (tapSettings != null && LootModes.IsRares(tapSettings.LootMode)) return false; + // A rare shown by its rare icon is kept in every mode (ClassifyLootItem), so no rule needs its + // ID: waiting for one that never came left it on the corpse ("left: no ID came"). + if (RareItems.IsRare(Host, item, out _)) + return false; bool manaTapNeedsId = tapSettings != null && tapSettings.EnableManaTapping && tapSettings.ManaTapMinMana > 0 && _manaStoneManager != null; @@ -4425,10 +4480,15 @@ public sealed partial class RynthAiPlugin return; } - _completedCorpses[corpseId] = CorpseNowMs; + // A rare still on it: set aside and looted again, not marked done (RynthAiPlugin.RareCorpses.cs). + bool rareLeft = SetAsideForRareLeft(corpseId, CorpseNowMs); + if (!rareLeft) + { + _completedCorpses[corpseId] = CorpseNowMs; + _corpseCooldownUntil.Remove(corpseId); + } EndBoostLootKillWait(corpseId); EndDeathWaitFor(corpseId); - _corpseCooldownUntil.Remove(corpseId); _processedCorpseItems.Clear(); _corpseItemAttempts.Clear(); _corpseIdsRequested = false; @@ -4460,7 +4520,7 @@ public sealed partial class RynthAiPlugin // Your own death corpse has its own end line (FinishOwnCorpseRecovery). WorldObject? doneCorpse = _objectCache?[corpseId]; string corpseName = doneCorpse?.Name is { Length: > 0 } cn ? cn : $"0x{(uint)corpseId:X8}"; - if ((doneCorpse == null || !EvaluateCorpseLootDecision(doneCorpse).IsOwnDeathCorpse) + if (!rareLeft && (doneCorpse == null || !EvaluateCorpseLootDecision(doneCorpse).IsOwnDeathCorpse) && NothingLootedLine(corpseName) is { } nothingLine) ChatLine(nothingLine); LootDiag($"[RynthAi] Corpse loot: completed 0x{(uint)corpseId:X8}, releasing container."); @@ -4960,6 +5020,7 @@ public sealed partial class RynthAiPlugin _corpseIdAskCount.Remove(sid); _corpseSkipLogged.Remove(sid); _corpseWaitingSince.Remove(sid); + _rareLeftRetries.Remove(sid); // If this is the corpse we were actively looting (container was open and we received // at least one inventory update), mark it completed before resetting. Without this, @@ -4970,8 +5031,17 @@ public sealed partial class RynthAiPlugin // taken, the mark prevents the pointless re-open. if (_targetCorpseId == sid && _openedContainerId == sid && _openedContainerInventoryObservedAt != 0) { - LootDiag($"[RynthAi] Corpse loot: corpse 0x{objectId:X8} left range mid-loot; marking completed to prevent re-open."); - _completedCorpses[sid] = CorpseNowMs; + // Not with a rare still on it: seen again, it is opened again (RynthAiPlugin.RareCorpses.cs). + if (RareStillOn(sid) is { } rare) + { + LootDiag($"[RynthAi] Corpse loot: corpse 0x{objectId:X8} left range mid-loot with the rare '{rare.Name}' still on it; not marked, so it is looted again if seen."); + ChatLine($"[RynthAi] {CorpseNameFor(sid)} went out of range with a rare still on it: {rare.Name}. It is looted again if it comes back in range."); + } + else + { + LootDiag($"[RynthAi] Corpse loot: corpse 0x{objectId:X8} left range mid-loot; marking completed to prevent re-open."); + _completedCorpses[sid] = CorpseNowMs; + } } if (_targetCorpseId == sid) @@ -5141,7 +5211,7 @@ public sealed partial class RynthAiPlugin /// private bool CanClaimNextCorpse(LegacyUiSettings settings, double maxMeters) { - if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) return false; + if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters) && !RareCorpseBypassesPackGate(settings, maxMeters)) return false; if (_useRefusals.HoldsOpens(CorpseNowMs)) return false; if (string.Equals(settings.BotAction, "Buffing", StringComparison.OrdinalIgnoreCase)) return false; if (_manaStoneManager?.HoldsLootForDrain() == true) return false; @@ -5267,8 +5337,14 @@ public sealed partial class RynthAiPlugin _corpseAbandonCounts.Remove(corpseId); ChatLine($"[RynthAi] Own corpse: giving up after {abandons} tries; recover what is left on it by hand."); } + else if (wasOpened && SetAsideForRareLeft(corpseId, now)) + { + // A rare still on it: set aside and looted again (RynthAiPlugin.RareCorpses.cs). + } else if (wasOpened || abandons >= 3) { + if (!wasOpened) + SayRareCorpseUnopened(corpseId); _completedCorpses[corpseId] = now; _corpseCooldownUntil.Remove(corpseId); _corpseAbandonCounts.Remove(corpseId); diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs index 8483eaf..1a6ab2e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs @@ -490,7 +490,7 @@ internal static partial class DungeonPathfinder foreach (uint nb in n.Neighbors) if (Closed(id, nb)) { touched = true; break; } if (!touched) { g[id] = n; continue; } - var copy = new DungeonNavNode { CellId = n.CellId, NS = n.NS, EW = n.EW, Z = n.Z }; + var copy = new DungeonNavNode { CellId = n.CellId, NS = n.NS, EW = n.EW, Z = n.Z, Visible = n.Visible }; foreach (uint nb in n.Neighbors) if (!Closed(id, nb)) copy.Neighbors.Add(nb); g[id] = copy; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs index 6413780..be2aee5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs @@ -40,6 +40,13 @@ internal sealed class DungeonNavNode public double NS, EW; public float Z; public List Neighbors = new(); // portal-connected cells only + /// + /// The cells seen from this one (cell.dat's visible-cell list, full cell ids; this one not in it), null when + /// not read (a hand-built graph). Never walking adjacency: it is what the server sends the client from + /// (ACE ObjectMaint.GetVisibleObjects: an indoor cell's objects and its visible cells' objects), so an + /// object in one of these cells is known to the client (a patrol's remembered portals, PortalShouldBeKnown). + /// + public uint[]? Visible; } internal static partial class DungeonPathfinder @@ -174,6 +181,22 @@ internal static partial class DungeonPathfinder neighbors.Add(nid); } + // The visible-cell list (ushort low words), right after the portal records: what the server sends the + // client from this cell (DungeonNavNode.Visible). Not adjacency: kept apart from Neighbors. + uint[]? visible = null; + if (ms.Position + numVisibleCells * 2L <= ms.Length) + { + var vis = new List(numVisibleCells); + for (int i = 0; i < numVisibleCells; i++) + { + ushort lo = reader.ReadUInt16(); + if (lo < 0x0100 || lo > 0xFFFD) continue; + uint vid = (landblockKey << 16) | lo; + if (vid != cellId) vis.Add(vid); + } + visible = vis.ToArray(); + } + // worldX = lbX × 192 + posX → EW = (worldX/24 − 1019.5) / 10 double ew = ((posX + gx) / 24.0 - 1019.5) / 10.0; double ns = ((posY + gy) / 24.0 - 1019.5) / 10.0; @@ -184,7 +207,8 @@ internal static partial class DungeonPathfinder NS = ns, EW = ew, Z = posZ, - Neighbors = neighbors + Neighbors = neighbors, + Visible = visible, }; } catch { /* malformed cell — skip */ } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs index 1f6c7d1..3bba953 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootModes.cs @@ -66,6 +66,9 @@ internal static class RareItems public const uint IconUnderlayKey = 52; public const uint RareUnderlay = 23308; // 0x5B0C, the low 24 bits of 0x06005B0C + /// The rule label of a rare in Profile mode: kept ahead of the loot profile (ClassifyLootItem). + public const string AlwaysKeptRule = "Rare (always kept)"; + /// True for a rare; says which mark showed it. public static bool IsRare(RynthCoreHost host, WorldObject item, out string how) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.VendorVisit.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.VendorVisit.cs new file mode 100644 index 0000000..aa48916 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.VendorVisit.cs @@ -0,0 +1,128 @@ +// ============================================================================ +// RynthSuite - NavigationEngine.VendorVisit.cs +// VTank "Vendor" nav points (OpenVendor, type 5): walk to the point, open the vendor, let +// AutoVendor trade, then go on (2026-11-29). +// +// NavRouteParser has always read type 5 (the vendor's id and name), but the point-type dispatch +// handled only Pause, Chat, Recall, Portal and NPC, so a Vendor point was walked like a plain +// waypoint and passed without the vendor being opened: a nav's sell or restock stop did nothing +// (the same gap NPC points had until 11-23, NavigationEngine.NpcTalk.cs). +// +// Now a Vendor point is walked to like any waypoint; on arriving (or passing it) the bot stops and +// uses the vendor by name, the nearest one with that name, as an NPC point does (FirePortalNpcUse: +// AC walks the character over and opens the vendor). Opening a vendor starts AutoVendor when it is +// on (AutoVendorManager.OnVendorOpen), and AutoVendor holds the whole bot while it trades, so nav +// doesn't tick again until it is done. The plugin tells nav when a vendor window opens +// (NoteVendorOpened); once it has, and VendorAfterOpenMs has passed, the route goes on. A vendor +// that can't be found in NpcFindTimeoutMs, or whose window doesn't open within VendorOpenMaxMs of +// the use, is said once in chat and the route goes on without it. +// ============================================================================ + +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +internal sealed partial class NavigationEngine +{ + /// After the use, how long the vendor's window may take to open (a long walk over, a busy client). + internal const long VendorOpenMaxMs = 20_000; + + /// + /// After the window opens: standing still this long before going on. AutoVendor starts in the open + /// itself and holds the bot until it is done, so this only matters with AutoVendor off (or nothing to trade). + /// + internal const long VendorAfterOpenMs = 2_000; + + private int _vendorIdx = -1; // the Vendor point being handled (-1: none) + private NavRouteParser? _vendorRoute; // on this route + private long _vendorStart, _vendorTriedAt, _vendorFiredAt, _vendorOpenedAt; + private bool _vendorFired; + + /// + /// A vendor's window opened (the plugin's OnVendorOpen, on the tick thread). Counts only while a + /// Vendor point has used its vendor; a vendor opened by hand at any other time is nothing to nav. + /// + public void NoteVendorOpened(uint vendorId) + { + if (_vendorIdx < 0 || !_vendorFired || _vendorOpenedAt != 0) return; + _vendorOpenedAt = Now; + _host.Log($"Nav: vendor 0x{vendorId:X8} opened for Vendor point [{_vendorIdx}]"); + } + + /// + /// Arrived at (or passed) waypoint : true when it is a Vendor point, which now + /// stops and opens its vendor (HandleVendorVisit) instead of advancing. + /// + private bool BeginVendorVisit(NavPoint pt, NavRouteParser route, int idx) + { + if (pt.Type != NavPointType.OpenVendor || string.IsNullOrWhiteSpace(pt.TargetName)) return false; + StopMovement(); + _vendorIdx = idx; + _vendorRoute = route; + _vendorStart = Now; + _vendorTriedAt = 0; + _vendorFiredAt = 0; + _vendorOpenedAt = 0; + _vendorFired = false; + _settings.NavStatusLine = $"Nav: vendor '{pt.TargetName.Trim()}'..."; + _host.Log($"Nav: at Vendor point [{idx}] '{pt.TargetName.Trim()}' - opening the vendor before going on"); + return true; + } + + private void HandleVendorVisit(NavPoint pt, NavRouteParser route) + { + long now = Now; + string name = pt.TargetName.Trim(); + if (!_vendorFired) + { + ClearTurnMotions(); + if (now - _vendorStart < (long)SettleDelayMs) return; // stand still first, as before a portal + if (now - _vendorStart > NpcFindTimeoutMs) + { + string msg = $"Nav: the vendor '{name}' at waypoint [{_vendorIdx}] wasn't found in {NpcFindTimeoutMs / 1000} s - going on without it."; + _host.Log(msg); + _host.WriteToChat(msg, 1); + EndVendorVisit(route); + return; + } + if (_vendorTriedAt == 0 || now - _vendorTriedAt >= (long)PortalNpcRetryMs) + { + _vendorTriedAt = now; + if (FirePortalNpcUse(pt, "vendor")) + { + _vendorFired = true; + _vendorFiredAt = now; + } + } + return; + } + + // Used: AC walks the character over and opens the vendor. No motions are cleared now, or the + // walk over would be cancelled (as for a portal or an NPC). + if (_vendorOpenedAt != 0) + { + _settings.NavStatusLine = $"Nav: at vendor '{name}'"; + if (now - _vendorOpenedAt >= VendorAfterOpenMs) + { + _host.Log($"Nav: vendor '{name}' done (opened {now - _vendorOpenedAt} ms ago) - going on"); + EndVendorVisit(route); + } + return; + } + if (now - _vendorFiredAt >= VendorOpenMaxMs) + { + string msg = $"Nav: the vendor '{name}' at waypoint [{_vendorIdx}] didn't open in {VendorOpenMaxMs / 1000} s - going on without it."; + _host.Log(msg); + _host.WriteToChat(msg, 1); + EndVendorVisit(route); + } + } + + private void EndVendorVisit(NavRouteParser route) + { + _vendorIdx = -1; + _vendorRoute = null; + _closestDist = double.MaxValue; + Advance(route); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 7464155..531024a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -177,6 +177,8 @@ internal sealed partial class NavigationEngine public long PausedAt; public double PausedNs = double.NaN, PausedEw = double.NaN; public int Replans; + public int StalledReplans; // re-plans that brought the walk no nearer (DetourMaxReplans of them end it) + public double BestYd = double.MaxValue; // the shortest plan so far public int DoorRequestCount; public long NextDoorCheckAt; public readonly Dictionary DoorRequests = new(); @@ -189,7 +191,8 @@ internal sealed partial class NavigationEngine private const int StuckSpotRepeat = 3; // stucks within StuckSpotYards: go straight to a detour private const double StuckSpotYards = 5.0; private const double DetourReplanMovedYd = 5.0; // moved this far while paused: plan again - private const int DetourMaxReplans = 3; + private const int DetourMaxReplans = 3; // re-plans that bring the walk no nearer + private const double DetourReplanNearerYd = 5.0; // a re-plan at least this much shorter than the best so far is progress private const double DetourDoorCheckMs = 400.0; private const double DetourDoorLookYd = 12.0; // look for doors this far along the next leg private const double DetourDoorCorridorYd = 3.0; // ... and this close to it @@ -689,11 +692,15 @@ internal sealed partial class NavigationEngine case NavPointType.Npc when _npcTalkIdx == idx && ReferenceEquals(_npcTalkRoute, route): HandleNpcTalk(pt, route); return; + case NavPointType.OpenVendor when _vendorIdx == idx && ReferenceEquals(_vendorRoute, route): + HandleVendorVisit(pt, route); + return; } // ── Standard coordinate waypoint ───────────────────────────────────── _portalState = PortalState.None; _npcTalkIdx = -1; + _vendorIdx = -1; _inPause = false; _teleportedRoute = null; _firedRoute = null; @@ -749,6 +756,7 @@ internal sealed partial class NavigationEngine // Advance before the jump: the Jumper pauses nav and later restores what it // saw, so jumping first turned a finished Once route back on (re-run from [0]). if (BeginNpcTalk(pt, route, idx)) return; // an NPC point advances once the NPC was used (NavigationEngine.NpcTalk.cs) + if (BeginVendorVisit(pt, route, idx)) return; // a Vendor point, once the vendor was opened (NavigationEngine.VendorVisit.cs) Advance(route); if (pt.Type == NavPointType.Jump) FireJump(pt, idx); return; @@ -766,6 +774,7 @@ internal sealed partial class NavigationEngine _closestDist = double.MaxValue; UpdateStatusLine(idx, dist, route, 0.0); if (BeginNpcTalk(pt, route, idx)) return; // an NPC point advances once the NPC was used (NavigationEngine.NpcTalk.cs) + if (BeginVendorVisit(pt, route, idx)) return; // a Vendor point, once the vendor was opened (NavigationEngine.VendorVisit.cs) Advance(route); if (pt.Type == NavPointType.Jump) FireJump(pt, idx); return; @@ -778,6 +787,7 @@ internal sealed partial class NavigationEngine _host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing"); _closestDist = double.MaxValue; if (BeginNpcTalk(pt, route, idx)) return; // an NPC point advances once the NPC was used (NavigationEngine.NpcTalk.cs) + if (BeginVendorVisit(pt, route, idx)) return; // a Vendor point, once the vendor was opened (NavigationEngine.VendorVisit.cs) Advance(route); if (pt.Type == NavPointType.Jump) FireJump(pt, idx); return; @@ -1176,9 +1186,22 @@ internal sealed partial class NavigationEngine if (_planner == null || !_host.HasGetPlayerPose) return -1; if (!_host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _)) return -1; if ((cell & 0xFFFF) < 0x0100) return -1; + // The planner's walk length: a waypoint in your own room with nothing in the way is the straight line to it + // (TryPlan has no plan for it, and it was left out: Desert Mine 2026-11-27). + return NearestOnFoot(route, from, once, cur, ns, ew, _planner.WalkLengthYd, out walkYd); + } + /// + /// Of the plain waypoints nearest (, ) by map + /// distance (from on; a Once route stops at its next step), plus , the one + /// says is the shortest walk (ties: the first looked at). -1 when none has a walk. The macro + /// start's pick indoors, and the dungeon patrol's start when nothing of it is in sight (RynthAiCommands.TryBuildDunPatrol). + /// + internal static int NearestOnFoot(NavRouteParser route, int from, bool once, int cur, double ns, double ew, + Func walk, out double walkYd, int candidatesNearest = WalkCandidates) + { var near = new List<(int Idx, double D)>(); - for (int i = from; i < route.Points.Count; i++) + for (int i = Math.Max(0, from); i < route.Points.Count; i++) { var p = route.Points[i]; if (once && !NavRouteParser.IsPlainWaypoint(p.Type)) break; @@ -1187,17 +1210,15 @@ internal sealed partial class NavigationEngine } near.Sort((a, b) => a.D.CompareTo(b.D)); var candidates = new List(); - for (int k = 0; k < near.Count && k < WalkCandidates; k++) candidates.Add(near[k].Idx); - if (IndexValid(cur, route) && cur >= from && NavRouteParser.IsPlainWaypoint(route.Points[cur].Type) && !candidates.Contains(cur)) + for (int k = 0; k < near.Count && k < candidatesNearest; k++) candidates.Add(near[k].Idx); + if (cur >= from && cur < route.Points.Count && NavRouteParser.IsPlainWaypoint(route.Points[cur].Type) && !candidates.Contains(cur)) candidates.Add(cur); int best = -1; double bestYd = double.MaxValue; foreach (int i in candidates) { - // The planner's walk length: a waypoint in your own room with nothing in the way is the straight line to it - // (TryPlan has no plan for it, and it was left out: Desert Mine 2026-11-27). - double? yd = _planner.WalkLengthYd(route.Points[i]); + double? yd = walk(route.Points[i]); if (yd == null) continue; if (yd.Value < bestYd) { bestYd = yd.Value; best = i; } } @@ -3420,6 +3441,7 @@ internal sealed partial class NavigationEngine RejoinIdx = rejoin, Skipped = skipped, LengthYd = plan.LengthYd, + BestYd = plan.LengthYd, Doorways = plan.Doorways, StartedAt = now, // Generous: ~0.6 s per yard (a slow walk) plus room for a door or two. @@ -3544,11 +3566,17 @@ internal sealed partial class NavigationEngine DriveHeading(error, currentDeg, dist); } + // 2026-11-29, Lugian Excavations (0x02E7) on the patrol: the walk back to a waypoint 425 yd off (the map's way, 20 + // points, 5 doorways) was broken into by a fight every 10-30 s (Deepvein lugians all the way). Each fight re-planned it + // from where it ended, every one nearer (531 -> 460 -> 442 -> 422 yd), but the third re-plan used the walk up: "out of + // re-plans", a failed recovery, and nav steered straight at the waypoint, through the cave walls, until the next fight. + // Three of those used up the waypoint's recoveries (the stuck escapes, running at the wall). A re-plan that is nearer + // is the walk going well between fights: only the re-plans that bring it no nearer count. private bool ReplanDetour(NavRouteParser route, Detour d, double movedYd) { - if (_planner == null || d.Replans >= DetourMaxReplans) + if (_planner == null) { - EndDetour($"moved {movedYd:F0}yd while paused and out of re-plans", success: false); + EndDetour($"moved {movedYd:F0}yd while paused and no planner", success: false); return false; } var plan = _planner.TryPlan(route.Points[d.RejoinIdx], out string why); @@ -3558,6 +3586,14 @@ internal sealed partial class NavigationEngine EndDetour($"moved {movedYd:F0}yd while paused, re-plan found nothing ({why})", success: false); return false; } + bool nearer = plan.LengthYd <= d.BestYd - DetourReplanNearerYd; + if (!nearer && d.StalledReplans >= DetourMaxReplans) + { + EndDetour($"moved {movedYd:F0}yd while paused and out of re-plans ({d.StalledReplans} brought it no nearer than {d.BestYd:F0}yd)", success: false); + return false; + } + if (nearer) d.BestYd = plan.LengthYd; + else d.StalledReplans++; d.Replans++; d.Points = plan.Points; d.Index = 0; @@ -3567,7 +3603,8 @@ internal sealed partial class NavigationEngine d.LengthYd = plan.LengthYd; d.Doorways = plan.Doorways; d.DoorRequests.Clear(); - _host.Log($"Nav: recovery #{d.Number} re-planned after a pause (moved {movedYd:F0}yd): {plan.Points.Count} pts, {plan.LengthYd:F0}yd via {plan.Planner}"); + _host.Log($"Nav: recovery #{d.Number} re-planned after a pause (moved {movedYd:F0}yd): {plan.Points.Count} pts, {plan.LengthYd:F0}yd via {plan.Planner}" + + (nearer ? "" : $" (no nearer: {d.StalledReplans}/{DetourMaxReplans})")); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 2d18f47..501ff0a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -3863,7 +3863,13 @@ public sealed partial class RynthAiPlugin // "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.) // (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, walkMap: geometry); + int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ, explore != null ? ExploreSightLookahead : int.MaxValue, + geometry, out bool noneInSight); + // Nothing of the lap in sight (a rebuild mid-dungeon, where the lap's [0] can be across the dungeon): the nearest + // waypoint on foot instead. Not the explore (a walk that ends: starting farther in skips rooms), not out of a + // hazard (its lead-in is [0]) or a portal's circle (the walk is from the walk-out spot, LeadPatrolPastPortals). + if (noneInSight && explore == null && !evacuate && walkOut == null) + startIdx = PatrolStartOnFoot(route, startIdx); // 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) { @@ -4501,7 +4507,15 @@ public sealed partial class RynthAiPlugin private int FindFirstLineOfSightWaypoint(NavRouteParser route, uint playerCell, float playerLocalX, float playerLocalY, float playerZ, int lookahead = int.MaxValue, DungeonGeometry? walkMap = null) + => FindFirstLineOfSightWaypoint(route, playerCell, playerLocalX, playerLocalY, playerZ, lookahead, walkMap, out _); + + /// The same; true when the waypoints were looked at and none was in sight (the + /// 0 returned is then only the first waypoint, wherever it is), false when one was or no look was possible. + private int FindFirstLineOfSightWaypoint(NavRouteParser route, uint playerCell, + float playerLocalX, float playerLocalY, float playerZ, + int lookahead, DungeonGeometry? walkMap, out bool noneInSight) { + noneInSight = false; if (route?.Points == null || route.Points.Count == 0) return 0; var geo = _raycast?.GeometryLoader; if (geo == null) return 0; @@ -4542,6 +4556,41 @@ public sealed partial class RynthAiPlugin return i; } + noneInSight = true; return 0; } + + /// The waypoints PatrolStartOnFoot compares by the dungeon map's walk (the nearest by map distance), besides [0]. + private const int PatrolStartWalkCandidates = 6; + + /// + /// The dungeon patrol's start when none of its waypoints is in sight from the character: the nearest on foot (the + /// dungeon map's walk, NavRecoveryPlanner.WalkLengthYd) of the few nearest by map distance and . + /// 2026-11-29, Lugian Excavations (0x02E7): a portal coming into view laid the patrol again mid-dungeon, from the + /// character's room, but the lap's first waypoint was in a room 425 yd away across the dungeon (room 191; the + /// character in the 173-cell cave, which the lap crosses later, 18 m off). Nothing was in sight from the fight's end, so + /// it started at [0]: a long walk through every fight on the way, and the walls between. + /// when the map gives no walk to any of them. + /// + private int PatrolStartOnFoot(NavRouteParser route, int fallback) + { + if (_navPlanner == null || route.Points.Count == 0 || !Host.HasGetPlayerPose) return fallback; + if (!Host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out _, out _, out _, out _, out _) + || !NavCoordinateHelper.TryConvertPoseToCoords(cell, lx, ly, out double ns, out double ew)) + return fallback; + var planner = _navPlanner; + int best; + double walkYd; + try { best = NavigationEngine.NearestOnFoot(route, 0, false, fallback, ns, ew, planner.WalkLengthYd, out walkYd, PatrolStartWalkCandidates); } + catch (Exception ex) + { + Host.Log($"[RynthAi] DunNav-Patrol: the start on foot failed ({ex.Message}): starting at waypoint {fallback}"); + return fallback; + } + if (best < 0 || best == fallback) return fallback; + var f = route.Points[fallback]; + double fallbackYd = Math.Sqrt((f.NS - ns) * (f.NS - ns) + (f.EW - ew) * (f.EW - ew)) * 240.0; + Host.Log($"[RynthAi] DunNav-Patrol: no waypoint in sight from here: starting at the nearest on foot, waypoint {best} ({walkYd:F0} yd walk), not {fallback} ({fallbackYd:F0} yd off)"); + return best; + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs index 150ff9d..75296b5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PatrolPortals.cs @@ -34,16 +34,38 @@ public sealed partial class RynthAiPlugin return DungeonPathfinder.PortalKeepOutRadius(cut); } + // ── Portals out of sight are still there (2026-11-29) ───────────────────── + // Lugian Excavations (0x02E7) has two Drift Network portals ~500 m apart. The client is sent a dungeon's objects in + // sight and forgets them 25 s after they're out of it, so the patrol, laid round the portals the client knew, came round + // to one, saw it "come into view", laid itself again round it alone (the other forgotten by then), and on the far side + // the other one "came into view" in turn: laid again every 6-14 minutes all session (47 and 67 points by turns), each + // time starting over across the dungeon. The portals seen in the dungeon are remembered until the character leaves it; + // one the client hasn't got for 5 s while the character sees its cell is gone (a summoned one) and forgotten. + + /// A remembered portal whose cell the character sees, this close (flat), that the client hasn't got ... + private const double PatrolPortalGoneMeters = 60.0; + /// ... for this long (the server's create can lag a step into sight) is gone. + private const long PatrolPortalGoneMs = 5000; + + /// The portals seen in dungeon , by id: where they stand. + private readonly Dictionary _seenPortals = new(); + private readonly Dictionary _portalMissingSince = new(); + private uint _seenPortalsLb = uint.MaxValue; + /// The clock the gone test reads (ms; tests set it). + internal static Func PortalClock = static () => Environment.TickCount64; + /// - /// Every portal the client knows in dungeon landblock (static and + /// Every portal in dungeon landblock the client knows (static and /// summoned: object class Portal, or an unclassified object whose item type says portal), with - /// its world position and cell, sorted by id. + /// its world position and cell, and those seen there before that are out of sight now, sorted by id. /// private List PatrolPortalsIn(uint landblock) { var list = new List(); if (_objectCache == null || !Host.HasGetObjectPosition) return list; + if (_seenPortalsLb != landblock) { _seenPortals.Clear(); _portalMissingSince.Clear(); _seenPortalsLb = landblock; } double radius = PatrolPortalRadius(); + var live = new HashSet(); foreach (var wo in _objectCache.GetLandscapeObjects()) { uint uid = unchecked((uint)wo.Id); @@ -52,17 +74,72 @@ public sealed partial class RynthAiPlugin if (!portal) 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; - list.Add(new PatrolPortal + var p = new PatrolPortal { Id = uid, Name = wo.Name ?? "", Cell = cell, X = ((cell >> 24) & 0xFF) * 192.0 + x, Y = ((cell >> 16) & 0xFF) * 192.0 + y, Z = z, Radius = radius, - }); + }; + list.Add(p); + live.Add(uid); + _seenPortals[uid] = new PatrolPortal { Id = p.Id, Name = p.Name, Cell = p.Cell, X = p.X, Y = p.Y, Z = p.Z }; + } + + foreach (uint id in live) _portalMissingSince.Remove(id); + if (_seenPortals.Count > live.Count) + { + long now = PortalClock(); + List? gone = null; + foreach (var (id, s) in _seenPortals) + { + if (live.Contains(id)) continue; + if (PortalShouldBeKnown(landblock, s)) + { + if (!_portalMissingSince.TryGetValue(id, out long since)) _portalMissingSince[id] = since = now; + if (now - since >= PatrolPortalGoneMs) { (gone ??= new List()).Add(id); continue; } + } + else _portalMissingSince.Remove(id); + // A fresh copy each time: the patrol build fills in a portal's cell and radius. + list.Add(new PatrolPortal { Id = s.Id, Name = s.Name, Cell = s.Cell, X = s.X, Y = s.Y, Z = s.Z, Radius = radius }); + } + if (gone != null) + foreach (uint id in gone) + { + var s = _seenPortals[id]; + _seenPortals.Remove(id); + _portalMissingSince.Remove(id); + Host.Log($"[RynthAi] Dungeon portals: 0x{id:X8} '{s.Name}' at ({s.X:F1},{s.Y:F1},{s.Z:F1}) isn't there any more (its cell is in sight): forgotten"); + } } list.Sort((a, b) => a.Id.CompareTo(b.Id)); return list; } + /// + /// The client would have portal if it were there: the character stands in its cell or in one that + /// sees it (cell.dat's visible cells: what the server sends, ACE ObjectMaint), within PatrolPortalGoneMeters (flat). + /// False where that can't be told (no map, no visible-cell lists, out of the dungeon). + /// + private bool PortalShouldBeKnown(uint landblock, PatrolPortal s) + { + if (s.Cell == 0 || !Host.HasGetPlayerPose + || !Host.TryGetPlayerPose(out uint pc, out float plx, out float ply, out _, out _, out _, out _, out _) + || (pc >> 16) != landblock || (pc & 0xFFFF) < 0x0100) + return false; + double dx = s.X - (((pc >> 24) & 0xFF) * 192.0 + plx), dy = s.Y - (((pc >> 16) & 0xFF) * 192.0 + ply); + if (dx * dx + dy * dy > PatrolPortalGoneMeters * PatrolPortalGoneMeters) return false; + if (pc == s.Cell) return true; + Dictionary? graph; + try + { + 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); + } + catch { return false; } + return graph != null && graph.TryGetValue(pc, out var n) && n.Visible != null && Array.IndexOf(n.Visible, s.Cell) >= 0; + } + /// /// 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 diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs index 6d1cb7b..a25997d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs @@ -13,9 +13,26 @@ // With the setting on, a corpse is opened only when its description has that sentence. One whose // description hasn't arrived yet waits for it, as Mine Only does. Your own death corpse // (Recover My Corpse) is decided before this, so it is always recovered. +// +// The sentence is the same for every rare tier (ACE writes it before the corpse enters the world), +// so tier never decides anything here. A waiting corpse is never claimed, so it never got the target's +// ID re-asks: since 2026-11-29 one in loot range is asked again (CorpseOpenController +// RareCorpseIdWaitInRange), or a dropped request left a rare corpse closed for good. +// +// No rare is left on a corpse (2026-11-29), in every loot mode: +// * a rare is always kept, ahead of the loot profile (ClassifyLootItem), and needs no ID when its +// rare icon shows it (ItemNeedsAppraisalForLoot); +// * it is taken first on a corpse, and may use the slots kept free for weapon swaps; +// * a corpse that generated a rare gets past Stop Looting When Pack Full while one slot is free, +// and is claimed ahead of other corpses (your own death corpse still comes first); +// * an opened corpse with a rare still on it is never marked done quietly: it is set aside and +// looted again (RareLeftMaxRetries times), then a chat line names the rare to take by hand. // ============================================================================ using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; namespace RynthCore.Plugin.RynthAi; @@ -24,6 +41,14 @@ public sealed partial class RynthAiPlugin /// The sentence ACE adds to a corpse that generated a rare (Corpse.TryGenerateRare). internal const string RareCorpseText = "This corpse generated a rare item"; + /// Times an opened corpse with a rare still on it is looted again before the chat line. + internal const int RareLeftMaxRetries = 3; + /// How long such a corpse is set aside before it is looted again. + internal const long RareLeftRetryMs = 5_000; + + /// Per corpse: times it was set aside for a rare still on it. + private readonly Dictionary _rareLeftRetries = new(); + /// The corpse's long description says it generated a rare. internal static bool IsRareCorpse(string? longDesc) => !string.IsNullOrEmpty(longDesc) && longDesc.IndexOf(RareCorpseText, StringComparison.OrdinalIgnoreCase) >= 0; @@ -35,4 +60,96 @@ public sealed partial class RynthAiPlugin return "Loot Only Rare Corpses: waiting for its description (the ID) to see whether it generated a rare."; return IsRareCorpse(longDesc) ? null : "Loot Only Rare Corpses: it didn't generate a rare."; } + + /// A rare still in container (its contents as the client last listed + /// them), or null. Chests are not asked: they regenerate and are never marked done. + private WorldObject? RareStillOn(int corpseId) + { + if (_objectCache == null || corpseId == 0 || IsChestLoot(corpseId)) + return null; + foreach (WorldObject item in _objectCache.GetContainedItems(corpseId)) + if (RareItems.IsRare(Host, item, out _) && !ObjectGoneFromClient(item.Id)) + return item; + return null; + } + + private string CorpseNameFor(int corpseId) + => _objectCache?[corpseId]?.Name is { Length: > 0 } n ? n : $"corpse 0x{(uint)corpseId:X8}"; + + /// + /// Called where an opened corpse would be marked done. With a rare still on it (not your own death + /// corpse, which has its own retries), it is set aside for and looted + /// again instead, and true is returned; the caller then skips the completed mark. After + /// such tries it says so in chat, naming the rare, and returns false. + /// + private bool SetAsideForRareLeft(int corpseId, long now) + { + WorldObject? rare = RareStillOn(corpseId); + if (rare == null || IsOwnDeathCorpseId(_dashboard?.Settings, corpseId)) + { + _rareLeftRetries.Remove(corpseId); + return false; + } + + string corpseName = CorpseNameFor(corpseId); + string rareName = string.IsNullOrWhiteSpace(rare.Name) ? $"0x{(uint)rare.Id:X8}" : rare.Name; + int tries = _rareLeftRetries.TryGetValue(corpseId, out int n) ? n + 1 : 1; + if (tries > RareLeftMaxRetries) + { + _rareLeftRetries.Remove(corpseId); + string why = IsPackFull() ? " No pack has a free slot." : string.Empty; + ChatLine($"[RynthAi] A rare is still on {corpseName}: {rareName}. Looted {RareLeftMaxRetries} more times and it stayed.{why} Take it by hand."); + LootDiag($"[RynthAi] Rare left: {rareName} 0x{(uint)rare.Id:X8} on 0x{(uint)corpseId:X8} after {RareLeftMaxRetries} retries; marking the corpse done."); + return false; + } + + _rareLeftRetries[corpseId] = tries; + _corpseCooldownUntil[corpseId] = now + RareLeftRetryMs; + ChatLine($"[RynthAi] A rare is still on {corpseName}: {rareName}. Looting it again in {RareLeftRetryMs / 1000} s (try {tries} of {RareLeftMaxRetries})."); + LootDiag($"[RynthAi] Rare left: {rareName} 0x{(uint)rare.Id:X8} on 0x{(uint)corpseId:X8}; set aside {RareLeftRetryMs} ms, try {tries} of {RareLeftMaxRetries}."); + return true; + } + + /// A corpse that generated a rare was written off without being opened: said in chat. + private void SayRareCorpseUnopened(int corpseId) + { + string longDesc = _objectCache?[corpseId]?.Values(StringValueKey.LongDesc, string.Empty) ?? string.Empty; + if (!IsRareCorpse(longDesc) || IsChestLoot(corpseId)) + return; + ChatLine($"[RynthAi] {CorpseNameFor(corpseId)} generated a rare, but it could not be opened. Take it by hand."); + } + + /// A corpse in loot range whose description says it generated a rare and that the loot rules + /// would open (not done, not set aside): the nearest one. + private bool TryFindRareCorpseInRange(double maxMeters, out WorldObject? corpse) + { + corpse = null; + if (_objectCache == null || _playerId == 0) + return false; + long now = CorpseNowMs; + int playerId = unchecked((int)_playerId); + double best = double.MaxValue; + foreach (WorldObject candidate in _objectCache.GetLandscapeObjects()) + { + if (candidate.ObjectClass != AcObjectClass.Corpse || _completedCorpses.ContainsKey(candidate.Id)) + continue; + if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long until) && until > now) + continue; + if (!IsRareCorpse(candidate.Values(StringValueKey.LongDesc, string.Empty))) + continue; + double dist = _objectCache.Distance(playerId, candidate.Id); + if (dist > maxMeters || dist >= best) + continue; + if (!EvaluateCorpseLootDecision(candidate).ShouldLoot) + continue; + corpse = candidate; + best = dist; + } + return corpse != null; + } + + /// Stop Looting When Pack Full lets a rare corpse through while any pack has a slot: the rare + /// goes first and the reserve check ends the corpse after it (as your own corpse is let through). + private bool RareCorpseBypassesPackGate(LegacyUiSettings settings, double maxMeters) + => !IsPackFull() && TryFindRareCorpseInRange(maxMeters, out _); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs index 03abe8a..c74cbe0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs @@ -94,6 +94,7 @@ internal static class ActionPacingTests r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, at most 3 re-asks per corpse", CorpseIdReaskedWithoutData); r.Add("corpse id: Loot From All Corpses needs no killer name - the first request goes out, no re-ask ever follows; My Kills Only gives up after 3 re-asks, a new corpse starts over", CorpseIdAllCorpsesNoReask); r.Add("corpse id: two corpses in range, no data for either - only the targeted one re-asks; the other stays at one accepted request (a refused one is still retried)", CorpseIdOnlyCandidateReasks); + r.Add("corpse id (11-29): Loot Only Rare Corpses - an unclaimed corpse in loot range with no description re-asks (3 s, 3 re-asks at most) and opens once the rare line lands; one out of range asks once, and again when the bot comes within range", CorpseIdRareOnlyWaitingReasks); r.Add("corpse id: 20 uncached corpses, a refusal window, then accept - at most 2 requests in the first accepted tick, the target among them; refused retries are 250 ms apart", CorpseIdBurstCapped); r.Add("corpse id: the open container is a candidate and re-asks; delete and the >200 prune clear every id map", CorpseIdOpenContainerAndCleanup); r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept); @@ -1068,6 +1069,52 @@ internal static class ActionPacingTests _t += 3_000; Both(); Check.Eq(Asked(CorpseB), 2, "once it becomes the candidate it re-asks"); }); + + // Loot Only Rare Corpses never claims a corpse before its description says "This corpse generated a + // rare item!", so no waiting corpse is the target and the target's re-asks never reached one: an + // accepted request the engine dropped (stale, around a portal) left a rare corpse closed for good. + private static void CorpseIdRareOnlyWaitingReasks() => Paced(() => + { + LootWorld(); + FakeHost.Strings.Remove((Corpse, LongDescKey)); + FakeHost.Strings.Remove((CorpseB, LongDescKey)); + FakeHost.Positions[CorpseB] = (Me0.Cell, Me0.X + 60f, Me0.Y, Me0.Z); // far past the 10 yd approach range + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.LootOnlyRareCorpses = true; + var cache = bot.Get("_objectCache"); + var near = cache[unchecked((int)Corpse)]!; + var far = cache[unchecked((int)CorpseB)]!; + int Asked(uint id) => FakeHost.IdRequests.Count(i => i == id); + bool Loots(WorldObject o) + { + object d = bot.Call("EvaluateCorpseLootDecision", o)!; + return (bool)d.GetType().GetProperty("ShouldLoot")!.GetValue(d)!; + } + void Both() { Loots(near); Loots(far); } + + Check.Eq(bot.Get("_targetCorpseId"), 0, "nothing is claimed"); + Check.False(Loots(near), "no description yet: the corpse waits, closed"); + Loots(far); + Check.Eq(Asked(Corpse), 1, "t=0: the first request goes out"); + Check.Eq(Asked(CorpseB), 1, "the far corpse gets its first request too"); + _t += 2_999; Both(); + Check.Eq(Asked(Corpse), 1, "2.999 s, no answer: not yet"); + _t += 1; Both(); + Check.Eq(Asked(Corpse), 2, "3 s, no answer (the request was dropped): asked again, though it is not the target"); + for (int i = 0; i < 6; i++) { _t += 3_000; Both(); } + Check.Eq(Asked(Corpse), 4, "three re-asks at most"); + Check.Eq(Asked(CorpseB), 1, "out of loot range: one request only"); + + FakeHost.Positions[CorpseB] = (Me0.Cell, Me0.X + 1.5f, Me0.Y, Me0.Z); + _t += 3_000; Both(); + Check.Eq(Asked(CorpseB), 2, "the bot came within range of it: asked again"); + + FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}. This corpse generated a rare item!"; + Check.True(Loots(near), "the description arrived with the rare line: it opens"); + FakeHost.Strings[(CorpseB, LongDescKey)] = $"Killed by {Me}."; + Check.False(Loots(far), "no rare line: it stays closed"); + }); private static void CorpseIdBurstCapped() => Paced(() => { LootWorld(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs index fe53b8f..d7f8d61 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs @@ -51,6 +51,7 @@ internal static class DunRouteTests r.Add("dun routes: plugin: the patrol save asks the server policy as dunnav-patrol does; dunroute isn't refused", PluginPatrolPolicy); r.Add("dun routes: plugin: interface jobs run on the tick, wait out portal space, give up after 30 s, answer JSON", PluginJobs); r.Add("dun routes: plugin: where lists the portals with distances and the exit; arrival is where the character landed", PluginWhere); + r.Add("dun routes (11-29): plugin: a portal the client forgot (out of sight) is still kept out of, and its coming back rebuilds nothing; one gone from its own cell for 5 s is forgotten", PluginPortalsRemembered); r.Add("dun routes: Tiny Hive 0x0289 on the real dats: a route to the Surface Portal and to the far end (if the dats are here)", TinyHiveRealDats); r.Add("dun doorways: the doorway flags survive save and reload (NavProfiles\\.rynthai-routes.json); the .nav stays VTank's", DoorwaysSurviveReload); r.Add("dun doorways: an edited file gets no flags (one log line); a nav the route maker didn't write is never touched", DoorwaysEditedFile); @@ -934,6 +935,57 @@ internal static class DunRouteTests Check.True(said[0].Contains("circular") && said[0].Contains("made for this dungeon: yes"), "info on the saved patrol: " + Show(said)); } + private static void PluginPortalsRemembered() + { + // 2026-11-29 Lugian Excavations (0x02E7): two portals ~500 m apart, the client forgetting each out of sight, the + // patrol laid again round whichever "came into view", the other forgotten: every 6-14 minutes all session. + var rig = new Rig("NavProfiles-portalmem"); + long clock = 1_000_000; + RynthAiPlugin.PortalClock = () => clock; + try + { + List Known() => (List)rig.Call("PatrolPortalsIn", Lb)!; + Check.Eq(Known().Count, 2, "both portals known"); + + // Out of sight: the client forgets the Surface Portal. It is still there. + rig.Cache.OnDeleteObject(SurfaceId); rig.Cache.Tick(); + var later = Known(); + Check.Eq(later.Count, 2, "the one the client forgot is still kept out of"); + var s = later.First(p => p.Id == SurfaceId); + Check.True(Math.Abs(s.X - (Ox + 15)) < 0.01 && Math.Abs(s.Y - (Oy + 52)) < 0.01 && s.Cell == rig.D.Nook && s.Name == "Surface Portal", + $"where it stood, by name ({s.X - Ox:F1}, {s.Y - Oy:F1}) cell {s.Cell:X8}"); + s.Radius = 99; // a build fills these in on its copy + Check.True(Known().First(p => p.Id == SurfaceId).Radius < 99, "a fresh copy each time"); + + // The patrol built round both: the Surface Portal coming back into view lays nothing again. + rig.Call("MarkPatrolPortals", Known()); + rig.Cache.OnCreateObject(SurfaceId); rig.Cache.Tick(); + rig.Set("_dunPatrolLandblock", Lb); + rig.Set("_dunPatrolPortalCheckAt", 0L); + Check.False((bool)rig.Call("PatrolPortalAppeared")!, "it coming back into view rebuilds nothing"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("came into view")), 0, "no 'came into view'"); + + // A portal really gone (a summoned one): in its own cell without the client having it, kept 5 s, then forgotten. + rig.Cache.OnDeleteObject(SurfaceId); rig.Cache.Tick(); + rig.At(15, 50, rig.D.Nook); + Check.True(Known().Any(p => p.Id == SurfaceId), "in its cell: kept at first (the server's create can lag)"); + clock += 4000; + Check.True(Known().Any(p => p.Id == SurfaceId), "kept after 4 s"); + clock += 1000; + var gone = Known(); + Check.False(gone.Any(p => p.Id == SurfaceId), "forgotten after 5 s"); + Check.Eq(gone.Count, 1, "the other portal stays"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("isn't there any more")), 1, "said once in the log"); + + // Far from it (not its cell) a forgotten-by-the-client portal is never taken for gone. + rig.At(15, 15, rig.D.Start); + rig.Cache.OnDeleteObject(DepthsId); rig.Cache.Tick(); + clock += 60_000; + Check.True(Known().Any(p => p.Id == DepthsId), "the Depths portal, out of sight from the start, is kept"); + } + finally { RynthAiPlugin.PortalClock = static () => Environment.TickCount64; } + } + private static void PluginPatrolPolicy() { // The patrol is off in Threads on DreamWeave (ServerPolicy): the save builds the same patrol, so it asks too. diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs index f43916e..c68163a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRaresModeTests.cs @@ -44,8 +44,10 @@ internal static class LootRaresModeTests { r.Add("loot rares mode: the rares and a needed mana stone are looted; the OD crossbow LootSnob keeps and the gold salvage are not", RaresModeCorpse); r.Add("loot rares mode: a mana stone at the keep count is left (not needed), and the corpse's end line says the mode", StoneNotNeeded); - r.Add("loot rares mode: profile mode is unchanged (crossbow kept, helm salvaged, stone kept, the rares left)", ProfileModeUnchanged); + r.Add("loot rares mode: profile mode keeps its rules (crossbow kept, helm salvaged, stone kept) and, since 11-29, the rares no LootSnob rule takes", ProfileModeUnchanged); r.Add("loot rares mode: a rare needs no ID (rare icon) or is known by its RareId; Mana Tap takes nothing", NoIdNoTap); + r.Add("rare left (11-29): a rare that won't move keeps its corpse from being marked done - set aside and looted again 3 times, each said in chat, then a line names it to take by hand", RareLeftSetAside); + r.Add("rare left (11-29): a corpse with a rare is claimed ahead of a nearer one, and its rare is picked up first", RareCorpseAndRareFirst); r.Add("loot rares mode: the loot details line names the reason (rare, mana stone (needed))", DetailsLineNamesReason); r.Add("loot rares mode: the setting round trip (profile file, profile switch, engine face, meta LootMode)", SettingRoundTrip); r.Add("loot rares mode: /ra loot mode replies with the mode, or why not and the usage; /ra loot why gives the mode's verdict", Commands); @@ -65,9 +67,13 @@ internal static class LootRaresModeTests finally { RynthAiPlugin.CorpseClock = old; } } + /// Moves the server never lands (the item stays on the corpse). + private static readonly HashSet NeverLands = new(); + private static void World(bool stoneInPack) { FakeHost.Reset(); + NeverLands.Clear(); FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId @@ -170,7 +176,8 @@ internal static class LootRaresModeTests while (_seenMoves < FakeHost.ExternalMoves.Count) { var m = FakeHost.ExternalMoves[_seenMoves++]; - FakeHost.Containers[m.Id] = m.Target; + if (!NeverLands.Contains(m.Id)) + FakeHost.Containers[m.Id] = m.Target; } } @@ -286,7 +293,10 @@ internal static class LootRaresModeTests Check.True(Said("Loot rule: Helm -> [Salvage] (Salv) Gold"), "for LootSnob's (Salv) Gold"); Check.True(Moved(Stone), "the mana stone is kept by the built-in stone rule"); Check.True(Said("Loot rule: Mana Stone -> [Keep] ManaStone (Consumable, 1/5)"), "under its old label"); - Check.False(Moved(RareGem), "the rare gem: no LootSnob rule takes it, so profile mode leaves it, as before"); + // 2026-11-29 (no rare may be left on a corpse): a rare is always kept, ahead of the profile. + Check.True(Moved(RareGem), "the rare gem: no LootSnob rule takes it, but a rare is always kept"); + Check.True(Moved(RareRing), "the rare ring (RareId) too"); + Check.True(Said("Loot rule: Pearl of Spirit Drinking -> [Keep] Rare (always kept)"), "under its own label"); Check.False(Said("Rares mode"), "nothing says rares mode"); }); @@ -315,15 +325,106 @@ internal static class LootRaresModeTests Check.True(stone.Taken && stone.Rule == LootModes.StoneRule, $"the stone: 1 in the pack, keep count 5: [{stone.Action}] {stone.Rule}"); Check.True(stone.BuiltIn.StartsWith("a needed mana stone, 1 of 5 kept", StringComparison.Ordinal), stone.BuiltIn); - // Profile mode, same world: no LootSnob rule takes the 4,000-mana ring, so Mana Tap does. + // Profile mode, same world: no LootSnob rule takes the 4,000-mana ring. As a rare it is kept, never + // drained (2026-11-29); the same ring without its RareId is a Mana Tap pickup, as before. FakeHost.Ints[(RareRing, 107)] = 4000; bot.S.LootMode = LootModes.Profile; + var kept = bot.Classify(RareRing); + Check.True(kept.Taken && kept.Action == "Keep" && kept.Rule == RareItems.AlwaysKeptRule, $"profile mode: the rare ring is kept, not drained: [{kept.Action}] {kept.Rule}"); + Check.False((bool)bot.Call("ItemNeedsAppraisalForLoot", bot.Cache[unchecked((int)RareGem)]!)!, "profile mode: a rare with its rare icon asks for no ID"); + FakeHost.Ints.Remove((RareRing, RareItems.RareIdKey)); var tap = bot.Classify(RareRing); - Check.True(tap.Taken && tap.Action == "ManaTap", $"profile mode: Mana Tap as before: [{tap.Action}] {tap.Rule}"); + Check.True(tap.Taken && tap.Action == "ManaTap", $"profile mode, not a rare: Mana Tap as before: [{tap.Action}] {tap.Rule}"); + FakeHost.Ints[(RareRing, RareItems.RareIdKey)] = 30183; bot.S.LootMode = LootModes.Rares; Check.Eq(bot.Classify(RareRing).Action, "Keep", "rares mode: the same ring is kept as a rare, not drained"); }); + /// Loots until the corpse is marked done or passes, answering every open + /// (the server's ViewContents) and every close. Returns how many opens were sent. + private static int LootWithReopens(Bot bot, long ms, Action? eachTick = null) + { + int opens = 0, closes = 0; + long end = _now + ms; + while (_now < end && !bot.CorpseDone) + { + eachTick?.Invoke(); + bot.Tick(); + int closed = FakeHost.Closes.Count(c => c == Corpse); + if (closed > closes) { closes = closed; FakeHost.GroundContainer = 0; } + int used = FakeHost.Uses.Count(u => u == Corpse); + if (used > opens) + { + opens = used; + FakeHost.UseDone(0); + FakeHost.GroundContainer = Corpse; + bot.P.OnViewObjectContents(Corpse); + bot.P.OnUpdateObjectInventory(Corpse); + } + } + return opens; + } + + // 2026-11-29: no rare may be left on a corpse. The gem's move is never answered, so every open + // ends with it still there. + private static void RareLeftSetAside() => Clocked(() => + { + World(stoneInPack: false); + NeverLands.Add(RareGem); + var host = FakeHost.Create(Player); + var bot = new Bot(host, LootModes.Profile); + var ids = new List { Corpse }; + ids.AddRange(OnCorpse); + bot.Create(ids.ToArray()); + + int opens = LootWithReopens(bot, 180_000); + const string Line = "[RynthAi] A rare is still on Corpse of Olthoi Swarm Drone: Pearl of Spirit Drinking."; + for (int t = 1; t <= RynthAiPlugin.RareLeftMaxRetries; t++) + Check.True(Said($"{Line} Looting it again in 5 s (try {t} of {RynthAiPlugin.RareLeftMaxRetries})."), $"try {t} is said ({ChatDump()})"); + Check.True(Said($"{Line} Looted {RynthAiPlugin.RareLeftMaxRetries} more times and it stayed. Take it by hand."), "then the line to take it by hand"); + Check.True(bot.CorpseDone, "the corpse is marked done only then"); + Check.True(opens >= 1 + RynthAiPlugin.RareLeftMaxRetries, $"opened again for each try ({opens} opens)"); + Check.True(Moved(RareRing) && Moved(Xbow), "the rest was looted on the first open"); + Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Xbow), 1, "and not taken again"); + + // The gem lands on a later open: no line to take it by hand, the corpse is done. + World(stoneInPack: false); + NeverLands.Add(RareGem); + bot = new Bot(FakeHost.Create(Player), LootModes.Profile); + bot.Create(ids.ToArray()); + LootWithReopens(bot, 60_000, () => { if (Said($"{Line} Looting it again in 5 s (try 1 of")) NeverLands.Clear(); }); + Check.True(FakeHost.Containers[RareGem] == Player, $"the gem is taken on a later open ({ChatDump()})"); + Check.True(bot.CorpseDone, "and the corpse is done"); + Check.False(Said("Take it by hand."), "and nothing says to take it by hand"); + }); + + private static void RareCorpseAndRareFirst() => Clocked(() => + { + // A nearer corpse with no rare, and ours (1 m) moved to 3 m with the rare line on it. + World(stoneInPack: false); + const uint Plain = 0x80267120; + FakeHost.Names[Plain] = "Corpse of Olthoi Swarm Drone"; + FakeHost.ItemTypes[Plain] = ItemTypeContainer; + FakeHost.Strings[(Plain, LongDescKey)] = $"Killed by {Me}."; + FakeHost.NotAttackable.Add(Plain); + FakeHost.Positions[Plain] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); + FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 3.0f, Me0.Y, Me0.Z); + FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}. This corpse generated a rare item!"; + var bot = new Bot(FakeHost.Create(Player), LootModes.Profile); + var ids = new List { Corpse, Plain }; + ids.AddRange(OnCorpse); + bot.Create(ids.ToArray()); + + object?[] args = { 30.0, null, null }; + bool found = (bool)typeof(RynthAiPlugin).GetMethod("TryFindNearestCorpse", Any)!.Invoke(bot.P, args)!; + Check.True(found && ((WorldObject)args[1]!).Id == unchecked((int)Corpse), "the rare corpse is claimed though another is nearer"); + + LootWithReopens(bot, 30_000); + int first = FakeHost.ExternalMoves.FindIndex(m => m.Id == RareGem || m.Id == RareRing); + int other = FakeHost.ExternalMoves.FindIndex(m => m.Id == Xbow || m.Id == Helm || m.Id == Stone); + Check.True(first >= 0 && (other < 0 || first < other), $"a rare is the first pickup ({string.Join(",", FakeHost.ExternalMoves.Select(m => $"{m.Id:X8}"))})"); + }); + private static void DetailsLineNamesReason() => Clocked(() => { LootCorpse(LootModes.Rares, setUp: bot => bot.S.ItemInfoSettings.LootChat = true); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs index 63f111e..c7d9660 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs @@ -52,6 +52,8 @@ internal static class NavEngineTests r.Add("nav engine (11-28): back from a fight, nothing of the route near in sight: the map's way to the waypoint", InSightNoneFallsBack); r.Add("nav engine (11-28): a fight during the walk to the route in sight: looked at again from where it ends", InSightInterrupted); r.Add("nav engine (11-28): Lugian Excavations 0x02E7 on the real dats: the patrol's legs are clear walks, the 18:56 wall stuck isn't, and the route in sight is found from there and from the rooms off the route (if the dats are here)", InSightLugianRealDats); + r.Add("nav engine (11-29): the map's long way back through fight after fight: planned again after each while it gets nearer; three that bring it no nearer end it", LongWalkThroughFights); + r.Add("nav engine (11-29): the nearest waypoint on foot (the patrol's start with nothing in sight): the shortest walk of the nearest few and the old start", NearestOnFootPick); r.Add("nav engine: Go To Closest Waypoint off keeps the last waypoint (hazard/corpse still rejoin)", ResumeNearestOff); r.Add("nav engine: a loaded route starts at [0] for Once/Follow, or for any route with the option off", StartsAtFirstPoint); r.Add("nav engine: nearest waypoint lookup", FindNearest); @@ -94,6 +96,10 @@ internal static class NavEngineTests r.Add("nav engine: an NPC point (VTank type 7) uses its NPC on arrival, once, waits for the answer, then goes on", NpcPointUsesTheNpc); r.Add("nav engine: an NPC point waits while the client is busy with the use, 20 s at most", NpcPointWaitsWhileBusy); r.Add("nav engine: an NPC point whose NPC can't be found says so once and goes on after 15 s", NpcPointNotFound); + r.Add("nav engine (11-29): a Vendor point (VTank type 5) opens its vendor on arrival, once, waits for the window, then goes on", VendorPointOpensTheVendor); + r.Add("nav engine (11-29): a Vendor point whose window never opens says so once and goes on after 20 s", VendorPointNeverOpens); + r.Add("nav engine (11-29): a Vendor point whose vendor can't be found says so once and goes on after 15 s", VendorPointNotFound); + r.Add("nav engine (11-29): a vendor opened by hand away from a Vendor point changes nothing", VendorOpenedElsewhere); } // ── Rig ─────────────────────────────────────────────────────────────────── @@ -527,6 +533,91 @@ internal static class NavEngineTests Check.True(nav.S.EnableNavigation, "nav stays on"); } + // ── Vendor points (OpenVendor, type 5) ──────────────────────────────────── + + private const uint VendorId = 0x7A000003; + + private static Nav VendorRoute(bool vendorThere) + { + FakeHost.Reset(); At(0, 0); + FakeHost.WeaponCalls = true; // UseObject + var pose = FakeHost.PlayerPose; + FakeHost.Names[NpcMe] = "Tester"; + FakeHost.Positions[NpcMe] = pose; + if (vendorThere) + { + FakeHost.Names[VendorId] = "Renald the Grocer"; + FakeHost.Positions[VendorId] = (pose.Cell, pose.X + 2f, pose.Y, pose.Z); + } + var host = FakeHost.Create(NpcMe); + var cache = FakeHost.MakeCache(host, NpcMe, vendorThere ? new[] { VendorId } : Array.Empty()); + var vendor = Pt(0, 0, T.OpenVendor); vendor.TargetName = "Renald the Grocer"; vendor.VendorId = VendorId; + var nav = new Nav(Route(RT.Once, vendor, Pt(20, 0), Pt(40, 0))); + nav.E.SetWorldObjectCache(cache); + nav.E.SetPlayerId(NpcMe); + return nav; + } + + private static void VendorPointOpensTheVendor() + { + var nav = VendorRoute(vendorThere: true); + nav.Tick(); + Check.Eq(nav.Idx, 0, "arrived at the Vendor point: it doesn't go on yet (it used to walk straight past)"); + Check.False(FakeHost.AutoRun, "it stops there"); + nav.Run(1.0); + Check.Eq(FakeHost.Uses.Count(u => u == VendorId), 1, $"the vendor is used, once (uses: {string.Join(",", FakeHost.Uses.Select(u => u.ToString("X8")))})"); + Check.Eq(LogCount("UseObject vendor 'Renald the Grocer'"), 1, "logged as a vendor use"); + nav.Run(10.0); + Check.Eq(nav.Idx, 0, "10 s after the use and no window yet: still waiting for it"); + Check.Eq(FakeHost.Uses.Count(u => u == VendorId), 1, "and not used again while it waits"); + nav.E.NoteVendorOpened(VendorId); // AutoVendor would hold the bot here; the fake doesn't + nav.Run(1.5); + Check.Eq(nav.Idx, 0, "under 2 s after the window opened: still at the vendor"); + nav.Run(1.0); + Check.Eq(nav.Idx, 1, "then on to [1]"); + Check.Eq(FakeHost.Uses.Count(u => u == VendorId), 1, "never used twice"); + Check.Eq(FakeHost.Chat.Count(l => l.Contains("vendor 'Renald the Grocer'")), 0, "nothing said in chat when it worked"); + At(19.5, 0); nav.Tick(); + Check.Eq(nav.Idx, 2, "the next plain waypoint is walked as before"); + } + + private static void VendorPointNeverOpens() + { + var nav = VendorRoute(vendorThere: true); + nav.Tick(); + nav.Run(1.0); + Check.Eq(FakeHost.Uses.Count(u => u == VendorId), 1, "used"); + nav.Run(18.0); + Check.Eq(nav.Idx, 0, "18 s after the use, no window: still waiting"); + nav.Run(2.5); + Check.Eq(nav.Idx, 1, "past 20 s: goes on without it"); + Check.Eq(FakeHost.Chat.Count(l => l.Contains("vendor 'Renald the Grocer'") && l.Contains("didn't open")), 1, "one chat line says so"); + Check.True(nav.S.EnableNavigation, "nav stays on"); + } + + private static void VendorPointNotFound() + { + var nav = VendorRoute(vendorThere: false); + nav.Tick(); + nav.Run(14.0); + Check.Eq(nav.Idx, 0, "14 s looking for the vendor: still there"); + Check.Eq(FakeHost.Uses.Count, 0, "nothing used"); + nav.Run(1.5); + Check.Eq(nav.Idx, 1, "15 s: goes on without it"); + Check.Eq(FakeHost.Chat.Count(l => l.Contains("vendor 'Renald the Grocer'") && l.Contains("wasn't found")), 1, "one chat line says so"); + Check.True(nav.S.EnableNavigation, "nav stays on"); + } + + private static void VendorOpenedElsewhere() + { + FakeHost.Reset(); At(0, 0); + var nav = new Nav(Line(RT.Once, 3, 20)); + nav.E.NoteVendorOpened(VendorId); + nav.Tick(); + Check.Eq(nav.Idx, 1, "a plain route arrives at [0] and goes on as before"); + Check.Eq(LogCount("opened for Vendor point"), 0, "the open isn't taken for a Vendor point's"); + } + private static void RecallTimeoutNear() { var nav = RecallRoute(30); @@ -867,6 +958,84 @@ internal static class NavEngineTests Check.Eq(nav.Idx, 2, "on to [2]"); } + // ── Long walks through fights, and the start on foot (11-29) ───────────── + // Lugian Excavations again: the patrol laid again mid-dungeon started at [0] 425 yd off, and the map's way there was + // broken into by a fight every 10-30 s. Every re-plan was nearer, but the third ended the walk ("out of re-plans") and + // nav steered straight at [0] through the cave walls until the next fight. + + private static void LongWalkThroughFights() + { + FakeHost.Reset(); At(14, 40); + double walk = 530; + var p = new FakePlanner { InSight = _ => false, WalkYd = _ => walk }; + var nav = new Nav(Square(), idx: 2, planner: p); + nav.E.KeepWaypointAfterPause = () => true; + nav.Tick(); + nav.E.Stop(); + At(14, 52); + nav.Run(1.0); + Check.Eq(LogCount("started (back from a pause, [2] is behind a wall"), 1, "the map's way to [2]"); + + // Five fights on the way, each ending 10 yd from where it began, the walk 40 yd shorter each time. + for (int k = 0; k < 5; k++) + { + nav.E.Stop(); + At(14, k % 2 == 0 ? 62 : 52); + walk -= 40; + nav.Run(1.0); + } + Check.Eq(LogCount("re-planned after a pause"), 5, "planned again after each fight"); + Check.Eq(LogCount("out of re-plans"), 0, "never out of re-plans while each is nearer"); + Check.Eq(LogCount("(no nearer"), 0, "none said to be no nearer"); + Check.True(nav.Recovery.Contains("via fake planner"), $"still walking it ({nav.Recovery})"); + Check.Eq(LogCount("attempt 2/"), 0, "no second recovery counted against [2]"); + Check.Eq(LogCount("FAILED"), 0, "nothing failed"); + + // Fights that pull it back as far each time: three bring it no nearer, the fourth ends the walk as before. + for (int k = 0; k < 4; k++) + { + nav.E.Stop(); + At(14, k % 2 == 0 ? 52 : 62); + nav.Run(1.0); + } + Check.Eq(LogCount("(no nearer: 1/3)") + LogCount("(no nearer: 2/3)") + LogCount("(no nearer: 3/3)"), 3, "three said to be no nearer"); + Check.Eq(LogCount("out of re-plans (3 brought it no nearer than 330yd)"), 1, "then out of re-plans, saying why"); + Check.False(nav.Recovery.Contains("via fake planner"), $"that walk is over ({nav.Recovery})"); + } + + private static void NearestOnFootPick() + { + // The lap's [0] across the dungeon; the lap crosses the character's cave later. [7] is nearest but behind a wall, + // [8] has no way there on the map, [9] is a short walk. + var route = Route(RT.Circular, + Pt(425, 0), Pt(300, 0), Pt(200, 0), Pt(120, 0), Pt(80, 0), Pt(60, 0), Pt(40, 0), + Pt(20, 0), Pt(0, 25), Pt(0, 30), Pt(-60, 0), Pt(-140, 0)); + var walks = new Dictionary { [0] = 520, [7] = 300, [8] = null, [9] = 35 }; + var asked = new List(); + double? Walk(NavPoint p) + { + int i = route.Points.IndexOf(p); + asked.Add(i); + if (walks.TryGetValue(i, out var w)) return w; + var (n, e) = NE(p); + return Math.Sqrt(n * n + e * e) * 1.2; + } + int best = NavigationEngine.NearestOnFoot(route, 0, false, 0, NS0, EW0, Walk, out double yd, candidatesNearest: 6); + Check.Eq(best, 9, "the short walk, not the nearer one behind the wall, the one with no way, or [0]"); + Check.True(Math.Abs(yd - 35) < 1e-9, $"its walk ({yd:F1} yd)"); + Check.Eq(string.Join(",", asked.OrderBy(i => i)), "0,5,6,7,8,9,10", "the six nearest and the old start asked, no more"); + + Check.Eq(NavigationEngine.NearestOnFoot(route, 0, false, 0, NS0, EW0, _ => null, out _, candidatesNearest: 6), -1, + "no walk to any: -1 (the patrol keeps its start)"); + walks[0] = 10; + Check.Eq(NavigationEngine.NearestOnFoot(route, 0, false, 0, NS0, EW0, Walk, out _, candidatesNearest: 6), 0, + "the old start the shortest walk: kept"); + + // Steps are never picked (a portal or a chat point between). + var steps = Route(RT.Circular, Pt(300, 0), Pt(5, 0, T.Chat), Pt(20, 0)); + Check.Eq(NavigationEngine.NearestOnFoot(steps, 0, false, 0, NS0, EW0, p => 1.0, out _), 2, "a tie goes to the nearer; never the chat point"); + } + // ── The same on the real map: Lugian Excavations (0x02E7) ─────────────── /// The dungeon patrol laid 2026-11-28 18:50:47 from cell 02E70285 (71 points; world x, y, z).