diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index f888a67..417a96d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -1437,6 +1437,17 @@ public class WorldObjectCache /// This bypasses the crash-prone full cache scan and is the source of truth /// for crafting and ammo diagnostics. /// + /// + /// Something just came into the inventory (a loot pickup landed): the next GetDirectInventory walks + /// the packs again, forced or not. The list is otherwise reused for up to a second (250 ms when + /// forced), and a sceptre on DreamWeave (2026-11-30 03:22) was left because the room check 3 ms after a + /// quick pickup read the list from before the helm landed: one free slot, so no room move. + /// + public void ExpireDirectInventory() + { + lock (_gate) _lastDirectInventoryScan = DateTime.MinValue; + } + public IReadOnlyList GetDirectInventory(bool forceRefresh = false) { // Whole-body lock: the rescan clears+rebuilds _directInventory*, and callers may @@ -1809,32 +1820,31 @@ public class WorldObjectCache } /// - /// Where a looted item goes: the main pack (the player) or 0. The pickup used to be a - /// UseObject, which let the client pick the spot, but a use on a wearable item lying in a - /// corpse is a get-and-wield: jewellery for an empty slot went straight onto the character - /// (2026-10-02). So it is a move, and a move from a corpse or chest can only go to the main - /// pack: the client refuses one straight into a side pack ("You must first pick up the X", - /// and nothing is sent), so the side-pack fallback this used to return when the main pack - /// was full never worked (2026-11-12: 75 such pickups in a week of logs, none landed; the - /// looter waited out 3 + 3 tries on each and left them). + /// Where a looted item goes: the main pack while it has a free slot, else the side pack with the + /// most room, 0 when nothing has room. The pickup used to be a UseObject, which let the client pick + /// the spot, but a use on a wearable item lying in a corpse is a get-and-wield: jewellery for an + /// empty slot went straight onto the character (2026-10-02). So it is a move. /// - /// The main pack has a free slot: the main pack. - /// It is full, and joins a stack you carry: the main pack anyway. - /// The client puts a stack onto a same-name stack with room wherever that is (the pea stacks - /// live in a side pack), so no slot is needed. - /// Otherwise 0: nothing can take it from the corpse ( tells - /// a full main pack from no room at all). + /// Into the main pack the client's own move goes (MoveItemExternal). + /// Into a side pack only the raw 0x19 PutItemInContainer packet goes (, + /// plugin API v80). The client's own move refuses a corpse or chest item aimed at a side pack ("You + /// must first pick up the X", nothing sent: 2026-11-12, 75 such pickups in a week, none landed), but + /// the server takes the packet as any pickup and puts the item in that pack (ACE + /// HandleActionPutItemInContainer: a move from the world to the player's own container). On an engine + /// without the packet a full main pack is the end ( tells that from no room at all). /// + /// A stack you carry is no slot (2026-11-30): the client drops a pickup aimed at a full main pack + /// whatever it would stack with; a DreamWeave hunt left every 'Obsidian Heartstone' from 03:27 to + /// 05:02 that way. /// - /// : packs (or the player id, for the main pack) the server refused lately; - /// a stack join needs no slot, so it goes whatever the main pack's mark. + /// : packs (or the player id, for the main pack) the server refused lately. public static int FindLootDestination(IReadOnlyList inv, int playerId, RynthCoreHost? host = null, - Func? skip = null, WorldObject? item = null) + Func? skip = null) { if (inv == null || playerId == 0) return 0; - if (item != null && JoinsCarriedStack(inv, playerId, item)) return playerId; if (MainPackFreeSlots(inv, playerId, host) > 0 && !(skip != null && skip(playerId))) return playerId; - return 0; + if (host is not { HasPutItemInContainer: true }) return 0; + return FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host, skip); } /// The main pack's free item slots (102 less the loose items in it; packs, foci and worn items don't count). @@ -1852,34 +1862,10 @@ public class WorldObjectCache return 102 - mainUsed; } - /// A side pack has a free slot (so a loot pickup that found no destination met a full main pack, not full packs). + /// A side pack has a free slot (so a loot pickup that found no destination on an engine without the raw move met a full main pack, not full packs). public static bool SidePackHasRoom(IReadOnlyList inv, int playerId, RynthCoreHost? host = null) => inv != null && playerId != 0 && FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host) != 0; - /// - /// stacks and a stack of the same kind you carry (main pack or a side - /// pack) still has room for one more: a pickup aimed at the main pack joins it. - /// - internal static bool JoinsCarriedStack(IReadOnlyList inv, int playerId, WorldObject item) - { - int max = RynthCore.Plugin.RynthAi.Loot.InventoryManager.GetMaxStackSize(item); - if (max <= 1 || string.IsNullOrEmpty(item.Name)) return false; - int wcid = item.Values(unchecked((int)DecalTypeKey), 0); - var packs = new HashSet(); - foreach (var p in inv) - if (p.Container == playerId && p.ObjectClass == AcObjectClass.Container) packs.Add(p.Id); - foreach (var s in inv) - { - if (s.Id == item.Id || s.ObjectClass == AcObjectClass.Container) continue; - if (s.Container != playerId && !packs.Contains(s.Container)) continue; - int sw = s.Values(unchecked((int)DecalTypeKey), 0); - bool same = wcid != 0 && sw != 0 ? sw == wcid : string.Equals(s.Name, item.Name, StringComparison.Ordinal); - if (!same) continue; - if (Math.Max(1, s.Values(LongValueKey.StackCount, 1)) < max) return true; - } - return false; - } - /// /// Re-reads the name and item type of an object stored with a blank name or an Unknown /// class, and replaces its entry when either improved. Corpse items are usually created diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 1f8ad17..ab826d6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -2134,9 +2134,8 @@ public sealed partial class RynthAiPlugin return; } - // The main pack is full and a side pack has room: one item goes from the main pack to - // the side pack first (the client takes loot only into the main pack), then this one. - if (HoldForLootRoom(firstMatchId, matchItemName)) + // A cram or stack move still out: the client would drop this pickup. + if (HoldForItemMove(firstMatchId, matchItemName)) return; ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}"); @@ -2211,7 +2210,6 @@ public sealed partial class RynthAiPlugin _scrollLearner?.NoteLooted(firstMatchId, matchItemName, fromProfile: matchRuleLabel != ScrollLearner.RuleLabel); // Keep # per day: on its way, so it counts until it lands (then it is recorded). NotePerDaySent(firstMatchId); - NoteLootBroughtIn(firstMatchId); _currentLootItemMovePending = true; _currentLootItemMoveRequestedAt = now; // A queued move that the client or server turned away (the client's one-request @@ -2631,16 +2629,15 @@ public sealed partial class RynthAiPlugin /// /// Somewhere other than the pack just tried could take the item (the client's own counts). - /// The only loot destination is the main pack (FindLootDestination), so after it this is a - /// stack join, and one already tried is not a new place to try. + /// FindLootDestination picks it (the main pack, else the side pack with the most room, packs + /// marked full skipped); the pack just tried is not a new place to try. /// private bool HasOtherLootDestination() { if (_objectCache == null || _playerId == 0) return false; long now = CorpseNowMs; int dest = WorldObjectCache.FindLootDestination(_objectCache.GetDirectInventory(forceRefresh: false), - unchecked((int)_playerId), Host, id => _packRefusals.IsRefused(id, now), - _objectCache[_currentLootItemId]); + unchecked((int)_playerId), Host, id => _packRefusals.IsRefused(id, now)); return dest != 0 && dest != _currentLootItemDest; } @@ -3103,9 +3100,9 @@ public sealed partial class RynthAiPlugin { _packRefusals.Refuse(dest, now, confirmed, _currentLootItemId); if (confirmed && !_currentLootItemFullPacks.Contains(dest)) _currentLootItemFullPacks.Add(dest); - // Another round only where there is somewhere else to go. Loot goes only to the main - // pack (FindLootDestination), so after it there is at most a stack join: an item - // refused there for room is given up below, not sent round again into nothing. + // Another round only where there is somewhere else to go (FindLootDestination: the main + // pack, else the side pack with the most room, skipping packs marked full): an item + // refused for room with nowhere else is given up below, not sent round again into nothing. bool another = !_currentLootItemPackRetried && HasOtherLootDestination(); LootDiag(confirmed ? $"[RynthAi] {LootTag}: {LootPackName(dest)} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8} (the server refused {_currentLootItemDestRefusals} after the pickup ran); treating it as full for {RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs / 60_000} min" + @@ -3156,8 +3153,8 @@ public sealed partial class RynthAiPlugin } if (PickupHeldByServerAction()) return; // a retry now would be refused as too busy and use up an attempt - if (HoldForLootRoom(_currentLootItemId, _currentLootItemName)) - return; // the main pack filled meanwhile: room first, then the resend + if (HoldForItemMove(_currentLootItemId, _currentLootItemName)) + return; // a cram or stack move is out: its answer first, then the resend RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId)); Host.SelectItem(unchecked((uint)_currentLootItemId)); @@ -3265,9 +3262,9 @@ public sealed partial class RynthAiPlugin ResetCurrentLootItem(); break; case LootPickupResult.MainPackFull: - // This item only: a stack the next item joins still goes, and so does everything - // once the main pack has a slot again (RynthSort or cram moving things out of it). - LootDiag($"[RynthAi] {LootTag}: leaving '{itemName}' 0x{(uint)itemId:X8} on 0x{(uint)corpseId:X8} — the main pack is full, it joins no stack you carry, and the client takes nothing from a corpse or chest straight into a side pack."); + // Only on an engine before plugin API v80 (no raw move to send it into a side pack): + // this item only; everything goes again once the main pack has a slot. + LootDiag($"[RynthAi] {LootTag}: leaving '{itemName}' 0x{(uint)itemId:X8} on 0x{(uint)corpseId:X8} — the main pack is full, and this engine has no raw move to put it straight into a side pack (the client's own move refuses that from a corpse or chest)."); WarnMainPackFull(itemName); _processedCorpseItems.Add(itemId); ResetCurrentLootItem(); @@ -3278,99 +3275,46 @@ public sealed partial class RynthAiPlugin private DateTime _mainPackFullWarnedAt = DateTime.MinValue; - /// Once per 5 minutes in chat: the main pack is full, so loot is being left (looting goes on). + /// Once per 5 minutes in chat: the main pack is full and this engine can't loot into a side pack (looting goes on). private void WarnMainPackFull(string itemName) { if ((RynthClock.Now - _mainPackFullWarnedAt).TotalMinutes < 5) return; _mainPackFullWarnedAt = RynthClock.Now; - ChatLine($"[RynthAi] Main pack full: '{itemName}' is left. AC loots only into the main pack (or onto a stack you already carry), " + - "and nothing in the main pack could be moved to a side pack to make room. Free a main-pack slot and looting takes everything again."); + ChatLine($"[RynthAi] Main pack full: '{itemName}' is left. This RynthCore is too old to loot into a side pack " + + "(it needs plugin API v80); update it, or free a main-pack slot."); } - // ── Room for loot in a full main pack (2026-11-28) ──────────────────── - // Since 8c14ea53 a pickup goes only into the main pack (the client refuses a corpse or chest item - // aimed straight at a side pack), so with the main pack full every item that joined no stack was - // left, even with side packs empty: looting looked stopped. Now the pickup first has one loose item - // moved from the main pack to a side pack (InventoryManager.MakeLootRoom), waits for that move's - // answer (the client refuses a pickup while it is out), and then takes the freed slot. Up to - // LootRoomMovesPerItem room moves per item; after that, or with nothing that may move, the item is - // left as before. + // ── A cram or stack move still out (2026-11-28) ─────────────────────── + // AutoCram's or AutoStack's last move has no answer yet: the client holds it in its one pending + // item request and drops a pickup sent through it now, so the pickup waits for that answer. - private readonly List _lootBroughtIn = new(); // items the looter sent for, oldest first - private readonly Dictionary _lootRoomMoves = new(); // corpse item -> room moves made for it - private const int LootRoomMovesPerItem = 2; - private bool _lootRoomHoldLogged; - private long _lootRoomHoldTickAt; + private bool _itemMoveHoldLogged; + private long _itemMoveHoldTickAt; - /// A pickup went out for : it is loot, so it is first to move when the main pack needs room. - private void NoteLootBroughtIn(int itemId) + /// True while the pickup of waits for an inventory move's answer. + private bool HoldForItemMove(int itemId, string itemName) { - _lootBroughtIn.Remove(itemId); - _lootBroughtIn.Add(itemId); - if (_lootBroughtIn.Count > 200) _lootBroughtIn.RemoveRange(0, _lootBroughtIn.Count - 200); - } - - private IEnumerable LootBroughtInNewestFirst(int except) - { - for (int i = _lootBroughtIn.Count - 1; i >= 0; i--) - if (_lootBroughtIn[i] != except) yield return _lootBroughtIn[i]; - } - - /// - /// True while the pickup of waits for room in the main pack: a room move - /// was just sent, or the last one has no answer yet. False when the item fits (a free main-pack - /// slot, or a stack it joins), when no side pack has room (the pickup's NoRoom finishes the corpse, - /// as before), or when no room move can be made (the item is left, as before). - /// - private bool HoldForLootRoom(int itemId, string itemName) - { - var inventory = _inventoryManager; - if (inventory == null || _objectCache == null || _playerId == 0 || !Host.HasMoveItemExternal) - return false; - if (inventory.MoveUnanswered(out string waiting)) + if (_inventoryManager == null || !_inventoryManager.MoveUnanswered(out string waiting)) { - if (!_lootRoomHoldLogged) - { - _lootRoomHoldLogged = true; - LootDiag($"[RynthAi] {LootTag}: the pickup of '{itemName}' 0x{(uint)itemId:X8} waits: {waiting}."); - } - PauseCorpseClockForLootRoom(); - return true; + _itemMoveHoldLogged = false; + _itemMoveHoldTickAt = 0; + return false; } - _lootRoomHoldLogged = false; - _lootRoomHoldTickAt = 0; - - int pid = unchecked((int)_playerId); - Func refused = id => _packRefusals.IsRefused(id, CorpseNowMs); - var item = _objectCache[itemId]; - if (WorldObjectCache.FindLootDestination(_objectCache.GetDirectInventory(forceRefresh: false), pid, Host, refused, item) != 0) - return false; - // Read afresh before moving anything: the last room move may have landed since the cached list - // was built (the pickup's own read then sees this list too). - var inv = _objectCache.GetDirectInventory(forceRefresh: true); - if (WorldObjectCache.FindLootDestination(inv, pid, Host, refused, item) != 0) - return false; - if (!WorldObjectCache.SidePackHasRoom(inv, pid, Host)) - return false; - _lootRoomMoves.TryGetValue(itemId, out int made); - if (made >= LootRoomMovesPerItem) - return false; - if (!inventory.MakeLootRoom(LootBroughtInNewestFirst(itemId), out string moved)) - return false; - - if (_lootRoomMoves.Count > 200) _lootRoomMoves.Clear(); - _lootRoomMoves[itemId] = made + 1; - LootDiag($"[RynthAi] {LootTag}: the main pack is full: moving {moved} so '{itemName}' 0x{(uint)itemId:X8} fits there."); - PauseCorpseClockForLootRoom(); + if (!_itemMoveHoldLogged) + { + _itemMoveHoldLogged = true; + LootDiag($"[RynthAi] {LootTag}: the pickup of '{itemName}' 0x{(uint)itemId:X8} waits: {waiting}."); + } + PauseCorpseClockForItemMove(); return true; } - /// The corpse's timeout clock stands still while a pickup waits for room (as PauseCorpseClockWhileHeld does for a server answer). - private void PauseCorpseClockForLootRoom() + /// The corpse's timeout clock stands still while a pickup waits for a move's answer (as PauseCorpseClockWhileHeld does for a server answer). + private void PauseCorpseClockForItemMove() { long now = CorpseNowMs; - long last = _lootRoomHoldTickAt; - _lootRoomHoldTickAt = now; + long last = _itemMoveHoldTickAt; + _itemMoveHoldTickAt = now; if (last == 0 || _targetCorpseId == 0 || _corpseTargetSince == 0) return; long gap = now - last; @@ -3392,6 +3336,9 @@ public sealed partial class RynthAiPlugin return; int itemId = _currentLootItemId; + // It is in a pack now (or merged): the next read of the inventory walks the packs again, so the + // next item's room check counts it (ExpireDirectInventory). + _objectCache?.ExpireDirectInventory(); if (answered) { // The pack it landed in has room, whatever it was marked (an earlier send may have diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs index be4ea07..643faf4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs @@ -1,4 +1,5 @@ // LegacyDashboardRenderer.NavEdit.cs — route editor commands from the engine Nav panel: +// (2026-11-29 also: Vendor, NPC and Jump steps, a Jump edited in place, Undo, New route.) // multi-select move / duplicate / delete, set active, move a step to the player, nearest, // reverse, snap to path, pause / portal / point-at-selection steps, simplify, recording and // trail -> route. @@ -21,6 +22,14 @@ internal sealed partial class LegacyDashboardRenderer /// Decal ObjectClass.Portal, as VTank writes it in Portal steps. private const int PortalObjectClass = 14; + /// Decal ObjectClass.Npc, for NPC steps added from the Nav panel. + private const int NpcObjectClass = 37; + + /// A Jump step's hold when the panel doesn't say (as /ra nav addjump: 300 ms, 30% power). + internal const int AddJumpDefaultMs = 300; + + private static double NormalizeDegrees(double d) => ((d % 360.0) + 360.0) % 360.0; + private string _navEditStatus = string.Empty; private long _navEditStatusAt; @@ -29,6 +38,40 @@ internal sealed partial class LegacyDashboardRenderer private List RoutePoints => _settings.CurrentRoute.Points; + // Undo for the Nav panel's ✕, Delete and Clear all steps (2026-11-29): the steps the last one took + // out, each with its place, for the route they came out of. Another route loaded: nothing to undo. + private List<(int Index, NavPoint Point)>? _navUndo; + private NavRouteParser? _navUndoRoute; + + private int NavUndoCount => + _navUndo != null && ReferenceEquals(_navUndoRoute, _settings.CurrentRoute) ? _navUndo.Count : 0; + + /// Keeps the steps at (before they are taken out) for Undo. + private void RememberNavDelete(IEnumerable indices) + { + var pts = RoutePoints; + var list = new List<(int, NavPoint)>(); + foreach (int i in indices) + if (i >= 0 && i < pts.Count) list.Add((i, pts[i])); + list.Sort((a, b) => a.Item1.CompareTo(b.Item1)); + _navUndo = list.Count > 0 ? list : null; + _navUndoRoute = _settings.CurrentRoute; + } + + /// Puts the last deleted steps back where they were (lowest index first, so each lands in its place). + private void UndoNavDelete() + { + if (NavUndoCount == 0) { SetNavEditStatus("Nothing to undo."); return; } + var undo = _navUndo!; + _navUndo = null; + EditRoute(l => + { + foreach (var (i, pt) in undo) l.Insert(Math.Min(i, l.Count), pt); + return l; + }); + SetNavEditStatus(undo.Count == 1 ? $"Step {undo[0].Index} is back." : $"{undo.Count} steps are back."); + } + /// The last edit's result while it is fresh, else empty. private string CurrentNavEditStatus() => _navEditStatus.Length > 0 && Environment.TickCount64 - _navEditStatusAt < NavEditStatusMs ? _navEditStatus : string.Empty; @@ -64,10 +107,14 @@ internal sealed partial class LegacyDashboardRenderer { var sel = PointsAt(cmd.Indices); if (sel.Count == 0) return; + RememberNavDelete(cmd.Indices!); EditRoute(l => NavRouteEditing.Remove(l, sel)); - SetNavEditStatus($"Deleted {sel.Count} step(s)."); + SetNavEditStatus(sel.Count == 1 && cmd.Indices!.Count == 1 ? $"Deleted step {cmd.Indices[0]}." : $"Deleted {sel.Count} steps."); break; } + case "undoDelete": + UndoNavDelete(); + break; case "setActive": if (cmd.Index < 0 || cmd.Index >= RoutePoints.Count) return; _settings.ActiveNavIndex = cmd.Index; @@ -135,6 +182,75 @@ internal sealed partial class LegacyDashboardRenderer SetNavEditStatus($"Added a point at '{name}'."); break; } + // ── The new Nav panel (2026-11-29): Vendor, NPC and Jump buttons beside Add waypoint here, + // a Jump step's facing / power / walk edited in place, and New route. ── + case "addVendor": + { + if (!TryDescribeNavSelection(out string name, out _, out _, out _) || !TryNavHere(out NavPoint p)) return; + p.Type = NavPointType.OpenVendor; + p.TargetName = name; + p.VendorId = _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0; + InsertNavPoint(p, cmd.AddMode, cmd.InsertAt); + SetNavEditStatus($"Added a Vendor step: open '{name}'."); + break; + } + case "addNpc": + { + if (!TryDescribeNavSelection(out string name, out double ons, out double oew, out double oz) || !TryNavHere(out NavPoint p)) return; + p.Type = NavPointType.Npc; + p.TargetName = name; + p.ObjectClass = NpcObjectClass; + p.PortalExitNS = ons; p.PortalExitEW = oew; p.PortalExitZ = oz; + InsertNavPoint(p, cmd.AddMode, cmd.InsertAt); + SetNavEditStatus($"Added an NPC step: talk to '{name}'."); + break; + } + case "addJump": + { + // Where you stand, facing the way you face unless the panel says (as /ra nav addjump). + if (!TryNavHere(out NavPoint p)) return; + double heading = cmd.Heading; + if (heading < 0) + { + if (!PlayerCompass.TryGet(_host, out float face)) { SetNavEditStatus("Could not read which way you face."); return; } + heading = face; + } + p.Type = NavPointType.Jump; + p.JumpHeading = Math.Round(NormalizeDegrees(heading), 1); + p.JumpMs = cmd.Ms < 0 ? AddJumpDefaultMs : Math.Clamp(Math.Round(cmd.Ms), 0, 1000); + p.JumpShift = cmd.Shift; + InsertNavPoint(p, cmd.AddMode, cmd.InsertAt); + if (_settings.IsRecordingNav) NavBreadcrumbs?.JumpAdded(); // recording waits until you land + SetNavEditStatus($"Added a Jump step: facing {p.JumpHeading:0}°, {p.JumpMs / 10:0}% power{(p.JumpShift ? ", walking" : "")}."); + break; + } + case "setJump": + { + if (cmd.Index < 0 || cmd.Index >= RoutePoints.Count || RoutePoints[cmd.Index].Type != NavPointType.Jump) return; + NavPoint p = RoutePoints[cmd.Index]; + // "Mine": the way the character faces now. + if (cmd.Text == "face") + { + if (!PlayerCompass.TryGet(_host, out float face)) { SetNavEditStatus("Could not read which way you face."); return; } + p.JumpHeading = Math.Round(NormalizeDegrees(face), 1); + } + else if (cmd.Heading >= 0) p.JumpHeading = Math.Round(NormalizeDegrees(cmd.Heading), 1); + if (cmd.Ms >= 0) p.JumpMs = Math.Clamp(Math.Round(cmd.Ms), 0, 1000); + p.JumpShift = cmd.Shift; + _navigationUi.TryAutoSaveNav(); + SetNavEditStatus($"Step {cmd.Index}: jump facing {p.JumpHeading:0}°, {p.JumpMs / 10:0}% power{(p.JumpShift ? ", walking" : "")}."); + break; + } + case "newRoute": + // An empty, unsaved route: the loaded file on disk is not changed. + _settings.IsRecordingNav = false; + _settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once }; + _settings.CurrentNavPath = string.Empty; + _settings.ActiveNavIndex = 0; + SaveSettings(); + SetNavEditStatus("New route: empty and unsaved. Add steps, then Save as."); + break; + case "simplifyRoute": { double tol = Math.Clamp(cmd.Yards, 0.2, 10.0); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 3ce5a1a..a0aeaa7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -3199,6 +3199,12 @@ internal sealed partial class LegacyDashboardRenderer /// The Meta Manager's snapshot JSON for BuildMetaJson (set by the plugin; built on the tick). public Func? ScheduleJsonProvider; + /// + /// The new Nav panel's Mode, Follow, Patrol and Hunt fields (RynthAiPlugin.NavPanel.cs): set by the + /// plugin, called from BuildNavJson. + /// + public Action? NavPanelState; + private void LoadSelectedNav() { // Same finding #16 class as SelectProfileAtIndex above — this direct @@ -3256,9 +3262,30 @@ internal sealed partial class LegacyDashboardRenderer NS = p.NS, EW = p.EW, Z = p.Z, + Name = p.Type switch + { + NavPointType.Recall => NavPoint.RecallName(p.SpellId), + NavPointType.OpenVendor or NavPointType.PortalNPC or NavPointType.Npc => p.TargetName ?? string.Empty, + _ => string.Empty, + }, + Seconds = p.Type == NavPointType.Pause ? p.PauseTimeMs / 1000.0 : 0, + Heading = p.JumpHeading, + Ms = p.JumpMs, + Shift = p.JumpShift, }); } + // How far the step nav walks to next is (the new Nav panel's status card and step list). + double activeDist = -1; + int ai = _settings.ActiveNavIndex; + bool hereKnown = NavCoordinateHelper.TryGetNavPosition(_host, out double hereNs, out double hereEw, out _); + if (hereKnown && ai >= 0 && ai < _settings.CurrentRoute.Points.Count) + { + var ap = _settings.CurrentRoute.Points[ai]; + double dNs = ap.NS - hereNs, dEw = ap.EW - hereEw; + activeDist = Math.Sqrt(dNs * dNs + dEw * dEw) * 240.0; + } + int routeTypeInt = _settings.CurrentRoute.RouteType switch { NavRouteType.Circular => 1, @@ -3293,7 +3320,14 @@ internal sealed partial class LegacyDashboardRenderer EditStatus = CurrentNavEditStatus(), StrayNavCount = _strayNavs?.Count ?? 0, StrayNavText = _strayNavText ?? string.Empty, + ActiveDist = activeDist, + HereKnown = hereKnown, + HereNS = hereKnown ? hereNs : 0, + HereEW = hereKnown ? hereEw : 0, + UndoCount = NavUndoCount, }; + // Follow, patrol and hunt live in the plugin: it fills in what is running and their state. + try { NavPanelState?.Invoke(payload); } catch { } return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.NavBridgePayload); } catch { return "{}"; } @@ -3397,6 +3431,8 @@ internal sealed partial class LegacyDashboardRenderer int di = cmd.Index; if (di >= 0 && di < _settings.CurrentRoute.Points.Count) { + RememberNavDelete(new[] { di }); // the Nav panel's Undo (LegacyDashboardRenderer.NavEdit.cs) + SetNavEditStatus($"Deleted step {di}."); _settings.CurrentRoute.Points.RemoveAt(di); _settings.ActiveNavIndex = LegacyNavigationUi.IndexAfterDelete(_settings.ActiveNavIndex, di, _settings.CurrentRoute.Points.Count); _navigationUi.TryAutoSaveNav(); @@ -3404,6 +3440,8 @@ internal sealed partial class LegacyDashboardRenderer break; case "clearRoute": + RememberNavDelete(System.Linq.Enumerable.Range(0, _settings.CurrentRoute.Points.Count)); + if (_settings.CurrentRoute.Points.Count > 0) SetNavEditStatus($"Cleared {_settings.CurrentRoute.Points.Count} steps."); _settings.CurrentRoute.Points.Clear(); _settings.ActiveNavIndex = 0; _navigationUi.TryAutoSaveNav(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 7fe3667..0d462cb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -1384,6 +1384,23 @@ public sealed class NavBridgePoint public double NS { get; set; } public double EW { get; set; } public double Z { get; set; } + // The new Nav panel (2026-11-29) shows each step as a label and a detail, and edits Jump steps. + /// Portal, Vendor and NPC steps: the object's name. Recall: the spell's name. Empty otherwise. + public string Name { get; set; } = string.Empty; + /// Pause steps: how long, in seconds. + public double Seconds { get; set; } + /// Jump steps: the facing (degrees, 0 north), the hold (0-1000 ms, the power) and a walking jump. + public double Heading { get; set; } + public double Ms { get; set; } + public bool Shift { get; set; } +} + +/// A player near the character, for the Nav panel's Follow tab (2026-11-29). +public sealed class NavBridgeNearby +{ + public string Name { get; set; } = string.Empty; + public double Dist { get; set; } // yd from the character + public string Tag { get; set; } = string.Empty; // "Leader", "Fellow" or "" } public sealed class NavBridgePayload @@ -1416,6 +1433,45 @@ public sealed class NavBridgePayload /// 0 / empty when there are none; an engine that predates them ignores both. public int StrayNavCount { get; set; } public string StrayNavText { get; set; } = string.Empty; + + // ── The new Nav panel (2026-11-29): its Route, Follow, Patrol and Hunt tabs. An engine that + // predates it ignores all of these; the plugin fills the mode fields (NavPanelState). ── + /// What is moving the character now: "route", "follow", "patrol", "hunt", or "" (nothing). + public string Mode { get; set; } = string.Empty; + /// yd from the character to the step nav walks to next; -1 when unknown. + public double ActiveDist { get; set; } = -1; + /// Where the character stands (nav coordinates), for each step's distance; HereKnown false when unknown. + public bool HereKnown { get; set; } + public double HereNS { get; set; } + public double HereEW { get; set; } + /// Steps the last delete or clear took out that Undo (undoDelete) can put back; 0 when none. + public int UndoCount { get; set; } + /// Follow is on (FollowMode), and who: 1 the fellowship leader, 2 someone by name. + public bool FollowOn { get; set; } + public int FollowWho { get; set; } + /// The name of whoever Follow follows (empty: no one yet), and yd to them (-1 unknown). + public string FollowName { get; set; } = string.Empty; + public double FollowDist { get; set; } = -1; + /// The fellowship leader's name (empty: no fellowship, or the character leads it), and yd to them. + public string LeaderName { get; set; } = string.Empty; + public double LeaderDist { get; set; } = -1; + /// The player selected in the game now (empty: none, or not a player), and yd to them. + public string SelectedName { get; set; } = string.Empty; + public double SelectedDist { get; set; } = -1; + /// Players nearby, nearest first (a few). + public List Nearby { get; set; } = new(); + /// In a dungeon now, and the patrol's dungeon ("dungeon 0x0083"); the patrol is on (laid, maybe paused). + public bool InDungeon { get; set; } + public string PlaceName { get; set; } = string.Empty; + public bool PatrolOn { get; set; } + /// The Hunt tab: false in builds without the hunt in its panels (public releases), and the tab hides. + public bool HuntAvailable { get; set; } + public bool HuntOn { get; set; } + /// The monster the hunt walks to (empty: none yet) and yd to it, and the hunt's last note. + public string HuntTarget { get; set; } = string.Empty; + public double HuntTargetDist { get; set; } = -1; + public string HuntNote { get; set; } = string.Empty; + public bool HuntKeepAfterDeath { get; set; } } /// One-shot command sent from the Avalonia NavPanel to the plugin. @@ -1438,6 +1494,9 @@ public sealed class NavCommand public double Seconds { get; set; } // addPause public double Yards { get; set; } // simplifyRoute tolerance public bool Reverse { get; set; } // trailToRoute: backtrack (walk the trail in reverse) + public double Heading { get; set; } = -1; // addJump / setJump / tryJump: degrees (-1: the way you face) + public double Ms { get; set; } = -1; // addJump / setJump / tryJump: hold 0-1000 (-1: 300) + public bool Shift { get; set; } // addJump / setJump / tryJump: a walking jump } /// Bridge payload for the engine-side Avalonia SettingsPanel. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs index 2e77627..b2e4aad 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -335,97 +335,6 @@ public sealed class InventoryManager // tip a near-full sub-pack). It reuses AutoCram's single per-tick `inv` snapshot via // the snapshot overload (no extra BFS / no double-refresh). - // ── Room for loot (2026-11-28) ──────────────────────────────────────── - // The client takes a corpse or chest item only into the main pack (8c14ea53, "You must first pick - // up the Silver Pea"), so with the main pack full the looter left every item that joins no stack, - // side packs empty or not. With RynthSort's auto-sort on (Auto Cram off) nothing ever emptied the - // main pack, and Auto Cram never runs while a corpse is open, so a big corpse lost what didn't fit. - // Now a pickup that finds the main pack full and a side pack with room first moves one loose item - // from the main pack into that side pack (a pack-to-pack move, which the client sends); the pickup - // then takes the freed slot. Loot the looter brought in goes first, newest first; then other loose - // items, newest first, with kits, stones and food last. Never a worn or wielded item, a pack, a - // focus, a weapon or wand, a UST, a Weapons-tab item, or one whose move failed lately. - - private int _roomMoveId; - - /// - /// Moves one loose item out of the main pack into the side pack with the most room, so a loot - /// pickup fits there. : the items the looter brought in, newest - /// first; they go first. False when no side pack has a free slot or nothing may move. The move is - /// noted like a cram move: holds the pickup until its answer. - /// - public bool MakeLootRoom(IEnumerable lootedNewestFirst, out string what) - { - what = ""; - if (!_host.HasMoveItemInternal) return false; - uint player = _host.GetPlayerId(); - if (player == 0) return false; - int pid = unchecked((int)player); - var inv = _cache.GetDirectInventory(forceRefresh: true).ToList(); - - // The last room move: still in the main pack after its answer, so it did not go. - if (_roomMoveId != 0) - { - var last = inv.FirstOrDefault(o => o.Id == _roomMoveId); - if (last != null && last.Container == pid) - { - RegisterFailure(_cramBackoff, _roomMoveId); - _host.Log($"[RynthAi] Loot room: '{last.Name}' 0x{_roomMoveId:X8} is still in the main pack after its move; trying another item."); - } - else - _cramBackoff.Remove(_roomMoveId); - _roomMoveId = 0; - } - - int pack = WorldObjectCache.FindPackFor(inv, pid, includeMainPack: false, requireFree: 1, _host); - if (pack == 0) return false; - - WorldObject? pick = null; - var byId = new Dictionary(); - foreach (var o in inv) byId[o.Id] = o; - foreach (int id in lootedNewestFirst) - if (byId.TryGetValue(id, out var wo) && MayMoveForRoom(wo, pid, looted: true)) { pick = wo; break; } - pick ??= inv.Where(o => MayMoveForRoom(o, pid, looted: false)) - .OrderBy(o => IsHandyKind(o) ? 1 : 0) - .ThenByDescending(o => unchecked((uint)o.Id)) - .FirstOrDefault(); - if (pick == null) return false; - - int amount = Math.Max(1, pick.Values(LongValueKey.StackCount, 1)); - if (!_host.MoveItemInternal(unchecked((uint)pick.Id), unchecked((uint)pack), slot: 0, amount: amount)) - { - RegisterFailure(_cramBackoff, pick.Id); - _host.Log($"[RynthAi] Loot room: the move of '{pick.Name}' 0x{pick.Id:X8} to pack 0x{(uint)pack:X8} was turned down; backing off that item."); - return false; - } - _roomMoveId = pick.Id; - NoteMoveSent(unchecked((uint)pick.Id), pid, amount, merge: false, $"'{pick.Name}'"); - what = $"'{pick.Name}' 0x{pick.Id:X8} to pack 0x{(uint)pack:X8}"; - return true; - } - - /// A loose main-pack item a loot room move may take (: one the looter brought in). - private bool MayMoveForRoom(WorldObject wo, int playerId, bool looted) - { - if (wo.Container != playerId) return false; - if (wo.Values(LongValueKey.EquippedSlots, 0) != 0) return false; - if (WorldObjectCache.IsWieldedByPlayer(_host, wo)) return false; - if (wo.ObjectClass is AcObjectClass.Container or AcObjectClass.Foci or AcObjectClass.Ust) return false; - if (!string.IsNullOrEmpty(wo.Name) && wo.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) return false; - if (wo.Values(LongValueKey.ItemsCapacity, 0) > 0 || wo.Values(LongValueKey.ContainersCapacity, 0) > 0) return false; - if (_cramPending.ContainsKey(wo.Id)) return false; - if (_cramBackoff.TryGetValue(wo.Id, out var b) && RynthClock.Now < b.NextRetry) return false; - if (_settings.ItemRules.Any(r => r.Id == wo.Id)) return false; // the Weapons tab keeps these at hand - // The character's own weapons and wands stay where the swaps find them; looted ones are loot. - if (!looted && wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb) - return false; - return true; - } - - /// Things a player reaches for (RynthSort's default handy kinds): moved for room only when nothing else may go. - private static bool IsHandyKind(WorldObject wo) => - wo.ObjectClass is AcObjectClass.HealingKit or AcObjectClass.ManaStone or AcObjectClass.Food; - // ── AutoStack ───────────────────────────────────────────────────────── private bool ProcessAutoStack(List inv, int playerId) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs index 7e49cdf..5678e99 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs @@ -12,8 +12,9 @@ internal enum LootPickupResult Used, /// No pack of ours has a free slot. NoRoom, - /// The main pack is full and the item joins no stack you carry. Side packs may have room, but the - /// client takes nothing from a corpse straight into one, so this item can't be looted now; others still can. + /// The main pack is full and side packs have room, but this engine has no raw move (plugin API + /// before v80) and the client's own move takes nothing from a corpse straight into a side pack, so this + /// item can't be looted now; others still can. MainPackFull, /// No move call, and a use could put the item on the character, so nothing was sent. Refused, @@ -45,11 +46,16 @@ internal static class LootPickup if (cache != null) { var inv = cache.GetDirectInventory(forceRefresh: false); - dest = WorldObjectCache.FindLootDestination(inv, pid, host, skip, cache[unchecked((int)itemId)]); + dest = WorldObjectCache.FindLootDestination(inv, pid, host, skip); if (dest == 0) - return WorldObjectCache.SidePackHasRoom(inv, pid, host) ? LootPickupResult.MainPackFull : LootPickupResult.NoRoom; + return WorldObjectCache.SidePackHasRoom(inv, pid, host) && !host.HasPutItemInContainer + ? LootPickupResult.MainPackFull : LootPickupResult.NoRoom; } destination = unchecked((uint)dest); + // A side pack: the raw 0x19 packet (the client's own move refuses a corpse item aimed at a + // side pack and sends nothing; the server takes the packet as a pickup into that pack). + if (dest != pid) + return host.PutItemInContainer(itemId, destination, 0) == 1 ? LootPickupResult.Moved : LootPickupResult.Failed; return host.MoveItemExternal(itemId, destination, 0) ? LootPickupResult.Moved : LootPickupResult.Failed; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index f04ab2f..d761331 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -795,6 +795,8 @@ public static unsafe class PluginExports string? json = Marshal.PtrToStringAnsi(ansiJson); if (string.IsNullOrEmpty(json)) return; var cmd = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.NavCommand); + // The Nav panel's Route / Follow / Hunt buttons and a jump's Try it (RynthAiPlugin.NavPanel.cs). + if (cmd != null && Runtime.Plugin?.HandleNavPanelCommand(cmd) == true) return; switch (cmd?.Cmd) { case "dunPatrol": Runtime.Plugin?.HandleDungeonNavPatrol(); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs index 56c6123..7687325 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs @@ -562,11 +562,11 @@ public sealed partial class RynthAiPlugin public string? HoldReason() => _p.ItemToolHoldReason(yieldToLooter: true); /// - /// No room for the chest's loot anywhere. Since 2026-11-28 the looter makes room itself when - /// only the main pack is full (one item goes to a side pack, then the pickup: HoldForLootRoom), - /// so a full main pack alone holds no key any more (it stopped with room left in the side - /// packs). Held: the main pack full and no side - /// pack with a free slot, or fewer free slots in all packs than the looter keeps for weapon + /// No room for the chest's loot anywhere. With the main pack full the looter puts the loot + /// straight into a side pack (the raw move, FindLootDestination; 2026-11-30), so a full main + /// pack alone holds no key (it stopped with room left in the side packs). Held: the main pack + /// full and no side pack with a free slot (or an engine with no raw move), or fewer free slots + /// in all packs than the looter keeps for weapon /// swaps (it would leave everything). /// public string? NoRoomReason() @@ -582,7 +582,7 @@ public sealed partial class RynthAiPlugin return $"{total} free slot(s) left in all your packs (looting keeps {WorldObjectCache.LootReserveFreeSlots} free for weapon swaps); sell, salvage or drop something"; int mainFree = WorldObjectCache.MainPackFreeSlots(inv, playerId, Host); if (mainFree > 0) return null; - if (Host.HasMoveItemExternal && WorldObjectCache.SidePackHasRoom(inv, playerId, Host)) return null; // the looter moves one item to a side pack, then picks up + if (Host.HasPutItemInContainer && WorldObjectCache.SidePackHasRoom(inv, playerId, Host)) return null; // the looter puts it straight into a side pack return "the main pack is full and no side pack has a free slot; sell, salvage or drop something"; } catch { return null; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NavPanel.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NavPanel.cs new file mode 100644 index 0000000..0049665 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NavPanel.cs @@ -0,0 +1,198 @@ +// ============================================================================ +// RynthSuite - RynthAiPlugin.NavPanel.cs +// The new engine Nav panel (2026-11-29, NavFace.cs): its Route, Follow, Patrol and Hunt tabs. +// +// FillNavPanelState adds to the panel's payload (LegacyDashboardRenderer.BuildNavJson) what lives +// in the plugin: what is moving the character now (route, follow, patrol or hunt), who Follow +// follows and who is around to follow, the dungeon patrol and the hunt. HandleNavPanelCommand takes +// the tabs' start and stop buttons, through the same code as the chat commands (/ra follow, +// /ra hunt, /ra dunnav-patrol), so the panel and the commands never disagree. +// ============================================================================ + +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// How far the Follow tab looks for players to pick from, and how many it lists. + private const double NavPanelNearbyYd = 150; + private const int NavPanelNearbyMax = 8; + + /// The Hunt tab: off in the public release builds, which leave the hunt out of their panels (on in PC builds). + private static readonly bool NavPanelHuntTab = false; + + private void FillNavPanelState(NavBridgePayload p) + { + var s = _dashboard?.Settings; + if (s == null) return; + int me = unchecked((int)_playerId); + + // What moves the character now. The hunt and the patrol each lay their own route, so they win + // over "route"; Follow overrides the route while it is on. + bool macro = s.IsMacroRunning; + if (HuntActive) p.Mode = "hunt"; + else if (_dunPatrolActive && macro && s.EnableNavigation) p.Mode = "patrol"; + else if (s.FollowMode && macro) p.Mode = "follow"; + else if (macro && s.EnableNavigation && s.CurrentRoute.Points.Count > 0) p.Mode = "route"; + + // Follow: who, and who is around. + p.FollowOn = s.FollowMode; + p.FollowWho = s.FollowNamedTargetId != 0 ? 2 : 1; + int leader = _fellowshipTracker?.IsInFellowship == true ? _fellowshipTracker.LeaderId : 0; + if (leader != 0 && leader != me) + { + p.LeaderName = ObjectName(unchecked((uint)leader)); + p.LeaderDist = YardsTo(me, leader); + } + uint followId = s.FollowNamedTargetId != 0 ? s.FollowNamedTargetId : unchecked((uint)(leader != me ? leader : 0)); + if (followId != 0) + { + p.FollowName = ObjectName(followId); + p.FollowDist = YardsTo(me, unchecked((int)followId)); + } + + if (Host.HasGetSelectedItemId && Host.GetSelectedItemId() is uint sel && sel != 0 && sel != _playerId + && _objectCache?[unchecked((int)sel)] is { ObjectClass: RynthCore.Loot.AcObjectClass.Player } selWo) + { + p.SelectedName = selWo.Name ?? string.Empty; + p.SelectedDist = YardsTo(me, selWo.Id); + } + + if (_objectCache != null) + { + var near = new List(); + foreach (var wo in _objectCache.GetLandscapeObjects()) + { + if (wo.ObjectClass != RynthCore.Loot.AcObjectClass.Player || wo.Id == me || string.IsNullOrEmpty(wo.Name)) continue; + double d = YardsTo(me, wo.Id); + if (d < 0 || d > NavPanelNearbyYd) continue; + string tag = wo.Id == leader ? "Leader" : _fellowshipTracker?.IsMember(wo.Id) == true ? "Fellow" : ""; + near.Add(new NavBridgeNearby { Name = wo.Name, Dist = Math.Round(d, 1), Tag = tag }); + } + near.Sort((a, b) => a.Dist.CompareTo(b.Dist)); + if (near.Count > NavPanelNearbyMax) near.RemoveRange(NavPanelNearbyMax, near.Count - NavPanelNearbyMax); + p.Nearby = near; + } + + // Patrol: in a dungeon, which one, and whether the patrol is laid. + if (TryHuntPosition(out uint cell, out _)) + { + p.InDungeon = InDungeon(cell); + if (p.InDungeon) p.PlaceName = $"dungeon 0x{cell >> 16:X4}"; + } + p.PatrolOn = _dunPatrolActive; + + // Hunt (outdoors, or the dungeon hunt in a dungeon). + p.HuntAvailable = NavPanelHuntTab; + if (NavPanelHuntTab) + { + p.HuntOn = HuntActive; + p.HuntKeepAfterDeath = s.KeepHuntingAfterDeath; + if (_hunt.Active) + { + p.HuntNote = _hunt.WalkingOut ? "Walking back out of a building" : _hunt.Note ?? string.Empty; + if (_hunt.TargetId != 0) + { + p.HuntTarget = ObjectName(unchecked((uint)_hunt.TargetId)); + p.HuntTargetDist = YardsTo(me, _hunt.TargetId); + } + } + } + } + + private string ObjectName(uint id) => + id != 0 && Host.HasGetObjectName && Host.TryGetObjectName(id, out string name) ? name ?? string.Empty : string.Empty; + + /// World units between two objects (what nav calls yards), or -1 when either has no position. + private double YardsTo(int from, int to) + { + if (_objectCache == null || from == 0 || to == 0) return -1; + double d = _objectCache.Distance(from, to); + return d == double.MaxValue || double.IsNaN(d) ? -1 : Math.Round(d, 1); + } + + /// + /// The Nav panel's mode buttons (RynthPluginSendNavCommand): true when the command was one of them. + /// startRoute, follow (Text: "leader", "target" or a name), followOff, hunt (On), huntDeath (On), tryJump. + /// + internal bool HandleNavPanelCommand(NavCommand cmd) + { + var s = _dashboard?.Settings; + switch (cmd.Cmd) + { + case "startRoute": + { + // The route's Start button: whatever else moves the character stops first. + if (s == null) return true; + if (HuntActive) ToggleHunt(); + if (s.FollowMode) HandleFollowCommand(new[] { "ra", "follow", "off" }); + if (!s.IsMacroRunning && RefuseMacroStartForVTank()) return true; + _dashboard!.HandleNavCommand("{\"Cmd\":\"startNav\"}"); + return true; + } + case "follow": + { + if (s == null) return true; + string who = (cmd.Text ?? string.Empty).Trim(); + if (who.Equals("target", StringComparison.OrdinalIgnoreCase)) + { + uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0; + string name = ObjectName(sel); + if (sel == 0 || sel == _playerId || name.Length == 0) { ReplyFail("[RynthAi] Follow: select the player to follow first."); return true; } + s.FollowNamedTargetId = sel; + s.FollowMode = true; + s.EnableNavigation = true; + ReplyOk($"[RynthAi] Follow ON — following {name}."); + } + else + { + var parts = new List { "ra", "follow" }; + parts.AddRange((who.Length == 0 ? "leader" : who).Split(' ', StringSplitOptions.RemoveEmptyEntries)); + HandleFollowCommand(parts.ToArray()); + } + if (!s.FollowMode) return true; // no one by that name: the reply said so + if (HuntActive) ToggleHunt(); + // Follow moves only while the macro runs: the panel's button starts it. + if (!s.IsMacroRunning) + { + if (RefuseMacroStartForVTank()) return true; + s.SetMacroRunning(true, "the Nav panel's Follow"); + } + s.EnableNavigation = true; + return true; + } + case "followOff": + if (s == null) return true; + HandleFollowCommand(new[] { "ra", "follow", "off" }); + s.EnableNavigation = false; // stop where you are, not on along the loaded route + return true; + case "hunt": + if (!NavPanelHuntTab) return true; + if (cmd.On != HuntActive) + { + if (cmd.On && s?.FollowMode == true) HandleFollowCommand(new[] { "ra", "follow", "off" }); + ToggleHunt(); + } + return true; + case "huntDeath": + if (NavPanelHuntTab) SetKeepHuntingAfterDeath(cmd.On ? "on" : "off"); + return true; + case "tryJump": + { + // Try it: the jump where you stand, with the step's values, the way a Jump step does it + // (forward, "ws" when walking: the nav engine's Jump in RynthAiPlugin.cs). + double heading = cmd.Heading < 0 ? 0 : cmd.Heading % 360.0; + int ms = (int)Math.Clamp(Math.Round(cmd.Ms < 0 ? LegacyDashboardRenderer.AddJumpDefaultMs : cmd.Ms), 0, 1000); + string verb = cmd.Shift ? "jumpws" : "jumpw"; + HandleJumpCommand(verb, new[] { "ra", verb, + heading.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture), + ms.ToString(System.Globalization.CultureInfo.InvariantCulture) }); + return true; + } + } + return false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs index aaccd83..8f5ced1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OwnCorpse.cs @@ -208,8 +208,8 @@ public sealed partial class RynthAiPlugin if (_busyCount > 0 && _lastLootActionAt != 0 && now - _lastLootActionAt < OwnCorpseBusyWaitMs) return; - // A full main pack: one item goes to a side pack first (the client loots only into the main pack). - if (HoldForLootRoom(next.Id, string.IsNullOrWhiteSpace(next.Name) ? $"0x{(uint)next.Id:X8}" : next.Name)) + // A cram or stack move still out: the client would drop this pickup. + if (HoldForItemMove(next.Id, string.IsNullOrWhiteSpace(next.Name) ? $"0x{(uint)next.Id:X8}" : next.Name)) return; // Still animating: right after a pickup's answer that is its Return, and ACE queues one diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index d726072..cf93c22 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -249,6 +249,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _dashboard = new LegacyDashboardRenderer(Host); _killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true; _dashboard.KillClock = _killClock; + _dashboard.NavPanelState = FillNavPanelState; // the Nav panel's mode tabs (RynthAiPlugin.NavPanel.cs) // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line // each, and no automatic door/corpse use while the macro is off. RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true); diff --git a/Plugins/Shared/RynthUi/RynthIcons.cs b/Plugins/Shared/RynthUi/RynthIcons.cs index 3f74be8..6c9e53c 100644 --- a/Plugins/Shared/RynthUi/RynthIcons.cs +++ b/Plugins/Shared/RynthUi/RynthIcons.cs @@ -21,6 +21,7 @@ internal static class RynthIcons public const string ArrowRight = "\uE06C"; public const string ArrowSquareIn = "\uE5DC"; public const string ArrowSquareOut = "\uE5DE"; + public const string ArrowUUpLeft = "\uE08A"; public const string ArrowUp = "\uE08E"; public const string ArrowsClockwise = "\uE094"; public const string ArrowsInLineVertical = "\uE532"; @@ -40,6 +41,7 @@ internal static class RynthIcons public const string ChartLineUp = "\uE156"; public const string ChatCircleText = "\uE16E"; public const string Check = "\uE182"; + public const string CheckCircle = "\uE184"; public const string CheckSquare = "\uE186"; public const string ClipboardText = "\uE198"; public const string ClockCounterClockwise = "\uE1A0"; @@ -60,6 +62,7 @@ internal static class RynthIcons public const string Fire = "\uE242"; public const string Flask = "\uE79E"; public const string FloppyDisk = "\uE248"; + public const string FolderOpen = "\uE256"; public const string Footprints = "\uEA88"; public const string Funnel = "\uE266"; public const string Gear = "\uE270"; diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 362d22a..9188f97 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -199,6 +199,7 @@ internal static class Program DamageRowsTests.Register(runner); ShieldFacingTests.Register(runner); NavMapEditTests.Register(runner); + NavPanelTests.Register(runner); LootSpeedTests.Register(runner); MeleeStallTests.Register(runner); NativeAttackTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs index f956057..6673912 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs @@ -58,7 +58,7 @@ internal static class ItemToolTests // Plugin glue r.Add("item tool: the chest looter picks the selected chest and key, unlocks, opens and loots with the macro off, stops when out of keys", PluginChestRun); r.Add("item tool: chest/key picks refuse the wrong things (a pack item as chest, a world object as key, house storage)", PluginChestPicks); - r.Add("item tool: a full main pack holds no key while a side pack has room (the looter makes room); every pack full or under the 2-slot reserve holds it (2026-11-28)", PluginNoRoomOnlyWhenAllFull); + r.Add("item tool: a full main pack holds no key while a side pack has room (loot goes straight into it, 2026-11-30); every pack full, the 2-slot reserve, or no raw move holds it (2026-11-28)", PluginNoRoomOnlyWhenAllFull); r.Add("item tool: Quick give hands over exactly the picked item to the picked NPC, never worn gear or other names", PluginQuickGive); r.Add("item tool: Quick give starts only from the panel or a typed line, never from a meta, a script or a remote line; stop works from anywhere", PluginGiveTrust); r.Add("item tool: Quick give targets are players or NPCs only", PluginGiveTargets); @@ -1178,9 +1178,10 @@ internal static class ItemToolTests private const uint SidePack = 0x80290200, JunkBase = 0x80291000, SideJunkBase = 0x80292000; /// The chest looter's room check with the main pack full and of a 24-slot side pack's slots used. - private static string? NoRoomWithFullMain(int sideUsed, bool mainFull = true) + private static string? NoRoomWithFullMain(int sideUsed, bool mainFull = true, bool rawMove = true) { BaseWorld(); + FakeHost.PutCalls = rawMove; // the raw 0x19 packet the looter puts side-pack loot through (v80) FakeHost.Names[SidePack] = "Backpack"; FakeHost.ItemTypes[SidePack] = 0x200; FakeHost.Ints[(SidePack, 6u)] = 24; // ItemsCapacity @@ -1206,11 +1207,13 @@ internal static class ItemToolTests } // 2026-11-28: looting stopped with a full main pack although the side packs had room; it should - // fill the side packs (the looter makes room since e026c97c). + // fill the side packs (since 2026-11-30 the looter puts the loot straight into a side pack by the raw packet). private static void PluginNoRoomOnlyWhenAllFull() { Check.Eq(NoRoomWithFullMain(0, mainFull: false), null, "room in the main pack: keys go"); - Check.Eq(NoRoomWithFullMain(0), null, "main pack full, an empty side pack: keys go (the looter moves one item to the side pack, then picks up)"); + Check.Eq(NoRoomWithFullMain(0), null, "main pack full, an empty side pack: keys go (the loot goes straight into the side pack)"); + string? old = NoRoomWithFullMain(0, rawMove: false); + Check.True(old != null && old.Contains("the main pack is full"), "main pack full on an engine with no raw move: held, nothing could take the loot: " + old); Check.Eq(NoRoomWithFullMain(22), null, "2 side slots left: still goes"); string? one = NoRoomWithFullMain(23); Check.True(one != null && one.Contains("1 free slot(s) left in all your packs"), "1 slot left in all: held (looting keeps 2 for weapon swaps): " + one); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index 7e201d6..a2cb303 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -71,7 +71,7 @@ internal static class LootCorpseTests r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed); r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse); r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation); - r.Add("loot: the main pack, the only place loot can go, takes none of an item's tries: judged full, the item given up, and one item's mark goes with it", RefusingPackIsLeftOut); + r.Add("loot: the main pack, the only place loot can go on an engine with no raw move, takes none of an item's tries: judged full, the item given up, and one item's mark goes with it", RefusingPackIsLeftOut); r.Add("loot pacing: no pickup (first or retry) while the server owes an answer to a cast; it goes on the UseDone", PickupWaitsForCastAnswer); r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory); r.Add("loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait", MergedPickupConfirmedQuickly); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs index a0f1de0..4e54288 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootRetryTimingTests.cs @@ -43,8 +43,10 @@ internal static class LootRetryTimingTests r.Add("loot retry (R-20261029-122319-321f): with 1.7 s answers no move is resent while one is out, no pack is marked full, every item lands", SlowServerNoFalseFull); r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends); a second item refused there keeps it marked full; nothing goes to a side pack", FullMainPackRefusals); r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait, three tries, then given up (no side-pack round); their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison); - r.Add("loot pickup, main pack full (2026-11-12 'You must first pick up the Silver Pea'): a pea joins the stack you carry, a gem is left at once with one chat line, nothing is aimed at a side pack, the corpse completes", FullMainPackPeaJoinsGemLeft); - r.Add("loot pickup, main pack full, a side pack with room (2026-11-28): one main-pack item moves to the side pack per pickup (loot it brought in first), the pickup waits for that move's answer, every gem lands in the main pack, nothing is left", FullMainPackMakesRoom); + r.Add("loot pickup, main pack full, an engine with no raw move (2026-11-12 'You must first pick up the Silver Pea'): the gem and a pea with a stack to join are left at once with one chat line, nothing is sent, the corpse completes", FullMainPackPeaJoinsGemLeft); + r.Add("loot pickup, main pack full, a side pack with room (2026-11-30: loot into side packs): every gem goes straight into the side pack by the raw packet, no room moves, the client drops nothing, nothing is left", FullMainPackLootsIntoSidePack); + r.Add("loot pickup, main pack full (2026-11-30 Heartstones): a stacking item with a carried stack to join goes to the side pack too, not to the full main pack; it lands", FullMainPackStackGoesToSidePack); + r.Add("loot pickup, main pack full (2026-11-30 03:22): with no timed re-walk of the inventory, the gem after the one that took the last main-pack slot sees it full and goes to the side pack (a landed pickup marks the list stale)", FullMainPackQuickPickupsSeeTheLastLanding); r.Add("loot retry (R-20261029-122319-321f): an item that lands late, after its pack was given up on, un-marks that pack", LateLandingUnmarks); r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming); r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts); @@ -202,6 +204,17 @@ internal static class LootRetryTimingTests public int QuestRefusals, Unlocks; public long ClientPendingTimeoutMs = 10_000; public int TooBusy, LocalRefused, Queued, RoomRefusals; + /// + /// The client's own checks on its own move (MoveItemExternal), which nothing passes on the wire: + /// a corpse item aimed at a side pack ("You must first pick up the X", 2026-11-12; + /// ), and a pickup aimed at the main pack while 102 loose items are + /// in it, a stackable one with a carried stack to join included (2026-11-30, DreamWeave + /// 'Obsidian Heartstone's; ). No answer comes to either. The raw + /// 0x19 packet (PutItemInContainer, ) skips these checks and the + /// client's one-request slot: it goes straight to the server. + /// + public bool ClientChecks; + public int MainPackDropped, SidePackDropped; public readonly List<(uint Id, uint Pack, long At)> Landed = new(); /// Pack-to-pack moves (MoveItemInternal) the server carried out: they take the client's one pending request too. public readonly List<(uint Id, uint Pack, long At)> PackMoves = new(); @@ -210,7 +223,9 @@ internal static class LootRetryTimingTests private enum St { Idle, Pickup, Return } private St _st; private (uint Id, uint Pack) _next; - private int _seenMoves; + private int _seenMoves, _seenPuts; + /// Raw PutItemInContainer packets that reached the server. + public int RawPuts; private uint _clientPending; private long _clientPendingAt; private int _seenCommands; @@ -228,6 +243,8 @@ internal static class LootRetryTimingTests var m = FakeHost.ExternalMoves[_seenMoves++]; if (Attacking) { AttackRefused++; continue; } // "You cannot move or use an item while attacking" if (LoseFirst.Remove(m.Id)) { Lost++; continue; } // never left the client + if (ClientChecks && m.Target != Player) { SidePackDropped++; continue; } + if (ClientChecks && m.Target == Player && ClientMainPackLoose() >= 102) { MainPackDropped++; continue; } if (_clientPending != 0 && now - _clientPendingAt >= ClientPendingTimeoutMs) _clientPending = 0; // the engine lets it go if (_clientPending != 0) { LocalRefused++; continue; } // "You can only move or use one item at a time" _clientPending = m.Id; @@ -237,6 +254,17 @@ internal static class LootRetryTimingTests if (Lag.Remove(m.Id, out long lag)) arrive += lag; At(arrive, () => Receive(m.Id, m.Target, arrive)); } + while (_seenPuts < FakeHost.Puts.Count) + { + // The raw packet: no client check, no pending slot; the server takes it as any pickup. + var p = FakeHost.Puts[_seenPuts++]; + if (Attacking) { AttackRefused++; continue; } + if (NeverAnswer.Contains(p.Id)) continue; + long arrive = now - TickMs + Rtt / 2; + if (Lag.Remove(p.Id, out long lag)) arrive += lag; + RawPuts++; + At(arrive, () => Receive(p.Id, p.Container, arrive)); + } while (_seenPackMoves < FakeHost.Moves.Count) { var m = FakeHost.Moves[_seenPackMoves++]; @@ -267,6 +295,10 @@ internal static class LootRetryTimingTests private void Answered(uint id) { if (_clientPending == id) _clientPending = 0; } + private static int ClientMainPackLoose() => + FakeHost.Containers.Count(kv => kv.Value == Player + && !(FakeHost.ItemTypes.TryGetValue(kv.Key, out uint t) && t == ItemTypeContainer)); + private void Receive(uint id, uint pack, long ts) { if (_st == St.Idle) { StartPickup(id, pack, ts); return; } @@ -461,12 +493,33 @@ internal static class LootRetryTimingTests Check.False(Logged("no pack has a free slot"), "looting does not stop for want of a pack"); }); - // ── 3b. The main pack is full by the client's own count ─────────────────── - // 2026-11-12, Drakkon on DreamWeave (and R-20261112-110130-5d71): the main pack filled at 07:35, - // the looter aimed every pickup at a side pack, the client refused each one ("You must first - // pick up the Silver Pea", nothing sent), and each item waited out 3 + 3 unanswered tries and - // was left: 48 peas and maps in two hours, the bot stuck on one corpse after another. + // ── 3. A full main pack (2026-11-12, 2026-11-28, 2026-11-30) ────────────── + // 2026-11-12 (R-20261112-110130-5d71, DreamWeave): with the main pack full the looter aimed each + // pickup at a side pack through the client's own move; the client refused every one ("You must first + // pick up the Silver Pea", nothing sent), and each item waited out 3 + 3 tries and was left. Then + // loot went only to the main pack, so with it full everything was left (11-28: "it should continue + // looting and fill the side packs"); a room move (one main-pack item to a side pack, then the pickup) + // followed, and on 2026-11-30 it still lost every stacking 'Obsidian Heartstone' and, on quick + // pickups, a second keep on a corpse. A room move was never the way: loot should go into the side + // packs. Now a side pack gets the raw 0x19 packet, which skips the client's + // check, and the server takes it as any pickup into that pack. No room moves. + private static List FullMainPack(uint junkBase) + { + var ids = new List(); + for (uint i = 0; i < 102; i++) + { + uint j = junkBase + i; + FakeHost.Names[j] = $"Junk {i}"; + FakeHost.ItemTypes[j] = 0x80; + FakeHost.Containers[j] = Player; + ids.Add(j); + } + return ids; + } + + // 3a. An engine without the raw packet (plugin API before v80): with the main pack full nothing can + // take the loot, so it is left at once (a pea with a stack to join too), one chat line says so. private static void FullMainPackPeaJoinsGemLeft() => Clocked(() => { const uint Gem = 0x80263171, Pea = 0x80263172, PeaStack = 0x80263173, JunkBase = 0x80264000; @@ -480,26 +533,16 @@ internal static class LootRetryTimingTests FakeHost.Ints[(PeaStack, 12)] = 40; FakeHost.Containers[PeaStack] = SidePack; var ids = new List { Gem, Pea, PeaStack }; - for (uint i = 0; i < 102; i++) // a full main pack - { - uint j = JunkBase + i; - FakeHost.Names[j] = $"Junk {i}"; - FakeHost.ItemTypes[j] = 0x80; - FakeHost.Containers[j] = Player; - ids.Add(j); - } - var sim = new SlowAce(); + ids.AddRange(FullMainPack(JunkBase)); + var sim = new SlowAce { ClientChecks = true }; var bot = Open(sim, sidePack: true, ids.ToArray()); long started = _now; Run(bot, () => bot.Completed, 60_000); - Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "no pickup is aimed at the side pack (the client would refuse it)"); - Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 0, "the gem is not sent at all: the main pack has no slot and it joins no stack"); - Check.True(Logged("leaving 'Gem 113' 0x80263171") && Logged("the main pack is full"), "the gem is left, and the log says why"); - Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Pea), 1, "the pea is sent once"); - Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Pea).All(m => m.Target == Player), "aimed at the main pack: the client joins it to your stack"); - Check.True(sim.Landed.Any(l => l.Id == Pea), "and it lands"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing is sent: the client would drop it into the side pack or the full main pack"); + Check.True(Logged("leaving 'Gem 113' 0x80263171") && Logged("no raw move"), "the gem is left, and the log says why"); + Check.True(Logged("leaving 'Silver Pea' 0x80263172"), "the pea is left at once too"); Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 1, "one chat line says the main pack is full and loot is left"); Check.False(Logged("pickup failed"), "nothing is waited out and given up"); Check.False(Logged("no pack has a free slot"), "and looting doesn't stop: the side pack has room"); @@ -507,55 +550,108 @@ internal static class LootRetryTimingTests Check.True(_now - started < 10_000, $"quickly ({_now - started} ms), not after 3 + 3 tries per item"); }); - // ── 3c. A full main pack, room in a side pack (2026-11-28) ──────────────── - // "Why does Rynth stop looting when the main pack is full? It should continue looting and fill the - // side packs." Since 3b every item that joined no stack was left once the main pack was full, side - // packs empty or not. Now the looter first moves one loose item from the main pack to the side pack - // (a pack-to-pack move, which the client sends), waits for its answer (the client refuses a pickup - // while it is out), then picks the item up into the freed slot. 3b runs with no inventory manager, - // so it still shows what happens when no room move can be made. - - private static void FullMainPackMakesRoom() => Clocked(() => + // 3b. The raw packet: with the main pack full every gem goes straight into the side pack. + private static void FullMainPackLootsIntoSidePack() => Clocked(() => { const uint G1 = 0x80263181, G2 = 0x80263182, G3 = 0x80263183, JunkBase = 0x80264100; World(sidePack: true, G1, G2, G3); + FakeHost.PutCalls = true; var ids = new List { G1, G2, G3 }; - for (uint i = 0; i < 102; i++) // a full main pack - { - uint j = JunkBase + i; - FakeHost.Names[j] = $"Junk {i}"; - FakeHost.ItemTypes[j] = 0x80; - FakeHost.Containers[j] = Player; - ids.Add(j); - } + ids.AddRange(FullMainPack(JunkBase)); + var sim = new SlowAce { ClientChecks = true }; + sim.Room[Player] = 0; // the server's main pack is full too + var bot = Open(sim, sidePack: true, ids.ToArray()); + bot.Set("_inventoryManager", new RynthCore.Plugin.RynthAi.Loot.InventoryManager(bot.Host, bot.S, bot.Cache)); + + long started = _now; + Run(bot, () => bot.Completed, 60_000); + + foreach (uint g in new[] { G1, G2, G3 }) + Check.True(sim.Landed.Any(l => l.Id == g && l.Pack == SidePack), $"0x{g:X8} is looted into the side pack"); + Check.Eq(FakeHost.Puts.Count, 3, "one raw pickup per gem"); + Check.True(FakeHost.Puts.All(p => p.Container == SidePack), "each aimed at the side pack"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing goes through the client's own move (it would drop them)"); + Check.Eq(FakeHost.Moves.Count, 0, "no room moves: nothing in the main pack is touched"); + Check.Eq(sim.SidePackDropped + sim.MainPackDropped, 0, "the client drops nothing"); + Check.Eq(sim.RoomRefusals, 0, "and the server refuses none for room"); + Check.False(Logged("leaving 'Gem"), "nothing is left on the corpse"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 0, "no main-pack-full chat line"); + Check.True(Logged("into pack 0x80263001"), "the log names the side pack"); + Check.False(Logged("pickup failed"), "nothing is waited out and given up"); + Check.True(bot.Completed, "the corpse completes"); + Check.True(_now - started < 20_000, $"in good time ({_now - started} ms)"); + }); + + // 3c. DreamWeave, 2026-11-30 03:27 to 05:02: every 'Obsidian Heartstone' (a stacking custom weenie) + // was left once the main pack was full: a Heartstone stack with room was carried, so the pickup went + // to the full main pack ("a stack joins anywhere", 3d76e08d, never seen in a client) and the client + // dropped each one, 3 unanswered tries of 4 s, then left. One corpse was opened 13 times in 90 s. + private static void FullMainPackStackGoesToSidePack() => Clocked(() => + { + const uint Stone = 0x80263191, StoneStack = 0x80263192, JunkBase = 0x80264200; + World(sidePack: true, Stone); + FakeHost.PutCalls = true; + FakeHost.Names[Stone] = "Obsidian Heartstone"; + FakeHost.Ints[(Stone, 11)] = 100; // MaxStackSize + FakeHost.Ints[(Stone, 12)] = 1; // StackCount + FakeHost.Names[StoneStack] = "Obsidian Heartstone"; // the stack you carry, in the side pack + FakeHost.ItemTypes[StoneStack] = ItemTypeGem; + FakeHost.Ints[(StoneStack, 11)] = 100; + FakeHost.Ints[(StoneStack, 12)] = 40; + FakeHost.Containers[StoneStack] = SidePack; + var ids = new List { Stone, StoneStack }; + ids.AddRange(FullMainPack(JunkBase)); + var sim = new SlowAce { ClientChecks = true }; + sim.Room[Player] = 0; + var bot = Open(sim, sidePack: true, ids.ToArray()); + + long started = _now; + Run(bot, () => bot.Completed, 60_000); + + Check.Eq(FakeHost.ExternalMoves.Count, 0, "no pickup is aimed at the full main pack (the client would drop it)"); + Check.True(FakeHost.Puts.Any(p => p.Id == Stone && p.Container == SidePack), "the Heartstone goes to the side pack by the raw packet"); + Check.True(sim.Landed.Any(l => l.Id == Stone && l.Pack == SidePack), "and is looted"); + Check.Eq(sim.SidePackDropped + sim.MainPackDropped, 0, "the client drops nothing"); + Check.False(Logged("pickup failed"), "nothing is waited out and given up"); + Check.False(Logged("leaving 'Obsidian Heartstone'"), "nothing is left"); + Check.True(bot.Completed, "the corpse completes"); + Check.True(_now - started < 10_000, $"quickly ({_now - started} ms), not after 3 tries of 4 s"); + }); + + // 3d. DreamWeave, 2026-11-30 03:22:01: right after a quick pickup (jump-loot, 203 ms, no bend-down) + // the next item's check read an inventory list from before that pickup landed (reused for up to 1 s) + // and saw a free main-pack slot that was gone. Here the main pack has one slot: the first gem takes + // it, and with no timed re-walk of the inventory the next two must still see it full and go to the + // side pack (a landed pickup marks the list stale, WorldObjectCache.ExpireDirectInventory). + private static void FullMainPackQuickPickupsSeeTheLastLanding() => Clocked(() => + { + const uint G1 = 0x802631A1, G2 = 0x802631A2, G3 = 0x802631A3, JunkBase = 0x80264300; + World(sidePack: true, G1, G2, G3); + FakeHost.PutCalls = true; + FakeHost.ContentsCalls = true; // the client's container walk, as live (the list is reused between walks) + var ids = new List { G1, G2, G3 }; + ids.AddRange(FullMainPack(JunkBase)); + FakeHost.Containers.Remove(JunkBase + 101); // one free main-pack slot + ids.Remove(JunkBase + 101); var oldClock = RynthClock.TestNow; - var t0 = new DateTime(2026, 11, 28, 12, 0, 0); + var t0 = new DateTime(2026, 11, 30, 3, 22, 0); RynthClock.TestNow = () => t0.AddMilliseconds(_now); try { - var sim = new SlowAce(); - sim.Room[Player] = 0; // the server's main pack is full too + var sim = new SlowAce { ClientChecks = true }; var bot = Open(sim, sidePack: true, ids.ToArray()); - bot.Set("_inventoryManager", new RynthCore.Plugin.RynthAi.Loot.InventoryManager(bot.Host, bot.S, bot.Cache)); + var frozen = t0.AddMilliseconds(_now); + bot.Cache.WalkClock = () => frozen; - long started = _now; Run(bot, () => bot.Completed, 60_000); - foreach (uint g in new[] { G1, G2, G3 }) - Check.True(sim.Landed.Any(l => l.Id == g && l.Pack == Player), $"0x{g:X8} is looted into the main pack"); - Check.True(FakeHost.ExternalMoves.All(m => m.Target == Player), "every pickup is aimed at the main pack"); - Check.Eq(FakeHost.Moves.Count, 3, "one room move per gem"); - Check.True(FakeHost.Moves.All(m => m.Pack == SidePack), "each into the side pack"); - Check.Eq(sim.PackMoves.Count, 3, "and the server carries each out"); - Check.Eq(FakeHost.Moves[0].Id, JunkBase + 101, "the first room move takes the newest loose item (nothing looted yet)"); - Check.Eq(FakeHost.Moves[1].Id, sim.Landed[0].Id, "the next takes the loot just brought in"); - Check.Eq(sim.LocalRefused, 0, "no pickup goes out while a room move has no answer"); - Check.Eq(sim.RoomRefusals, 0, "and the server refuses none for room"); + Check.True(sim.Landed.Any(l => l.Id == G1 && l.Pack == Player), "the first gem takes the main pack's last slot"); + Check.True(sim.Landed.Any(l => l.Id == G2 && l.Pack == SidePack), "the second sees the main pack full and goes to the side pack"); + Check.True(sim.Landed.Any(l => l.Id == G3 && l.Pack == SidePack), "so does the third"); + Check.Eq(sim.MainPackDropped, 0, "no pickup is aimed at the full main pack"); Check.False(Logged("leaving 'Gem"), "nothing is left on the corpse"); - Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 0, "no main-pack-full chat line"); - Check.True(Logged("the main pack is full: moving"), "the log says why each room move went"); + Check.False(Logged("pickup failed"), "nothing is waited out and given up"); Check.True(bot.Completed, "the corpse completes"); - Check.True(_now - started < 20_000, $"in good time ({_now - started} ms)"); } finally { RynthClock.TestNow = oldClock; } }); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs index 2e18d9b..ac0cdb5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs @@ -35,7 +35,7 @@ internal static class LootSalvageTests public static void Register(Runner r) { r.Add("loot pickup: a corpse item is moved into the main pack, never used (no get-and-wield)", PickupMovesNeverUses); - r.Add("loot pickup: a full main pack never sends an item to a side pack (the client refuses that from a corpse); a stack you carry is still joined, anything else is left", PickupFullMainPackNeverSidePack); + r.Add("loot pickup: with the main pack full the client's own move never goes to a side pack or (a stackable item included) to the full main pack; with the raw move (v80) the item goes straight into the side pack", PickupFullMainPackNeverSidePack); r.Add("loot pickup: no move call -> wearables are left, other items are used", PickupWithoutMoveCall); r.Add("salvage: a worn item is left alone and never taken off", SalvageLeavesWornItem); r.Add("salvage: a corpse's items go in one batch and all are salvaged", SalvageOneBatch); @@ -88,10 +88,12 @@ internal static class LootSalvageTests // logs, none landed, each item waited out 3 + 3 tries and was left. private const uint PeaInPack = 0x80262E01, Pea = 0x80262E02, SpareMain = 0x80262E03; - private static (RynthCoreHost Host, WorldObjectCache Cache) FullMainPack(bool sideRoom, bool peaStack) + /// The engine has the raw 0x19 packet (plugin API v80, PutItemInContainer). + private static (RynthCoreHost Host, WorldObjectCache Cache) FullMainPack(bool sideRoom, bool peaStack, bool rawMove = false) { FakeHost.Reset(); FakeHost.SalvageCalls = true; + FakeHost.PutCalls = rawMove; var ids = new List(); for (uint i = 0; i < 102; i++) { @@ -137,26 +139,40 @@ internal static class LootSalvageTests private static void PickupFullMainPackNeverSidePack() { + // An engine without the raw packet (plugin API before v80): nothing can take the loot. var (host, cache) = FullMainPack(sideRoom: true, peaStack: true); Check.Eq(LootPickup.Send(host, cache, Ring, Player, out uint dest), LootPickupResult.MainPackFull, - "a ring with the main pack full and room in a side pack: left (MainPackFull)"); + "no raw move: a ring with the main pack full and room in a side pack is left (MainPackFull)"); Check.Eq(dest, 0u, "no destination"); - Check.Eq(FakeHost.ExternalMoves.Count, 0, "and no move sent, least of all into the side pack"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "and no move sent, least of all the client's own move into the side pack"); - Check.Eq(LootPickup.Send(host, cache, Pea, Player, out dest), LootPickupResult.Moved, - "a Silver Pea joins the stack you carry: sent"); - Check.Eq(dest, Player, "aimed at the main pack: the client joins it to the stack in the side pack"); - Check.True(FakeHost.ExternalMoves.All(m => m.Target != SidePack), "never aimed at the side pack"); + // 2026-11-30 (DreamWeave, 'Obsidian Heartstone' x many): a pickup aimed at a full main pack is + // dropped by the client even when a stack you carry has room for it; no answer ever came. + Check.Eq(LootPickup.Send(host, cache, Pea, Player, out dest), LootPickupResult.MainPackFull, + "a Silver Pea with a stack you carry in the side pack, main pack full: not sent at the main pack either (the client drops it)"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "no move sent"); Check.Eq(FakeHost.Uses.Count, 0, "no UseObject"); - var (host2, cache2) = FullMainPack(sideRoom: true, peaStack: false); - Check.Eq(LootPickup.Send(host2, cache2, Pea, Player, out _), LootPickupResult.MainPackFull, - "a pea with no stack to join, main pack full: left too"); - var (host3, cache3) = FullMainPack(sideRoom: false, peaStack: false); Check.Eq(LootPickup.Send(host3, cache3, Ring, Player, out _), LootPickupResult.NoRoom, "no room in any pack: NoRoom, as before"); + + // The raw packet (v80; 2026-11-30, loot into side packs): the side pack. + var (host4, cache4) = FullMainPack(sideRoom: true, peaStack: true, rawMove: true); + Check.Eq(LootPickup.Send(host4, cache4, Ring, Player, out dest), LootPickupResult.Moved, + "with the raw move: the ring goes to the side pack"); + Check.Eq(dest, SidePack, "aimed at the side pack"); + Check.True(FakeHost.Puts.Any(p => p.Id == Ring && p.Container == SidePack), "by the raw 0x19 packet"); + Check.Eq(LootPickup.Send(host4, cache4, Pea, Player, out dest), LootPickupResult.Moved, + "the pea with a stack to join goes there too, not to the full main pack"); + Check.Eq(dest, SidePack, "aimed at the side pack"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing through the client's own move, which would drop both"); + + var (host5, cache5) = FullMainPack(sideRoom: false, peaStack: false, rawMove: true); + Check.Eq(LootPickup.Send(host5, cache5, Ring, Player, out _), LootPickupResult.NoRoom, + "with the raw move and every pack full: NoRoom"); + Check.Eq(FakeHost.Puts.Count, 0, "nothing sent"); } private static void PickupWithoutMoveCall() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavPanelTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavPanelTests.cs new file mode 100644 index 0000000..c5006f3 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavPanelTests.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; +using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The new engine Nav panel (2026-11-29, NavFace.cs): its buttons beside Add waypoint here (Jump, Vendor, +// NPC), a Jump step edited in place (facing, power, walk), Undo after a delete or clear, New route, and +// what the nav JSON now says about each step and where the character stands. +internal static class NavPanelTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("nav panel: setJump changes a Jump step's facing, power and walk, and the file keeps them", SetJumpEdits); + r.Add("nav panel: addJump adds a jump where you stand, facing your way at 30% unless told", AddJump); + r.Add("nav panel: addVendor and addNpc take the selected object", AddVendorAndNpc); + r.Add("nav panel: Undo puts deleted steps back in their places (delete, multi-delete, clear)", UndoPutsBack); + r.Add("nav panel: newRoute starts an empty, unsaved route", NewRoute); + r.Add("nav panel: the nav JSON has each step's name, seconds and jump, where you stand, and the Undo count", JsonFields); + r.Add("nav panel: the engine's jump fields read; left out they mean unchanged", CommandJson); + } + + private sealed class Rig + { + public readonly LegacyUiSettings S = new(); + public readonly LegacyDashboardRenderer Dash; + public readonly string Root; + + public Rig(string name, params NavPoint[] pts) + { + FakeHost.Reset(); + Root = Path.Combine(Program.TempRoot, "nav-panel", name); + if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true); + Directory.CreateDirectory(Root); + S.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Circular }; + S.CurrentRoute.Points.AddRange(pts); + + var nav = (LegacyNavigationUi)RuntimeHelpers.GetUninitializedObject(typeof(LegacyNavigationUi)); + typeof(LegacyNavigationUi).GetField("_settings", Any)!.SetValue(nav, S); + Dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + Set("_profileLoaded", true); // a stand-in with its profile in memory + Set("_settings", S); + Set("_host", FakeHost.Create()); + Set("_navigationUi", nav); + Set("_navFiles", new List()); + Set("_navFolder", Root); + Set("_profileListsLock", new object()); + Set("_navEditStatus", string.Empty); // field initializers don't run on an uninitialized object + // _settingsFilePath stays null: SaveSettings writes nothing. + } + + private void Set(string f, object v) => typeof(LegacyDashboardRenderer).GetField(f, Any)!.SetValue(Dash, v); + + public void Cmd(string json) => Dash.HandleNavCommand(json); + + public NavBridgePayload Nav() => + JsonSerializer.Deserialize(Dash.BuildNavJson(), RynthAiJsonContext.Default.NavBridgePayload)!; + + public string Status() => Nav().EditStatus; + } + + private static NavPoint P(double ns, double ew, T type = T.Point) => new() { Type = type, NS = ns, EW = ew, Z = -0.1 }; + + private static NavPoint Jump(double heading, double ms, bool shift) => + new() { Type = T.Jump, NS = 1, EW = 1, Z = 0, JumpHeading = heading, JumpMs = ms, JumpShift = shift }; + + private static void SetJumpEdits() + { + var rig = new Rig("setjump", P(1, 1), Jump(90, 300, false), P(2, 2)); + string path = Path.Combine(rig.Root, "jumps.nav"); + rig.S.CurrentRoute.Save(path); + rig.S.CurrentNavPath = path; + + rig.Cmd("{\"Cmd\":\"setJump\",\"Index\":1,\"Heading\":212,\"Ms\":-1,\"Shift\":false}"); + NavPoint j = rig.S.CurrentRoute.Points[1]; + Check.Near(j.JumpHeading, 212, 1e-9, "facing set"); + Check.Near(j.JumpMs, 300, 1e-9, "power unchanged (Ms -1)"); + + rig.Cmd("{\"Cmd\":\"setJump\",\"Index\":1,\"Heading\":-1,\"Ms\":600,\"Shift\":true}"); + Check.Near(j.JumpHeading, 212, 1e-9, "facing unchanged (Heading -1)"); + Check.Near(j.JumpMs, 600, 1e-9, "power 60%"); + Check.True(j.JumpShift, "walking jump"); + + rig.Cmd("{\"Cmd\":\"setJump\",\"Index\":1,\"Heading\":-450,\"Ms\":5000,\"Shift\":true}"); + Check.Near(j.JumpHeading, 212, 1e-9, "a negative facing changes nothing"); + Check.Near(j.JumpMs, 1000, 1e-9, "power capped at 100%"); + + rig.Cmd("{\"Cmd\":\"setJump\",\"Index\":1,\"Heading\":450,\"Ms\":-1,\"Shift\":true}"); + Check.Near(j.JumpHeading, 90, 1e-9, "450° is 90°"); + + // Not a jump, or out of range: nothing changes. + rig.Cmd("{\"Cmd\":\"setJump\",\"Index\":0,\"Heading\":10,\"Ms\":10,\"Shift\":true}"); + Check.Near(rig.S.CurrentRoute.Points[0].JumpHeading, 0, 0, "a Point isn't made a jump"); + rig.Cmd("{\"Cmd\":\"setJump\",\"Index\":9,\"Heading\":10,\"Ms\":10,\"Shift\":true}"); + + NavRouteParser reread = NavRouteParser.Load(path); + Check.Eq(reread.Points[1].Type, T.Jump, "still a jump in the file"); + Check.Near(reread.Points[1].JumpHeading, 90, 1e-6, "file: facing"); + Check.Near(reread.Points[1].JumpMs, 1000, 1e-6, "file: power"); + Check.True(reread.Points[1].JumpShift, "file: walking"); + } + + private static void AddJump() + { + var rig = new Rig("addjump", P(1, 1), P(2, 2)); + FakeHost.SetNavPosition(10.5, -20.25); + FakeHost.HeadingDeg = 135; + + rig.Cmd("{\"Cmd\":\"addJump\",\"AddMode\":0,\"InsertAt\":-1,\"Heading\":-1,\"Ms\":-1,\"Shift\":false}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 3, "a step added"); + NavPoint j = rig.S.CurrentRoute.Points[2]; + Check.Eq(j.Type, T.Jump, "a Jump step"); + Check.Near(j.NS, 10.5, 1e-4, "where you stand (NS)"); + Check.Near(j.EW, -20.25, 1e-4, "where you stand (EW)"); + Check.Near(j.JumpHeading, 135, 0.5, "facing your way"); + Check.Near(j.JumpMs, 300, 1e-9, "30% power"); + Check.False(j.JumpShift, "not walking"); + + // Told: after step 0, facing 270, full power, walking. + rig.Cmd("{\"Cmd\":\"addJump\",\"AddMode\":2,\"InsertAt\":0,\"Heading\":270,\"Ms\":1000,\"Shift\":true}"); + NavPoint k = rig.S.CurrentRoute.Points[1]; + Check.Eq(k.Type, T.Jump, "after step 0"); + Check.Near(k.JumpHeading, 270, 1e-9, "facing as told"); + Check.Near(k.JumpMs, 1000, 1e-9, "power as told"); + Check.True(k.JumpShift, "walking as told"); + } + + private static void AddVendorAndNpc() + { + var rig = new Rig("vendor-npc", P(1, 1)); + FakeHost.SetNavPosition(5, 5); + // Nothing selected: nothing added, and the panel says why. + rig.Cmd("{\"Cmd\":\"addVendor\",\"AddMode\":0,\"InsertAt\":-1}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 1, "no selection: nothing added"); + Check.True(rig.Status().Contains("Select"), "says to select: " + rig.Status()); + + const uint Vendor = 0x7A000010, Npc = 0x7A000011; + uint cell = FakeHost.NavCell(5.01, 5.01, out float vx, out float vy); + FakeHost.Names[Vendor] = "Renald the Grocer"; + FakeHost.Positions[Vendor] = (cell, vx, vy, 0); + FakeHost.Names[Npc] = "Town Crier"; + FakeHost.Positions[Npc] = (cell, vx, vy, 0); + + FakeHost.SelectedItem = Vendor; + rig.Cmd("{\"Cmd\":\"addVendor\",\"AddMode\":0,\"InsertAt\":-1}"); + NavPoint v = rig.S.CurrentRoute.Points[^1]; + Check.Eq(v.Type, T.OpenVendor, "a Vendor step"); + Check.Eq(v.TargetName, "Renald the Grocer", "the vendor's name"); + Check.Eq(v.VendorId, Vendor, "the vendor's id"); + Check.Near(v.NS, 5, 1e-4, "where you stand"); + + FakeHost.SelectedItem = Npc; + rig.Cmd("{\"Cmd\":\"addNpc\",\"AddMode\":1,\"InsertAt\":0}"); + NavPoint n = rig.S.CurrentRoute.Points[0]; + Check.Eq(n.Type, T.Npc, "an NPC step, before step 0"); + Check.Eq(n.TargetName, "Town Crier", "the NPC's name"); + Check.Near(n.PortalExitNS, 5.01, 1e-3, "the NPC's own spot"); + + // Saved and read back: both keep their names (the file format's trailers). + string path = Path.Combine(rig.Root, "stops.nav"); + rig.S.CurrentRoute.Save(path); + NavRouteParser reread = NavRouteParser.Load(path); + Check.Eq(reread.Points.Count, 3, "three steps in the file"); + Check.Eq(reread.Points[0].TargetName, "Town Crier", "file: NPC"); + Check.Eq(reread.Points[2].TargetName, "Renald the Grocer", "file: vendor"); + Check.Eq(reread.Points[2].VendorId, Vendor, "file: vendor id"); + } + + private static void UndoPutsBack() + { + NavPoint a = P(1, 1), b = P(2, 2), c = P(3, 3), d = P(4, 4); + var rig = new Rig("undo", a, b, c, d); + Check.Eq(rig.Nav().UndoCount, 0, "nothing to undo yet"); + + rig.Cmd("{\"Cmd\":\"deletePoints\",\"Indices\":[1,3]}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 2, "two deleted"); + var nav = rig.Nav(); + Check.Eq(nav.UndoCount, 2, "Undo can put two back"); + Check.True(nav.EditStatus.StartsWith("Deleted"), "the panel's Undo shows after 'Deleted...': " + nav.EditStatus); + rig.Cmd("{\"Cmd\":\"undoDelete\"}"); + var pts = rig.S.CurrentRoute.Points; + Check.Eq(pts.Count, 4, "both back"); + Check.True(ReferenceEquals(pts[1], b) && ReferenceEquals(pts[3], d), "each in its place"); + Check.Eq(rig.Nav().UndoCount, 0, "and Undo is used up"); + + rig.Cmd("{\"Cmd\":\"deletePoint\",\"Index\":0}"); + Check.True(rig.Status().StartsWith("Deleted step 0"), "the row's X says so: " + rig.Status()); + rig.Cmd("{\"Cmd\":\"undoDelete\"}"); + Check.True(ReferenceEquals(rig.S.CurrentRoute.Points[0], a), "the X's step is back first"); + + rig.Cmd("{\"Cmd\":\"clearRoute\"}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "cleared"); + Check.True(rig.Status().StartsWith("Cleared"), "says cleared: " + rig.Status()); + rig.Cmd("{\"Cmd\":\"undoDelete\"}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 4, "all four back"); + Check.True(ReferenceEquals(rig.S.CurrentRoute.Points[2], c), "in order"); + + // Another route loaded: Undo has nothing to put into it. + rig.Cmd("{\"Cmd\":\"deletePoint\",\"Index\":0}"); + rig.S.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once }; + Check.Eq(rig.Nav().UndoCount, 0, "a different route: nothing to undo"); + rig.Cmd("{\"Cmd\":\"undoDelete\"}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "nothing put into the other route"); + } + + private static void NewRoute() + { + var rig = new Rig("newroute", P(1, 1), P(2, 2)); + rig.S.CurrentNavPath = Path.Combine(rig.Root, "kept.nav"); + rig.S.ActiveNavIndex = 1; + rig.S.IsRecordingNav = true; + rig.Cmd("{\"Cmd\":\"newRoute\"}"); + Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "empty"); + Check.Eq(rig.S.CurrentRoute.RouteType, NavRouteType.Once, "Run once"); + Check.Eq(rig.S.CurrentNavPath, string.Empty, "unsaved: no file"); + Check.Eq(rig.S.ActiveNavIndex, 0, "from step 0"); + Check.False(rig.S.IsRecordingNav, "recording stopped"); + Check.False(File.Exists(Path.Combine(rig.Root, "kept.nav")), "no file written"); + } + + private static void JsonFields() + { + var rig = new Rig("json", + P(1, 1), + new NavPoint { Type = T.Pause, NS = 1, EW = 1, PauseTimeMs = 5000 }, + new NavPoint { Type = T.OpenVendor, NS = 1, EW = 1, TargetName = "Renald the Grocer", VendorId = 7 }, + new NavPoint { Type = T.PortalNPC, NS = 1, EW = 1, TargetName = "Portal to Holtburg" }, + new NavPoint { Type = T.Npc, NS = 1, EW = 1, TargetName = "Town Crier" }, + Jump(212, 600, true), + new NavPoint { Type = T.Chat, NS = 1, EW = 1, ChatCommand = "/ub usei Healing Kit" }); + rig.S.ActiveNavIndex = 0; + var nav = rig.Nav(); + Check.Near(nav.Points[1].Seconds, 5, 1e-9, "Pause: seconds"); + Check.Eq(nav.Points[2].Name, "Renald the Grocer", "Vendor: name"); + Check.Eq(nav.Points[3].Name, "Portal to Holtburg", "Portal: name"); + Check.Eq(nav.Points[4].Name, "Town Crier", "NPC: name"); + Check.Near(nav.Points[5].Heading, 212, 1e-9, "Jump: facing"); + Check.Near(nav.Points[5].Ms, 600, 1e-9, "Jump: power"); + Check.True(nav.Points[5].Shift, "Jump: walking"); + Check.Eq(nav.Points[6].Text, "/ub usei Healing Kit", "Chat: the command (as before)"); + Check.Eq(nav.Points[0].Name, string.Empty, "Point: no name"); + + // Where you stand, and how far the next step is (yd = nav units x 240). + FakeHost.SetNavPosition(1.1, 1); + nav = rig.Nav(); + Check.True(nav.HereKnown, "position known"); + Check.Near(nav.HereNS, 1.1, 1e-4, "here NS"); + Check.Near(nav.ActiveDist, 24, 0.05, "step 0 is 24 yd away"); + // No plugin hook (a stand-in renderer): the mode fields stay at their defaults. + Check.Eq(nav.Mode, string.Empty, "no mode without the plugin"); + Check.False(nav.HuntAvailable, "no Hunt tab without the plugin"); + + // The plugin's hook fills the mode fields. + rig.Dash.NavPanelState = p => { p.Mode = "follow"; p.FollowName = "Leader"; p.HuntAvailable = true; }; + nav = rig.Nav(); + Check.Eq(nav.Mode, "follow", "the hook's mode"); + Check.Eq(nav.FollowName, "Leader", "the hook's follow name"); + Check.True(nav.HuntAvailable, "the hook's Hunt tab"); + // A hook that throws doesn't take the panel's data with it. + rig.Dash.NavPanelState = _ => throw new InvalidOperationException("test"); + nav = rig.Nav(); + Check.Eq(nav.Points.Count, 7, "points still there"); + } + + private static void CommandJson() + { + NavCommand? c = JsonSerializer.Deserialize("{\"Cmd\":\"setJump\",\"Index\":2,\"Heading\":90.5,\"Ms\":450,\"Shift\":true,\"Text\":\"face\"}", + RynthAiJsonContext.Default.NavCommand); + Check.Near(c!.Heading, 90.5, 1e-9, "Heading"); + Check.Near(c.Ms, 450, 1e-9, "Ms"); + Check.True(c.Shift, "Shift"); + Check.Eq(c.Text, "face", "Text"); + NavCommand? old = JsonSerializer.Deserialize("{\"Cmd\":\"addJump\"}", RynthAiJsonContext.Default.NavCommand); + Check.Near(old!.Heading, -1, 0, "no Heading: -1 (your facing / unchanged)"); + Check.Near(old.Ms, -1, 0, "no Ms: -1 (30% / unchanged)"); + } +}